<template>
    <div class="hc-datav-select-main">
        <div class="hc-datav-select-name">{{ name || placeholder }}</div>
        <el-select
            v-model="selectKey" popper-class="hc-datav-select-popper"
            :placeholder="placeholder" size="small" :clearable="clearable" :disabled="disabled"
            placement="bottom-end"
            @change="selectChange"
        >
            <el-option v-for="item in data" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { isNullES } from 'js-fast-way'

const props = defineProps({
    datas: {
        type: Array,
        default: () => [],
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    clearable: {
        type: Boolean,
        default: true,
    },
    placeholder: {
        type: String,
        default: '请选择',
    },
})

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

//双向绑定
const selectKey = defineModel('modelValue', {
    default: '',
})

onMounted(() => {
    name.value = getDataNmae(selectKey.value)
})

//监听数据变化
const data = ref(props.datas)
watch(() => props.datas, (val) => {
    data.value = val
})

//监听值变化
const name = ref('')
watch(() => selectKey, (val) => {
    name.value = getDataNmae(val.value)
})

//获取数据名称
const getDataNmae = (id) => {
    if (isNullES(id)) return props.placeholder
    const item = data.value.find((item) => item.id === id)
    return item ? item.name : props.placeholder
}

//下来框被改变
const selectChange = (id) => {
    name.value = getDataNmae(id)
    emit('change', id)
}
</script>

<style lang="scss">
.hc-datav-select-main {
    position: relative;
    display: inline-block;
    .hc-datav-select-name {
        position: relative;
        padding-left: 16px;
        z-index: -10;
    }
    .el-select {
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        .el-select__wrapper {
            font-size: 14px;
            gap: unset;
            line-height: unset;
            min-height: unset;
            padding: 0;
            height: 100%;
            background: unset;
            box-shadow: unset;
            border-radius: 0;
        }
        .el-select__placeholder {
            color: white;
        }
        .el-select__placeholder.is-transparent {
            color: #d6d6d6;
        }
        .el-select__caret {
            color: #ffffff;
        }
    }
}
.el-popper.hc-datav-select-popper {
    background: #565656;
    border: 1px solid #000000;
    .el-popper__arrow:before {
        background: #565656;
        border-color: #000000;
    }
    .el-select-dropdown__item {
        height: 28px;
        line-height: 28px;
        color: #34e3ff;
        padding: 0 28px 0 14px;
    }
    .el-select-dropdown__item.is-hovering {
        background-color: #395cc6;
    }
}
.hc-datav-select-main + .hc-datav-select-main {
    margin-left: 40px;
}
</style>
