<template>
    <div class="h-full">
        <HcCard id-ref="wbs-node-tree-card-target" v-if="wbsTypeTabKey === 'map'">
            <template #header>
                <HcTooltip keys="wbs_views_division">
                    <el-button type="primary" hc-btn @click="divisionClick">
                        <HcIcon name="node-tree" :line="false"/>
                        <span>划分变更</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="wbs_views_drawings" v-if="isDrawer">
                    <el-button hc-btn :disabled="!nodeDataInfo?.fileUrl" @click="viewsDrawings">
                        <HcIcon name="image"/>
                        <span>查看图纸</span>
                    </el-button>
                </HcTooltip>
                <el-button :type="authBtnTabKey === '1'?'primary':''" hc-btn @click="authBtnTabClick('1')" v-if="isDrawer">
                    <HcIcon name="folder-user"/>
                    <span>施工自检</span>
                </el-button>
                <el-button :type="authBtnTabKey === '2'?'primary':''" hc-btn @click="authBtnTabClick('2')" v-if="isDrawer">
                    <HcIcon name="folder-shield"/>
                    <span>监理质检</span>
                </el-button>
            </template>
            <template #extra>
                <HcNewSwitch :datas="wbsTypeTab" :keys="wbsTypeTabKey" @change="wbsTypeTabChange"/>
            </template>
            <NodeTree ref="NodeTreeRef" :autoExpandKeys="TreeAutoExpandKeys" :menus="ElTreeMenu" :isMark="TreeMark" :projectId="projectId" :contractId="contractId"
                      :accordion='NodeTreeAccordion' @nodeClick="NodeTreeClick" @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>
            <HcDrawer :show="isDrawer" actionUi="text-center" to-id="wbs-node-tree-card-target" @close="drawerClose">
                <!--清表列表-->
                <el-scrollbar ref="ListItemScrollRef" v-if="ListItemDatas.length > 0">
                    <ListItem ref="ListItemsRef"
                     :datas="ListItemDatas" 
                     :status="NodeStatus" 
                     :classify="authBtnTabKey"
                     @offsetTop="ListItemOffsetTop" 
                     :projectInfo="projectInfo" 
                     :primaryKeyId="primaryKeyId" 
                     :contractId="contractId" 
                     @renew="getTableDataAll"
                      :drawType="isDrawType"
                    />
                </el-scrollbar>
                <HcStatus text="暂无表单" v-else/>
                <!--底部按钮区域-->
                <template #action>
                    <HcTooltip keys="wbs_save" v-if="NodeStatus !== '3'">
                        <el-button type="primary" hc-btn :disabled="NodeStatus === '3' || ListItemDatas.length <= 0" :loading="tableFormSaveLoading" @click="tableFormSaveClick">
                            <HcIcon name="save"/>
                            <span>保存</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="wbs_report" v-if="NodeStatus !== '3'">
                        <el-button hc-btn :disabled="NodeStatus === '3' || NodeStatus === '1'" :loading="reportLoading" @click="reportModalClick">
                            <HcIcon name="send-plane-2"/>
                            <span>上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="wbs_preview">
                        <el-button hc-btn :disabled="NodeStatus === '1'" :loading="bussPdfsLoading" @click="bussPdfsClick">
                            <HcIcon name="eye"/>
                            <span>预览</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="wbs_abolish" v-if="NodeStatus === '3'">
                        <el-button hc-btn @click="abolishOneClick">
                            <HcIcon name="arrow-go-back"/>
                            <span>撤回上报流程</span>
                        </el-button>
                    </HcTooltip>
                    <el-button hc-btn @click="drawerClose">
                        <HcIcon name="close"/>
                        <span>关闭填报页面</span>
                    </el-button>
                </template>
            </HcDrawer>
        </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="stack"/>
                    </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 @keyup="searchTreeKeyUp">
                            <template #suffix>
                                <HcIcon name="search-2" ui="text-xl" @click="searchTreeClick"/>
                            </template>
                        </el-input>
                    </div>
                    <div class="hc-tree-scrollbar" v-loading="treeLoading" element-loading-text="获取数据中...">
                        <el-scrollbar>
                            <KeepAlive>
                                <template v-if="isSearchTree">
                                    <HcTreeData 
                                    :datas="searchTreeData" 
                                    :menus="ElTreeMenu" 
                                    :isMark="TreeMark" 
                                    :autoExpandKeys="TreeAutoExpandKeys" 
                                    :searchTreeVal="searchTreeVal" i
                                    sColor @nodeTap="wbsElTreeClick"
                                     @menuTap="ElTreeMenuClick"  
                                     @changeSearch="changeisSearch" 
                                     :submitCounts="false"
                                     />
                                </template>
                                <template v-else>
                                    <WbsTree :submitCounts="false" :menus="ElTreeMenu" :isMark="TreeMark" :autoExpandKeys="TreeAutoExpandKeys" :projectId="projectId" :contractId="contractId" isColor @nodeTap="wbsElTreeClick" @menuTap="ElTreeMenuClick" @nodeLoading="ElTreeNodeLoading" />
                                </template>
                            </KeepAlive>
                        </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 actionUi="text-center">
                    <template #header>
                        <HcTooltip keys="wbs_views_drawings">
                            <el-button hc-btn :disabled="!nodeDataInfo?.fileUrl" @click="viewsDrawings">
                                <HcIcon name="image"/>
                                <span>查看图纸</span>
                            </el-button>
                        </HcTooltip>
                        <el-button :type="authBtnTabKey === '1'?'primary':''" hc-btn @click="authBtnTabClick('1')">
                            <HcIcon name="folder-user"/>
                            <span>施工自检</span>
                        </el-button>
                        <el-button :type="authBtnTabKey === '2'?'primary':''" hc-btn @click="authBtnTabClick('2')">
                            <HcIcon name="folder-shield"/>
                            <span>监理质检</span>
                        </el-button>
                    </template>
                    <!--切换导图或树形模式-->
                    <template #extra>
                        <HcNewSwitch :datas="wbsTypeTab" :keys="wbsTypeTabKey" @change="wbsTypeTabChange"/>
                    </template>
                    <!--清表列表-->
                    <el-scrollbar ref="ListItemScrollRef" v-loading="ListItemLoading" v-if="ListItemDatas.length > 0">
                        <ListItem 
                        ref="ListItemRef" 
                        :datas="ListItemDatas" 
                        :status="NodeStatus" 
                        :classify="authBtnTabKey" 
                        :authBtnTabKey="authBtnTabKey"
                        @offsetTop="ListItemOffsetTop" 
                        :projectInfo="projectInfo" 
                        :primaryKeyId="primaryKeyId" 
                        :contractId="contractId" 
                        @renew="getTableDataAll"
                         :drawType="!isDrawType"
                        :wbsTempId="projectInfo?.referenceWbsTemplateIdTrial" :wbsType="2" :tenantId="userInfo?.tenant_id"
                        />
                    </el-scrollbar>

                    <HcStatus text="暂无表单" v-else/>

                    <!--底部按钮区域-->
                    <template #action>
                        <HcTooltip keys="wbs_save" v-if="NodeStatus !== '3'">
                            <el-button type="primary" hc-btn :disabled="NodeStatus === '3' || ListItemDatas.length <= 0" :loading="tableFormSaveLoading" @click="tableFormSaveClick">
                                <HcIcon name="save"/>
                                <span>保存</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip keys="wbs_report" v-if="NodeStatus !== '3'">
                            <el-button hc-btn :disabled="NodeStatus === '3' || NodeStatus === '1'" :loading="reportLoading" @click="reportModalClick">
                                <HcIcon name="send-plane-2"/>
                                <span>上报</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip keys="wbs_preview">
                            <el-button hc-btn :disabled="NodeStatus === '1'" :loading="bussPdfsLoading" @click="bussPdfsClick">
                                <HcIcon name="eye"/>
                                <span>预览</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip keys="wbs_abolish" v-if="NodeStatus === '3'">
                            <el-button hc-btn @click="abolishOneClick">
                                <HcIcon name="arrow-go-back"/>
                                <span>撤回上报流程</span>
                            </el-button>
                        </HcTooltip>
                    </template>
                </HcCard>
            </div>
        </div>

        <!--上传图纸-->
        <div class="upload-drawing">
            <el-upload :action="action" :accept="accept" :headers="getTokenHeader()" :before-upload="beforeUpload" :on-success="uploadFinish" :on-error="uploadError">
                <div id="upload-drawing">上传图纸</div>
            </el-upload>
        </div>

        <!--查看图纸-->
        <HcDragModal title="查看图纸" ui="hc-image-preview-box" :isShow="drawingsShow" closeIcon tops="100" lefts="145" widths="380px" @close="drawingsClose">
            <div class="hc-image-preview-view">
                <el-image-viewer :url-list="[nodeDataInfo.fileUrl]"/>
            </div>
        </HcDragModal>

        <!--编辑节点-->
        <HcDialog :show="editNodeModal" title="编辑节点" widths="600px" :loading="editNodeLoading" @close="editNodeModal = false" @save="editNodeClick">
            <el-form ref="formEditNodeRef" :model="formEditNodeModel" :rules="formEditNodeRules" label-width="auto" size="large">
                <el-form-item label="节点名称" prop="title">
                    <el-input v-model="formEditNodeModel.title"  placeholder="请输入节点名称"/>
                </el-form-item>
                <el-form-item label="上级节点">
                    <el-input v-model="formEditNodeModel.parent.title" disabled/>
                </el-form-item>
                <el-form-item label="节点类型">
                    <el-select v-model="formEditNodeModel.type" block disabled>
                        <el-option v-for="item in nodeTypeData" :label="item.label" :value="item.value"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="划分编号">
                    <el-input v-model="formEditNodeModel.partitionCode" placeholder="请输入划分编号"/>
                </el-form-item>
            </el-form>
        </HcDialog>

        <!--复制节点-->
        <HcDialog :show="copyNodeModal" title="复制节点" :widths="copyNodeTabKey === '1'?'600px':'1200px'" @close="copyNodeModal = false">
            <el-form ref="formCopyNodeModelRef" :model="formCopyNodeModel" :rules="formCopyNodeModelRules" label-width="auto" size="large" v-if="copyNodeTabKey !== '3'">
                <el-form-item label="节点名称" prop="title" style="margin-bottom: 0;">
                    <el-input v-model="formCopyNodeModel.title" placeholder="请输入节点名称"/>
                </el-form-item>
            </el-form>
            <div class="copy-node-many-box" v-if="copyNodeTabKey !== '1'">
                <div class="copy-node-many-tree">
                    <el-scrollbar>
                        <WbsTree :autoExpandKeys="TreeAutoExpandKeys" :projectId="projectId" :contractId="contractId" idPrefix="tree-node-copy-" :isAutoClick="false" :isAutoKeys="false" @nodeTap="copyNodeElTreeClick"/>
                    </el-scrollbar>
                </div>
                <div class="copy-node-many-table">
                    <el-scrollbar>
                        <el-table :data="copyNodeTable" border stripe>
                            <el-table-column prop="title" label="复制到的位置"/>
                            <el-table-column prop="nodeName" label="节点名称" v-if="copyNodeTabKey === '2'">
                                <template #default="{row}">
                                    <el-form ref="copyNodeTableRef" :model="row" :rules="copyNodeTableRules" label-width="0" size="large">
                                        <el-form-item prop="nodeName" style="margin-bottom: 0;">
                                            <el-input v-model="row.nodeName" placeholder="请输入节点名称"/>
                                        </el-form-item>
                                    </el-form>
                                </template>
                            </el-table-column>
                            <el-table-column prop="action" label="操作" width="120" align="center">
                                <template #default="{_,$index}">
                                    <el-button type="danger" plain @click="copyNodeTableDel($index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-scrollbar>
                </div>
            </div>
            <template #footer>
                <div class="lr-dialog-footer">
                    <div class="left">
                        <template v-for="item in copyNodeTab">
                            <el-button size="large" type="primary" plain v-if="item?.key === copyNodeTabKey" @click="copyNodeTabChange(item?.key)">{{item.name}}</el-button>
                            <el-button size="large" text bg @click="copyNodeTabChange(item?.key)" v-else>{{item.name}}</el-button>
                        </template>
                    </div>
                    <div class="right">
                        <el-button size="large" @click="copyNodeModal = false">取消</el-button>
                        <el-button type="primary" hc-btn :loading="copyNodeLoading" @click="copyNodeClick">提交</el-button>
                    </div>
                </div>
            </template>
        </HcDialog>

        <!--新增子节点-->
        <HcDialog :show="addNodeModal" title="新增子节点" widths="720px" @close="addNodeModal = false">
            <el-alert title="双击节点，可编辑节点名称，编辑完成后，请按回车或输入框消失后，再点提交" type="warning" :closable="false"/>
            <HcTreeNode :projectId="projectId" :nodeId="addTreeNodeId" :oldId="addTreeNodeOldId" @check-change="addTreeNodeCheckChange" v-if="addTreeNodeType === '1'"/>
            <HcTreeNode :projectId="projectId" :nodeId="addTreeNodeId" :oldId="addTreeNodeOldId" strictly @check-change="addTreeNodeCheckChange" v-if="addTreeNodeType === '2'"/>
            <template #footer>
                <div class="lr-dialog-footer">
                    <div class="left flex items-center">
                        <div class="mr-4">选中方式:</div>
                        <el-radio-group v-model="addTreeNodeType">
                            <el-radio label="1">当前及子节点</el-radio>
                            <el-radio label="2" class="ml-4">仅当前节点</el-radio>
                        </el-radio-group>
                    </div>
                    <div class="right">
                        <el-button size="large" @click="addNodeModal = false">取消</el-button>
                        <el-button type="primary" hc-btn :loading="addNodeLoading" @click="addNodeClick">提交</el-button>
                    </div>
                </div>
            </template>
        </HcDialog>

        <!--调整排序-->
        <HcDialog :show="sortNodeModal" title="调整排序" widths="700px" :loading="sortNodeLoading" @close="sortNodeModal = false" @save="sortNodeClick">
            <el-alert title="可拖动排序，也可在后面点击图标，切换排序" type="warning" :closable="false"/>
            <div class="sort-node-body-box list-group header">
                <div class="list-group-item">
                    <div class="index-box">序号</div>
                    <div class="title-box">节点名称</div>
                    <div class="icon-box">排序</div>
                </div>
            </div>
            <Draggable class="sort-node-body-box list-group" ghost-class="ghost" :list="sortNodeData" item-key="id" @start="sortNodeDrag = true" @end="sortNodeDrag = false">
                <template #item="{element, index}">
                    <div class="list-group-item">
                        <div class="index-box">{{index + 1}}</div>
                        <div class="title-box">{{element.title}}</div>
                        <div class="icon-box">
                            <span class="icon" @click="downSortClick(index)">
                                <HcIcon name="arrow-down" ui="text-lg"/>
                            </span>
                            <span class="icon" @click="upSortClick(index)">
                                <HcIcon name="arrow-up" ui="text-lg"/>
                            </span>
                        </div>
                    </div>
                </template>
            </Draggable>
        </HcDialog>

        <!--批量上报审批-->
        <HcReportModal  title="批量上报审批" url="informationWriteQuery/taskOne" :show="showReportModal" :projectId="projectId" :contractId="contractId" type="wbs" :typeData="reportTypeData"
                        :taskName="reportTaskName" :ids="reportIds" :addition="reportAddition" @hide="showReportModal = false" @finish="showReportFinish"/>
    </div>
