<template>
    <el-radio-group v-model="radioKeys" @change="treeRadioChange">
        <ElTree class="hc-tree-node tree-line" :class="ui" ref="ElTreeRef" :props="ElTreeProps" :load="ElTreeLoadNode" lazy highlight-current accordion node-key="primaryKeyId"
                show-checkbox :default-expanded-keys="defaultExpandedCids" @node-click="ElTreeClick" @node-contextmenu="ElTreeLabelContextMenu" :indent="0">
            <template #default="{ node, data }">
                <div class="data-custom-tree-node" :id="`${idPrefix}${data['primaryKeyId']}`">
                    <!--树组件，节点名称-->
                    <div class="label level-name" v-if="node.level === 1">{{ node.label }}</div>
                    <div class="label" v-else>
                        <el-radio class="size-xl" :label="data['primaryKeyId']" @click.stop v-if="isRadio">{{ node.label }}</el-radio>
                        <span v-else>{{ node.label }}</span>
                    </div>
                    <!--树组件，操作菜单-->
                    <div class="menu-icon" :class="node.showTreeMenu?'show':''" v-if="node.level !== 1 && menusData.length > 0">
                        <div class="cu-tree-node-popover-menu-icon" @click.prevent.stop="ElTreeLabelContextMenu($event,data,node)">
                            <HcIcon name="apps" ui="text-2xl"/>
                        </div>
                    </div>
                    <!--树组件，操作菜单 END-->
                </div>
            </template>
        </ElTree>
    </el-radio-group>
    <!--右键菜单-->
    <HcContextMenu ref="contextMenuRef" :datas="menusData" @item-click="handleMenuSelect" v-if="menusData.length > 0" @closed="handleMenuClosed">
        <template #sort="{item}">
            <HcIcon :name="item.icon" :line="false" class="menu-item-icon"/>
            <span class="menu-item-name">{{item.label}}</span>
        </template>
    </HcContextMenu>
</template>

<script setup>
import {ref,nextTick,watch} from "vue";
import dataFillQuery from '~api/data-fill/query';
import {isArrItem, getArrValue, getObjValue, isNullES} from "js-fast-way"
//参数
const props = defineProps({
    ui: {
        type: String,
        default: ''
    },
    menus: {
        type: Array,
        default: () => ([])
    },
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    autoExpandKeys: {
        type: Array,
        default: () => ([])
    },
    idPrefix: {
        type: String,
        default: 'hc-tree-'
    },
    isAutoKeys: {
        type: Boolean,
        default: true
    },
    isAutoClick: {
        type: Boolean,
        default: true
    },
    isRadio: {
        type: Boolean,
        default: false
    },
    radioKey: {
        type: String,
        default: ''
    },
})

//变量
const ElTreeRef = ref(null)
const treeRefNode = ref(null)
const treeRefData = ref(null)
const ElTreeProps = ref({
    label: 'title',
    children: 'children',
    isLeaf: 'notExsitChild'
})
const menusData = ref(props.menus)
const isAutoKeys = ref(props.isAutoKeys)
const TreeExpandKey = ref(props.autoExpandKeys)
const projectId = ref(props.projectId);
const contractId = ref(props.contractId);
const idPrefix = ref(props.idPrefix);
const radioKeys = ref(Number(props.radioKey));

//监听
watch(() => [
    props.menus,
    props.isAutoKeys,
    props.autoExpandKeys,
    props.projectId,
    props.contractId,
    props.idPrefix,
    props.radioKey,
], ([menus, AutoKeys, expandKeys, UserProjectId, UserContractId, UserIdPrefix, radioKey]) => {
    menusData.value = menus
    isAutoKeys.value = AutoKeys
    TreeExpandKey.value = expandKeys
    projectId.value = UserProjectId
    contractId.value = UserContractId
    idPrefix.value = UserIdPrefix
    radioKeys.value = Number(radioKey)
})

//事件
const emit = defineEmits(['menuTap','nodeTap', 'nodeLoading', 'radioChange'])

//单选框事件
const treeRadioChange = (val) => {
    emit('radioChange', val)
}

