<template>
    <div class="h-full">
        <div v-if="wbsTypeTabKey === 'tree'" v-loading="nodeSaveLoading" class="hc-layout-box" element-loading-text="批量保存数据中...">
            <div
                id="wbs-left-tree" :class="[isWbsTreeShow ? 'show' : '', isMouseTree ? 'on-transition' : '']"
                :style="`width:${isWbsTreeShow ? leftWidth : 0}px;`"
                class="hc-layout-left-box"
            >
                <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 clearable placeholder="请输入名称关键词检索"
                            size="large" @keyup="searchTreeKeyUp"
                        >
                            <template #suffix>
                                <HcIcon name="search-2" ui="text-xl iscusor" @click="searchTreeClick" />
                            </template>
                        </el-input>
                    </div>
                    <div v-if="isShowLeft" id="hc-tree-scrollbar" v-loading="treeLoading" class="hc-tree-scrollbar" element-loading-text="获取数据中...">
                        <!-- <HcTreeV2
                            :isShow="isSearchTree"
                            :datas="searchTreeData"
                            :height="searchTreeHeight"
                            :isMark="TreeMark"
                            :menus="ElTreeMenu"
                            :searchVal="searchTreeVal"
                            isCounts
                            isType
                            @menuTap="ElTreeMenuClick"
                            @nodeTap="wbsElTreeClick"
                        /> -->
                        <el-scrollbar v-show="isSearchTree" class="scroll-bar-right-16">
                            <HcDataTree
                                :datas="searchTreeData"
                                :is-mark="TreeMark"
                                :menus="ElTreeMenu"
                                is-counts
                                is-type
                                :auto-expand-keys="TreeAutoExpandKeys"
                                default-expand-all
                                @nodeTap="wbsElTreeClick"
                                @menuTap="ElTreeMenuClick"
                            />
                        </el-scrollbar>
                        <el-scrollbar v-show="!isSearchTree" class="scroll-bar-right-16">
                            <HcLazyTree
                                ref="wbstree"
                                :auto-expand-keys="TreeAutoExpandKeys"
                                :is-mark="TreeMark"
                                :menus="ElTreeMenu"
                                is-counts
                                is-type
                                show-checkbox
                                check-strictly
                                @load="treeLoadNode"
                                @menuTap="ElTreeMenuClick"
                                @nodeLoading="ElTreeNodeLoading"
                                @nodeTap="wbsElTreeClick"
                                @check="ElTreeNodeCheck"
                            />
                        </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 id="wbs-content-box" class="hc-layout-content-box">
                <!---展开收缩树 -->
                <div class="hc-expansion-contraction-tree" @click="setWbsTreeShow">
                    <HcIcon v-show="isWbsTreeShow" name="arrow-left-s" />
                    <HcIcon v-show="!isWbsTreeShow" name="arrow-right-s" />
                </div>

                <HcCard action-ui="text-center">
                    <template #header>
                        <HcNewSwitch
                            :datas="authBtnTabdata" :keys="authBtnTabKey" :round="false"
                            size="default" @change="authBtnTabClick"
                        />
                    </template>
                    <!-- 切换导图或树形模式 -->
                    <template #extra>
                        <HcNewSwitch :datas="wbsTypeTab" :keys="wbsTypeTabKey" @change="wbsTypeTabChange" />
                    </template>
                    <!-- 清表列表 -->
                    <el-scrollbar v-if="ListItemDatas.length > 0" ref="ListItemScrollRef" v-loading="ListItemLoading">
                        <CollapseForm
                            ref="ListItemRef"
                            :tree-auto-expand-keys="TreeAutoExpandKeys"
                            :classify="authBtnTabKey"
                            :contract-id="contractId"
                            :datas="ListItemDatas"
                            :draw-type="!isDrawType"
                            :primary-key-id="primaryKeyId"
                            :status="NodeStatus"
                            :tenant-id="userInfo?.tenant_id"
                            :wbs-temp-id="projectInfo?.referenceWbsTemplateIdTrial"
                            :wbs-type="2"
                            :treenode-data-info="nodeDataInfo"
                            :newlistdata="newlistdata"
                            @offsetTop="ListItemOffsetTop"
                            @renew="getTableDataAll"
                            @getList="searchNodeAllTable1"
                        />
                    </el-scrollbar>

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

                    <!-- 底部按钮区域 -->
                    <template #action>
                        <div class="hc-table-form-action-tip">
                            <el-alert
                                :closable="false"
                                class="hc-alert"
                                show-icon
                                style=""
                                title="完善资料填写后记得一定要保存哦"
                                type="warning"
                            />
                        </div>

                        <el-button :loading="nodeSaveLoading" hc-btn type="primary" style="position: absolute;left: 10px;" @click="NodeSaveClick">辅助保存</el-button>

                        <HcTooltip v-if="NodeStatus !== '3'" keys="wbs_save">
                            <el-button
                                :disabled="NodeStatus === '3' || ListItemDatas.length <= 0"
                                :loading="tableFormSaveLoading"
                                hc-btn
                                style="width:150px;font-weight: bold;font-size:large"
                                type="primary"
                                @click="tableFormSaveClick"
                            >
                                <HcIcon name="save" />
                                <span>保存</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip v-if="NodeStatus !== '3'" keys="wbs_report">
                            <el-button
                                :disabled="NodeStatus === '3' || NodeStatus === '1'" :loading="reportLoading"
                                hc-btn @click="reportModalClick"
                            >
                                <HcIcon name="send-plane-2" />
                                <span>上报</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip keys="wbs_preview">
                            <el-button
                                :disabled="NodeStatus === '1'" :loading="bussPdfsLoading" hc-btn
                                @click="bussPdfsClick"
                            >
                                <HcIcon name="eye" />
                                <span>预览</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip v-if="NodeStatus === '3'" keys="wbs_abolish">
                            <el-button hc-btn :laoding="abolishLoaing" @click="abolishOneClick">
                                <HcIcon name="arrow-go-back" />
                                <span>撤回上报流程</span>
                            </el-button>
                        </HcTooltip>
                        <HcTooltip keys="wbs_views_drawings">
                            <el-button :disabled="!nodeDataInfo?.fileUrl" hc-btn @click="viewsDrawings">
                                <HcIcon name="image" />
                                <span>图纸</span>
                            </el-button>
                        </HcTooltip>
                        <el-button hc-btn @click="attachmentModalShow">
                            <HcIcon name="file" />
                            <span>附件</span>
                        </el-button>
                        <el-button hc-btn :disabled="isCanadd" @click="addFilelist">
                            <HcIcon name="add" />
                            <span>附件添加</span>
                        </el-button>
                        <el-button v-if="authBtnTabKey === '2'" hc-btn :loading="syncdataloading" @click="syncdata">
                            <HcIcon name="refresh" />
                            <span>同步质检资料</span>
                        </el-button>
                    </template>
                </HcCard>
            </div>
        </div>
        <HcCard v-if="wbsTypeTabKey === 'map'" id-ref="wbs-node-tree-card-target">
            <template #header>
                <HcTooltip keys="wbs_views_division_btn">
                    <el-button class="mr-10" hc-btn type="primary" @click="divisionClick">
                        <HcIcon :line="false" name="node-tree" />
                        <span>划分变更</span>
                    </el-button>
                </HcTooltip>
                <HcNewSwitch
                    v-if="isDrawer" :datas="authBtnTabdata" :keys="authBtnTabKey" :round="false"
                    size="default" @change="authBtnTabClick"
                />
            </template>
            <template #extra>
                <HcNewSwitch :datas="wbsTypeTab" :keys="wbsTypeTabKey" @change="wbsTypeTabChange" />
            </template>
            <NodeTree
                ref="NodeTreeRef"
                :accordion="NodeTreeAccordion"
                :auto-expand-keys="TreeAutoExpandKeys"
                :contract-id="contractId"
                :is-mark="TreeMark"
                :menus="ElTreeMenu"
                :project-id="projectId"
                @menuClick="NodeTreeMenuClick"
                @nodeClick="NodeTreeClick"
                @nodeDblClick="NodeTreeDblClick"
            />
            <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" action-ui="text-center" to-id="wbs-node-tree-card-target" @close="drawerClose">
                <!-- 清表列表 -->
                <el-scrollbar v-if="ListItemDatas.length > 0" ref="ListItemScrollRef">
                    <CollapseForm
                        ref="ListItemsRef"
                        :classify="authBtnTabKey"
                        :contract-id="contractId"
                        :datas="ListItemDatas"
                        :draw-type="isDrawType"
                        :primary-key-id="primaryKeyId"
                        :status="NodeStatus"
                        :tenant-id="userInfo?.tenant_id"
                        :wbs-temp-id="projectInfo?.referenceWbsTemplateIdTrial"
                        :wbs-type="2"
                        @offsetTop="ListItemOffsetTop"
                        @renew="getTableDataAll"
                    />
                </el-scrollbar>
                <HcStatus v-else text="暂无表单" />
                <!-- 底部按钮区域 -->
                <template #action>
                    <HcTooltip v-if="NodeStatus !== '3'" keys="wbs_save">
                        <el-button
                            :disabled="NodeStatus === '3' || ListItemDatas.length <= 0"
                            :loading="tableFormSaveLoading"
                            hc-btn
                            type="primary"
                            @click="tableFormSaveClick"
                        >
                            <HcIcon name="save" />
                            <span>保存</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip v-if="NodeStatus !== '3'" keys="wbs_report">
                        <el-button
                            :disabled="NodeStatus === '3' || NodeStatus === '1'"
                            :loading="reportLoading"
                            hc-btn
                            @click="reportModalClick"
                        >
                            <HcIcon name="send-plane-2" />
                            <span>上报</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="wbs_preview">
                        <el-button
                            :disabled="NodeStatus === '1'"
                            :loading="bussPdfsLoading"
                            hc-btn
                            @click="bussPdfsClick"
                        >
                            <HcIcon name="eye" />
                            <span>预览</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip v-if="NodeStatus === '3'" keys="wbs_abolish">
                        <el-button hc-btn>
                            <HcIcon name="arrow-go-back" />
                            <span>撤回上报流程</span>
                        </el-button>
                    </HcTooltip>
                    <HcTooltip keys="wbs_views_drawings">
                        <el-button :disabled="!nodeDataInfo?.fileUrl" hc-btn @click="viewsDrawings">
                            <HcIcon name="image" />
                            <span>图纸</span>
                        </el-button>
                    </HcTooltip>
                    <el-button hc-btn @click="attachmentModalShow">
                        <HcIcon name="file" />
                        <span>附件</span>
                    </el-button>
                    <el-button hc-btn @click="drawerClose">
                        <HcIcon name="close" />
                        <span>关闭填报页面</span>
                    </el-button>
                </template>
            </HcDrawer>
        </HcCard>

        <!-- 上传文件 -->
        <HcUploadFile
            ref="HcUploadFileRef"
            :options="uploadFileOptions"
            :params="uploadFileParams"
            :echo-params="uploadFileEchoParams"
            @success="uploadFileSuccess"
            @item="uploadFileItem"
            @finish="uploadFileFinish"
        />

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

        <!-- 编辑节点 -->
        <HcDialog
            :loading="editNodeLoading" :show="editNodeModal" title="编辑节点" widths="600px"
            @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.nodeType" 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-item class="hc-position-input-icon" label="模板位置">
                    <el-input
                        v-model="formEditNodeModel.position" :autosize="{ minRows: 3, maxRows: 6 }"
                        type="textarea"
                    />
                    <el-tooltip content="一键复制模板位置">
                        <HcIcon name="file-copy-2" @click="copyPositionText(formEditNodeModel.position)" />
                    </el-tooltip>
                </el-form-item>
            </el-form>
        </HcDialog>

        <!-- 复制节点 -->
        <HcDialog
            :loading="copyNodeLoading" :show="copyNodeModal" :widths="copyNodeTabKey === '1' ? '600px' : '1200px'"
            loading-text="复制节点中，请耐心等待..."
            title="复制节点" @close="copyNodeModal = false"
        >
            <div class="header-new-switch">
                <el-form
                    ref="formCopyNodeModelRef" :model="formCopyNodeModel" label-position="left"
                    :rules="formCopyNodeModelRules" label-width="auto" size="large"
                >
                    <el-form-item label="是否复制数据" prop="isCopyData" style="margin-bottom: 0;">
                        <!-- <el-input v-model="formCopyNodeModel.classify" placeholder="请输入节点名称"/> -->
                        <el-radio-group v-model="isCopyData">
                            <el-radio :label="1">
                                是
                            </el-radio>
                            <el-radio :label="0">
                                否
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-if="isCopyData === 1" label="所属方" prop="classify" style="margin-bottom: 0;">
                        <!-- <el-input v-model="formCopyNodeModel.classify" placeholder="请输入节点名称"/> -->
                        <el-checkbox-group v-model="classifyList">
                            <el-checkbox label="施工" />
                            <el-checkbox label="监理" />
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                <!-- HcNewSwitch :datas="authBtnTabdata" :keys="classifyType" :round="false" size="default"
                             @change="classifyTypeTabClick"/ -->
            </div>
            <div v-if="copyNodeTabKey === '1'" class="copy-node-form-box">
                <el-form
                    ref="formCopyNodeModelRef" :model="formCopyNodeModel"
                    :rules="formCopyNodeModelRules" label-width="auto" size="large"
                >
                    <el-form-item v-if="copyNodeTabKey === '1'" label="节点名称" prop="title" style="margin-bottom: 0;">
                        <el-input v-model="formCopyNodeModel.title" placeholder="请输入节点名称" />
                    </el-form-item>
                    <el-form-item
                        v-if="copyNodeTabKey === '1'" label="划分编号" prop="partitionCode"
                        style="margin-top: 10px;"
                    >
                        <el-input v-model="formCopyNodeModel.partitionCode" placeholder="请输入划分编号" />
                    </el-form-item>
                </el-form>
            </div>
            <div v-if="copyNodeTabKey === '3'" class="copy-node-form-box">
                <el-form
                    ref="formCopyNodeModelRef" :model="formCopyNodeModel"
                    :rules="formCopyNodeModelRules" label-width="auto" size="large"
                >
                    <el-form-item label="所属方" prop="classify" style="margin-bottom: 0;">
                        <!-- <el-input v-model="formCopyNodeModel.classify" placeholder="请输入节点名称"/> -->
                        <el-checkbox-group v-model="classifyList">
                            <el-checkbox label="施工" />
                            <el-checkbox label="监理" />
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <div v-if="copyNodeTabKey !== '1'" class="copy-node-many-box">
                <div class="copy-node-many-tree">
                    <el-scrollbar>
                        <HcLazyTree :auto-expand-keys="TreeAutoExpandKeys" is-type @load="treeLoadNode" @nodeTap="copyNodeElTreeClick" />
                    </el-scrollbar>
                </div>
                <div class="copy-node-many-table">
                    <el-scrollbar>
                        <el-table :data="copyNodeTable" border stripe>
                            <el-table-column label="复制到的位置" prop="title" />
                            <el-table-column v-if="copyNodeTabKey === '2'" label="节点名称" prop="nodeName">
                                <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 v-if="copyNodeTabKey === '2'" label="划分编号" prop="partitionCode">
                                <template #default="{ row }">
                                    <el-form
                                        ref="copyNodeTableRef" :model="row" :rules="copyNodeTableRules"
                                        label-width="0" size="large"
                                    >
                                        <el-form-item prop="partitionCode" style="margin-bottom: 0;">
                                            <el-input v-model="row.partitionCode" placeholder="请输入划分编号" />
                                        </el-form-item>
                                    </el-form>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="操作" prop="action" width="120">
                                <template #default="{ _, $index }">
                                    <el-button plain type="danger" @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
                                v-if="item?.key === copyNodeTabKey" plain size="large" type="primary"
                                @click="copyNodeTabChange(item?.key)"
                            >
                                {{ item.name }}
                            </el-button>
                            <el-button v-else bg size="large" text @click="copyNodeTabChange(item?.key)">
                                {{ item.name }}
                            </el-button>
                        </template>
                    </div>
                    <div class="right">
                        <el-button :disabled="copyNodeLoading" size="large" @click="copyNodeModal = false">
                            取消
                        </el-button>
                        <el-button :loading="copyNodeLoading" hc-btn type="primary" @click="copyNodeClick">
                            提交
                        </el-button>
                    </div>
                </div>
            </template>
        </HcDialog>

        <!-- 新增子节点 -->
        <HcDialog
            :loading="addNodeLoading" :show="addNodeModal" loading-text="新增节点中，请耐心等待..."
            title="新增子节点"
            widths="720px" @close="addNodeModal = false"
        >
            <el-alert
                :closable="false" title="双击节点，可编辑节点名称，编辑完成后，请按回车或输入框消失后，再点提交"
                type="warning"
            />
            <HcTreeNode
                v-if="addTreeNodeType === '1'"
                :node-id="addTreeNodeId"
                :old-id="addTreeNodeOldId"
                :contract-id="contractId"
                :wbs-id="projectInfo.referenceWbsTemplateId"
                :project-id="projectId"
                @check-change="addTreeNodeCheckChange"
            />
            <HcTreeNode
                v-if="addTreeNodeType === '2'"
                :node-id="addTreeNodeId"
                :old-id="addTreeNodeOldId"
                :contract-id="contractId"
                :wbs-id="projectInfo.referenceWbsTemplateId"
                :project-id="projectId"
                strictly @check-change="addTreeNodeCheckChange"
            />
            <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 class="ml-4" label="2">
                                仅当前节点
                            </el-radio>
                        </el-radio-group>
                    </div>
                    <div class="right">
                        <el-button size="large" @click="addNodeModal = false">
                            取消
                        </el-button>
                        <el-button :loading="addNodeLoading" hc-btn type="primary" @click="addNodeClick">
                            提交
                        </el-button>
                    </div>
                </div>
            </template>
        </HcDialog>

        <!-- 调整排序 -->
        <HcDialog
            :loading="sortNodeLoading" :show="sortNodeModal" title="调整排序" widths="700px"
            @close="sortNodeModal = false" @save="sortNodeClick"
        >
            <el-alert :closable="false" title="可拖动排序，也可在后面点击图标，切换排序" type="warning" />
            <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
                :list="sortNodeData" class="sort-node-body-box list-group" ghost-class="ghost" item-key="id"
                @end="sortNodeDrag = false" @start="sortNodeDrag = true"
            >
                <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
            :addition="reportAddition"
            :contract-id="contractInfo?.contractType == 2 ? nodeDataInfo?.contractIdRelation : contractId"
            :ids="reportIds"
            :table-owner="authBtnTabKey"
            :classify-type="classType"
            :project-id="projectId"
            :show="showReportModal"
            :task-name="reportTaskName"
            :type-data="reportTypeData"
            title="批量上报审批" type="wbs" url="informationWriteQuery/taskOne"
            @finish="showReportFinish" @hide="showReportModal = false"
        />

        <!-- 查看附件 -->
        <HcDialog
            :footer="false" :show="attachmentModal" is-table title="附件列表" widths="780px"
            @close="attachmentModal = false"
        >
            <div v-if="attachmentList.length > 0" v-loading="attachmentListLoaing">
                <div v-for="item in attachmentList " :key="item.id" class="hc-attachment-card">
                    <div class="hc-attachment-header">
                        {{ item?.nodeName }}
                    </div>
                    <div class="hc-attachment-content">
                        <div v-for="item1 in item.fileList " :key="item1.id" class="hc-attachment-item">
                            <div class="hc-attachment-file-name">
                                <HcIcon name="attachment" />
                                <div class="name">
                                    {{ item1?.name }}
                                </div>
                            </div>
                            <div class="hc-attachment-btn-box">
                                <el-button plain size="small" type="primary" @click="previewFile(item1)">
                                    <HcIcon name="eye" />
                                    <span>预览</span>
                                </el-button>
                                <el-button v-if=" NodeStatus != 3" plain size="small" style="margin-left: 16px" type="danger" :loading="item1?.loading" @click="delFile(item1)">
                                    <HcIcon name="close" />
                                    <span>删除</span>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else style="height: 100%;width: 100%;">
                <HcNoData />
            </div>
        </HcDialog>

        <!-- 附件添加 -->
        <!-- 上传文件 -->
        <HcDialog :footer="false" :show="uploadModal" title="上传文件" widths="38rem" @close="uploadModalClose">
            <HcUpload :datas="uploadData" :file-list="fileListData" :is-canupload="false" action="/api/blade-manager/exceltab/add-bussfile-node" accept="application/pdf" accept-tip="允许格式：pdf" @change="uploadChange" />
        </HcDialog>
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '~src/store'
import { HcIsButton } from '~src/plugins/IsButtons'
import CollapseForm from './collapse-form/index.vue'
import NodeTree from './components/nodeTree/index.vue'
import HcTreeNode from './components/HcTreeNode.vue'
import { getTokenHeader } from '~src/api/request/header'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import {
    deepClone,
    formValidate,
    getArrValue,
    getObjVal,
    getObjValue,
    isNullES,
    isString,
    setCopyText,
} from 'js-fast-way'
import { eVisaTaskCheckApi, getDictionary } from '~api/other'
import wbsApi from '~api/data-fill/wbs'
import queryApi from '~api/data-fill/query'
import Draggable from 'vuedraggable'
import { delMessageV2 } from '~com/message/index.js'
import HcUpload from './components/HcUpload.vue'

