<template>
    <el-select
        :model-value="modelValue"
        :placeholder="placeholder"
        :clearable="clearable"
        :filterable="filterable"
        :allow-create="allowCreate"
        :default-first-option="allowCreate"
        :disabled="disabled"
        :loading="loading"
        :class="selectClass"
        :style="selectStyle"
        @update:model-value="emit('update:modelValue', $event)"
        @change="emit('change', $event)"
        @visible-change="onVisibleChange"
    >
        <el-option
            v-for="item in normalizedOptions"
            :key="item.name"
            :label="item.name"
            :value="item.name"
        />
        <!-- 旧记录可能存在不在当前字典内的值：保留显示，避免编辑时反查不到 -->
        <el-option
            v-if="modelValue && !hasCurrentValue"
            :key="`__legacy_${modelValue}`"
            :label="`${modelValue}（已停用）`"
            :value="modelValue"
        />
    </el-select>
</template>

<script lang="ts" setup>
interface OptionItem {
    name: string
    value?: string
}

const props = withDefaults(
    defineProps<{
        modelValue?: string
        options: Array<OptionItem | string>
        loading?: boolean
        placeholder?: string
        clearable?: boolean
        filterable?: boolean
        allowCreate?: boolean
        disabled?: boolean
        selectClass?: string
        selectStyle?: string | Record<string, string>
    }>(),
    {
        modelValue: '',
        loading: false,
        placeholder: '请选择自媒体来源',
        clearable: true,
        filterable: true,
        allowCreate: false,
        disabled: false,
    }
)

const emit = defineEmits<{
    'update:modelValue': [value: string]
    change: [value: string]
    'visible-change': [visible: boolean]
}>()

const normalizedOptions = computed<OptionItem[]>(() => {
    return (props.options || []).map((item) =>
        typeof item === 'string' ? { name: item } : { name: item.name, value: item.value }
    )
})

const hasCurrentValue = computed(() => {
    return normalizedOptions.value.some((item) => item.name === props.modelValue)
})

const onVisibleChange = (visible: boolean) => {
    emit('visible-change', visible)
}
</script>