//树形结构异步加载数据
const defaultExpandedCids = ref([])
const ElTreeLoadNode = async (node, resolve) => {
    if (contractId.value) {
        let contractIdRelation = '', parentId = '', primaryKeyId = '';
        if (node.level !== 0) {
            const nodeData = getObjValue(node?.data);
            contractIdRelation = nodeData?.contractIdRelation || ''
            parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
            primaryKeyId = nodeData?.id || ''
        }
        //获取数据
        const {error, code, data} = await dataFillQuery.queryWbsTreeData({
            contractId: contractId.value || '',
            contractIdRelation,
            primaryKeyId,
            parentId
        })
        //处理数据
        if (!error && code === 200) {
            let clickKey = '', defaultExpandedArr = [];
            const keys = TreeExpandKey.value || []
            const resData = getArrValue(data)
            if (keys.length > 0) {
                let lastKey = keys[keys.length-1];
                for (const item of resData) {
                    //自动展开
                    if (isArrItem(keys,item?.primaryKeyId)) {
                        defaultExpandedArr.push(item?.primaryKeyId)
                    }
                    //最后一个，选中点击
                    if (item?.primaryKeyId === lastKey) {
                        clickKey = item?.primaryKeyId
                    }
                }
            } else if (node.level === 0) {
                defaultExpandedArr.push(resData[0]?.primaryKeyId)
            }
            //自动展开
            defaultExpandedCids.value = defaultExpandedArr
            if (node.level === 0) {
                emit('nodeLoading')
            }
            resolve(resData)
            //最后一个，执行点击
            if (props.isAutoClick && clickKey) {
                await nextTick(() => {
                    document.getElementById(`${idPrefix.value}${clickKey}`)?.click()
                })
            }
        } else {
            if (node.level === 0) {
                emit('nodeLoading')
            }
            resolve([])
        }
    } else {
        resolve([])
    }
}

//节点被点击
const ElTreeClick = async (data,node) => {
    if (isAutoKeys.value) {
        let autoKeysArr = []
        await getNodeExpandKeys(node, autoKeysArr)
        const autoKeys = autoKeysArr.reverse()
        emit('nodeTap', {node, data, keys: autoKeys})
    } else {
        emit('nodeTap', {node, data, keys: []})
    }
}

//处理自动展开的节点KEY
const getNodeExpandKeys = async (node, newKeys) => {
    const parent = node?.parent ?? []
    const primaryKeyId = node?.data?.primaryKeyId ?? ''
    if (primaryKeyId) {
        newKeys.push(primaryKeyId)
        await getNodeExpandKeys(parent, newKeys)
    }
}

//鼠标右键事件
const contextMenuRef = ref(null)
const ElTreeLabelContextMenu = (e,data,node) => {
    const rows = menusData.value || [];
    if (node.level !== 1 && rows.length > 0) {
        e.preventDefault();
        treeRefNode.value = node;
        treeRefData.value = data;
        node.showTreeMenu = true
        //展开菜单
        contextMenuRef.value?.showMenu(e)
    }
}

//鼠标右键菜单被点击
const handleMenuSelect = ({key}) => {
    const node = treeRefNode.value;
    const data = treeRefData.value;
    emit('menuTap', {key, node, data})
}

const handleMenuClosed = () => {
    const node = treeRefNode.value;
    if (!isNullES(node)) {
        treeRefNode.value['showTreeMenu'] = false
    }
}

//设置树菜单的标记数据
const removeElTreeNode = (key) => {
    //根据 data 或者 key 拿到 Tree 组件中的 node
    let node = ElTreeRef.value.getNode(key)
    //删除 Tree 中的一个节点，使用此方法必须设置 node-key 属性
    ElTreeRef.value.remove(node)
}

// 暴露出去
defineExpose({
    removeElTreeNode
})
</script>

<style lang="scss" scoped>
@import "../../../../styles/app/tree.scss";
.data-custom-tree-node {
    .menu-icon {
        position: absolute;
        pointer-events: none;
        transition: opacity 0.2s;
        opacity: 0;
        right: 0;
        background: rgba(255, 255, 255, 0.25);
        border-radius: 2px;
        .cu-tree-node-popover-menu-icon {
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
    &:hover {
        .menu-icon {
            opacity: 1;
            pointer-events: all;
            cursor: context-menu;
        }
    }
    .menu-icon.show {
        opacity: 1;
        pointer-events: all;
        cursor: context-menu;
    }
}
</style>