//初始变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()

//全局变量
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 typeName = routerQuery?.type || 'tree'
//是否是抽屉
const isDrawType = ref(true)
//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])

//树搜索
const isSearchTree = ref(false)
const wbstreeKey = ref(Math.random())
const searchElTreeLoadNode = ref(true)
const searchTreeHeight = ref()
const getSearchTreeData = async () => {
    treeLoading.value = true
    const { error, code, data } = await queryApi.getTreeNodeByQueryValueAndContractId({
        contractId: contractId.value,
        queryValue: searchTreeVal.value,
        tableOwner:authBtnTabKey.value,
    })
    //判断状态
    if (!error && code === 200) {
        let treedata = getArrValue(data)
        searchTreeData.value = treedata
        treeLoading.value = false

    } else {
        treeLoading.value = false

        searchTreeData.value = []
    }

}
// const getSearchTreeData = async () => {
//     searchElTreeLoadNode.value = true
//     const contractType = Number(contractInfo.value?.contractType)
//     if (contractType === 2 || contractType === 3) {
//         const {error, code, data} = await queryApi.getTreeallJl({
//             contractId: contractId.value,
//         })
//         //判断状态
//         if (!error && code === 200) {
//             // searchTreeData.value = getArrValue(data)
//             let searchobj = getObjValue(data)
//             let searcharr = []
//             for (let key in searchobj) {
//                 searcharr.push(searchobj[key][0])
//             }
//             searchTreeData.value = searcharr
//             searchElTreeLoadNode.value = false
//             treeLoading.value = false
//         } else {
//             treeLoading.value = false
//             searchElTreeLoadNode.value = false
//             searchTreeData.value = []
//         }
//         console.log(searchTreeData.value)
//     } else {
//         searchElTreeLoadNode.value = true
//         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)
//             searchElTreeLoadNode.value = false
//             treeLoading.value = false
//         } else {
//             treeLoading.value = false
//             searchElTreeLoadNode.value = false
//             searchTreeData.value = []
//         }
//         console.log(searchTreeData.value)
//     }
// }
//监听
//监听
const searchTreeVal = ref('')
watch(() => [
    useAppState.getCollapse, searchTreeVal.value,
], ([Collapse, search]) => {
    isCollapse.value = Collapse
    if (search.length == 0) {
        isSearchTree.value = false
    }

})