</template>

<script setup>
import {ref,watch,onMounted} from "vue";
import {useRouter, useRoute} from 'vue-router'
import {useAppStore} from "~src/store";
import {HcIsButton} from "~src/plugins/IsButtons";
import ListItem from "./components/ListItem.vue"
import NodeTree from "./components/nodeTree/index.vue"
import HcTreeNode from "./components/HcTreeNode.vue"
import HcTreeData from "./components/HcTreeData.vue"
import WbsTree from "./components/WbsTree.vue"
import {getTokenHeader} from '~src/api/request/header';
import {getStoreData, setStoreData} from '~src/utils/storage'
import {isType, deepClone, formValidate} from "vue-utils-plus"
import {getDictionary, eVisaTaskCheckApi} from "~api/other"
import wbsApi from "~api/data-fill/wbs"
import queryApi from '~api/data-fill/query';
import Draggable from "vuedraggable";

//初始变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()
const {getObjValue, getArrValue, getObjNullValue, isString} = isType()

//全局变量
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 userInfo = ref(useAppState.getUserInfo);
//路由参数
const routerQuery = useRoutes?.query;
const typeName = routerQuery?.type || 'map'
//是否是抽屉
const isDrawType = ref(true)
//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreData('wbsTreeExpandKeys') || [])
//树搜索
const isSearchTree = ref(false)
const getSearchTreeData=async()=>{
        const {error, code, data} = await queryApi.getTreeall({
            contractId: contractId.value,
            projectId: projectId.value,
            wbsId:projectInfo?.value.referenceWbsTemplateId
        })
        //判断状态
        if (!error && code === 200) {
            searchTreeData.value = getArrValue(data)
            treeLoading.value = false
        } else {
            treeLoading.value = false
            searchTreeData.value = []
        }
    
}
//监听
watch(() => [
    useAppState.getCollapse,
], ([Collapse]) => {
    isCollapse.value = Collapse
   
})
watch(projectId, (val) => {
    console.log(val,'val')
    if(val){
        getSearchTreeData()
    }
   
},

{immediate:true}

)
//渲染完成
onMounted(()=> {
    treeLoading.value = typeName === 'tree';
    setContractType(contractInfo.value?.contractType)
    getDictionaryApi()
  
})

