<script setup lang="ts">
import { fetchtNationalityList } from '@/api/modules/anycallService'

// 定义组件属性
interface Props {
  modelValue?: string
  disabled?: boolean
  placeholder?: string
  style?: string | object
  className?: string
}

// 定义组件事件
interface Emits {
  (e: 'update:modelValue', value: string | undefined): void
  (e: 'update:key', value: string | undefined): void
}

// 设置默认属性
const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  placeholder: '请选择',
  style: 'width: 140px;',
})

// 定义事件触发器
const emit = defineEmits<Emits>()

// 创建本地响应式变量用于v-model绑定
const localValue = ref(props.modelValue)

// 监听props中的modelValue变化，同步到本地变量
watch(
  () => props.modelValue,
  (newValue) => {
    localValue.value = newValue
  },
  { immediate: true }
)


const options = ref<Array<{value: string, name: string}>>([])

const fetchData = async () => {
  try {
    const res = await fetchtNationalityList()
    if (res.code === 0) {
      console.log(res.data,3333)
      options.value = res.data
      // // 将API返回的数据转换为select需要的格式
      // options.value = res.data.content.map((item: any) => ({
      //   value: item.id,
      //   name: item.name
      // }))
    } else {
      console.error('获取 I18n 失败:', res.msg)
    }
  } catch (error) {
    console.error('获取 I18n 失败:', error)
  }
}

onMounted(() => {
  fetchData()
})

const updateModelValue = (value: string) => {
  emit('update:modelValue', value)
  const f = options.value.find(item => item.value === value)
  if(f){
    emit('update:key', f.name)
  }

}

</script>

<template>
  <el-select
    v-model="localValue"
    :placeholder="placeholder"
    :style="style"
    :disabled="disabled"
    :class="className"
    clearable
    filterable
    @update:model-value="updateModelValue"
  >
    <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value" />
  </el-select>
</template>