//加载树需要的classType
const classType = ref('')
watch(() => [
    classType.value,
], ([classify]) => {
 if (classify) {
      //重新加载左边树
      isShowLeft.value = false
        setTimeout(()=>{
            isShowLeft.value = true
        }, 500)
 }

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

//身份按钮切换数据
const authBtnTabKey = ref('1')

//变量
const wbstree = ref(null)
const isShowLeft = ref(true)
const authBtnTabClick = (val) => {
    if (!primaryKeyId.value) {
        window?.$message?.warning('请先在左侧项目树选择一个节点')
    } else if (val['key'] !== authBtnTabKey.value) {
        authBtnTabKey.value = val['key']
        //重新加载左边树
        isShowLeft.value = false
        setTimeout(()=>{
            isShowLeft.value = true
        }, 500)
        getTableDataAll()
    }
}
//contractType,  1施工，2监理
const setContractType = (contractType) => {
    if (contractType <= 0) {
        authBtnTabKey.value = '1'
        classType.value = '1'
    } else if (contractType === 3) {
        authBtnTabKey.value = '1'
        classType.value = '1'
    } else {
        authBtnTabKey.value = contractType + ''
        classType.value = contractType + ''
    }
    setElTreeMenu(contractType)
}

const getTableDataAll = async (key) => {
    await searchNodeAllTable()
    await queryNodeStatus()
//     wbstree.value.resetNode().then((res)=>{
//         if(res){
//             searchNodeAllTable()
//             queryNodeStatus()
//         }
//  })
    //保存后自动展开到当前表单
    if (!isNullES(key)) {
        console.log(key)
        await nextTick(() => {
            ListItemRef.value?.setCollapseKey(key)
        })
    }
}

//结构类型tab数据和相关处理
const wbsTypeTabKey = ref(typeName)
const wbsTypeTab = ref([
    { key: 'map', name: '导图结构填报' },
    { key: 'tree', name: '树形结构填报' },
])
const authBtnTabdata = ref([
    { key: '1', name: '施工质检' },
    { key: '2', 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 HcUploadFileRef = ref(null)
const uploadFileOptions = ref({})
const uploadFileParams = ref({})
const uploadFileEchoParams = ref({})
//上传成功
const uploadFileSuccess = ({ echoParams, resData }) => {
    if (echoParams['type'] === 'upload-drawing' && resData?.link) {
        setUploadDrawingsData(echoParams, resData?.link)
    } else if (echoParams['type'] === 'add-fileList' && resData?.link) {
        console.log(echoParams, 'echoParams', ' resData?.link')
    } else {
        window?.$message?.error('文件上传失败')
    }
}
//上传完成
const uploadFileFinish = ()=>{
    nextTick(()=>{
        HcUploadFileRef?.value.setModalShow(false)
    })
}
//点击使用文件
const uploadFileItem = ({ item }) => {
    const { echoParams, resData } = item
    if (echoParams['type'] === 'upload-drawing' && resData?.link) {
        setUploadDrawingsData(echoParams, resData?.link)
    } else if (echoParams['type'] === 'add-fileList' && resData?.link) {
        console.log(echoParams, 'echoParams111', ' resData?.link111')
    } else {
        window?.$message?.error('文件上传失败')
    }
}

//设置图纸数据
const setUploadDrawingsData = async (echoParams, link) => {
    const info = nodeDataInfo.value
    const { error, code, data } = await wbsApi.saveContractTreeDrawings({
        fileUrl: link,
        id: echoParams['drawingsId'],
        primaryKeyId: echoParams['primaryKeyId'],
    }, false)
    //处理数据
    if (!error && code === 200) {
        if (info['primaryKeyId'] === echoParams['primaryKeyId']) {
            nodeDataInfo.value['drawingsId'] = data
            nodeDataInfo.value['fileUrl'] = link
            window?.$message?.success('图纸上传成功')
        } else {
            window?.$message?.success('图纸上传成功，由于您切换了其他节点，需要手动刷新才能查看到图纸')
        }
    } else {
        window?.$message?.error('图纸保存失败')
    }
}

const NodeTreeAccordion = ref(true)

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

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



const searchTreeData = ref([])

//回车
const searchTreeKeyUp = (e) => {
    if (e.key === 'Enter') {
        searchTreeClick()
    }
}


const treeLoading = ref(false)

const searchTreeClick = async () => {
    if (searchTreeVal.value) {
        searchTreeHeight.value = document.getElementById('hc-tree-scrollbar').offsetHeight
        isSearchTree.value = true
        //treeLoading.value = true
        getSearchTreeData()
    } else {
        isSearchTree.value = false
    }
}

//懒加载的数据
const treeLoadNode = async ({ node, item, level }, resolve) => {
    let contractIdRelation = '', parentId = '', primaryKeyId = ''
    if (level !== 0) {
        const nodeData = getObjValue(item)
        contractIdRelation = nodeData?.contractIdRelation || ''
        parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
        primaryKeyId = nodeData?.id || ''
    }
    //获取数据
    const { data } = await queryApi.queryWbsTreeData({
        contractId: contractId.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId,
        // classifyType: authBtnTabKey.value,
        classifyType: classType.value,
        tableOwner:authBtnTabKey.value,
    })
    treeLoading.value = false
    resolve(getArrValue(data))
}

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

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

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

//鼠标左键单击事件
const NodeTreeClick = ({ keys }) => {
    setStoreValue('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') {
        console.log(data, 'data')
        let form = {}
        if (tabKey === 'tree') {
            const parent = deepClone(node?.parent?.data || {})
            form = { ...deepClone(data), parent: parent }
        } else if (tabKey === 'map') {
            const parent = deepClone(node?.parentNodes?.data || {})
            form = { ...deepClone(data), parent: parent }
        }
        formEditNodeModel.value = form
        editNodeModal.value = true
        //处理路径
        let pathArr = []
        getPathName(node, pathArr)
        form.position = pathArr.join('\\')
        formEditNodeModel.value = form
    } 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 }
        }
        classifyType.value = authBtnTabKey.value
        copyNodeTabKey.value = '1'
        copyNodeTable.value = []
        copyNodeLoading.value = false
        copyNodeModal.value = true
    } else if (key === 'add') {
        console.log(data, 'data')
        addTreeNodeId.value = data?.primaryKeyId
        addTreeNodeOldId.value = data?.oldId
        addNodeLoading.value = false
        addNodeModal.value = true
    } else if (key === 'upload') {
        const info = nodeDataInfo.value
        //上传的配置
        uploadFileOptions.value = {
            url: '/api/blade-resource/oss/endpoint/put-file',
            accept: 'image/png,image/jpg,image/jpeg',
            accept_tip: 'png、jpg、jpeg',
            headers: getTokenHeader(),
            multiple: false,
        }
        uploadFileEchoParams.value = {
            type: 'upload-drawing',
            drawingsId: info['drawingsId'],
            primaryKeyId: info['primaryKeyId'],
        }
        uploadFileParams.value = {}
        HcUploadFileRef.value?.selectFile()
    } else if (key === 'del') {
        console.log(data, 'data')
        if (data['colorStatus'] === 1 || data['colorStatus'] === 2 || data['colorStatus'] === null || data['colorStatus'] === -1) {
            delModalClick()
        } else {
            window?.$message?.warning('该节点已存在上报数据，不允许删除')
        }
    } else if (key === 'sort') {
        let nodes = [], childNodes = []
        if (tabKey === 'tree') {
            childNodes = node?.parent?.childNodes || node?.parent?.children || []
        } 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
    } else if (key === 'nodetree') {
        divisionClick()
    }
}

//获取节点的路径名字
const getPathName = (node, pathArr) => {
    if (node.parent?.parent) {
        pathArr.unshift(node.data?.title.replace(/(^\s*)|(\s*$)/g, '')) //去掉头尾空格
        getPathName(node.parent, pathArr)
    } else {
        //根节点结束
        pathArr.unshift(node.data?.title.replace(/(^\s*)|(\s*$)/g, '')) //去掉头尾空格
        return pathArr
    }
}

//确认标记为首件
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('')
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 classifyList = ref([])
const copyNodeTable = ref([])
const isCopyData = ref(0)

//复制树被点击
const copyNodeElTreeClick = ({ data, node }) => {
    const TabKey = copyNodeTabKey.value
    const { title, type, partitionCode } = formCopyNodeModel.value
    if (TabKey === '2') {
        // setCopyNodeTable(data, title, partitionCode)
        //1 单位工程，2 分部工程，3 子分部工程，4 分项工程， 5 子分项工程，6 工序
//         //不能复制到本身节点下
//         //只能往上一级点击，不能跨层级点击
//         //已上报的工序节点不能点击选择
//         //如果选择的是父级节点，那不能复制到子级节点
        if (data['colorStatus'] === 2 || data['colorStatus'] == 1 || data['colorStatus'] === null || data['colorStatus'] === -1) {//已上报的工序不能点击
            if (data['id'] !== formCopyNodeModel.value.id) {//不能复制到本身节点下
                //只能往上一级点击，不能跨层级点击
                //如果选择的是父级节点，那不能复制到子级节点
                if (type === 6 && (data['type'] === 4 || data['type'] === 5 || data['type'] == 6)) {
                    setCopyNodeTable(data, title)
                }
                if (type === 5 && data['type'] === 4) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 4 && (data['type'] === 2 || data['type'] === 3)) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 3 && data['type'] === 2) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 2 && data['type'] === 1) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 1 && data['type'] === 1) {
                    setCopyNodeTable(data, title, partitionCode)
                }


            }
        } else {
            window?.$message?.warning('该节点已存在上报数据，不允许复制')
        }


    } else if (TabKey === '3') {
        console.log(1111111)
        setCopyNodeTable(data, data?.title)


    }
}


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

    })
}