//身份按钮切换数据
const authBtnTabKey = ref('1')
const authBtnTabClick = (val) => {
    if (!primaryKeyId.value) {
        window?.$message?.warning('请先在左侧项目树选择一个节点')
    } else if (val !== authBtnTabKey.value) {
        authBtnTabKey.value = val
        getTableDataAll()
    }
}
//contractType,  1施工，2监理
const setContractType = (contractType) => {
    if (contractType <= 0) {
        authBtnTabKey.value = '1'
    } else {
        authBtnTabKey.value = contractType + ''
    }
    setElTreeMenu(contractType)
}

const getTableDataAll = () => {
    searchNodeAllTable()
    queryNodeStatus()
}

//结构类型tab数据和相关处理
const wbsTypeTabKey = ref(typeName)
const wbsTypeTab = ref([
    {key:'map',  name: '导图结构填报'},
    {key:'tree', name: '树形结构填报'}
]);
const wbsTypeTabChange = (item) => {
    wbsTypeTabKey.value = item?.key;
    ListItemDatas.value = []
    isDrawer.value = false;
    treeLoading.value = typeName === 'tree';
    //路由跳转
    router.push({
        path: useRoutes.path,
        query: {
            type: item?.key
        }
    })
    getSearchTreeData()
}

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

const NodeTreeAccordion = ref(true)

