<script setup lang="ts">
import { ref, watch } from 'vue';
import request from '~/utils/request';


const props = defineProps<{
  to: string,
  modelValue?: string,
  modelName?: string,
  change?: (item: object | undefined) => void
}>()
const emits = defineEmits(["update:modelValue", "update:modelName"])

const loading = ref(false)

const value = ref(props.modelValue)
const options = ref<{ n: string, v: string }[]>((props.modelValue && props.modelName) ? [{
  n: props.modelName,
  v: props.modelValue
}] : [])

remoteMethod().then(() => {
  if (props.modelValue && props.modelName && !options.value.find(({ v: val }) => val === props.modelValue)) {
    // console.log('true :>> ', true);
    options.value.unshift({
      n: props.modelName,
      v: props.modelValue
    })
  }
})

function remoteMethod(keyword?: string) {
  loading.value = true
  return request({
    url: '/common/sjzd/option',
    data: {
      // keyword,
      limit: 100,
      cs_code:props.to
    }
  }).then(({ data }) => {
    options.value = data.option
    loading.value = false
  })
}



watch(
  () => value.value,
  (val) => {
    const item = options.value.find(({ v }) => v === val)
    emits("update:modelValue", val)
    emits("update:modelName", item?.n)
  }
)

watch(() => props.modelValue, (val) => {
  if (val === undefined) {
    value.value = undefined
  }
})
</script>



<template>
  <!-- remote :remote-method="remoteMethod"-->
  <el-select class="w-full" v-model="value" filterable reserve-keyword clearable :loading="loading">
    <el-option v-for="item in options" :key="item.v" :label="item.n" :value="item.v" />
  </el-select>
</template>