//节点表单
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 classifyType = ref(authBtnTabKey.value)
const classifyTypeTabClick = ({ key }) => {
    classifyType.value = key
}

//复制节点
const copyNodeClick = async () => {
    const type = copyNodeTabKey.value
    const form = formCopyNodeModel.value
    const table = copyNodeTable.value
    let classify = ''
    let arr = []
    if (classifyList.value.length > 0) {
        classifyList.value.forEach((item) => {
            if (item === '施工') {
                arr.push(1)
            } else if (item === '监理') {
                arr.push(2)
            }
        })
        classify = arr.join(',')
    }
    //isSameNode 是否同节点 1=同节点，0=跨节点
    if (table.length > 0) {
        table.forEach((ele) => {
            if (ele.parentId === formCopyNodeModel.value.parentId || ele.id === formCopyNodeModel.value.parentId) {
                ele.isSameNode = 1
            } else {
                ele.isSameNode = 0
            }
        })
    }
    if (isCopyData.value === 1) {
        if (classify) {
            //效验数据
            if (type === '1') {
                const validate = await formValidate(formCopyNodeModelRef.value)
                if (validate) await copyContractTreeNode(type, form, [], classify)
            } else if (type === '2') {
                if (table.length > 0) {
                    const validate = await formValidate(copyNodeTableRef.value)
                    if (validate) await copyContractTreeNode(type, form, table, classify)
                } else {
                    window?.$message?.warning('请先在左侧选择要复制到的节点')
                }
            }
        } else {
            window?.$message?.warning('请选择所属方')
        }
    } else {
        if (type === '1') {
            const validate = await formValidate(formCopyNodeModelRef.value)
            if (validate) await copyContractTreeNode(type, form, [], classify)
        } else if (type === '2') {
            if (table.length > 0) {
                const validate = await formValidate(copyNodeTableRef.value)
                if (validate) await copyContractTreeNode(type, form, table, classify)
            } else {
                window?.$message?.warning('请先在左侧选择要复制到的节点')
            }
        }
    }
}
//单个复制、多份复制请求
const copyContractTreeNode = async (type, form, table, classify) => {
    copyNodeLoading.value = true
    if (type === '1') {
        const { error, code } = await wbsApi.copyContractTreeNode({
            copyType: type,
            needCopyNodeName: form?.title || '',
            partitionCode: form?.partitionCode || '',
            needCopyPrimaryKeyId: form?.primaryKeyId || '',
            parentPrimaryKeyId: form?.parent?.primaryKeyId || '',
            copyBatchToPaths: table,
            classifyType: classify,
            isCopyData:isCopyData.value,
        })
        //判断状态
        copyNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('复制成功')
            copyNodeModal.value = false
            window?.location?.reload() //刷新页面
        }
    } else {
        const { error, code } = await wbsApi.copyContractTreeNode({
            copyType: type,
            needCopyNodeName: form?.title || '',
            needCopyPrimaryKeyId: form?.primaryKeyId || '',
            parentPrimaryKeyId: form?.parent?.primaryKeyId || '',
            copyBatchToPaths: table,
            classifyType: classify,
            isCopyData:isCopyData.value,
        })
        //判断状态
        copyNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('复制成功')
            copyNodeModal.value = false
            window?.location?.reload() //刷新页面
        }
    }
}
//复制数据
const copyContractNodeSubmitBusinessData = async (form, table, classify) => {
    copyNodeLoading.value = true
    const { error, code } = await wbsApi.copyContractNodeSubmitBusinessData({
        needCopyPrimaryKeyId: form?.primaryKeyId || '',
        copyBatchToPaths: table,
        classify: classify,
    })
    //判断状态
    copyNodeLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('复制成功')
        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 || []
    console.log(keys, 'keys')
    for (let i = 0; i < keys.length; i++) {
        NodesArr.push({
            nodeName: keys[i].nodeName,
            primaryKeyId: keys[i].pKeyId,
            isPeer:keys[i].isPeer || 2,
        })
    }
    allSelectedList.value = NodesArr
    console.log( allSelectedList.value, ' allSelectedList.value')
    //半选数据
    const halfNodes = nodes.halfCheckedNodes || []
    for (let i = 0; i < halfNodes.length; i++) {
        halfArr.push({
            nodeName: halfNodes[i].nodeName,
            primaryKeyId: halfNodes[i].pKeyId,
            isPeer:halfNodes[i].isPeer || 2,
        })
    }
    halfSelectedList.value = halfArr
    console.log( halfSelectedList.value, ' halfSelectedList.value')
}

