<script setup>
const props = defineProps({
  modelValue: String,
  modelName: String,
  modelRealName: String,
  change: Function,
  fields: Array,
  d: Object,
  showKey: String
})
const emits = defineEmits(["update:modelValue", "update:modelName", "update:modelRealName"])

const showValue = ref(props.showKey || "user_realname");

const loading = ref(false)

const value = ref(props.modelValue)
const options = ref((props.modelValue && props.modelName) ? [{
  user_name: props.modelName,
  user_id: props.modelValue,
  user_realname: props.modelRealName,
}] : [])

remoteMethod().then(() => {
  if (props.modelValue && props.modelName && !options.value.find(({ value: val }) => val === props.modelValue)) {
    options.value.unshift({
      user_id: props.modelValue,
      user_name: props.modelName,
      user_realname: props.modelRealName,
    })
  }
})

function remoteMethod(keyword) {
  loading.value = true
  return request({
    url: "/user/main/index",
    data: {
      ...props.d,
      keyword,
      limit: 100,
    }
  }).then(({ data }) => {
    options.value = data.page_data;
    loading.value = false
  })
}

watch(
  () => value.value,
  (val) => {
    const item = options.value.find((v) => v.user_id === val)
    // if (item) {
    emits("update:modelValue", val)
    emits("update:modelName", item?.user_name)
    emits("update:modelRealName", item?.user_realname)
    props.change?.item
    // } else {
    //   emits("update:modelValue", "")
    //   emits("update:modelName", "")
    //   emits("update:modelRealName", "")
    // }
    // props.change?.(item || val)
  }
)

watch(() => [props.modelValue, props.modelRealName],
  (val) => {
    value.value = val[0];
    // if (val[0] && val[0] != 0 && val[1]) {
    //   value.value = val[0];
    // } else if ((!val[0] || val[0] == 0) && val[1]) {
    //   value.value = val[1];
    // }
  },
  { immediate: true }
)

watch(
  () => props.d,
  (val, oldVal) => {
    if (Object.keys(val).some(k => val[k] !== oldVal[k])) {
      remoteMethod("");
    }
  },
  { immediate: false }
)
</script>

<template>
  <el-select v-model="value" filterable reserve-keyword remote :remote-method="remoteMethod" clearable :loading="loading">
    <template #default :key="loading">
      <el-option v-for="item in options" :key="item.user_id" :label="item[showValue]" :value="item.user_id">
        {{ item.user_realname }}（{{ item.user_name }}）
      </el-option>
    </template>
  </el-select>
</template>