<script setup>
import {onMounted, reactive} from "vue";

const emits = defineEmits(['change']);
const modelValue = defineModel();
const {api, fieldName, apiPo, init, defaultValue} = defineProps({
    api: {
        type: Function,
        default: async () => {
        },
        required: true,
    },
    apiPo: {
        type: Object,
        default: {}
    },
    fieldName: {
        type: Object,
        default: {value: 'id', label: 'name'},
    },
    init: {
        type: Boolean,
        default: false,
    },
    defaultValue: {
        type: Number,
        default: null,
    },
});
const list = reactive([]);

const popupChange = async (visible) => {
    if (visible) {
        api && api(apiPo).then(({data}) => {
            list.length = 0;
            list.push(...data);
        });
    }
}

onMounted(() => {
    if (init) api && api(apiPo).then(({data}) => {
        list.length = 0;
        list.push(...data);
    });
});

const handleSelect = (id) => {
    modelValue.value = id;
    emits('change');
}
</script>

<template>
    <a-dropdown @select="handleSelect">
        <a-tag v-bind="$attrs" :color="list.find(v => v.id === modelValue)?.color">
            <div class="flex gap-[6px] items-center justify-center cursor-pointer">
                <div v-if="modelValue===null">请选择</div>
                <div v-else>{{ list.find(v => v.id === modelValue)?.name }}</div>
                <icon-down/>
            </div>
        </a-tag>
        <template v-slot:content>
            <a-doption v-for="v in list" :key="v.id" :value="v.id">
                {{ v.name }}
            </a-doption>
        </template>
    </a-dropdown>
</template>

<style scoped lang="scss">

</style>
