<template>
    <ElTree
        ref="ElTreeRef" :current-node-key="treeKey" :data="treeDatas" :default-expanded-keys="[treeKey]" :indent="0"
        :props="ElTreeProps" accordion
        class="hc-tree-node tree-line" highlight-current node-key="id"
        @node-click="ElTreeClick" @node-contextmenu="ElTreeLabelContextMenu"
    >
        <template #default="{ node, data }">
            <div :id="`${idPrefix}${data.id}`" class="data-custom-tree-node">
                <!-- 树组件，节点名称 -->
                <div class="label">{{ node.label }}</div>
                <!-- 树组件，操作菜单 -->
                <div v-if="menusData.length > 0" :class="node.showTreeMenu ? 'show' : ''" class="menu-icon" @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 v-if="menusData.length > 0" ref="contextMenuRef" :datas="menusData" @item-click="handleMenuSelect">
        <template #sort="{ item }">
            <HcIcon :line="false" :name="item.icon" class="menu-item-icon" />
            <span class="menu-item-name">{{ item.label }}</span>
        </template>
    </HcContextMenu>

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

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { HcIsButton } from '~src/plugins/IsButtons'
import { getTreeAll, removeTree, submitTree } from '~api/tentative/detect'
import { formValidate, getArrValue } from 'js-fast-way'
import { delMessageV2 } from '~com/message/index.js'
//参数
const props = defineProps({
    autoExpandKeys: {
        type: [String, Number],
        default: '',
    },
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    type: {
        type: String,
        default: 'leftTree',
    },
})

//事件
const emit = defineEmits(['menuTap', 'nodeTap'])
//变量
const ElTreeRef = ref(null)
const idPrefix = ref('detect-tree-data-')
const treeKey = 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
    treeKey.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])
        if (treeKey.value) {
            await nextTick(() => {
                document.getElementById(`${idPrefix.value}${treeKey.value}`)?.click()
            })
        }
    } else {
        treeDatas.value = []
    }
}

//节点被点击
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') {
        emit('menuTap', { data })
        nodeFormModel.value = {
            parentId: data.id,
            nodeType: data.nodeType,
            nodeName: '',
        }
        if (data?.isData !== 1) {
            nodeFormModal.value = true
        }

    } else if (key === 'edit') {
        nodeFormModel.value = data
        nodeFormModal.value = true
    } else if (key === 'del') {
        delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                await treeRemoveData(data.id)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
        })
    }
}

//新增/编辑 节点
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>
