<script setup lang="ts">
import { computed } from 'vue'
import { getLookup } from '../../services/api'

const value = defineModel<unknown>()

const props = withDefaults(defineProps<{
  lookupId?: string
  placeholder?: string
}>(), {
  lookupId: 'Party',
  placeholder: '搜索编号或名称'
})

const fallbackSuggestions = computed(() => [
  { value: '', label: `${props.lookupId} 暂无匹配记录` }
])

function candidateValue(row: Record<string, unknown>) {
  const idKey = Object.keys(row).find((key) => key.toLowerCase().endsWith('id'))
  return String(row[idKey || 'partyId'] || row.description || row.name || '')
}

async function suggest(query: string, cb: (items: Array<{ value: string; label?: string }>) => void) {
  try {
    const data = await getLookup(props.lookupId, { query, pageSize: 8 })
    const rows = Array.isArray(data.rows) ? data.rows as Array<Record<string, unknown>> : []
    const options = rows
      .map((row) => {
        const optionValue = candidateValue(row)
        return optionValue ? { value: optionValue, label: String(row.description || row.name || optionValue) } : null
      })
      .filter(Boolean) as Array<{ value: string; label?: string }>
    cb(options.length ? options : fallbackSuggestions.value)
  } catch {
    cb(fallbackSuggestions.value)
  }
}
</script>

<template>
  <el-autocomplete
    v-model="value"
    class="erp-entity-lookup"
    :placeholder="placeholder"
    :fetch-suggestions="suggest"
    clearable
  >
    <template #default="{ item }">
      <div class="erp-lookup-option">
        <strong>{{ item.value }}</strong>
        <span v-if="item.label && item.label !== item.value">{{ item.label }}</span>
      </div>
    </template>
    <template #append>
      <el-button>选择</el-button>
    </template>
  </el-autocomplete>
</template>
