<template>
    <div class="h-full">
        <HcCard :scrollbar="false" v-if="wbsTypeTabKey === 'map'">
            <template #extra>
                <HcNewSwitch :datas="wbsTypeTab" :keys="wbsTypeTabKey" @change="wbsTypeTabChange"/>
            </template>
            <NodeTree ref="NodeTreeRef" :data="NodeTreeData" :format="NodeTreeFormat" :autoExpandKeys="TreeAutoExpandKeys" :menus="ElTreeMenu" :isMark="TreeMark" isColor
                      :accordion='NodeTreeAccordion' @nodeClick="NodeTreeClick" @expand="expandClick" @nodeDblClick="NodeTreeDblClick" @menuClick="NodeTreeMenuClick"/>
            <template #action>
                <div class="hc-tree-mp-tip-box">
                    <div class="dot-view green">已审批</div>
                    <div class="dot-view black">未填报</div>
                    <div class="dot-view orange">已填报-待审批</div>
                    <div class="dot-view blue">已填报-未上报</div>
                </div>
            </template>
        </HcCard>
        <div class="hc-layout-box" v-if="wbsTypeTabKey === 'tree'">
            <div class="hc-layout-left-box" id="wbs-left-tree" :style="'width:' + leftWidth + 'px;'">
                <div class="hc-project-box">
                    <div class="hc-project-icon-box">
                        <HcIcon name="layers"/>
                    </div>
                    <div class="ml-2 project-name-box">
                        <span class="text-xl text-cut project-alias">{{projectInfo['projectAlias']}}</span>
                        <div class="text-xs text-cut project-name">{{projectInfo['name']}}</div>
                    </div>
                </div>
                <div class="hc-tree-box">
                    <div class="hc-search-tree-val">
                        <el-input v-model="searchTreeVal" block size="large" placeholder="请输入名称关键词检索" clearable>
                            <template #suffix>
                                <HcIcon name="search" ui="text-2xl"/>
                            </template>
                        </el-input>
                    </div>
                    <div class="hc-tree-scrollbar">
                        <el-scrollbar>
                            <WbsTree ref="HcTreeRef" :params="treeParams" :menus="ElTreeMenu" :isMark="TreeMark" :autoExpandKeys="TreeAutoExpandKeys" @nodeTap="wbsElTreeClick" @menuTap="ElTreeMenuClick"/>
                        </el-scrollbar>
                    </div>
                </div>
                <div class="hc-tree-foot-tip-box">
                    <div class="dot-view green">已审批</div>
                    <div class="dot-view black">未填报</div>
                    <div class="dot-view orange">已填报-待审批</div>
                    <div class="dot-view blue">已填报-未上报</div>
                </div>
                <!--左右拖动-->
                <div class="horizontal-drag-line" @mousedown="onmousedown"/>
            </div>
            <div class="hc-layout-content-box">
                <HcCard :scrollbar="false">
                    <template #extra>
                        <HcNewSwitch :datas="wbsTypeTab" :keys="wbsTypeTabKey" @change="wbsTypeTabChange"/>
                    </template>
                    456789
                    <template #action>
                        123456
                    </template>
                </HcCard>
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref,watch,nextTick,onMounted} from "vue";
import {useRoute} from 'vue-router'
import router from '~src/router/index';
import website from '~src/config/index'
import {useAppStore} from "~src/store/index";
import {hIconJs} from "~src/plugins/renderele";
import HcTabs from "~com/plugins/naive/HcTabs.vue"
import HcTree from "~com/plugins/element/HcTree.vue"
import BtnTab from "~com/btnTab/index.vue"
import ListItem from "~com/data-fill/ListItem.vue"
import NodeTree from "./components/nodeTree/index.vue"
import DragModal from "~com/dragModal/index.vue"
import ImgPreview from "~com/imgPreview/index.vue"
import HcReportModal from "~com/reportModal/index.vue"
import HcTreeNode from "./components/HcTreeNode.vue"
import WbsTree from "./components/WbsTree.vue"
import wbsApi from "~api/data-fill/wbs"
import {deepClone} from "~src/utils/lib/util";
import {getTokenHeader} from '~src/api/request/header';
import {isArray,isObjNull} from "~src/utils/lib/isApp";
//import {setStore,getStore} from "~src/utils/lib/storage";
import {utilsStore} from "vue-utils-plus"
import Draggable from "vuedraggable";

