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

const emits = defineEmits(['change']);
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);
    });
});
</script>

<template>
    <a-select
        v-bind="$attrs"
        :options="list"
        :field-names="fieldName"
        :default-value="defaultValue"
        @change="emits('change')"
        @popup-visible-change="popupChange"
        placeholder="请选择">
    </a-select>
</template>

<style scoped>

</style>
