<template>
  <ElSelect
    v-model="internalValue"
    filterable
    clearable
    :loading="loading"
    :placeholder="placeholder || t('store.form.categoryIdPlaceholder')"
    class="w-full"
    @change="handleChange"
  >
    <ElOption v-for="item in options" :key="item.id" :label="getLabel(item)" :value="item.id">
      <span>{{ getLabel(item) }}</span>
      <span class="ml-2 text-xs text-[var(--el-text-color-secondary)]">[{{ item.key }}]</span>
    </ElOption>
  </ElSelect>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElSelect, ElOption } from 'element-plus'
  import { getDictionary } from '@/api/dictionary/query'

  defineOptions({ name: 'CategorySelect' })

  interface Props {
    modelValue?: string | null
    placeholder?: string
    dictCode?: string
  }

  const props = withDefaults(defineProps<Props>(), {
    dictCode: 'STORE_CATEGORY'
  })

  const emit = defineEmits<{
    (e: 'update:modelValue', value: string | null): void
    (e: 'change', value: string | null, item?: Api.Dictionary.DictionaryItemDto): void
  }>()

  const { t, locale } = useI18n()
  const loading = ref(false)
  const internalValue = ref<string | null>(null)
  const options = ref<Api.Dictionary.DictionaryItemDto[]>([])

  /** 获取字典多语言标签 */
  const getLabel = (item: Api.Dictionary.DictionaryItemDto) => {
    // 优先匹配当前语言，匹配不到则取第一个
    const labels = item.value || {}
    const currentLocale = locale.value
    return labels[currentLocale] || labels['zh-CN'] || Object.values(labels)[0] || item.key
  }

  /** 加载字典数据 */
  const loadOptions = async () => {
    loading.value = true
    try {
      options.value = await getDictionary(props.dictCode)
    } catch (error) {
      console.warn(`Fetch Dictionary [${props.dictCode}] Error:`, error)
    } finally {
      loading.value = false
    }
  }

  /** 处理值变更 */
  const handleChange = (val: string | null) => {
    const selected = options.value.find((item) => item.id === val)
    emit('update:modelValue', val)
    emit('change', val, selected)
  }

  watch(
    () => props.modelValue,
    (newVal) => {
      internalValue.value = newVal || null
    },
    { immediate: true }
  )

  onMounted(loadOptions)
</script>