//初始变量
const useRoutes = useRoute()
const useAppState = useAppStore()
const {getStoreData, setStoreData} = utilsStore(website.key)

//全局变量
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);
const contractInfo = ref(useAppState.getContractInfo);
const isCollapse = ref(useAppState.getCollapse)
const bubbleVal = ref(useAppState.getBubble);

//路由参数
const routerQuery = useRoutes?.query;
const typeName = routerQuery?.type || 'map'

//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreData('wbsTreeExpandKeys') || [])

//监听
watch(() => [
    useAppState.getProjectId,
    useAppState.getContractId,
    useAppState.getProjectInfo,
    useAppState.getContractInfo,
    useAppState.getBubble,
    useAppState.getCollapse
], ([UserProjectId, UserContractId, UserProjectInfo, UserContractInfo, Bubble, Collapse]) => {
    projectId.value = UserProjectId
    contractId.value = UserContractId
    projectInfo.value = UserProjectInfo
    contractInfo.value = UserContractInfo
    bubbleVal.value = Bubble
    isCollapse.value = Collapse
    setContractType(UserContractInfo?.contractType)
})

//获取气泡数据
const getButtonsVal = (value) => {
    return useAppState.getButtonsVal(value)
}
//气泡数据
const btn_drawings = ref(getButtonsVal('wbs_views_drawings'))   //查看图纸
const btn_save = ref(getButtonsVal('wbs_save'))                 //保存
const btn_preview = ref(getButtonsVal('wbs_preview'))           //预览
const btn_report = ref(getButtonsVal('wbs_report'))             //上报

//树菜单
const tree_menu_edit = ref(getButtonsVal('wbs_tree_edit'))  //编辑节点
const tree_menu_mark = ref(getButtonsVal('wbs_tree_mark'))  //标记为首件
const tree_menu_copy = ref(getButtonsVal('wbs_tree_copy'))  //复制节点
const tree_menu_add = ref(getButtonsVal('wbs_tree_add'))    //新增节点
const tree_menu_up = ref(getButtonsVal('wbs_tree_upload'))  //上传图纸
const tree_menu_del = ref(getButtonsVal('wbs_tree_del'))    //删除节点
const tree_menu_sort = ref(getButtonsVal('wbs_tree_sort'))  //调整排序


//上传文件的
const action = ref("/api/blade-resource/oss/endpoint/put-file")
const accept = ref("image/png,image/jpg,image/jpeg")

//身份按钮切换数据
const authBtnTabKey = ref('1')
const authBtnTabData = [
    {key: "1", label: "施工质检", icon: 'hcicon-a-Frame1'},
    {key: "2", label: "监理抽检", icon: 'hcicon-a-Frame2'}
]
const authBtnTabClick = (val) => {
    authBtnTabKey.value = val
    searchNodeAllTable()
}

//结构类型tab数据和相关处理
const wbsTypeTabKey = ref(typeName)
const wbsTypeTab = ref([
    {key:'map',  name: '导图结构填报'},
    {key:'tree', name: '树形结构填报'}
]);

//渲染完成
onMounted(()=> {
    const contractType = contractInfo.value?.contractType
    setContractType(contractType)
    setElTreeMenu()
    if (wbsTypeTabKey.value === 'map') {
        queryMappingStructureTree()
    }
})

const setContractType = (contractType) => {
    //contractType,  1施工，2监理
    if (contractType <= 0) {
        authBtnTabKey.value = '1'
    } else {
        authBtnTabKey.value = contractType + ''
    }
}

const wbsTypeTabChange = async (item) => {
    wbsTypeTabKey.value = item?.key;
    isDrawer.value = false;
    router.push({
        path: useRoutes.path,
        query: {
            type: item?.key
        }
    })
    await nextTick(() => {
        if (item?.key === 'map') {
            queryMappingStructureTree()
        }
    })
}

