<template>
    <el-popover :width="widths" :visible="visible" >
        <template #reference>
            <div class="form-item-div" :id="uuid" @click="itemClick">
                <div class="lable truncate" v-if="nodeId && nodeTitle">{{nodeTitle}}</div>
                <div class="placeholder truncate" v-else>{{placeholder}}</div>
                <HcIcon name="arrow-down-s"/>
            </div>
        </template>
        <div v-click-outside="onClickOutside">
            <TestTree ui="hc-select-tree" :projectId="projectId" :contractId="contractId" :wbsId="wbsId" @nodeTap="testTreeClick"/>
        </div>
    </el-popover>
</template>

<script setup>
import {ref, watch, nextTick} from "vue";
import {getRandom} from "vue-utils-plus"
import TestTree from "./TestTree.vue"
import {ClickOutside as vClickOutside} from 'element-plus'

const props = defineProps({
    modelValue: {
        type: [String,Number],
        default: ''
    },
    title: {
        type: [String,Number],
        default: ''
    },
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    wbsId: {
        type: [String,Number],
        default: ''
    },
    placeholder: {
        type: [String,Number],
        default: '请选择一个树节点'
    },
})

//变量
const uuid = getRandom()
const widths = ref(266)
const nodeId = ref(props.modelValue)
const nodeTitle = ref(props.title)

const projectId = ref(props.projectId);
const contractId = ref(props.contractId);
const wbsId = ref(props.wbsId);

const visible = ref(false)

//加载完成
nextTick(() => {
    widths.value = document.getElementById(uuid).clientWidth - 20
})

//监听
watch(() => [
    props.modelValue,
    props.title,
    props.projectId,
    props.contractId,
    props.wbsId,
], ([val, title, pid, cid, wbs_id]) => {
    nodeId.value = val
    nodeTitle.value = title
    projectId.value = pid
    contractId.value = cid
    wbsId.value = wbs_id
})

//显示弹窗
const itemClick = () => {
    visible.value = true
}

const onClickOutside = () => {
    visible.value = false
}

//事件
const emit = defineEmits(['update:modelValue', 'change'])

//树被点击
const testTreeClick = (data) => {
    const {title, primaryKeyId} = data
    nodeTitle.value = title
    nodeId.value = primaryKeyId
    visible.value = false
    emit('update:modelValue', primaryKeyId)
    emit('change', data)
}
</script>

<style lang="scss" scoped>
.el-radio-group {
   width: auto !important;
}
.form-item-div {
    background-color: white;
    cursor: pointer;
    .lable, .placeholder {
        flex: 1;
    }
    .placeholder {
        color: #a9abb2;
    }
}
</style>
<style lang="scss">
.form-item-div .hc-icon-i {
    color: #a7abb2;
}
.hc-select-tree.el-tree.hc-tree-node {
    margin-left: -12px;
}
.el-popper:not([class*='aside-menu-popper']) {
    // height: 400px;
    overflow-y: auto;
}
</style>
