<script setup lang="ts">
import DOWNICON from "../static/icons/down.png";
import {onMounted, reactive} from "vue";

const emits = defineEmits(['change']);
const {placeholder, api} = defineProps({
    placeholder: {
        type: String,
        default: "请选择"
    },
    api: {
        type: Function,
        default: () => {
        }
    }
});

const list = reactive([]);
const modelValue = defineModel();

const change = ({detail: {value}}) => {
    modelValue.value = list.filter(v => !v.hidden)[value].id;
    emits('change', list.filter(v => !v.hidden)[value].id);
}

onMounted(() => {
    api && api().then(({data}) => {
        list.length = 0;
        list.push(...data);
    });
});
</script>

<template>
    <picker :range="list.filter(v => !v.hidden).map(v => v.name)" @change="change">
        <view class="x-select" v-if="!$slots.default">
            <view v-if="modelValue === null" class="text-[#86909C] test-28r">
                {{ placeholder }}
            </view>
            <view v-else>
                {{ list.find(v => v.id === modelValue)?.name }}
            </view>

            <image :src="DOWNICON" class="!size-[24rpx]" mode="aspectFill"></image>
        </view>
        <slot v-else></slot>
    </picker>
</template>

<style scoped lang="scss">
.x-select {
    @apply px-[24rpx] py-[16rpx] bg-[#F2F3F5] rounded-[4rpx] h-[80rpx] flex items-center justify-between;
}
</style>