const NodeTreeAccordion = ref(true)

//设置树菜单数据
const ElTreeMenu = ref([])
const TreeMark = ref(false)
const setElTreeMenu = () => {
    let newArr = [];
    if (tree_menu_edit.value) {
        newArr.push({icon: hIconJs({name:'border_color'}), label: '编辑节点', key: "edit"})
    }
    if (tree_menu_mark.value) {
        newArr.push({icon: hIconJs({name:'grade'}), label: '标记为首件', key: "mark"})
        TreeMark.value = true
    }
    if (tree_menu_copy.value) {
        newArr.push({icon: hIconJs({name:'difference'}), label: '复制节点', key: "copy"})
    }
    if (tree_menu_add.value) {
        newArr.push({icon: hIconJs({name:'add_box'}), label: '新增节点', key: "add"})
    }
    if (tree_menu_up.value) {
        newArr.push({icon: hIconJs({name:'backup'}), label: '上传图纸', key: "upload"})
    }
    if (tree_menu_del.value) {
        newArr.push({icon: hIconJs({name:'delete'}), label: '删除节点', key: "del"})
    }
    if (tree_menu_sort.value) {
        newArr.push({icon: hIconJs({name:'sort'}), label: '调整排序', key: "sort"})
    }
    ElTreeMenu.value = newArr
}

//树的配置
const searchTreeVal = ref('')
const HcTreeRef = ref(null)
const treeParams = ref({contractId: contractId.value})

//树被点击
const wbsElTreeClick = ({node, data, keys}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    console.log(keys)
    setStoreData('wbsTreeExpandKeys',keys)
    searchNodeAllTable()
}


//导图结构数据
const NodeTreeRef = ref(null)
const NodeTreeFormat = ref({key: "primaryKeyId", label: "title", children: "children"})
const NodeTreeData = ref({})

//导图结构树节点查询
const queryMappingStructureTree = () => {
    wbsApi.queryMappingStructureTree({
        contractId: contractId.value,
        contractIdRelation: '',
        parentId: '0',
        wbsType: 1
    }).then(({data}) => {
        NodeTreeData.value = data?.data[0] || {}
    })
}

//导图结构展开和收缩被点击
const expandClick = ({node,data}) => {
    if (!node.children) {
        node.expanded = false;
    }
    node.isExpand = !node.isExpand;
}

//鼠标左键单击事件
const NodeTreeClick = ({node,data}) => {
    let ifChildren = !!(node.childNodes && node.childNodes.length > 0);
    if (!ifChildren) {
        node.loading = true
        const cid = data?.contractIdRelation
        const key = data?.primaryKeyId
        const id = data?.id
        wbsApi.queryMappingStructureTree({
            contractId: contractId.value,
            contractIdRelation: cid,
            parentId: cid?key:id,
            wbsType: 1
        }).then((res) => {
            const resData = res?.data?.data || []
            node.childNodes = resData
            nextTick(() => {
                if (resData.length > 0) {
                    node.expanded = true;
                    node.isExpand = true;
                } else {
                    node.expanded = false;
                    node.expanded = false;
                }
                node.loading = false
            })
        })
    } else {
        node.expanded = true;
        node.isExpand = true;
        node.loading = false
    }
}

//双击事件
const isDrawer = ref(false)
const NodeTreeDblClick = ({node,data}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    isDrawer.value = true;
    searchNodeAllTable()
}

