<template>
    <div class="hc-dropdown-box relative">
        <el-dropdown trigger="click">
            <div class="hc-dropdown-body">
                <span class="hc-dropdown-label">{{ labels || '请选择' }}</span>
                <hc-icon name="arrow-down-s" class="ml-1" />
            </div>
            <template #dropdown>
                <el-dropdown-menu>
                    <template v-for="(item, index) in menuData" :key="index">
                        <el-dropdown-item @click="itemClick(item, index)">{{ item[propsa.label] }}</el-dropdown-item>
                    </template>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'

const define_props = defineProps({
    datas: {
        type: Array,
        default: () => ([]),
    },
    props: {
        type: Object,
        default: () => ({
            key: 'key',
            label: 'label',
        }),
    },
})

//事件
const emit = defineEmits(['change'])

defineOptions({
    name: 'HcDropdown',
})

//双向绑定
const labels = ref('')
const curKey = defineModel('modelValue', {
    default: -1,
})

//监听数据
const menuData = ref(define_props.datas)
watch(() => define_props.datas, (data) => {
    menuData.value = data
}, { deep: true })

//监听数据
watch(() => define_props.props, (obj) => {
    setPropsa(obj)
}, { deep: true })

//监听
watch(curKey, (key) => {
    if (key) {
        console.log(key)
        getItemLabel()
    }
})

//渲染完成
onMounted(() => {
    setPropsa(define_props.props)
    getItemLabel()
})

//设置参数配置
const propsa = ref({})
const setPropsa = (obj) => {
    propsa.value = {
        key: obj.key || 'key',
        label: obj.label || 'label',
    }
}

//获取名称
const getItemLabel = () => {
    if (!curKey.value) return
    const { key, label } = propsa.value
    const data = menuData.value
    for (let i = 0; i < data.length; i++) {
        if (data[i][key] === curKey.value) {
            labels.value = data[i][label]
        }
    }
}

//被点击
const itemClick = (item, index) => {
    const { key, label } = propsa.value
    labels.value = item[label]
    curKey.value = item[key]
    emit('change', item, index)
}
</script>

<style scoped lang="scss">
.hc-dropdown-body {
    cursor: pointer;
}
</style>
