<template>
    <el-radio-group v-model="selectedValue" :disabled="disabled" v-if="type === 'radio'">
        <template v-for="item in getEnumOptions()" :key="item.autoid">
            <el-radio :label="item.label" :value="item.value" />
        </template>
    </el-radio-group>
    <el-select v-model="selectedValue" :empty-values="[null, undefined, ...emptyValues]" :placeholder="placeholder"
        v-else>
        <template v-for="item in getEnumOptions()" :key="item.autoid">
            <el-option :label="item.label" :value="item.value" />
        </template>
    </el-select>
</template>

<script lang="ts" setup>
import { computed, PropType } from 'vue'
import { useEnum } from '@/hooks/enum'
import { i18n } from '@/stores'

const props = defineProps({
    modelValue: Number,
    type: {
        type: String as PropType<'radio' | 'select'>,
    },
    code: {
        type: String,
        required: true
    },
    emptyValues: {
        type: Array,
        default: () => ([])
    },
    placeholder: {
        type: String,
        default: i18n.global.t('common.pleasechoice')
    },
    disabled: {
        type: Boolean
    }
})

const emit = defineEmits(['update:modelValue'])

const { getEnumOptions, registerEnumReadyCallback } = useEnum(props.code)

const selectedValue = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

registerEnumReadyCallback(() => {
    const options = getEnumOptions()
    if (!options.some((e) => e.value === props.modelValue)) {
        selectedValue.value = undefined
    }
})
</script>