//设置树菜单数据
const ElTreeMenu = ref([])
const TreeMark = ref(false)
const setElTreeMenu = (contractType) => {
    let newArr = [];
    if (contractType === 1) {
        if (HcIsButton('wbs_tree_edit')) {
            newArr.push({icon: 'draft', label: '编辑节点', key: "edit"})
        }
        if (HcIsButton('wbs_tree_mark')) {
            newArr.push({icon: 'star', label: '标记为首件', key: "mark"})
            TreeMark.value = true
        }
        if (HcIsButton('wbs_tree_copy')) {
            newArr.push({icon: 'file-copy-2', label: '复制节点', key: "copy"})
        }
        if (HcIsButton('wbs_tree_add')) {
            newArr.push({icon: 'add-circle', label: '新增节点', key: "add"})
        }
        if (HcIsButton('wbs_tree_upload')) {
            newArr.push({icon: 'file-upload', label: '上传图纸', key: "upload"})
        }
        if (HcIsButton('wbs_tree_del')) {
            newArr.push({icon: 'delete-bin', label: '删除节点', key: "del"})
        }
        if (HcIsButton('wbs_tree_sort')) {
            newArr.push({icon: 'sort-asc', label: '调整排序', key: "sort"})
        }
    } else if (contractType === 2) {
        if (HcIsButton('wbs_tree_copy')) {
            newArr.push({icon: 'file-copy-2', label: '复制节点', key: "copy"})
        }
        if (HcIsButton('wbs_tree_add')) {
            newArr.push({icon: 'add-circle', label: '新增节点', key: "add"})
        }
    }
    ElTreeMenu.value = newArr
}