//新增节点
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 = () => {
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                removeContractTreeNode()
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
     })
}

const removeContractTreeNode = async () => {
    const loadingInstance = window.$loading.service({
        fullscreen: true,
        text: '删除节点中，请耐心等待...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const { error, code } = await wbsApi.removeContractTreeNode({
        ids: nodeDataInfo.value?.primaryKeyId || '',
    })
    //处理结果
    loadingInstance.close()
    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 newlistdata = ref([])
const searchNodeAllTable1 = async () => {
  console.log('重新获取表单列表')
    const info = nodeDataInfo.value
    const { error, code, data } = await wbsApi.searchNodeAllTable({
        projectId: projectId.value,
        contractId: contractId.value,
        primaryKeyId: info['primaryKeyId'],
        type: authBtnTabKey.value,
    })
    //处理数据
    if (!error && code === 200) {
        newlistdata.value = getArrValue(data)
    } else {
        newlistdata.value = []
    }
}
//查询状态
const NodeStatus = ref('1')
const queryNodeStatus = async () => {
    const info = nodeDataInfo.value
    if (contractInfo.value?.contractType == 1) {
        const { error, code, data } = await wbsApi.queryNodeStatus({
            primaryKeyId: info['primaryKeyId'],
            //classify:1
            classify: authBtnTabKey.value,
        })
        //1 未填报，2待上报，3已上报
        if (!error && code === 200) {
            NodeStatus.value = data ?? '1'
        } else {
            NodeStatus.value = '1'
        }
    } else {
        const { error, code, data } = await wbsApi.queryNodeStatusJl({
            // primaryKeyId: info['contractIdRelation'] ? info['id'] : info['primaryKeyId'],
            primaryKeyId: info['primaryKeyId'],
            //classify: 1
            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: contractInfo.value?.contractType == 2 ? info?.contractIdRelation : contractId.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 = await ListItemsRef.value?.getFormData()
        FormRegExpJson = await ListItemsRef.value?.getFormRegExpJson()
    } else {

        FormData = await ListItemRef.value?.getFormData()
        FormRegExpJson = await ListItemRef.value?.getFormRegExpJson()
    }
    //效验数据
    if (getObjVal(FormRegExpJson)) {
        setFormRegExpJson(FormRegExpJson)
    } else if (FormData.length > 0) {
        console.log('保存')
        tableFormSaveLoading.value = true
        console.log('FormData', FormData)
        const { error, code } = await wbsApi.saveExcelBussData({
            dataInfo: { orderList: FormData },
        })
        tableFormSaveLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('保存成功')
            // await bussPdfsClick()
             const activeKey = ListItemRef.value?.getActiveKey()
            getTableDataAll(activeKey)
        }
    } else {
        console.log('预览')
        // await 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
        contractId: contractInfo.value?.contractType == 2 ? info?.contractIdRelation : contractId.value,
    })
    tableFormSaveLoading.value = false
    bussPdfsLoading.value = false
    if (!error && code === 200) {
        window.open(data, '_blank')
    } else {
        window.$message?.warning('获取PDF失败')
    }
}

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

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

    }
}

