<template>
  <a-select
    v-if="multiple"
    :value="multiValue"
    mode="multiple"
    :options="normalizedOptions"
    :max-tag-count="2"
    :allow-clear="true"
    :placeholder="placeholder"
    style="width: 100%"
    @change="onChange"
  />
  <a-select
    v-else
    :value="singleValue"
    :options="normalizedOptions"
    :allow-clear="true"
    :placeholder="placeholder"
    style="width: 100%"
    @change="onChange"
  />
</template>

<script lang="ts">
export interface ISelectOption {
  label: string
  value: string
  color?: string
}
</script>

<script setup lang="ts">
import { computed } from 'vue'
import { Select as ASelect } from 'ant-design-vue'

const props = withDefaults(
  defineProps<{
    modelValue: string | string[] | null | undefined
    options: ISelectOption[] | string[] | Record<string, unknown>[] | undefined
    multiple?: boolean
    placeholder?: string
  }>(),
  {
    multiple: false,
    placeholder: '请选择',
  },
)

const emit = defineEmits<{
  (e: 'update:modelValue', value: string | string[] | null): void
  (e: 'change', value: string | string[] | null): void
}>()

// Normalize options to {label, value} format — handles string[], {label,value}[], and mixed
const normalizedOptions = computed<ISelectOption[]>(() => {
  if (!props.options) return []
  return (props.options as unknown[]).map((opt) => {
    if (typeof opt === 'string') return { label: opt, value: opt }
    const o = opt as Record<string, unknown>
    return {
      label: (o.label as string) ?? (o.value as string) ?? String(opt),
      value: (o.value as string) ?? (o.label as string) ?? String(opt),
      color: o.color as string | undefined,
    }
  })
})

// Coerce modelValue to the type a-select expects (string[] for multiple)
const multiValue = computed<string[]>(() => {
  if (Array.isArray(props.modelValue)) return props.modelValue
  return []
})

// Coerce modelValue to string | undefined for single select
const singleValue = computed<string | undefined>(() => {
  if (typeof props.modelValue === 'string') return props.modelValue
  return undefined
})

// a-select @change passes SelectValue (string | string[] | number | ... | undefined)
// We normalize to string | string[] | null for our consumers
function onChange(value: unknown): void {
  if (value == null) {
    emit('update:modelValue', null)
    emit('change', null)
    return
  }
  if (Array.isArray(value)) {
    const next = value.map((v) => String(v))
    emit('update:modelValue', next)
    emit('change', next)
    return
  }
  const next = String(value)
  emit('update:modelValue', next)
  emit('change', next)
}
</script>