//菜单被点击
const firstItemModal = ref(false)
const editNodeModal = ref(false)
const nodeItemInfo = ref({})
const nodeDataInfo = ref({})
const treeExpandKeys = ref([])
const ElTreeMenuClick = async ({key,node,data}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    if (key === 'mark' || key === 'cancel_mark') {
        firstItemModal.value = true
    } else if (key === 'edit') {
        const parent = deepClone(node?.parent?.data || {})
        formEditNodeModel.value = {...deepClone(data), parent: parent}
        editNodeModal.value = true
    } else if (key === 'copy') {
        const parent = deepClone(node?.parent?.data || {})
        formCopyNodeModel.value = {...deepClone(data), parent: parent}
        copyNodeTable.value = []
        copyNodeLoading.value = false
        copyNodeModal.value = true
    } else if (key === 'add') {
        addTreeNodeId.value = data?.id
        addTreeNodeOldId.value = data?.oldId
        addNodeLoading.value = false
        addNodeModal.value = true
    } else if (key === 'upload') {
        const uploadDom = document.getElementById('upload-drawing');
        let inputDom = uploadDom?.getElementsByTagName('input')[0];
        inputDom.click()
    } else if (key === 'del') {
        delModalClick()
    } else if (key === 'sort') {
        let nodes = []
        const childNodes = node?.parent?.childNodes || []
        for (let i = 0; i < childNodes.length; i++) {
            const res = childNodes[i]?.data
            nodes.push({
                id: res?.primaryKeyId,
                title: res?.title
            })
        }
        sortNodeData.value = nodes
        sortNodeModal.value = true
    }
}

const NodeExpandKeys = async (wbsTab = false) => {
    let newKeysArr = [], node = nodeItemInfo.value || {}
    await getNodeExpandKeys(node,newKeysArr,wbsTab)
    const treeKeys = newKeysArr.reverse()
    await setStore({name: 'wbsTreeExpandKeys', content: treeKeys})
    return treeKeys
}

//处理自动展开的节点KEY
const getNodeExpandKeys = async (node, newKeys, wbsTab = false) => {
    const tabType = wbsTypeTabKey.value || ''
    const primaryKeyId = node?.data?.primaryKeyId || ''
    if (primaryKeyId) {
        const nodes = node?.parentNodes || []
        const parent = node?.parent || []
        newKeys.push(primaryKeyId)
        if (tabType === 'map' && !wbsTab) {
            await getNodeExpandKeys(nodes, newKeys,wbsTab)
        } else if (tabType === 'tree' && !wbsTab) {
            await getNodeExpandKeys(parent, newKeys,wbsTab)
        } else if (tabType === 'map' && wbsTab) {
            await getNodeExpandKeys(parent, newKeys,wbsTab)
        } else if (tabType === 'tree' && wbsTab) {
            await getNodeExpandKeys(nodes, newKeys,wbsTab)
        }
    }
}

const NodeTreeMenuClick = async ({key,node,data}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    if (key === 'mark' || key === 'cancel_mark') {
        firstItemModal.value = true
    } else if (key === 'edit') {
        const parent = deepClone(node?.parentNodes?.data || {})
        formEditNodeModel.value = {...deepClone(data), parent: parent}
        editNodeModal.value = true
    } else if (key === 'copy') {
        const parent = deepClone(node?.parentNodes?.data || {})
        formCopyNodeModel.value = {...deepClone(data), parent: parent}
        copyNodeTable.value = []
        copyNodeLoading.value = false
        copyNodeModal.value = true
    } else if (key === 'add') {
        addTreeNodeId.value = data?.id
        addTreeNodeOldId.value = data?.oldId
        addNodeLoading.value = false
        addNodeModal.value = true
    } else if (key === 'upload') {
        const uploadDom = document.getElementById('upload-drawing');
        let inputDom = uploadDom?.getElementsByTagName('input')[0];
        inputDom.click()
    } else if (key === 'del') {
        delModalClick()
    } else if (key === 'sort') {
        let nodes = []
        const childNodes = node?.parentNodes?.childrenNodes || []
        for (let i = 0; i < childNodes.length; i++) {
            const res = childNodes[i]?.data
            nodes.push({
                id: res?.primaryKeyId,
                title: res?.title
            })
        }
        sortNodeData.value = nodes
        sortNodeModal.value = true
    }
}

//上传前
const loadingReactive = ref(null)
const beforeUpload = () => {
    loadingReactive.value = window?.$message?.loading('上传中...', {
        duration: 0
    })
    return true
}

