<template>
    <ElTree class="hc-tree-node tree-line" ref="ElTreeRef" :props="ElTreeProps" :data="treeDatas" highlight-current accordion node-key="primaryKeyId"
            :default-expanded-keys="TreeExpandKey" @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">{{ node.label }}</div>
                <!--树组件，操作菜单-->
                <div class="menu-icon" :class="node.showTreeMenu?'show':''" v-if="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 #sort="{item}">
            <HcIcon :name="item.icon" :line="false" class="menu-item-icon"/>
            <span class="menu-item-name">{{item.label}}</span>
        </template>
    </HcContextMenu>

    <!--新增/编辑 节点-->
    <HcDialog :show="nodeFormModal" :title="`${nodeFormModel.id?'编辑':'新增'}节点`" widths="30rem" :loading="nodeFormLoading" @save="nodeFormModalSave" @close="nodeFormModalClose">
        <el-form ref="nodeFormRef"  :model="nodeFormModel" :rules="nodeFormRules" label-width="auto" label-position="top" size="large">
            <el-form-item class="mb-0" label="节点名称">
                <el-input v-model="nodeFormModel.nodeName" placeholder="请输入节点名称"/>
            </el-form-item>
        </el-form>
    </HcDialog>

</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import {HcIsButton} from "~src/plugins/IsButtons";
import {formValidate, getArrValue} from "vue-utils-plus"
import {getTreeAll, submitTree, removeTree} from "~api/tentative/detect"
import {delMessage} from "~uti/tools";

//参数
const props = defineProps({
    autoExpandKeys: {
        type: Array,
        default: () => ([])
    },
    projectId: {
        type: [String,Number],
        default: ''
    },
    contractId: {
        type: [String,Number],
        default: ''
    },
    type: {
        type: String,
        default: 'leftTree'
    },
})

//变量
const ElTreeRef = ref(null)
const idPrefix = ref('detect-tree-data-')
const TreeExpandKey = ref(props.autoExpandKeys)
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const dataType = ref(props.type)
const ElTreeProps = ref({
    label: 'nodeName',
    children: 'children',
    isLeaf: 'hasChildren'
})

//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.type,
    props.autoExpandKeys
], ([pid, cid, type, expandKeys]) => {
    projectId.value = pid
    contractId.value = cid
    dataType.value = type
    TreeExpandKey.value = expandKeys
})

//渲染完成
onMounted(() => {
    setElTreeMenu()
    getTreeDatas()
})

//树菜单配置
const menusData = ref([])
const setElTreeMenu = () => {
    let newArr = [];
    if (HcIsButton('tentative_detect_third_tree_add')) {
        newArr.push({icon: 'add-circle', label: '新增节点', key: "add"})
    }
    if (HcIsButton('tentative_detect_third_tree_edit')) {
        newArr.push({icon: 'draft', label: '修改节点', key: "edit"})
    }
    if (HcIsButton('tentative_detect_third_tree_del')) {
        newArr.push({icon: 'delete-bin', label: '删除节点', key: "del"})
    }
    menusData.value = newArr
}

//获取树数据
const treeDatas = ref([])
const getTreeDatas = async () => {
    const { error, code, data } = await getTreeAll({
        projectId: projectId.value,
        contractId: contractId.value
    })
    if (!error && code === 200) {
        treeDatas.value = getArrValue(data[dataType.value])
    } else {
        treeDatas.value = []
    }
}

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

//节点被点击
const ElTreeClick = async (data,node) => {
    emit('nodeTap', {node, data, keys: [data.id]})
}

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

//鼠标右键菜单被点击
const handleMenuSelect = ({key}) => {
    const data = treeRefData.value;
    if (key === 'add') {
        nodeFormModel.value = {
            parentId: data.id,
            nodeType: data.nodeType,
            nodeName: ''
        }
        nodeFormModal.value = true
    } else if (key === 'edit') {
        nodeFormModel.value = data
        nodeFormModal.value = true
    } else if (key === 'del') {
        delMessage(() => {
            treeRemoveData(data.id)
        })
    }
}

//新增/编辑 节点
const nodeFormModal = ref(false)
const nodeFormRef = ref(null)
const nodeFormModel = ref({
    nodeName: ''
})
const nodeFormRules = {
    nodeName: {
        required: true,
        trigger: 'blur',
        message: "请输入节点名称"
    },
}

//保存节点信息
const nodeFormLoading = ref(false)
const nodeFormModalSave = async () => {
    const validate = await formValidate(nodeFormRef.value)
    if (validate) {
        //发起请求
        const { error, code } = await submitTree({
            ...nodeFormModel.value,
            projectId: projectId.value,
            contractId: contractId.value
        })
        //处理数据
        if (!error && code === 200) {
            window?.$message?.success('操作成功')
            nodeFormModal.value = false
            await getTreeDatas()
        }
    }
}

//关闭节点编辑弹窗
const nodeFormModalClose = () => {
    nodeFormModal.value = false
}

//删除节点
const treeRemoveData = async (id) => {
    const { error, code } = await removeTree({
        projectId: projectId.value,
        contractId: contractId.value,
        id: id
    })
    //处理数据
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        await getTreeDatas()
    }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/app/tree.scss";
.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;
    }
}
</style>
