<template>
    <ElTree class="hc-tree-node tree-line el-radio-group" :class="[ui,submitCounts?'tree-line1':'']" ref="ElTreeRef" :props="ElTreeProps" :data="datas" highlight-current accordion node-key="primaryKeyId"
            :default-expanded-keys="TreeExpandKey" @node-click="ElTreeClick" @node-contextmenu="ElTreeLabelContextMenu" :indent="0"  :filter-node-method="filterNode">
        <template #default="{ node, data }">
            <div class="data-custom-tree-node" :id="`${idPrefix}${data['primaryKeyId']}`">
                <!--树组件，节点名称-->
                <div class="label" :class="node.level === 1?'level-name':''"  style="display: flex;justify-content: space-between;">
                   <div>
                        <span :class="data?.colorStatus === 2?'text-blue':data?.colorStatus === 3?'text-orange':data?.colorStatus === 4?'text-green':''" v-if="isColor">{{ node.label }}</span>
                        <span v-else>{{ node.label }}</span>
                   </div>
                     <div class="text-blue submit-counts" v-if="submitCounts">【{{ data.submitCounts ?? 0 }}】</div>
                </div>
                <!-- <div class="text-blue submit-counts" v-if="isSubmitCounts">【{{ data.submitCounts ?? 0 }}】</div> -->
                <!--树组件，操作菜单-->
                <div class="menu-icon1" :class="node.showTreeMenu?'show':''" v-if="node.level !== 1 && menusData.length > 0" @click.stop>
                    <div class="cu-tree-node-popover-menu-icon" @click.prevent.stop="ElTreeLabelContextMenu($event,data,node)">
                        <HcIcon name="menu" ui="text-2xl"/>
                    </div>
                </div>
                <!--树组件，操作菜单 END-->
            </div>
        </template>
    </ElTree>
    <!--右键菜单-->
    <HcContextMenu ref="contextMenuRef" :datas="menusData" @item-click="handleMenuSelect" v-if="menusData.length > 0">
        <template #mark="{item}">
            <HcIcon :name="item.icon" :fill="treeRefData?.isFirst" class="menu-item-icon"/>
            <span class="menu-item-name">{{treeRefData?.isFirst ? '取消标记为首件' : '标记为首件'}}</span>
        </template>
        <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,watch,nextTick} from "vue";
import {getArrValue,getObjValue} from "vue-utils-plus"
//参数
const props = defineProps({
    menus: {
        type: Array,
        default: () => ([])
    },
    datas: {
        type: Array,
        default: () => ([])
    },
    autoExpandKeys: {
        type: Array,
        default: () => ([])
    },
    isMark: {
        type: Boolean,
        default: false
    },
    idPrefix: {
        type: String,
        default: 'tree-data-'
    },
    isAutoKeys: {
        type: Boolean,
        default: true
    },
    isAutoClick: {
        type: Boolean,
        default: true
    },
    isColor: {
        type: Boolean,
        default: false
    },
    submitCounts: {
        type: Boolean,
        default: false
    },
    searchTreeVal:{
      type: String,
        default: '11'  
    }
})

//变量
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 menuMark = ref(props.isMark)
const isAutoKeys = ref(props.isAutoKeys)
const TreeExpandKey = ref(props.autoExpandKeys)
const idPrefix = ref(props.idPrefix);
const isSubmitCounts = ref(props.submitCounts);
const searchInfo=ref(props.searchTreeVal)

//监听
watch(() => [
    props.menus,
    props.isMark,
    props.isAutoKeys,
    props.autoExpandKeys,
    props.idPrefix,
    props.submitCounts,
    props.searchTreeVal
], ([menus, isMark, AutoKeys, expandKeys, UserIdPrefix, submitCounts,searchTreeVal]) => {
    menusData.value = menus
    menuMark.value = isMark
    isAutoKeys.value = AutoKeys
    TreeExpandKey.value = expandKeys
    idPrefix.value = UserIdPrefix
    isSubmitCounts.value = submitCounts
    searchInfo.value=searchTreeVal
})
watch(searchInfo, (val) => {
    if(val){
        nextTick(()=> {
            ElTreeRef?.value.filter(val)
        })
        
    }else{
        emit('changeSearch')
    }
   
},

{immediate:true}

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

//节点被点击
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 = getArrValue(node?.parent)
//     const nodeData = getObjValue(node?.data);
//     console.log(nodeData,'nodeData');
//     const primaryKeyId = nodeData?.primaryKeyId ?? ''
//     if (primaryKeyId) {
//         newKeys.push(primaryKeyId)
//         await getNodeExpandKeys(parent, newKeys)
//     }
// }
//处理自动展开的节点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;
        //展开菜单
        contextMenuRef.value?.showMenu(e)
    }
}

//鼠标右键菜单被点击
const handleMenuSelect = async({key}) => {
    const node = treeRefNode.value;
    const data = treeRefData.value;
    //如果为标记菜单
    if (key === 'mark' && menuMark.value) {
        if (data.isFirst === true) {
            emit('menuTap', {key: 'cancel_mark', node, data})
        } else {
            emit('menuTap', {key: 'mark', node, data})
        }
    } else {
        // emit('menuTap', {key, node, data})
        if (isAutoKeys.value) {
            let autoKeysArr = []
            await getNodeExpandKeys(node, autoKeysArr)
            const autoKeys = autoKeysArr.reverse()
            emit('menuTap', {key, node, data,keys:autoKeys})
        }
    }
}
//设置树菜单的标记数据
const setElTreeMenuMark = (keys,isFirst) => {
    keys.forEach(item => {
        //根据 data 或者 key 拿到 Tree 组件中的 node
        let node = ElTreeRef.value.getNode(item)
        if (!!node) node.data.isFirst = isFirst;
    })
}

//设置树菜单的标记数据
const removeElTreeNode = (key) => {
    //根据 data 或者 key 拿到 Tree 组件中的 node
    let node = ElTreeRef.value.getNode(key)
    //删除 Tree 中的一个节点，使用此方法必须设置 node-key 属性
    ElTreeRef.value.remove(node)
}
 const getReturnNode=(node,_array,value)=>{
        let isPass = node.data &&  node.data.title && node.data.title.indexOf(value) !== -1;
        isPass?_array.push(isPass):'';
        if(!isPass && node.level!=1 && node.parent){
          getReturnNode(node.parent,_array,value);
        }
 }
const filterNode = (value, data,node) => {
    if(!value){
            return true;
        }
        let level = node.title;
        let _array = [];//这里使用数组存储 只是为了存储值。
        getReturnNode(node,_array,value);
        let result = false;
        _array.forEach((item)=>{
            result = result || item;
        });
        return result;
    }
// 暴露出去
defineExpose({
    setElTreeMenuMark,
    removeElTreeNode,
    filterNode
})
</script>

<style lang="scss" scoped>
@import "../../../styles/app/tree.scss";
.el-radio-group {
   width: auto;
   
}
// .data-custom-tree-node {
//     .menu-icon {
//         position: relative;
//         font-size: 20px;
//         opacity: 0;
//         pointer-events: none;
//         transition: opacity 0.2s;
//         .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;
//     }
// }
.data-custom-tree-node {
    .menu-icon1 {
        // position: absolute;
        vertical-align: bottom;
        display:inline-block;
            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-icon1 {
                opacity: 1;
                pointer-events: all;
                cursor: context-menu;
            }
        }
        .menu-icon1.show {
            opacity: 1;
            pointer-events: all;
            cursor: context-menu;
        }
}
</style>