//树相关变量
const primaryKeyId = ref('')
const nodeItemInfo = ref({})
const nodeDataInfo = ref({})


const searchTreeVal = ref('')
const searchTreeData = ref([])
//回车
const searchTreeKeyUp = (e) => {
    if (e.key === "Enter") {
        searchTreeClick()
    }
}
const changeisSearch=()=>{
    isSearchTree.value=false
}
const treeLoading = ref(false)
const searchTreeClick = async () => {
     isSearchTree.value=true
}

    // if (searchTreeVal.value) {
    //     isSearchTree.value = true
    //     treeLoading.value = true
    //     const {error, code, data} = await wbsApi.searchContractTree({
    //         contractId: contractId.value,
    //         queryValue: searchTreeVal.value
    //     })
    //     //判断状态
    //     if (!error && code === 200) {
    //         searchTreeData.value = getArrValue(data)
    //         treeLoading.value = false
    //     } else {
    //         treeLoading.value = false
    //         searchTreeData.value = []
    //     }
    // } else {
    //     treeLoading.value = false
    //     isSearchTree.value = false
    // }


//树被点击
const wbsElTreeClick = ({node, data, keys}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    primaryKeyId.value = data?.primaryKeyId || ''
    setStoreData('wbsTreeExpandKeys',keys)
    TreeAutoExpandKeys.value = keys || []
    getTableDataAll()
}
//树加载完成
const ElTreeNodeLoading = () => {
    treeLoading.value = false
}

//树菜单被点击
const ElTreeMenuClick = async ({key,node,data,keys}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    setStoreData('wbsTreeExpandKeys',keys)
    setTreeMenuDataClick({key,node,data})
}

//导图结构数据
const NodeTreeRef = ref(null)

//鼠标左键单击事件
const NodeTreeClick = ({keys}) => {
    setStoreData('wbsTreeExpandKeys',keys)
    TreeAutoExpandKeys.value = keys || []
}

//双击事件
const isDrawer = ref(false)
const NodeTreeDblClick = ({node,data}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    primaryKeyId.value = data?.primaryKeyId || ''
    isDrawer.value = true;
    getTableDataAll()
}
const drawerClose = () => {
    isDrawer.value = false;
    ListItemDatas.value = []
}

//导图树菜单被点击
const NodeTreeMenuClick = async ({key,node,data}) => {
    nodeItemInfo.value = node
    nodeDataInfo.value = data
    setTreeMenuDataClick({key,node,data})
}