//上传完成
const uploadFinish = ({event}) => {
    const res = JSON.parse(event?.target?.response);
    const info = nodeDataInfo.value;
    let link = res?.data?.link;
    wbsApi.saveContractTreeDrawings({
        fileUrl: link,
        id: info['drawingsId'],
        primaryKeyId: info['primaryKeyId']
    }).then(({data}) => {
        loadingReactive.value.destroy()
        loadingReactive.value = null
        if (data.code === 200) {
            nodeDataInfo.value['drawingsId'] = data.data
            nodeDataInfo.value['fileUrl'] = link
            window?.$message?.success('上传成功')
        } else {
            window?.$message?.error(data.msg || '上传失败')
        }
    }).catch(erro => {
        loadingReactive.value.destroy()
        loadingReactive.value = null
        window?.$message?.error('请求异常')
    })
}

//确认标记为首件
const firstItemLoading = ref(false)
const firstItemClick = () => {
    const info = nodeDataInfo.value;
    const TabKey = wbsTypeTabKey.value;
    wbsApi.wbsTreeFirstSave({
        primaryKeyId: info['primaryKeyId'],
        saveOrDeleted: !!info['isFirst']?1:0,
    }).then(({data}) => {
        if (data.code === 200) {
            const isFirst = !info['isFirst'];
            firstItemModal.value = false
            nodeDataInfo.value['isFirst'] = isFirst
            //处理菜单状态
            if (TabKey === 'tree') {
                HcTreeRef.value.setElTreeMenuMark(data?.data || [], isFirst)
            } else {
                setNodeTreeMenuMark(info['primaryKeyId'],data?.data || [], isFirst)
            }
            window?.$message?.success('操作成功')
        } else {
            window?.$message?.error(data.msg || '操作失败')
        }
    })
}

//设置树菜单的标记数据
const setNodeTreeMenuMark = (KeyId,keys,isFirst) => {
    const info = nodeItemInfo.value;
    setNodeTreeParentNodes(info['parentNodes'],keys,isFirst)
    setNodeTreeChildNodes(info['childrenNodes'],keys,isFirst)
}

//设置父级
const setNodeTreeParentNodes = (parent,keys,isFirst) => {
    if (keys.indexOf(parent['key']) !== -1) {
        parent['data']['isFirst'] = isFirst
    }
    if (!isObjNull(parent['parentNodes'])) {
        setNodeTreeParentNodes(parent['parentNodes'],keys,isFirst)
    }
}

//设置子级
const setNodeTreeChildNodes = (child,keys,isFirst) => {
    if (child.length > 0) {
        child.forEach(item => {
            if (keys.indexOf(item['key']) !== -1) {
                item['data']['isFirst'] = isFirst
            }
            if (item['childrenNodes'].length > 0) {
                setNodeTreeChildNodes(item['childrenNodes'],keys,isFirst)
            }
        })
    }
}

//编辑节点
const nodeTypeData = ref([{label: "分项工程", value: 1}, {label: "分部工程", value: 2}])
const editNodeLoading = ref(false)
const formEditNodeRef = ref(null)
const formEditNodeModel = ref({})
const formEditNodeRules = {
    title: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入节点名称"
    },
}
const editNodeClick = () => {
    editNodeLoading.value = true
    const {primaryKeyId,title,partitionCode} = formEditNodeModel.value
    wbsApi.wbsTreeUpdateNode({
        deptName: title,
        pKeyId: primaryKeyId,
        partitionCode: partitionCode||''
    }).then(({data}) => {
        editNodeLoading.value = false
        if (data.code === 200) {
            window?.$message?.success('修改成功')
            nodeDataInfo.value['title'] = title || ''
            nodeDataInfo.value['partitionCode'] = partitionCode || ''
            editNodeModal.value = false
        } else {
            window?.$message?.error(data.msg || '修改失败')
        }
    }).catch(erro => {
        editNodeLoading.value = false
        window?.$message?.error('请求异常')
    })
}

//复制节点
const copyNodeModal = ref(false)

//复制节点类型tab数据和相关处理
const copyNodeTabKey = ref('2')
const copyNodeTab = ref([
    {key:'1',  name: '单份复制'},
    {key:'2', name: '多份复制'}
]);
const copyNodeTabChange = (value) => {
    copyNodeTabKey.value = value;
    copyNodeLoading.value = false
}
const copyNodeLoading = ref(false)
const formCopyNodeModel = ref({})
const copyNodeTable = ref([])

