<template>
  <ElSelect
    v-model="internalValue"
    filterable
    remote
    clearable
    :remote-method="handleSearch"
    :loading="loading"
    :placeholder="placeholder || '输入商户名搜索...'"
    class="w-full"
    @change="handleChange"
  >
    <template #prefix>
      <ElIcon><Search /></ElIcon>
    </template>
    <ElOption v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
      <div class="flex items-center justify-between">
        <span>{{ item.name }}</span>
        <span class="ml-2 text-xs text-[var(--el-text-color-secondary)]">ID: {{ item.id }}</span>
      </div>
    </ElOption>
  </ElSelect>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue'
  import { ElSelect, ElOption, ElIcon } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { fetchMerchantList, fetchMerchantDetail } from '@/api/merchant'

  defineOptions({ name: 'MerchantSelect' })

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

  const props = defineProps<Props>()
  const emit = defineEmits<{
    (e: 'update:modelValue', value: string | null): void
    (
      e: 'change',
      value: string | null,
      merchant?: Api.Merchant.MerchantListItem | Api.Merchant.MerchantDetail
    ): void
  }>()

  const loading = ref(false)
  const internalValue = ref<string | null>(null)
  const options = ref<Api.Merchant.MerchantListItem[]>([])

  /** 搜索商户 */
  const handleSearch = async (query: string) => {
    if (!query) {
      options.value = []
      return
    }

    loading.value = true
    try {
      const res = await fetchMerchantList({
        keyword: query,
        Page: 1,
        PageSize: 20
      })
      options.value = res.items || []
    } catch (error) {
      console.error('Fetch Merchant List 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,
    async (newVal) => {
      const stringVal = newVal ? String(newVal) : null
      if (stringVal === internalValue.value) return

      internalValue.value = stringVal

      // 如果有值但不在当前选项列表中，需要反查详情以显示 Label
      if (stringVal && !options.value.some((item) => item.id === stringVal)) {
        try {
          const detail = await fetchMerchantDetail(stringVal, { showErrorMessage: false })
          if (detail) {
            // @ts-expect-error MerchantDetail to ListItem mapping
            options.value = [detail]
          }
        } catch (error) {
          console.warn('Fetch Merchant Detail for Select failed', error)
        }
      }
    },
    { immediate: true }
  )

  /** 初始化加载部分数据（可选） */
  onMounted(async () => {
    if (!props.modelValue) {
      loading.value = true
      try {
        const res = await fetchMerchantList({ Page: 1, PageSize: 10 })
        options.value = res.items || []
      } finally {
        loading.value = false
      }
    }
  })
</script>
