<template>
  <el-select-v2
      ref="selectRef"
      v-model="value"
      :remote-method="method"
      filterable
      :disabled="props.disabled"
      remote
      @clear="clear"
      :title="selectRef?.states?.selectedLabel"
      :options="tempData"
      :clearable="props.clearable"
      @change="change"
      :placeholder="props.placeholder"
      style="width: 240px">
    <template #default="{ item }">
      <div :title="item.label" style="width: 100%;height: 100%">
        {{ item.label }}
      </div>
    </template>
  </el-select-v2>
</template>

<script setup name='SelectV4'>
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: null
  },
  data: {
    type: Array,
    default: []
  },
  clearable: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue', 'change', 'clear'])

const value = ref()
const tempData = ref([])

const selectRef = ref()

const change = (val) => {
  emits('update:modelValue', val)
  for (let i = 0, len = tempData.value.length; i < len; i++) {
    let item = tempData.value[i]
    if (val === item.code) {
      emits('change', item)
    }
  }
}

const focus = () => {
  selectRef.value.handleFocus()
}

const clear = () => {
  emits('clear')
}

watch(() => props.modelValue, () => {
  value.value = props.modelValue
  tempData.value = props.data
}, {immediate: true})

watch(() => props.data, () => {
  tempData.value = props.data
}, {immediate: true})

const method = (query) => {
  if (query) {
    tempData.value = props.data.filter((item) => {
      if (item.name && item.name.indexOf(query) > -1) {
        return true;
      } else if (item.pyCode && item.pyCode.indexOf(query.toLocaleUpperCase()) > -1) {
        return true;
      } else if (item.wCode && item.wCode.indexOf(query.toLocaleUpperCase()) > -1) {
        return true;
      } else if (item.code && item.code.indexOf(query) > -1) {
        return true
      } else if (item.code && item.code.indexOf(query.toLocaleUpperCase()) > -1) {
        return true;
      }
      return false;
    });
  } else {
    tempData.value = props.data
  }
}

defineExpose({
  focus
})

</script>

<style scoped lang="scss">

</style>