//树被点击
const copyNodeElTreeClick = ({data}) => {
    const {title} = formCopyNodeModel.value;
    if (!data?.exsitChild) {
        copyNodeTable.value.push({
            title: data?.title || '',
            nodeName: title || '',
            primaryKeyId: data?.primaryKeyId || ''
        })
    }
}

const formCopyNodeModelRef = ref(null)
const formCopyNodeModelRules = {
    title: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入节点名称"
    }
}

//删除选中的节点
const copyNodeTableDel = (index) => {
    copyNodeTable.value.splice(index,1)
}
const copyNodeTableRef = ref(null)
const copyNodeTableRules = {
    nodeName: {
        required: true,
        trigger: ["blur", "input"],
        message: "请输入节点名称"
    }
}

const copyNodeClick = async () => {
    const type = copyNodeTabKey.value
    const form = formCopyNodeModel.value
    const table = copyNodeTable.value
    //效验数据
    let validate = false
    if (type === '1') {
        const errors = await formCopyNodeModelRef.value?.validate()
        validate = !errors
    } else if (type === '2') {
        if (table.length > 0) {
            const errors = await copyNodeTableRef.value?.validate()
            validate = !errors
        } else {
            validate = false
            window?.$message?.warning('请先在左侧选择要复制到的节点')
        }
    }
    //发起请求
    if (validate) {
        copyNodeLoading.value = true
        const {data} = await wbsApi.copyContractTreeNode({
            copyType: type,
            needCopyNodeName: form?.title || '',
            needCopyPrimaryKeyId: form?.primaryKeyId || '',
            parentPrimaryKeyId: form?.parent?.primaryKeyId || '',
            copyBatchToPaths: table
        })
        //判断状态
        if (data.code === 200) {
            window?.$message?.success('复制成功')
            copyNodeLoading.value = false
            copyNodeModal.value = false
            await NodeExpandKeys()
            window?.location?.reload()  //刷新页面
        } else {
            copyNodeLoading.value = false
            window?.$message?.error(data.msg || '复制失败')
        }
    } else {
        window?.$message?.warning('请先检查相关表单是否正确填写或节点是否选择')
    }
}

//新增节点
const addNodeModal = ref(false)
const addTreeNodeId = ref('')
const addTreeNodeOldId = ref('')
const addTreeNodeType = ref('1')

//选中的节点
const allSelectedList = ref([])
const halfSelectedList = ref([])
const addTreeNodeCheckChange = (nodes) => {
    let NodesArr = [], halfArr = []
    //全选数据
    const keys = nodes.checkedNodes || []
    for (let i = 0; i < keys.length; i++) {
        NodesArr.push({
            nodeName: keys[i].title,
            primaryKeyId: keys[i].primaryKeyId
        })
    }
    allSelectedList.value = NodesArr
    //半选数据
    const halfNodes = nodes.halfCheckedNodes || []
    for (let i = 0; i < halfNodes.length; i++) {
        halfArr.push({
            nodeName: halfNodes[i].title,
            primaryKeyId: halfNodes[i].primaryKeyId
        })
    }
    halfSelectedList.value = halfArr
}

//新增节点
const addNodeLoading = ref(false)
const addNodeClick = async () => {
    const keys = allSelectedList.value || []
    if (keys.length <= 0) {
        window?.$message?.warning('请先选择节点')
    } else {
        //发起请求
        addNodeLoading.value = true
        const {data} = await wbsApi.saveContractTreeNode({
            projectId: projectId.value,
            contractId: contractId.value,
            saveType: addTreeNodeType.value,
            allSelectedList: allSelectedList.value,
            halfSelectedList: halfSelectedList.value,
            currentNodePrimaryKeyId: nodeDataInfo.value?.primaryKeyId
        })
        //判断状态
        if (data.code === 200) {
            window?.$message?.success('新增成功')
            await NodeExpandKeys()
            addNodeLoading.value = false
            addNodeModal.value = false
            window?.location?.reload()  //刷新页面
        } else {
            addNodeLoading.value = false
            window?.$message?.error(data.msg || '新增失败')
        }
    }
}

