<script setup>
// <{
//   url?: string,
//   to?: 'team' | 'grade' | 'class' | 'subject',
//   modelValue?: string,
//   modelName?: string,
//   change?: (item: object | undefined) => void,
//   fields?: [string, string],
//   d?:{}
// }>
const props = defineProps({
  url: String,
  to: String,
  modelValue: String,
  modelName: String,
  change: Function,
  fields: Array,
  d: Object
})
const emits = defineEmits(["update:modelValue", "update:modelName"])

const loading = ref(false)

const value = ref(props.modelValue)
const options = ref((props.modelValue && props.modelName) ? [{
  name: props.modelName,
  value: props.modelValue
}] : [])

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

function remoteMethod(keyword) {
  loading.value = true
  return request({
    url: props.to ? `/txwx/${props.to}/index` : props.url,
    data: {
      ...props.d,
      keyword,
      limit: 100,
    }
  }).then(({ data }) => {
    options.value = data.page_data.map((item) => ({
      value: item[props.fields ? props.fields[0] : props.to + '_id'],
      name: item[props.fields ? props.fields[1] : props.to + '_name'],
      origin: item
    }))
    loading.value = false
  })
}

watch(
  () => value.value,
  (val) => {
    const item = options.value.find(({ value }) => value === val)
    emits("update:modelValue", val)
    emits("update:modelName", item?.name)
    props.change?.(item?.origin)
  }
)

watch(() => props.modelValue, (val) => {
  if (val === undefined) {
    value.value = undefined
  } else {
    value.value = val;
  }
})

watch(
  () => props.d,
  (val, oldVal) => {
    // console.log('watch :>> ', val, oldVal);
    if (Object.keys(val).some(k => val[k] !== oldVal[k])) {
      console.log('watch request :>> ');
      request({
        url: props.to ? `/txwx/${props.to}/index` : props.url,
        data: {
          ...props.d,
          limit: 100,
        }
      }).then(({ data }) => {
        options.value = data.page_data.map((item) => ({
          value: item[props.fields ? props.fields[0] : props.to + '_id'],
          name: item[props.fields ? props.fields[1] : props.to + '_name'],
          origin: item
        }))

      })
    }
  },
  { immediate: false }
)
</script>

<template>
  <!-- remote :remote-method="remoteMethod"-->
  <el-select v-model="value" filterable reserve-keyword clearable :loading="loading">
    <template #default :key="loading">
      <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
        <slot :item="item.origin">
          <span>{{item.name}}</span>
        </slot>
      </el-option>
    </template>
  </el-select>
</template>