import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ucardApi } from '@/api/ucard'

export default function useIdTypeOptions() {
    const { t } = useI18n()
    const idTypesConfigList = ref('')
    const allIdTypeOptions = computed(() => [
        { text: t('card.Form.v3'), value: 'HK_HKID' },
        { text: t('card.Form.v4'), value: 'PASSPORT' },
        { text: t('card.Form.v5'), value: 'DLN' },
        { text: t('card.Form.v6'), value: 'GOVERNMENT_ISSUED_ID_CARD' }
    ])
    /** 根据接口配置过滤后的可用证件类型 */
    const availableIdTypeOptions = computed(() => {
        const allowList = (idTypesConfigList.value || '')
            .split(',')
            .map(i => i.trim())
            .filter(Boolean)
        if (!allowList.length) return []
        return allIdTypeOptions.value.filter(opt =>
            allowList.includes(opt.value)
        )
    })

    /** 拉取接口配置 */
    async function loadIdTypesConfig(code: string) {
        try {
            const res = await ucardApi.idTypesConfigList({
                code,
                page: { current: 1, row: 10 }
            })

            if (res?.code === 200) {
                idTypesConfigList.value = res?.data?.[0]?.idType || ''
            }
        } catch (err) {
            console.error('[useIdTypeOptions] load failed:', err)
            idTypesConfigList.value = ''
        }
    }
    return {
        /** options */
        availableIdTypeOptions,
        allIdTypeOptions,
        /** methods */
        loadIdTypesConfig
    }
}