//附件列表
const attachmentModal = ref(false)
const attachmentModalShow = () => {
    attachmentModal.value = true
    getAttachmentList()
}
const attachmentListLoaing = ref(false)
const attachmentList = ref([])
const getAttachmentList = async ()=>{
    attachmentListLoaing.value = true
    const info = nodeDataInfo.value
    const { error, code, data } = await wbsApi.tablesAndFile({
        primaryKeyId: info?.primaryKeyId || '',
        type: authBtnTabKey.value,
        contractId:contractId.value,
        projectId:projectId.value,
    })
    attachmentListLoaing.value = false
    if (!error && code === 200) {
        attachmentList.value = getArrValue(data)


    } else {
        attachmentList.value = []
    }
 }
 //预览
 const previewFile = (item)=>{
    window.open(item['domainPdfUrl'], '_blank')
 }
 //删除
 const delFile = async (item)=>{
    item.loading = true
    const { error, code } = await wbsApi.removeBussFile({
        ids: item.id,
    })
    item.loading = false
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        getAttachmentList()
        getTableDataAll()
        return true
    } else {
        return false
    }
 }
//划分变更
const divisionClick = () => {
    router.push({
        path: '/data-fill/division',
    })
}

//树展开和收起
const isWbsTreeShow = ref(true)
const setWbsTreeShow = () => {
    isWbsTreeShow.value = !isWbsTreeShow.value
}

