<template>
    <div class="selectbox">
        <div
            v-for="v in props.options"
            :class="{ item: true, active: isActive(v) }"
            :key="v[props.valueKey]"
            @click="onClickItem(v)"
        >
            {{ v[props.labelKey] }}
        </div>
    </div>
</template>

<script setup>
const props = defineProps({
    // 默认值
    modelValue: {
        type: [String, Number, Array],
        default: () => ""
    },
    //值的键
    valueKey: {
        type: String,
        default: () => "value"
    },
    //label的键
    labelKey: {
        type: String,
        default: () => "label"
    },
    // 是否多选
    multiple: {
        type: Boolean,
        default: () => false
    },
    // 默认值
    options: {
        type: Array,
        default: () => []
    }
});
const emit = defineEmits(["update:modelValue", "update"]);
// 激活类名
const isActive = e => {
    if (props.multiple) {
        return props.modelValue.includes(e[props.valueKey]);
    } else {
        return props.modelValue === e[props.valueKey];
    }
};
// 点击选项
const onClickItem = e => {
    const value = e[props.valueKey];
    if (props.multiple) {
        const index = props.modelValue.indexOf(value);
        if (index > -1) {
            emit("update:modelValue", props.modelValue.slice(index, 1));
        } else {
            emit("update:modelValue", [...props.modelValue, value]);
        }
    } else {
        emit("update:modelValue", value);
    }

    emit("update",value);
};
</script>

<style lang="scss" scoped>
.selectbox {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
    .item {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 32px;
        font-size: 12px;
        color: #1f86ff;
        background: #1f86ff0f;
        border-radius: 4px;
    }
    .active {
        color: #ffffff;
        background: #1f86ff;
    }
}
</style>