//删除确认弹窗
const delModalClick  = () => {
    window?.$dialog?.error({
        title: "确认此操作？",
        content: "请谨慎考虑后，确认是否需要删除",
        positiveText: "确认删除",
        negativeText: "取消",
        onPositiveClick: () => {
            const info = nodeDataInfo.value;
            const TabKey = wbsTypeTabKey.value;
            wbsApi.removeContractTreeNode({
                ids: info['primaryKeyId']
            }).then(({data}) => {
                if (data.code === 200) {
                    window?.$message?.success('删除成功')
                    //处理菜单状态
                    if (TabKey === 'tree') {
                        HcTreeRef.value.removeElTreeNode(info['primaryKeyId'])
                    } else {
                        removeNodeTreeNode()
                    }
                } else {
                    window?.$message?.error(data.msg || '删除失败')
                }
            }).catch(erro => {
                window?.$message?.error('请求异常')
            })
        }
    });
}
const removeNodeTreeNode = () => {
    const info = nodeItemInfo.value;
    const parent = info['parentNodes']
    const childNodes = parent['childNodes'] || []
    const childrenNodes = parent['childrenNodes'] || []
    //删除
    for (let i = 0; i < childNodes.length; i++) {
        if (info['key'] === childNodes[i]['primaryKeyId']) {
            childNodes.splice(i, 1);
        }
    }
    //删除
    for (let i = 0; i < childrenNodes.length; i++) {
        if (info['key'] === childrenNodes[i]['key']) {
            childrenNodes.splice(i, 1);
        }
    }
}

//调整排序
const sortNodeModal = ref(false)
const sortNodeLoading = ref(false)
const sortNodeData = ref([])
const sortNodeDrag = ref(false)
//向下
const downSortClick = (index) => {
    const indexs = index + 1
    const data = sortNodeData.value || []
    if(indexs !== data.length) {
        const tmp = data.splice(indexs,1);
        sortNodeData.value.splice(index,0,tmp[0]);
    } else {
        window?.$message?.warning('已经处于置底，无法下移')
    }
}
//向上
const upSortClick = (index) => {
    const data = sortNodeData.value || []
    if(index !== 0) {
        const tmp = data.splice(index - 1,1);
        sortNodeData.value.splice(index,0,tmp[0]);
    } else {
        window?.$message?.warning('已经处于置顶，无法上移')
    }
}
//确认排序
const sortNodeClick = async () => {
    const sortList = [];
    const nodes = sortNodeData.value || []
    nodes.forEach(item => {
        sortList.push(item?.id)
    })
    //发起请求
    sortNodeLoading.value = true
    const { data } = await wbsApi.diySortTreeNode({sortList})
    //判断状态
    if (data.code === 200) {
        window?.$message?.success('保存成功')
        await NodeExpandKeys()
        sortNodeLoading.value = false
        sortNodeModal.value = false
        window?.location?.reload()  //刷新页面
    } else {
        sortNodeLoading.value = false
        window?.$message?.error(data.msg || '保存失败')
    }
}


//查看图纸
const drawingsShow = ref(false);
const viewsDrawings = () => {
    drawingsShow.value = true
}
const drawingsClose = (res) => {
    drawingsShow.value = res
}
const viewsDrawingsTip = () => {
    const {primaryKeyId,fileUrl} = nodeDataInfo.value
    if (!primaryKeyId) {
        window?.$message?.warning('请先选择树节点')
    } else if (!fileUrl) {
        window?.$message?.warning('该节点暂未上传图纸')
    }
}

//数据列表
const ListItemDatas = ref([]);