//拷贝内容
const copyPositionText = (val) => {
    if (val) {
        //navigator.clipboard.writeText(val);
        setCopyText(val).then(() => {
            window.$message?.success('复制成功')
        }).catch(() => {
            window.$message?.error('复制失败，请手动复制')
        })
    } else {
        window.$message?.warning('没有可复制的数据')
    }
}

//左右拖动，改变树形结构宽度
const leftWidth = ref(382)
const isMouseTree = ref(false)
const onmousedown = () => {
    const leftNum = isCollapse.value ? 142 : 272
    isMouseTree.value = true
    document.onmousemove = (ve) => {
        let diffVal = ve.clientX - leftNum
        if (diffVal >= 310 && diffVal <= 900) {
            leftWidth.value = diffVal
        }
    }
    document.onmouseup = () => {
        document.onmousemove = null
        document.onmouseup = null
        isMouseTree.value = false
    }
}
//同步质检资料
const syncdataloading = ref(false)
const syncdata = async ()=>{
    ListItemRef.value?.setActiveKey('')
    const info = nodeDataInfo.value
    syncdataloading.value = true
    const { error, code, msg } = await wbsApi.syncTbadata({
        pKeyId: info?.primaryKeyId || '',

    })
    syncdataloading.value = false
    if (!error && code === 200) {
        window.$message?.success(msg)
        getTableDataAll()

        // window?.location?.reload()  //刷新页面

    }
}
//附件添加
const isCanadd = ref(true)
 const uploadModal = ref(false)
 const fileListData = ref([])