//处理菜单被点击数据
const setTreeMenuDataClick = ({key,node,data}) => {
    const tabKey = wbsTypeTabKey.value
    if (key === 'mark' || key === 'cancel_mark') {
        firstItemBox()
    } else if (key === 'edit') {
        if (tabKey === 'tree') {
            const parent = deepClone(node?.parent?.data || {})
            formEditNodeModel.value = {...deepClone(data), parent: parent}
        } else if (tabKey === 'map') {
            const parent = deepClone(node?.parentNodes?.data || {})
            formEditNodeModel.value = {...deepClone(data), parent: parent}
        }
        editNodeModal.value = true
    } else if (key === 'copy') {
        if (tabKey === 'tree') {
            const parent = deepClone(node?.parent?.data || {})
            formCopyNodeModel.value = {...deepClone(data), parent: parent}
        } else if (tabKey === 'map') {
            const parent = deepClone(node?.parentNodes?.data || {})
            formCopyNodeModel.value = {...deepClone(data), parent: parent}
        }
        copyNodeTabKey.value = '1'
        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') {
        document.getElementById('upload-drawing').click()
    } else if (key === 'del') {
        
        if(data['colorStatus']!==1){
             window?.$message?.warning('该节点已存在上报数据，不允许删除')
           
        }else{
            delModalClick()
        }
        
    } else if (key === 'sort') {
        let nodes = [], childNodes = []
        if (tabKey === 'tree') {
            childNodes = node?.parent?.childNodes || []
        } else if (tabKey === 'map') {
            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.$loading?.service({
        lock: true,
        text: '图纸上传中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return true
}
//上传完成
const uploadFinish = async (response) => {
    const res = getObjValue(response.data)
    const info = nodeDataInfo.value;
    if (res?.link) {
        const { error, code, data } = await wbsApi.saveContractTreeDrawings({
            fileUrl: res?.link,
            id: info['drawingsId'],
            primaryKeyId: info['primaryKeyId']
        },false)
        //处理数据
        loadingReactive.value.close();
        if (!error && code === 200) {
            nodeDataInfo.value['drawingsId'] = data
            nodeDataInfo.value['fileUrl'] = res?.link
            window?.$message?.success('图纸上传成功')
        } else {
            window?.$message?.error('图纸保存失败')
        }
    } else {
        loadingReactive.value.close();
        window?.$message?.error('图纸上传失败')
    }
}
//上传失败
const uploadError = () => {
    loadingReactive.value.close();
    window?.$message?.error('图纸上传失败')
}

//确认标记为首件
const firstItemBox = () => {
    const info = nodeDataInfo.value;
    window?.$messageBox?.alert(`<div class="text-base font-bold">
            <span>请确认将</span>
            <span class="text-main">【${info['title']}】</span>
            <span>${info['isFirst']?'取消':''}标记为首件</span>
        </div>`, '标记首件制', {
        showCancelButton: true,
        dangerouslyUseHTMLString: true,
        callback: (action) => {
            if (action === 'confirm') {
                firstItemHttp(info)
            }
        }
    })
}
//首件请求
const firstItemHttp = async (info) => {
    const { error, code } = await wbsApi.wbsTreeFirstSave({
        primaryKeyId: info['primaryKeyId'],
        saveOrDeleted: !!info['isFirst']?1:0,
    })
    //处理数据
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        window?.location?.reload()  //刷新页面
    }
}

//编辑节点
const editNodeModal = ref(false)

//获取节点类型
const nodeTypeData = ref([])
const getDictionaryApi = async () => {
    const { data } = await getDictionary({
        code: 'wbs_node_type'
    })
    //处理数据
    let newArr = []
    const newData = getArrValue(data)
    for (let i = 0; i < newData.length; i++) {
        newArr.push({
            label: newData[i]['dictValue'],
            value: Number(newData[i]['dictKey']),
        })
    }
    nodeTypeData.value = newArr
}

const formEditNodeRef = ref(null)
const formEditNodeModel = ref({})
const formEditNodeRules = {
    title: {
        required: true,
        trigger: 'blur',
        message: "请输入节点名称"
    },
}
const editNodeLoading = ref(false)
//保存编辑节点数据
const editNodeClick = async () => {
    const validate = await formValidate(formEditNodeRef.value)
    if (validate) {
        //发起请求
        editNodeLoading.value = true
        const { primaryKeyId, title, partitionCode } = formEditNodeModel.value
        const { error, code } = await wbsApi.wbsTreeUpdateNode({
            nodeName: title || '',
            pKeyId: primaryKeyId || '',
            partitionCode: partitionCode || ''
        })
        //处理数据
        editNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('修改成功')
            nodeDataInfo.value['title'] = title || ''
            nodeDataInfo.value['partitionCode'] = partitionCode || ''
            editNodeModal.value = false
            window?.location?.reload()  //刷新页面
        }
    }
}

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

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

//复制节点变量
const copyNodeLoading = ref(false)
const formCopyNodeModel = ref({})
const copyNodeTable = ref([])

//复制树被点击
const copyNodeElTreeClick = ({data}) => {
    const TabKey = copyNodeTabKey.value;
    const {title, type} = formCopyNodeModel.value;
    if (TabKey === '2') {
        //1 单位工程，2 分部工程，3 子分部工程，4 分项工程， 5 子分项工程，6 工序
        //工序节点不能复制到工序节点下面
        // if (type === 6 && (data['type'] === 4 || data['type'] === 5 || data['type'] == 6)) {
        //     setCopyNodeTable(data, title)
        // }
        if (type === 6 && (data['type'] === 4 || data['type'] === 5 || data['type'] !== 6)) {
            setCopyNodeTable(data, title)
        }
        if (type === 5 && data['type'] === 4) {
            setCopyNodeTable(data, title)
        }
        if (type === 4 && (data['type'] === 2 || data['type'] === 3)) {
            setCopyNodeTable(data, title)
        }
        if (type === 3 && data['type'] === 2) {
            setCopyNodeTable(data, title)
        }
        if (type === 2 && data['type'] === 1) {
            setCopyNodeTable(data, title)
        }
        if (type === 1 && data['type'] === 1) {
            setCopyNodeTable(data, title)
        }
    } else if (TabKey === '3') {
        if (data['notExsitChild']) {
            setCopyNodeTable(data, data?.title)
        }
    }
}

const setCopyNodeTable = (data, title) => {
    copyNodeTable.value.push({
        title: data?.title || '',
        nodeName: title || '',
        primaryKeyId: data?.primaryKeyId || ''
    })
}

//节点表单
const formCopyNodeModelRef = ref(null)
const formCopyNodeModelRules = {
    title: {
        required: true,
        trigger: "blur",
        message: "请输入节点名称"
    }
}
//表格节点表单
const copyNodeTableRef = ref(null)
const copyNodeTableRules = {
    nodeName: {
        required: true,
        trigger: "blur",
        message: "请输入节点名称"
    }
}
//删除选中的节点
const copyNodeTableDel = (index) => {
    copyNodeTable.value.splice(index,1)
}
//复制节点
const copyNodeClick = async () => {
    const type = copyNodeTabKey.value
    const form = formCopyNodeModel.value
    const table = copyNodeTable.value
    //效验数据
    if (type === '1') {
        const validate = await formValidate(formCopyNodeModelRef.value)
        if (validate) await copyContractTreeNode(type, form,[])
    } else if (type === '2') {
        if (table.length > 0) {
            const validate = await formValidate(copyNodeTableRef.value)
            if (validate) await copyContractTreeNode(type, form,table)
        } else {
            window?.$message?.warning('请先在左侧选择要复制到的节点')
        }
    } else if (type === '3') {
        if (table.length > 0) {
            await copyContractNodeSubmitBusinessData(form,table)
        } else {
            window?.$message?.warning('请先在左侧选择要复制的节点')
        }
    }
}
//单个复制、多份复制请求
const copyContractTreeNode = async (type, form,table) => {
    copyNodeLoading.value = true
    const {error, code} = await wbsApi.copyContractTreeNode({
        copyType: type,
        needCopyNodeName: form?.title || '',
        needCopyPrimaryKeyId: form?.primaryKeyId || '',
        parentPrimaryKeyId: form?.parent?.primaryKeyId || '',
        copyBatchToPaths: table
    })
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('复制成功')
        copyNodeLoading.value = false
        copyNodeModal.value = false
        window?.location?.reload()  //刷新页面
    }
}
//复制数据
const copyContractNodeSubmitBusinessData = async (form,table) => {
    copyNodeLoading.value = true
    const {error, code} = await wbsApi.copyContractNodeSubmitBusinessData({
        needCopyPrimaryKeyId: form?.primaryKeyId || '',
        copyBatchToPaths: table
    })
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('复制成功')
        copyNodeLoading.value = false
        copyNodeModal.value = false
        window?.location?.reload()  //刷新页面
    }
}