//获取数据列表
const searchNodeAllTable = () => {
    const info = nodeDataInfo.value;
    const cid = info?.contractIdRelation || ''
    const key = info?.primaryKeyId || ''
    const id = info?.id || ''
    wbsApi.searchNodeAllTable({
        primaryKeyId: cid?id:key,
        type: authBtnTabKey.value
    }).then(({data}) => {
        if (data.code === 200) {
            let tableData = isArray(data?.data)?data['data']:[]
            if (tableData.length > 0) {
                tableData.forEach(item => {
                    item.name = item.deptName
                })
            }
            ListItemDatas.value = tableData
        } else {
            ListItemDatas.value = []
        }
    }).catch(erro => {
        ListItemDatas.value = []
    })
}

//批量上报
const showReportModal = ref(false)
const reportModalClick = () => {
    showReportModal.value = true
}

//被展开
const ListItemOffsetTop = (offsetTop) => {
    if (offsetTop > 0) {
        const type = wbsTypeTabKey.value || 'map'
        setTimeout(() => {
            if (type === 'map') {
                document.getElementById('hc-drawer-list-item').scrollTop = offsetTop
            } else if (type === 'tree') {
                document.getElementById('hc-card-list-item').scrollTop = offsetTop
            }
        }, 200)
    }
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(382);
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum;
        if(diffVal >= 310 && diffVal <= 900) {
            leftWidth.value = diffVal;
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}
</script>

<style lang="scss" scoped>
@import "../../styles/data-fill/wbs.scss";
.hc-add-node-modal-foot-box {
    position: relative;
    display: flex;
    align-items: center;
    .left-box {
        position: relative;
        flex: 1;
        display: flex;
        align-items: center;
    }
    .right-box {
        position: relative;
    }
}

html.theme-dark {
    .bg-svg-xml {
        background-color: initial;
        background-image: initial;
    }
    .hc-layout-box .hc-layout-content-box .hc-card-max-h-box.node-tree .hc-tree-foot-tip-box {
        border-top: 1px solid #303030;
    }
}
</style>

<style lang="scss">
.data-fill-wbs-content {
    position: relative;
    height: 100%;
    .n-drawer-container {
        margin: -20px -24px;
    }
    .n-drawer.n-drawer--top-placement {
        height: auto !important;
        background-color: initial;
        pointer-events: none;
        bottom: 0;
    }
    .drawer-data-fill-content-box {
        position: relative;
        height: 100%;
        padding: 24px;
        .n-card {
            pointer-events: auto;
            height: 100%;
            overflow: auto;
        }
        .data-fill-content {
            position: relative;
            height: 100%;
            overflow-y: auto;
            scroll-behavior: smooth;
            .data-fill-list-box .data-fill-list-item-content {
                height: calc(100vh - 470px);
                .data-fill-table-form-box {
                    height: 100%;
                }
            }
        }
        .data-fill-foot {
            position: relative;
            text-align: center;
        }
    }
}
.n-card.hc-card-overflow-box .n-card__content {
    padding: 24px;
}
.n-card.hc-custom-card > .n-card-header {
    padding: 15px 24px;
}
.n-card.hc-custom-card.copy {
    width: 1200px;
    max-height: 90vh;
    overflow: auto;
    .n-card-header .n-card-header__close {
        display: none;
    }
    &.one {
        width: 600px;
    }
    &.many {
        width: 1200px;
        .copy-node-many-box {
            position: relative;
            height: 60vh;
            display: flex;
            .copy-node-many-tree {
                position: relative;
                flex: 1;
                height: 100%;
                overflow: auto;
                padding-right: 20px;
                border-right: 1px solid #efeff5;
            }
            .copy-node-many-table {
                position: relative;
                flex: 1;
                height: 100%;
                margin-left: 20px;
                .copy-node-many-table-data {
                    position: relative;
                    height: calc(100% - 74px);
                    margin-bottom: 20px;
                    overflow: auto;
                }
                .copy-node-many-foot-center {
                    position: relative;
                    text-align: center;
                    padding-top: 20px;
                    border-top: 1px solid #efeff5;
                }
            }
        }
    }
}
.img-preview-box {
    position: relative;
    height: 100%;
    width: 100%;
    .cu-img-preview.cu-img-preview-dom .cu-img-preview-box {
        height: calc(100% - 60px);
    }
    .cu-img-preview.cu-img-preview-dom .cu-img-preview-tools-box{
        position: absolute;
    }
}
</style>