const uploadData = ref({})
const uploadModalClose = ()=>{
    uploadModal.value = false
 }
//获取附件添加列表
const getBussFileList = async (pkeyId) => {
    const { error, code, data } = await wbsApi.selectTableFileListByTen({
        pkeyid: pkeyId,
    })
    if (!error && code === 200) {
        fileListData.value = getArrValue(data)
    } else {
        fileListData.value = []
    }
}
const addFilelist = ()=>{
    getBussFileList(primaryKeyId.value)
     uploadModal.value = true
       //上传的配置
       uploadData.value = {
                classify:authBtnTabKey.value,
                nodeId: primaryKeyId.value,
            }

}
//上传文件
const uploadChange = async ({ type }) => {
    if (type === 'success') {
        getBussFileList(primaryKeyId.value)
    } else if (type === 'del') {
        getBussFileList(primaryKeyId.value)
    }
}

//树节点被选中
const treeSelectNode = ref([])
const ElTreeNodeCheck = (_, { checkedKeys }) => {
    treeSelectNode.value = getArrValue(checkedKeys)
}

//批量保存
const nodeSaveLoading = ref(false)
const NodeSaveClick = async () => {
    const keys = treeSelectNode.value
    if (keys.length <= 0) {
        window?.$message?.warning('请先在左侧项目树选择节点')
        return
    }
    //发起请求
    nodeSaveLoading.value = true
    const { error, code } = await wbsApi.save_nodeId({
        projectId: projectId.value,
        contractId: contractId.value,
        classify: authBtnTabKey.value,
        nodeIds: keys.join(),
    }, false)
    nodeSaveLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('批量保存成功')
        window?.location?.reload() //刷新页面
    }
}
</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;
    }
}
.hc-expansion-contraction-tree {
    position: absolute;
    left: -21px;
    top: 0;
    width: 18px;
    height: 100%;
    user-select: none;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #8c9099;
    font-size: 22px;
    border-radius: 5px;
    transition: background 0.2s;
    background: rgba(255, 255, 255, 0);
    &:hover {
        background: #f1f5f8;
        color: var(--el-color-primary);
    }
}
.hc-table-form-action-tip {
    position: absolute;
    bottom: 77px;
    width: 100%;
}
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">
.hc-tree-box .el-tree-node {
    .el-checkbox {
        margin-right: 0;
        .el-checkbox__inner {
            display: none;
        }
    }
    .is-leaf + .el-checkbox {
        margin-right: 8px;
        .el-checkbox__inner {
            display: inline-block;
        }
    }
}

.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%;
}
.hc-layout-content-box {
    position: relative;
}

.iscusor {
    cursor: pointer;
}
.hc-table-form-action-tip .hc-alert {
    background-color: #f1f5f8;
    display: inline;
    vertical-align: middle;
    box-shadow: -2px 0 10px 0 rgba(32, 37, 50, 0.03), 0 10px 21px 20px rgba(32, 37, 50, 0.03);
}
.copy-node-form-box {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #efeff5;
}
.hc-position-input-icon {
    position: relative;
    margin-bottom: 0;
    .el-form-item__content {
        position: relative;
        .el-textarea .el-textarea__inner {
            padding-right: 30px;
        }
        .hc-icon-i {
            position: absolute;
            right: 10px;
            bottom: 0;
            font-size: 20px;
            cursor: pointer;
            color: #0081ff;
            opacity: 1;
            transition: opacity 0.2s;
            &:hover {
                opacity: .5;
            }
        }
    }
}
</style>