//新增节点
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 primaryKeyId = nodeDataInfo.value?.primaryKeyId || ''
        const {error, code} = await wbsApi.saveContractTreeNode({
            projectId: projectId.value,
            contractId: contractId.value,
            saveType: addTreeNodeType.value,
            allSelectedList: allSelectedList.value,
            halfSelectedList: halfSelectedList.value,
            currentNodePrimaryKeyId: primaryKeyId
        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('新增成功')
            addNodeModal.value = false
            window?.location?.reload()  //刷新页面
        }
    }
}

//删除节点
const delModalClick  = () => {
    window?.$messageBox?.alert('请谨慎考虑后，确认是否需要删除？', '删除节点', {
        showCancelButton: true,
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                removeContractTreeNode()
            }
        }
    })
}
const removeContractTreeNode = async () => {
    const {error, code} = await wbsApi.removeContractTreeNode({
        ids: nodeDataInfo.value?.primaryKeyId || ''
    })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        window?.location?.reload()  //刷新页面
    }
}

//调整排序
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 { error, code } = await wbsApi.diySortTreeNode({sortList})
    sortNodeLoading.value = false
    //判断状态
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        sortNodeModal.value = false
        window?.location?.reload()  //刷新页面
    }
}

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

//设置滚动条位置
const ListItemScrollRef = ref(null)
const ListItemOffsetTop = (offsetTop) => {
    if (offsetTop > 0) {
        setTimeout(() => {
            ListItemScrollRef.value?.setScrollTop(offsetTop)
        }, 350)
    } else {
        ListItemScrollRef.value?.setScrollTop(offsetTop)
    }
}

//获取数据列表
const ListItemDatas = ref([]);
const ListItemLoading = ref(false);
const searchNodeAllTable = async () => {
    ListItemDatas.value = []
    const info = nodeDataInfo.value;
    ListItemLoading.value = true
    const {error, code, data} = await wbsApi.searchNodeAllTable({
        projectId: projectId.value,
        contractId: contractId.value,
        primaryKeyId: info['primaryKeyId'],
        type: authBtnTabKey.value
    })
    //处理数据
    ListItemLoading.value = false
    if (!error && code === 200) {
        ListItemDatas.value = getArrValue(data)
    } else {
        ListItemDatas.value = []
    }
}

//查询状态
const NodeStatus = ref('1')
const queryNodeStatus = async () => {
    const info = nodeDataInfo.value;
    const {error, code, data} = await wbsApi.queryNodeStatus({
        primaryKeyId: info['contractIdRelation'] ? info['id'] : info['primaryKeyId'],
        classify: authBtnTabKey.value
    })
    //1 未填报，2待上报，3已上报
    if (!error && code === 200) {
        NodeStatus.value = data ?? '1'
    } else {
        NodeStatus.value = '1'
    }
}

