<template>
    <app-remote-select v-model="selectedValue" :options="dataList"
        :option-props="{ label: getLocalizedKey(), value: 'goodsId' }" :remote-method="remoteMethod" @change="onChange"
        @reset="onReset">
        <template #default="{ option }">
            <div style="display: flex;justify-content: space-between;">
                <span>{{ option.goodsCode }}</span>
                <span>{{ option[getLocalizedKey()] || option.goodsId }}</span>
            </div>
        </template>
    </app-remote-select>
</template>

<script lang="ts" setup>
import { computed, toRaw, PropType, nextTick } from 'vue'
import { Language } from '@/constants/language'
import { useRequest } from '@/hooks/request'
import { queryGoodsSelect } from '@/services/api/common'
import { i18n } from '@/stores'
import AppRemoteSelect from '@pc/components/base/remote-select/index.vue'

const props = defineProps({
    modelValue: [Number, String],
    params: {
        type: Object as PropType<Model.GoodsSelectReq>
    },
})

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

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

// 获取本地化属性键
const getLocalizedKey: () => keyof Model.GoodsSelectRsp = () => {
    switch (i18n.global.locale) {
        case Language.Simplified:
            return 'goodsName'
        case Language.Thai:
            return 'goodsnameth'
        case Language.Traditional:
            return 'goodsnametw'
        case Language.Vietnamese:
            return 'goodsnamevi'
        default:
            return 'goodsnameen'
    }
}

const { dataList, loading, run } = useRequest(queryGoodsSelect, {
    manual: true,
    params: props.params,
    onSuccess: (res) => {
        if (!res.data.some((e) => e.goodsId.toString() === selectedValue.value?.toString())) {
            selectedValue.value = undefined
            onChange()
        }
    }
})

const onReset = () => {
    nextTick(() => {
        if (!loading.value) {
            run(props.params)
        }
    })
}

const remoteMethod = (query: string) => {
    nextTick(() => {
        if (!loading.value) {
            if (query) {
                run({
                    ...props.params,
                    searchCode: query
                })
            } else if (!dataList.value.length) {
                onReset()
            }
        }
    })
}

const onChange = (value?: number) => {
    const item = dataList.value.find((e) => e.goodsId === value)
    emit('change', item && toRaw(item))
}

defineExpose({
    onReset
})
</script>