""" @author: yy @desc：下拉搜索 @date: 2025-07-24 22:44:54 """
<template>
  <el-select
    v-model="formValue"
    filterable
    remote
    reserve-keyword
    remote-show-suffix
    :disabled="disabled"
    placeholder="请选择"
    :remote-method="remoteMethod"
    :loading="loading"
    style="width: 100%"
    @change="handleChange"
  >
    <el-option v-for="item in options" :key="item[fieldNames.value]" :label="item[fieldNames.label]" :value="item[fieldNames.value]" />
  </el-select>
</template>
<script setup>
import { computed, ref, watch } from "vue"
import { getApi2, postApi2 } from "@/api/tobAcco_api.js"

const props = defineProps({
  value: {
    type: String,
    required: true
  },
  remoteMethodType: {
    type: String,
    default: "get"
  },
  remoteMethodApi: {
    type: String,
    required: true
  },
  othParams: {
    type: Object,
    default: () => ({})
  },
  // options的数据格式
  fieldNames: {
    type: Object,
    validator: value => {
      return "label" in value && "value" in value
    },
    default: () => ({ label: "label", value: "value" })
  },
  // 搜索关键词key
  keyword: {
    type: String,
    default: "keyword"
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(["update:value", "change"])

const formValue = computed({
  get() {
    return props.value
  },
  set(val) {
    emits("update:value", val)
  }
})

const loading = ref(false)
const options = ref([])

const remoteMethod = async query => {
  try {
    loading.value = true
    const api = props.remoteMethodType === "get" ? getApi2 : postApi2
    const res = await api({ ...props.othParams, [props.keyword]: query }, props.remoteMethodApi)
    options.value = res instanceof Array ? res : res?.records || []
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

const handleChange = val => {
  formValue.value = val
  const item = options.value.find(item => item[props.fieldNames.value] === val)
  if (item) {
    emits("change", item)
  }
}

watch(
  () => props.value,
  val => {
    if (val) {
      const len = options.value.filter(item => item[props.fieldNames.value] === val).length
      if (!len) {
        remoteMethod(val)
      }
    }
  }
)
</script>
<style lang="scss" scoped></style>