//批量上报
const reportIds = ref('')
const reportTaskName = ref('')
const reportAddition = ref({})
const showReportModal = ref(false)
const reportLoading = ref(false)
const reportTypeData = ref([])
const reportModalClick = async () => {
    const info = nodeDataInfo.value;
    const rows = ListItemDatas.value;
    if (rows.length > 0) {
        reportLoading.value = true
        const taskCheck = await eVisaTaskCheckApi({
            projectId: projectId.value,
            contractId: contractId.value
        })
        //处理数据
        let newArr = [];
        for (let i = 0; i < rows.length; i++) {
            newArr.push(rows[i]['isTypePrivatePid'])
        }
        reportTypeData.value = newArr
        reportLoading.value = false
        if (taskCheck) {
            //初始弹出弹窗，防呆
            reportIds.value = info['primaryKeyId']
            reportAddition.value = {
                classify: authBtnTabKey.value,
                contractIdRelation: info['contractIdRelation'],
            }
            showReportModal.value = true
            //请求文件题名
            const {data} = await wbsApi.queryDocumentTitle({
                primaryKeyId: info['primaryKeyId'],
                classify: authBtnTabKey.value
            })
            reportTaskName.value = isString(data)? data : ''
        }
    } else {
        window.$message?.warning('暂无相关数据')
    }
}

//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableDataAll()
    window?.location?.reload()  //刷新页面

}

//表单变量
const ListItemRef = ref(null)
const ListItemsRef = ref(null)

//保存
const tableFormSaveLoading = ref(false)
const tableFormSaveClick = async () => {
    //获取数据
    let FormData = [], FormRegExpJson = {};
    if (isDrawer.value) {
        FormData = ListItemsRef.value?.getFormData()
        FormRegExpJson = ListItemsRef.value?.getFormRegExpJson()
    } else {
        FormData = ListItemRef.value?.getFormData()
        FormRegExpJson = ListItemRef.value?.getFormRegExpJson()
    }
    //效验数据
    if (getObjNullValue(FormRegExpJson)) {
        setFormRegExpJson(FormRegExpJson)
    } else if (FormData.length > 0) {
        tableFormSaveLoading.value = true
        const {error, code} = await wbsApi.saveExcelBussData({
            dataInfo: {orderList: FormData}
        })
        tableFormSaveLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('保存成功')
            bussPdfsClick()
            getTableDataAll()
        }
    } else {
        //http://testcandao.hcxxy.com/bug-view-819.html
        bussPdfsClick()
    }
}

//效验数据
const setFormRegExpJson = (FormRegExpJson) => {
    let nodeName = '', itemId = '';
    Object.keys(FormRegExpJson).forEach(key => {
        const name = FormRegExpJson[key]?.nodeName ?? ''
        if (name) {
            if (nodeName) {
                nodeName += ',' + name
            } else {
                nodeName = name
                itemId = FormRegExpJson[key]?.itemId
            }
        }
    })
    //const activeKey = ListItemRef.value?.getActiveKey()
    //弹出提示
    const val = '<div style="font-size: 16px;">请先完善  <span style="color:#1ECC95;">' + nodeName + '</span>  的数据内容</div>'
    window?.$messageBox?.alert(val, '表单完善提醒', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        callback: (action) => {
            if (action === 'confirm') {
                ListItemRef.value?.setActiveKey(itemId)
                ListItemOffsetTop(0)
                setTimeout(() => {
                    const offsetTop = document.getElementById(itemId)?.offsetTop
                    ListItemOffsetTop(offsetTop)
                }, 350)
            }
        }
    })
}


//多表预览
const bussPdfsLoading = ref(false)
const bussPdfsClick = async () => {
    const info = nodeDataInfo.value;
    bussPdfsLoading.value = true
    const {error, code, data} = await wbsApi.getBussPdfs({
        nodeId: info?.primaryKeyId || '',
        classify: authBtnTabKey.value,
        projectId: projectId.value,
        contractId: contractId.value
    })
    tableFormSaveLoading.value = false
    bussPdfsLoading.value = false
    if (!error && code === 200) {
        window.open(data,'_blank')
    } else {
        window.$message?.warning('获取PDF失败')
    }
}

//撤回上报流程
const abolishOneClick = () => {
    window?.$messageBox?.alert('请谨慎考虑后，是否确定撤回？', '撤回上报', {
        showCancelButton: true,
        confirmButtonText: '确定撤回',
        cancelButtonText: '取消',
        callback: (action) => {
            if (action === 'confirm') {
                abolishOneSave()
            }
        }
    })
}

//撤回请求
const abolishOneSave = async () => {
    const info = nodeDataInfo.value;
    const {error, code} = await wbsApi.abolishOne({
        primaryKeyId:  info?.primaryKeyId || '',
        classify: authBtnTabKey.value
    })
    if (!error && code === 200) {
        window.$message?.success('撤回成功')
        getTableDataAll()
        window?.location?.reload()  //刷新页面

    }
}


//划分变更
const divisionClick = () => {
    router.push({
        path: '/data-fill/division'
    })
}


//左右拖动，改变树形结构宽度
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;
    }
}
.img-preview-box {
    position: relative;
    height: 100%;
    width: 100%;
}
</style>
