<template>
    <div class="hc-page-layout-box">
        <div
            :style="`width:${leftWidth}px;`"
            class="hc-layout-left-box bg-white"
        >
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="stack" />
                </div>
                <div class="project-name-box flex justify-between">
                    <div class="project-name">
                        {{ projectInfo.projectName }}
                    </div>

                    <hc-tooltip keys="data-division-batch-btn">
                        <el-button
                            :disabled="isLoading || leftPid === ''"
                            :loading="batchDelLoading"
                            hc-btn
                            type="danger"
                          
                            @click="batchDelClick"
                        >
                            <HcIcon name="delete" />
                            <span>删除</span>
                        </el-button>
                    </hc-tooltip>
                </div>
            </div>
            <div
                v-loading="treeLoading"
                class="hc-tree-box"
                element-loading-text="加载中..."
            >
                <el-scrollbar>
                    <HcLazyTree
                        v-model:loading="isLoading"
                        is-form-date
                        :is-auto-check="true"
                        :show-checkbox="isShowCheckbox"
                        :auto-expand-keys="treeAutoExpandKeys"
                        is-counts
                        is-type
                        :menus="ElTreeMenu"
                        ui="page-division-tree"
                        is-load-menu
                        @load="treeLoadNode"
                        @menu-tap="ElTreeMenuClick"
                        @node-loading="treeNodeLoading"
                        @node-tap="wbsElTreeClick"
                        @load-menu="loadMenu"
                        @check="leftCheckChange"
                    />
                </el-scrollbar>
            </div>
            <!-- 左右拖动 -->
            <div class="horizontal-drag-line" @mousedown="onmousedown" />
        </div>
        <div class="hc-page-content-box hc-division-page">
            <div v-if="isTemplateType" style="height: 50px" class="mb-2">
                <hc-card>
                    <div class="aligin-center flex justify-between">
                        <div>
                            <el-button
                                :loading="downloadLoading"
                                hc-btn
                                type="warning"
                                color="#1591E4"
                                class="text-white"
                                @click="divisionExportClick"
                            >
                                <HcIcon name="folder-download" />
                                <span>导出划分</span>
                            </el-button>
                            <el-button
                                hc-btn
                                color="#1591E4"
                                class="text-white"
                                @click="divisionImportCodeClick"
                            >
                                <HcIcon name="folder-upload" />
                                <span>导入划分编码</span>
                            </el-button>
                        </div>
                        <div>
                            <el-button
                   
                                hc-btn
                                type="warning"
                                @click="divisionClick"
                            >
                                <HcIcon name="git-merge" />
                                <span>节点划分</span>
                            </el-button>
                            <el-button
                                hc-btn
                                type="primary"
                      
                                @click="divisionImportClick"
                            >
                                <HcIcon name="folder-received" />
                                <span>节点导入</span>
                            </el-button>
                        </div>
                    </div>
                </hc-card>
            </div>
            <div class="basic-info">
                <HcNewCard title="当前节点基础信息">
                    <template #extra>
                        <el-checkbox
                            v-model="treeItemInfo.isConcealedWorksNode"
                            :false-value="0"
                            :true-value="1"
                            label="标记为隐蔽工程节点"
                            size="large"
                            @change="concealedChange"
                        />
                    </template>
                    <HcTable
                        :column="tableBasicColumn"
                        :datas="tableBasicData"
                        :is-index="false"
                        is-new
                    >
                        <template #nodeType="{ row }">
                            {{ getRowType(row.nodeType) }}
                        </template>
                        <template #majorDataType="{ row }">
                            {{ getRowMajorType(row.majorDataType) }}
                        </template>
                    </HcTable>
                </HcNewCard>
            </div>
            <div class="project-info" :style="contentStyle">
                <hc-new-card title="当前节点工程用表信息">
                    <template #extra>
                        <el-button
                            hc-btn
                            type="primary"
                            @click="addingFormClick"
                        >
                            <HcIcon name="add" />
                            <span>引用元素表</span>
                        </el-button>
                        <el-button
                            v-if="isTemplateType"
                            hc-btn
                            color="#3EB1A5"
                            class="text-white"
                            @click="editNamingConfigClick"
                        >
                            <HcIcon name="edit-2" />
                            <span>节点命名配置</span>
                        </el-button>
                    </template>
                    <HcTable
                        :column="tableProjectColumn"
                        :datas="tableProjectData"
                        :is-index="false"
                        is-new
                    >
                        <template #tableType="{ row }">
                            {{ getRowTableType(row.tableType) }}
                        </template>
                        <template #tableOwner="{ row }">
                            {{ getRowTableOwnerType(row.tableOwner) }}
                        </template>
                        <template #action="{ row }">
                            <HcTooltip keys="wbs_views_delexcel">
                                <el-button
                                    plain
                                    size="small"
                                    type="primary"
                                    @click="deltableexcel(row)"
                                >
                                    <HcIcon name="delete-bin" />
                                    <span>删除</span>
                                </el-button>
                            </HcTooltip>
                        </template>
                    </HcTable>
                </hc-new-card>
            </div>
            <div class="footer-box bg-white">
                <!-- <el-button hc-btn color="#A16222" @click="downloadXlsx">
                    <HcIcon name="download-2" />
                    <span>下载导入划分模板</span>
                </el-button>
                <el-button :disabled="!treePrimaryKeyId" hc-btn type="primary" @click="toImportTempClick">
                    <HcIcon name="folder-upload" />
                    <span>导入划分模板</span>
                </el-button> -->
                <el-button hc-btn color="#e03997" @click="toBackClick">
                    <HcIcon name="arrow-go-back" />
                    <span>进入资料填报</span>
                </el-button>
            </div>
        </div>

        <!-- 编辑节点 -->
        <hc-new-dialog
            v-model="editNodeModal"
            :loading="editNodeLoading"
            title="编辑节点"
            widths="600px"
            @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"
                        disabled
                        block
                    >
                        <el-option
                            v-for="item in nodeTypeData"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间" prop="digitizeTime">
                    <el-date-picker
                        v-model="formEditNodeModel.digitizeTime"
                        class="block"
                        format="YYYY-MM-DD"
                        placeholder="请选择"
                        type="date"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item
                    v-if="formEditNodeModel.nodeClass == 2"
                    label="内业资料类型"
                    prop="majorDataType"
                >
                    <el-select
                        v-model="formEditNodeModel.majorDataType"
                        block
                    >
                        <el-option
                            v-for="item in majorDataTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                    v-if="formEditNodeModel.notExsitChild"
                    label="标准分类"
                    prop="className"
                >
                    <el-select
                        v-model="formEditNodeModel.className"
                        block
                        @change="changeStandType"
                    >
                        <el-option
                            v-for="item in standardTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                    v-if="formEditNodeModel.notExsitChild"
                    label="单元名称"
                    prop="unitName"
                >
                    <el-select v-model="formEditNodeModel.unitName" block>
                        <el-option
                            v-for="item in unitNameOptions"
                            :key="item.value"
                            :label="item.dictValue"
                            :value="item.dictKey"
                        />
                    </el-select>
                </el-form-item>
                <el-row v-if="formEditNodeModel.nodeClass === 2" :gutter="24">
                    <el-col :span="12">
                        <el-form-item prop="unitNum" label="单元个数">
                            <el-input-number
                                v-model="formEditNodeModel.unitNum"
                                placeholder="请输入单元个数"
                                :controls="false"
                                :min="0"
                                :precision="0"
                                class="w-100"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="excellentNum" label="优良个数">
                            <el-input-number
                                v-model="formEditNodeModel.excellentNum"
                                placeholder="请输入优良个数"
                                :controls="false"
                                :min="0"
                                :precision="0"
                                class="w-100"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-tooltip
                    v-if="formEditNodeModel?.isReferenceNumber === 0"
                    class="item"
                    effect="light"
                    content="当前合同段未开启引用标号功能，表格无法获取，请联系维护人员处理"
                    placement="top"
                >
                    <el-form-item label="划分编号">
                        <el-input
                            v-model="formEditNodeModel.partitionCode"
                            placeholder="请输入划分编号"
                        />
                    </el-form-item>
                </el-tooltip>
                <el-form-item v-else label="划分编号">
                    <el-input
                        v-model="formEditNodeModel.partitionCode"
                        placeholder="请输入划分编号"
                    />
                </el-form-item>
            </el-form>
        </hc-new-dialog>

        <!-- 复制节点 -->
        <hc-new-dialog
            v-model="copyNodeModal"
            :loading="copyNodeLoading"
            :widths="copyNodeTabKey === '1' ? '600px' : '1200px'"
            loading-text="复制节点中，请耐心等待..."
            title="复制节点"
        >
            <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 :value="1">是</el-radio>
                            <el-radio :value="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 value="施工">施工</el-checkbox>
                            <el-checkbox value="监理">监理</el-checkbox>
                        </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 value="施工">施工</el-checkbox>
                            <el-checkbox value="监理">监理</el-checkbox>
                        </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"
                            @node-tap="copyNodeElTreeClick"
                        />
                    </el-scrollbar>
                </div>
                <div class="copy-node-many-table">
                    <el-scrollbar>
                        <el-table :data="copyNodeTable" border>
                            <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, index) in copyNodeTab"
                            :key="index"
                        >
                            <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>
        </hc-new-dialog>

        <!-- 新增子节点 -->
        <hc-new-dialog
            v-model="addNodeModal"
            :loading="addNodeLoading"
            loading-text="新增节点中，请耐心等待..."
            title="新增子节点"
            widths="720px"
            is-table
        >
            <el-alert
                :closable="false"
                title="双击节点，可编辑节点名称，编辑完成后，请按回车或输入框消失后，再点提交"
                type="warning"
            />
            <HcTreeNode
                v-if="addTreeNodeType === '1'"
                :node-id="addTreeNodeId"
                :old-id="addTreeNodeOldId"
                :contract-id="contractId"
                :project-id="projectId"
                :is-custom="isCustom"
                @check-change="addTreeNodeCheckChange"
            />
            <HcTreeNode
                v-if="addTreeNodeType === '3'"
                :node-id="addTreeNodeId"
                :old-id="addTreeNodeOldId"
                :contract-id="contractId"
                :project-id="projectId"
                :is-custom="isCustom"
                :strictly="true"
                only-children-check
                @check-change="addTreeNodeCheckChange"
            />
            <HcTreeNode
                v-if="addTreeNodeType === '2'"
                :node-id="addTreeNodeId"
                :old-id="addTreeNodeOldId"
                :contract-id="contractId"
                :project-id="projectId"
                :strictly="true"
                :is-custom="isCustom"
                @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 value="3">当前及子节点</el-radio>
                            <el-radio class="ml-4" value="2">
                                仅当前节点
                            </el-radio>
                            <el-radio value="1">当前及父节点</el-radio>
                            <!-- <el-radio value="1">当前及子节点</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>
        </hc-new-dialog>
        <!-- 新增自定义节点 -->
        <hc-new-dialog
            v-model="addNodeModalCus"
            :loading="addNodeLoadingCus"
            loading-text="新增节点中，请耐心等待..."
            title="新增自定义节点（水利工程）"
            widths="720px"
            @save="addNodeClickCur"
        >
            <!-- <div>节点名称：</div>
            <el-input
                v-model="nodeNameinput"
                placeholder="请输入节点名称"
                size="large"
                style="margin-top: 15px"
            /> -->
            <el-form
                ref="formWaterNodeRef"
                :model="formWaterNodeModel"
                :rules="formWaterNodeRules"
                label-width="auto"
                size="large"
                label-position="left"
            >
                <el-form-item label="节点名称" prop="nodeName">
                    <el-input
                        v-model="formWaterNodeModel.nodeName"
                        placeholder="请输入节点名称"
                    />
                </el-form-item>

                <el-form-item label="节点类型" prop="nodeType">
                    <el-select v-model="formWaterNodeModel.nodeType" block>
                        <el-option
                            v-for="item in nodeTypeData"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="编号" prop="number">
                    <el-input
                        v-model="formWaterNodeModel.number"
                        placeholder="请输入编号"
                    />
                </el-form-item>
            </el-form>
        </hc-new-dialog>
        <!-- 新增自定义节点-数字化文件 -->
        <hc-new-dialog
            v-model="addNodeModalData"
            :loading="addNodeLoadingData"
            loading-text="新增节点中，请耐心等待..."
            title="新增自定义节点（数字化文件）"
            widths="720px"
            @save="addNodeClickData"
        >
            <el-form
                ref="formDataNodeRef"
                :model="formDataNodeModel"
                :rules="formDataNodeRules"
                label-width="auto"
                size="large"
                label-position="left"
            >
                <el-form-item label="节点名称" prop="nodeName">
                    <el-input
                        v-model="formDataNodeModel.nodeName"
                        placeholder="请输入节点名称"
                    />
                </el-form-item>

                <el-form-item label="节点类型" prop="nodeType">
                    <el-select v-model="formDataNodeModel.nodeType" block>
                        <el-option
                            v-for="item in nodeTypeData"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否含单元评定" prop="isClassifition">
                    <el-radio-group v-model="formDataNodeModel.isClassifition">
                        <el-radio :value="1">是</el-radio>
                        <el-radio :value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="时间" prop="digitizeTime">
                    <el-date-picker
                        v-model="formDataNodeModel.digitizeTime"
                        class="block"
                        format="YYYY-MM-DD"
                        placeholder="请选择"
                        type="date"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item
                    label="内业资料类型"
                    prop="majorDataType"
                >
                    <el-select
                        v-model="formDataNodeModel.majorDataType"
                        block
                    >
                        <el-option
                            v-for="item in majorDataTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item
                            v-if="formDataNodeModel.isClassifition === 1"
                            label="标准分类"
                            prop="className"
                        >
                            <el-select
                                v-model="formDataNodeModel.className"
                                block
                                @change="changeStandType"
                            >
                                <el-option
                                    v-for="item in standardTypeOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            v-if="formDataNodeModel.isClassifition === 1"
                            label="单元名称"
                            prop="unitName"
                        >
                            <el-select
                                v-model="formDataNodeModel.unitName"
                                block
                            >
                                <el-option
                                    v-for="item in unitNameOptions"
                                    :key="item.value"
                                    :label="item.dictValue"
                                    :value="item.dictKey"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item
                            v-if="formDataNodeModel.isClassifition === 1"
                            prop="unitNum"
                            label="单元个数"
                        >
                            <el-input-number
                                v-model="formDataNodeModel.unitNum"
                                placeholder="请输入单元个数"
                                :controls="false"
                                :min="0"
                                :precision="0"
                                class="w-100"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            v-if="formDataNodeModel.isClassifition === 1"
                            prop="excellentNum"
                            label="优良个数"
                        >
                            <el-input-number
                                v-model="formDataNodeModel.excellentNum"
                                placeholder="请输入优良个数"
                                :controls="false"
                                :min="0"
                                :precision="0"
                                class="w-100"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </hc-new-dialog>
        <!-- 调整排序 -->
        <hc-new-dialog
            v-model="sortNodeModal"
            :loading="sortNodeLoading"
            title="调整排序"
            widths="700px"
            @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>
        </hc-new-dialog>

        <!-- 导入划分模板 -->
        <hc-new-dialog
            v-model="importTempModal"
            title="导入划分模板"
            ui="hc-modal-table"
            widths="84%"
        >
            <div class="hc-import-temp-box">
                <!-- div class="hc-choose-type-box">
                    <div class="text-title text-orange">请选择需要导入的工程类别：</div>
                    <div class="hc-type-box">
                        <el-radio-group v-model="importRadio" size="large">
                            <el-radio v-for="item in importRadioData" :label="item.key">{{item.name}}</el-radio>
                        </el-radio-group>
                    </div>
                </div -->
                <div
                    v-loading="uploadLoading"
                    class="hc-import-node-tree-box"
                    element-loading-text="Loading..."
                >
                    <div class="import-node-tree-box">
                        <div class="hc-tree-title-box">导入并识别成功</div>
                        <div class="hc-tree-bar-box">
                            <el-scrollbar>
                                <HcTreeData :datas="matchedData" />
                            </el-scrollbar>
                        </div>
                    </div>
                    <div class="import-node-tree-box">
                        <div class="hc-tree-title-box">
                            未被系统识别：手动关联
                        </div>
                        <div class="hc-tree-bar-box">
                            <el-scrollbar>
                                <HcTreeData1
                                    :datas="unmatchedData"
                                    @relation-tap="unmatchedTreeTap"
                                />
                            </el-scrollbar>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="lr-dialog-footer">
                    <div class="left">
                        <HcUpload
                            ref="uploadRef"
                            :contract-id="contractId"
                            :is-splicing-number="isSplicingNumber"
                            :primary-key-id="treePrimaryKeyId"
                            :type="importRadio"
                            @change="uploadChange"
                            @finished="uploadFinished"
                            @progress="uploadprogress"
                        />
                    </div>
                    <div class="right flex">
                        <div class="mr-6">
                            <span class="text-grey">是否拼接划分编号：</span>
                            <el-switch
                                v-model="isSplicingNumber"
                                :active-value="1"
                                :inactive-value="0"
                                active-text="是"
                                inactive-text="否"
                                inline-prompt
                                size="large"
                            />
                        </div>
                        <el-button size="large" @click="importTempModalClose">
                            <HcIcon name="close" />
                            <span>取消</span>
                        </el-button>
                        <el-button
                           
                            :disabled="uploadLoading"
                            :loading="uploadLoading"
                            hc-btn
                            type="primary"
                            @click="importTempFolder"
                        >
                            <HcIcon name="folder-upload" />
                            <span>导入模板</span>
                        </el-button>
                    </div>
                </div>
            </template>
        </hc-new-dialog>

        <!-- 替换并关联节点 -->
        <hc-new-dialog
            v-model="relationModal"
            :loading="relationLoading"
            save-text="确认关联"
            title="替换并关联节点"
            ui="hc-modal-table"
            widths="47rem"
            @save="relationSaveClick"
        >
            <el-scrollbar>
                <DivisionTree
                    :datas="unmatchedTreeData"
                    @node-tap="divisionTreeClick"
                />
            </el-scrollbar>
        </hc-new-dialog>

        <!-- 添加独立表单 -->
        <hc-new-dialog
            v-model="addingFormModal"
            :loading="addingFormLoading"
            :padding="false"
            is-table
            title="引用元素表"
            widths="84%"
            @close="addingFormClose"
            @save="addingFormSave"
        >
            <div class="adding-form-dialog-box">
                <div class="dialog-tree-box">
                    <el-scrollbar>
                        <ElTree
                            ref="addingFormTreeRef"
                            :load="addingFormTreeLoadNode"
                            :props="addingFormTreeProps"
                            accordion
                            class="hc-tree-node"
                            highlight-current
                            lazy
                            @node-click="addingFormTreeClick"
                        />
                    </el-scrollbar>
                </div>
                <div class="dialog-table-box">
                    <div class="dialog-search">
                        <el-autocomplete
                            v-model="searchTreeTitle"
                            :fetch-suggestions="querySearchTree"
                            class="block"
                            clearable
                            node-key="primaryKeyId"
                            placeholder="请输入关键词检索"
                            value-key="title"
                            @select="searchTreeSelect"
                        />
                    </div>
                    <div class="dialog-table">
                        <HcTable
                            ref="dialogTableRef"
                            :column="dialogTableColumn"
                            :datas="dialogTableData"
                            :loading="dialogTableLoading"
                            is-new
                            :index-style="{ width: 60 }"
                            is-check
                            :check-style="{ width: 29 }"
                            @select="dialogTableSelect"
                            @select-all="dialogTableSelectAll"
                        />
                    </div>
                    <div class="dialog-pages">
                        <HcPages
                            :pages="searchFormPage"
                            @change="searchFormPageChange"
                        />
                    </div>
                </div>
            </div>
        </hc-new-dialog>

        <!-- 节点导入 -->
        <hc-dialog v-model="divisionImportDialog" title="上传文件">
            <div style="position: relative;">
                <el-upload
                    ref="dialogUploadRef" :headers="getHeader()" drag 
                    action="/api/blade-manager/wbsTreeContract/importTree" 
                    :data="{ pkeyId: pKeyIdData }"
                    :on-success="handleSuccess" :on-error="handleError" accept=".xls,.xlsx"
                    :auto-upload="false"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    :on-change="handleChange"
                    :disabled="isCanClickImport"
                >
                    <div class="mt-24px text-black">将文件拖动到此处，<span class="text-blue">或点击上传</span></div>
                    <div class="mt-8px text-12px">支持的文件格式：.xls,.xlsx</div>
                </el-upload>
                <!-- 自定义文件列表 -->
                <div v-if="fileList.length > 0" class="upload-file-list mt-4">
                    <div v-for="file in fileList" :key="file.uid" class="mb-2 flex items-center justify-between border rounded p-2">
                        <div class="flex items-center">
                            <HcIcon name="file-excel" class="mr-2 text-green-500" />
                            <span>{{ file.name }}</span>
                        </div>
                        <el-button type="danger" link @click="handleRemove(file)">
                            <HcIcon name="delete" />
                        </el-button>
                    </div>
                </div>
                <div class="mt-2 text-right">
                    <el-button hc-btn type="primary" :loading="downLoadTemplateLoading" @click="downLoadTemplate">
                        <HcIcon name="download-2" />
                        导入模板
                    </el-button>
                </div>
                <div v-if="progressData > 0" class="mt-4">
                    <el-progress
                        :text-inside="true"
                        :stroke-width="24"
                        :percentage="progressData"
                        status="success"
                    />
                </div>
            </div>
            
            <template #footer>
                <el-button @click="divisionImportDialog = false">取消</el-button>
                <el-button type="primary" :loading="confirmLoading" @click="confirmTap">确认上传</el-button>
            </template>
        </hc-dialog>

        <!-- 节点划分 -->
        <division-dialog
            v-model="divisionDialogShow"
            :classify-type="classifyType"
            :tree-item-info="treeItemInfo"
            :first-tree="firstTree"
            @save="divisionSaveClick"
        />
        <!-- 节点命名配置 -->
        <hc-dialog v-model="nodeNameDialogShow" title="文件题名(全局)" widths="800px" @save="saveNodeNmeClick">
            <div class="mb-4 text-orange">
                <span
                    class="mr-4"
                >提示:修改文件题名后，点击【<HcIcon name="refresh" />】按钮查看修改后的名称。修改保存后，需重新保存资料才能生效。</span>
            </div>
            <el-select
                v-model="titleSetValue"
                multiple
                placeholder="请选择"
            >
                <el-option
                    v-for="item in titleOptions"
                    :key="item.id"
                    :label="item.dictValue"
                    :value="item.dictKey"
                />
            </el-select>

            <div class="align-items-center flex items-center justify-center">
                <el-input v-model="inputVal" class="mt-4 w-full" style="background-color: #E8E8E8;" disabled />
                <el-link class="ml-1 mt-5">
                    <HcIcon name="refresh" class="text-2xl" style="color:var(--el-color-primary)" @click="refreshName" />
                </el-link>
            </div>
        </hc-dialog>
    </div>
</template>

<script setup>
import { computed, nextTick, onActivated, onMounted, onUnmounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { useRouter } from 'vue-router'
import HcUpload from './components/division/HcUpload.vue'
import HcTreeData from './components/division/HcTreeData.vue'
import HcTreeData1 from './components/division/HcTreeData1.vue'
import DivisionTree from './components/division/DivisionTree.vue'
import HcTreeNode from './components/HcTreeNode.vue'
import divisionDialog from './components/divisionDialog.vue'
import { HcIsButton } from '~src/plugins/IsButtons'
import {
    arrIndex,
    arrToId,
    deepClone,
    downloadBlob,
    formValidate,
    getArrValue,
    getObjValue,
    isNullES,
  
} from 'js-fast-way'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { getDictionary } from '~api/other'
import wbsApi from '~api/data-fill/wbs'
import queryApi from '~api/data-fill/query'
import divisionApi from '~api/data-fill/division'
import Draggable from 'vuedraggable'
import { HcDelMsg, getHeader } from 'hc-vue3-ui'

import { getChildList } from '~api/other'
import { getDictionaryData } from '~uti/tools'
import { HcUploadFileApi } from 'hc-vue3-ui'

//初始变量
const router = useRouter()

const useAppState = useAppStore()

//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const isCollapse = ref(useAppState.getCollapse)
const contractInfo = ref(useAppState.getContractInfo)
const { contractType } = contractInfo.value
const classifyType = ref(contractType === 2 ? '2' : '1')
const isTemplateType = ref(useAppState.contractInfo?.templateType === 2)
//监听
watch(
    () => [useAppState.getCollapse],
    ([Collapse]) => {
        isCollapse.value = Collapse
    },
)
const isShowCheckbox = ref(false)
//自动展开缓存
const treeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
//监听
const isLoading = ref(false)
watch(isLoading, (newVal) => {
  console.log('加载状态变化：', newVal)
})
//渲染完成
onMounted(() => {
    if (HcIsButton('data-division-batch-btn')) {
        isShowCheckbox.value = true
    } else {
        isShowCheckbox.value = false
    }
    //setElTreeMenu()
    getWbsNodeTypeApi()
    getMajorDataTypeApi()
    getWbsNodeTableTypeApi()
    getTableOwnerTypeApi()
    getStandardTypeOptions()
    getMajorDataTypeOptions()
})
//缓存被激活时
onActivated(() => {
    searchNodeAllTableApi(treeItemInfo.value['primaryKeyId']) //重新获取引用表格数据
})
const treeLoading = ref(true)
const treeNodeLoading = () => {
    treeLoading.value = false
}

//获取节点类型
const nodeTypeData = ref([])
const getWbsNodeTypeApi = 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 getRowType = (type) => {
    const nodeData = nodeTypeData.value
    const index = arrIndex(nodeData, 'value', type)
    return nodeData[index]?.label ?? type
}

//获取资料类型
const majorDataTypeData = ref([])
const getMajorDataTypeApi = async () => {
    const { data } = await getDictionary({
        code: 'major_data_type',
    })
    //处理数据
    majorDataTypeData.value = getArrValue(data)
}

//获取资料类型名称
const getRowMajorType = (type) => {
    if (type) {
        const nodeData = majorDataTypeData.value
        const index = arrIndex(nodeData, 'dictKey', type)
        return nodeData[index]?.dictValue ?? type
    }
}

//获取表类型数据
const nodeTableTypeData = ref([])
const getWbsNodeTableTypeApi = async () => {
    const { data } = await getDictionary({
        code: 'table_type',
    })
    nodeTableTypeData.value = getArrValue(data)
}

//获取表类型
const getRowTableType = (type) => {
    if (type > 0) {
        const nodeData = nodeTableTypeData.value
        const index = arrIndex(nodeData, 'dictKey', type)
        return nodeData[index]?.dictValue ?? type
    } else {
        return ''
    }
}

//获取表类型数据
const tableOwnerTypeData = ref([])
const getTableOwnerTypeApi = async () => {
    const { data } = await getDictionary({
        code: 'owner_type',
    })
    tableOwnerTypeData.value = getArrValue(data)
}

//获取表类型
const getRowTableOwnerType = (type) => {
    if (type > 0) {
        const nodeData = tableOwnerTypeData.value
        const index = arrIndex(nodeData, 'dictKey', type)
        return nodeData[index]?.dictValue ?? type
    } else {
        return ''
    }
}
const pKeyIdData = ref('')
//懒加载的数据
const treeLoadNode = async ({ node, item, level }, resolve) => {
    let contractIdRelation = '',
        parentId = '',
        primaryKeyId = ''
    if (level !== 0) {
        const nodeData = getObjValue(node.data)
        contractIdRelation = nodeData?.contractIdRelation || ''
        parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
        primaryKeyId = nodeData?.id || ''
    }
 console.log(parentId, 'parentId')
 
    //获取数据
    const { data } = await queryApi.queryWbsTreeData({
        contractId: contractId.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId,
        classifyType: classifyType.value,
        tableOwner: classifyType.value,
        dataTime:new Date(),
    })
    resolve(getArrValue(data))
    // 获取最顶层节点的 pKeyId 和第一个节点数据
    if (level === 0 && getArrValue(data).length > 0) {
        pKeyIdData.value = data[0]?.pKeyId
        firstTree.value = data[0] // 存储第一个节点数据
    }
    treeLoading.value = false
}

//树被点击
const treeNodeInfo = ref({})
const treeItemInfo = ref({})
const treePrimaryKeyId = ref('')
const wbsElTreeClick = ({ node, data, keys }) => {
    treeNodeInfo.value = node
    treeItemInfo.value = data
    tableBasicData.value = [data]
    const { notExsitChild } = data
    setStoreValue('wbsTreeExpandKeys', keys)
    treeAutoExpandKeys.value = keys || []
    if (node.level === 3) {
        treePrimaryKeyId.value = data['primaryKeyId']
    } else {
        treePrimaryKeyId.value = ''
    }
    if (node.level > 1) {
        if (notExsitChild) {
            searchNodeAllTableApi(data['primaryKeyId'])
        } else {
            tableProjectData.value = []
        }
    }
}

//当前节点基础信息
const tableBasicColumn = ref([
    { key: 'title', name: '节点名称' },
    { key: 'partitionCode', name: '划分编号' },
    { key: 'nodeType', name: '节点类型' },
    { key: 'majorDataType', name: '资料类型' },
])
const tableBasicData = ref([])

//标记为隐蔽工程节点
const concealedChange = async () => {
    const { primaryKeyId, isConcealedWorksNode } = treeItemInfo.value
    if (primaryKeyId) {
        const { error, code, msg } = await divisionApi.concealedWorksNnode(
            {
                pKeyId: primaryKeyId,
                type: isConcealedWorksNode,
            },
            false,
        )
        if (!error && code === 200) {
            window?.$message?.success(msg)
        } else {
            window?.$message?.error(msg || '操作失败')
        }
    } else {
        window?.$message?.warning('请先在左侧选择节点')
    }
}

//当前节点工程用表信息
const tableProjectColumn = ref([
    { key: 'nodeName', name: '工程用表名称' },
    { key: 'tableType', name: '用表类型' },
    { key: 'tableOwner', name: '用表单位' },
    { key: 'fillRate', name: '填报完整率' },
    { key: 'action', name: '操作', width: 100 },
])
const tableProjectData = ref([])
//获取数据
const searchNodeAllTableApi = async (pid) => {
    const { error, code, data } = await wbsApi.searchNodeAllTable({
        projectId: projectId.value,
        contractId: contractId.value,
        primaryKeyId: pid,
    })
    if (!error && code === 200) {
        tableProjectData.value = getArrValue(data)
    } else {
        tableProjectData.value = []
    }
}

//树菜单配置
const ElTreeMenu = ref([
    { icon: 'add-circle', label: '新增节点', key: 'add' },
    { icon: 'file-copy-2', label: '复制节点', key: 'copy' },
    { icon: 'draft', label: '修改节点', key: 'edit' },
    { icon: 'sort-asc', label: '调整排序', key: 'sort' },
    { icon: 'delete-bin', label: '删除节点', key: 'del' },
])
const orString = ref('')
//树菜单被点击
const ElTreeMenuClick = async ({ key, node, data, keys }) => {
    treeNodeInfo.value = node
    treeItemInfo.value = data
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
    if (key === 'add') {
        isCustom.value = data?.isCustom
        addTreeNodeId.value = data?.primaryKeyId
        addTreeNodeOldId.value = data?.oldId
        addNodeLoading.value = false
        // addNodeModal.value = true;
        if (data?.isClassifition === 1) {
            window.$message.warning('该节点下不能创建子节点')
            addNodeModal.value = false
            return
        } else {
            addNodeModal.value = true
        }
    } else if (key === 'add1') {
        addTreeNodeId.value = data?.primaryKeyId
        addTreeNodeOldId.value = data?.oldId
        addNodeLoadingCus.value = false
        formWaterNodeModel.value = {
            nodeName: '',
            nodeType: null,
        }
        if (data?.isClassifition === 1) {
            window.$message.warning('该节点下不能创建子节点')
            addNodeModalCus.value = false
            return
        } else {
            addNodeModalCus.value = true
        }
    } else if (key === 'add2') {
        addTreeNodeId.value = data?.primaryKeyId
        addTreeNodeOldId.value = data?.oldId
        addNodeLoadingCus.value = false

        addNodeModalData.value = true
        formDataNodeModel.value = {
            nodeName: '',
            nodeType: null,
            isClassifition: 0,
            className: '',
            unitName: '',
            unitNum: 1,
            excellentNum: 1,
            digitizeTime: '',
        }
        if (data?.isClassifition === 1) {
            window.$message.warning('该节点下不能创建子节点')
            addNodeModalData.value = false
        } else {
            addNodeModalData.value = true
        }
    } else if (key === 'copy') {
        const parent = deepClone(node?.parent?.data || {})
        formCopyNodeModel.value = { ...deepClone(data), parent: parent }
        copyNodeTabKey.value = '1'
        copyNodeTable.value = []
        copyNodeLoading.value = false
        copyNodeModal.value = true
    } else if (key === 'edit') {
        const parent = deepClone(node?.parent?.data || {})
        formEditNodeModel.value = { ...deepClone(data), parent: parent }
        orString.value = formEditNodeModel.value?.className
        changeStandType(formEditNodeModel.value?.className)
        editNodeModal.value = true
    } else if (key === 'sort') {
 
        let nodes = [],
            childNodes = []
        childNodes = node?.parent?.childNodes || []
        for (let i = 0; i < childNodes.length; i++) {
            const res = childNodes[i]?.data
            nodes.push({
                id: res?.primaryKeyId,
                title: res?.title,
            })
        }
        sortNodeData.value = nodes
        sortNodeModal.value = true
    } else if (key === 'del') {
        // delModalClick()
        if (
            data['colorStatus'] === 1
            || data['colorStatus'] === 2
            || data['colorStatus'] === null
            || data['colorStatus'] === -1
        ) {
            delModalClick()
        } else {
            window?.$message?.warning('该节点已存在上报数据，不允许删除')
        }
    }
}
const loadMenu = ({ node, item, level }, resolve) => {
    ElTreeMenu.value = [
        { icon: 'add-circle', label: '新增节点', key: 'add' },
        { icon: 'add-circle', label: '自定义节点（水利工程）', key: 'add1' },
        { icon: 'add-circle', label: '自定义节点（数字化文件）', key: 'add2' },
        { icon: 'file-copy-2', label: '复制节点', key: 'copy' },
        { icon: 'draft', label: '修改节点', key: 'edit' },
        { icon: 'sort-asc', label: '调整排序', key: 'sort' },
        { icon: 'delete-bin', label: '删除节点', key: 'del' },
    ]
    let menusArr = ElTreeMenu.value
    const { isCustomChild, notExsitChild } = item //isCustomChild===1//代表子级是自定义节点
    // const { isCustom } = item
    // if (isCustom === 1 && isCustomChild === 0 && notExsitChild) {//无子级，显示两个按钮
    //     menusArr.unshift( { icon: 'add-circle', label: '新增自定义节点', key: 'add1' })
    //     resolve(menusArr)
    // } else if (isCustom === 1 && isCustomChild === 1) {//自定义节点类型下如果有自定义节点，就不允许新增节点
    //     menusArr.unshift( { icon: 'add-circle', label: '新增自定义节点', key: 'add1' })
    //     let menusArr1 = arrDelKey(menusArr, 'label', '新增节点') // [{id:1}]
    //     resolve(menusArr1)
    // } else if (isCustom === 1 && isCustomChild === 0 && !notExsitChild) { //自定义节点类型下如果有划分节点，就不允许新增自定义节点
    //     resolve(menusArr)
    // } else if (level === 1) {
    //     menusArr = [ { icon: 'add-circle', label: '新增自定义节点', key: 'add1' }]
    //     resolve(menusArr)
    // } else {
    //     resolve(menusArr)
    // }
    if (level === 1) {
        menusArr = [
            {
                icon: 'add-circle',
                label: '自定义节点（水利工程）',
                key: 'add1',
            },
            {
                icon: 'add-circle',
                label: '自定义节点（数字化文件）',
                key: 'add2',
            },
        ]
        resolve(menusArr)
    } else {
        resolve(menusArr)
    }
}
//编辑节点
const editNodeModal = ref(false)

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,
            className,
            unitName,
            excellentNum,
            unitNum,
            digitizeTime,
            majorDataType,
            nodeType,
        } = formEditNodeModel.value
        const { error, code, msg } = await wbsApi.wbsTreeUpdateNode({
            nodeName: title || '',
            pKeyId: primaryKeyId || '',
            partitionCode: partitionCode || '',
            className,
            unitName,
            unitNum,
            excellentNum,
            digitizeTime,
            majorDataType,
            nodeType,
        })
        //处理数据
        editNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('修改成功')
            treeItemInfo.value['title'] = title || ''
            treeItemInfo.value['partitionCode'] = partitionCode || ''
            editNodeModal.value = false
            window?.location?.reload() //刷新页面
        } else {
            window?.$message?.error(msg || '操作失败')
        }
    }
}

//复制节点
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 classifyList = 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 工序
        //         //不能复制到本身节点下
        //         //只能往上一级点击，不能跨层级点击
        //         //已上报的工序节点不能点击选择
        //         //如果选择的是父级节点，那不能复制到子级节点
        const { hasChildren } = data
        if (hasChildren === 0) {
            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 (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 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 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, msg } = 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 {
            window?.$message?.error(msg || '操作失败')
        }
    } else {
        const { error, code, msg } = 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() //刷新页面
        } else {
            window?.$message?.error(msg || '操作失败')
        }
    }
}

//复制数据
const copyContractNodeSubmitBusinessData = async (form, table, classify) => {
    copyNodeLoading.value = true
    const { error, code, msg }
        = 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() //刷新页面
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

//新增节点
const addNodeModal = ref(false)
const addTreeNodeId = ref('')
const addTreeNodeOldId = ref('')
// const addTreeNodeType = ref('1')
const addTreeNodeType = ref('1')
const isCustom = ref(null)
//新增自定义节点
const addNodeModalCus = ref(false)
const addNodeLoadingCus = ref(false)
const nodeNameinput = ref('')
const formWaterNodeRef = ref(null)
const formWaterNodeModel = ref({
    nodeName: '',
    nodeType: null,
})
const formWaterNodeRules = {
    nodeName: {
        required: true,
        trigger: 'blur',
        message: '请输入节点名称',
    },

    nodeType: {
        required: true,
        trigger: 'blur',
        message: '请选择节点类型',
    },
}
//选中的节点
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].nodeName,
            primaryKeyId: keys[i].pKeyId,
            isPeer: keys[i].isPeer || 2,
        })
    }
    allSelectedList.value = NodesArr
    //半选数据
    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
}

//新增节点
const addNodeLoading = ref(false)
const addNodeClick = async () => {
    const keys = allSelectedList.value || []
    if (keys.length <= 0) {
        window?.$message?.warning('请先选择节点')
    } else {
        //发起请求
        addNodeLoading.value = true
        const primaryKeyId = treeItemInfo.value?.primaryKeyId || ''
        const { error, code, msg } = await wbsApi.saveContractTreeNode({
            projectId: projectId.value,
            contractId: contractId.value,
            saveType: addTreeNodeType.value,
            allSelectedList: allSelectedList.value,
            halfSelectedList: halfSelectedList.value,
            currentNodePrimaryKeyId: primaryKeyId,
            templateType:useAppState.contractInfo?.templateType,
        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('新增成功')
            addNodeModal.value = false
            window?.location?.reload() //刷新页面
        } else {
            window?.$message?.error(msg || '操作失败')
        }
    }
}
const addNodeClickCur = async () => {
    const validate = await formValidate(formWaterNodeRef.value)
    if (!validate) return
    //发起请求
    addNodeLoadingCus.value = true
    const { error, code, msg } = await wbsApi.saveCustomAddContractNode({
        nodeName: formWaterNodeModel.value.nodeName,
        nodeType: formWaterNodeModel.value?.nodeType || '',
        newPartitionCode:formWaterNodeModel.value?.number || '',
        partitionCode: treeItemInfo.value?.partitionCode || '',
        primaryKeyId: treeItemInfo.value?.primaryKeyId || '',
        nodeClass: 1, //1水利化工程，2数字化文件
        templateType:useAppState.contractInfo?.templateType,
    })
    //判断状态
    addNodeLoadingCus.value = false
    if (!error && code === 200) {
        window?.$message?.success('新增成功')
        addNodeModalCus.value = false
        window?.location?.reload() //刷新页面
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

//新增自定义节点-数字化文件

const addNodeModalData = ref(false)
const addNodeLoadingData = ref(false)
const formDataNodeRef = ref(null)
const formDataNodeModel = ref({
    nodeName: '',
    nodeType: null,
    isClassifition: 0,
    className: '',
    unitName: '',
    unitNum: 1,
    excellentNum: 1,
    digitizeTime: '',
    majorDataType:'',
})
const majorDataTypeOptions = ref([])
const getMajorDataTypeOptions = async () => {
    majorDataTypeOptions.value = await getDictionaryData('major_data_type', false)
}
const standardTypeOptions = ref([])
const getStandardTypeOptions = async () => {
    const { data } = await getDictionary({
        code: 'classification',
    })
    standardTypeOptions.value = await getDictionaryData(
        'classification',
        false,
    )

    standardTypeOptions.value.forEach((element) => {
        // element.parentId=
        data.forEach((ele) => {
            if (ele.dictKey == element.value) {
                element.id = ele.id
            }
        })
    })
    // 定义要过滤的 dictKey 值
    const targetKeys = [1, 2, 3, 4, 5]
    // 过滤数组
    standardTypeOptions.value = standardTypeOptions.value.filter((item) =>
        targetKeys.includes(item.value),
    )
}
const unitNameOptions = ref([])
const changeStandType = async (val) => {
    if (val !== orString.value) {
        formEditNodeModel.value.unitName = ''
    }
    formDataNodeModel.value.unitName = ''
    let parentId = ''
    standardTypeOptions.value.forEach((item) => {
        if (item.value == val) {
            parentId = item.id
        }
    })
    const { data } = await getChildList({ current: 1, size: 10000, parentId })
    unitNameOptions.value = data
    unitNameOptions.value = unitNameOptions.value.filter(
        (item) => item.dictKey != -1,
    )
    unitNameOptions.value.forEach((ele) => {
        ele.dictKey = Number(ele.dictKey)
    })
}

const formDataNodeRules = {
    nodeName: {
        required: true,
        trigger: 'blur',
        message: '请输入节点名称',
    },

    nodeType: {
        required: true,
        trigger: 'blur',
        message: '请选择节点类型',
    },

    isClassifition: {
        required: true,
        trigger: 'blur',
        message: '请选择是否含单元评定',
    },
    className: {
        required: true,
        trigger: 'blur',
        message: '请选择标准分类',
    },
    unitName: {
        required: true,
        trigger: 'blur',
        message: '请选择单位名称',
    },

    excellentNum: {
        required: true,
        trigger: 'blur',
        message: '请输入优良个数',
    },
    unitNum: {
        required: true,
        trigger: 'blur',
        message: '请输入单元个数',
    },
    digitizeTime: {
        required: true,
        trigger: 'blur',
        message: '请选择时间',
    },
    majorDataType:{
        required: true,
        trigger: 'blur',
        message: '请选择内业资料类型',
    },
}

const addNodeClickData = async () => {
    const validate = await formValidate(formDataNodeRef.value)
    if (!validate) return
    //发起请求
    addNodeLoadingData.value = true
    const { error, code, msg } = await wbsApi.saveCustomAddContractNode({
        nodeName: formDataNodeModel.value.nodeName,
        nodeType: formDataNodeModel.value?.nodeType || '',
        partitionCode: treeItemInfo.value?.partitionCode || '',
        primaryKeyId: treeItemInfo.value?.primaryKeyId || '',
        nodeClass: 2, //数字化文件
        isClassifition: formDataNodeModel.value?.isClassifition || 0,
        className: formDataNodeModel.value?.className || '',
        unitName: Number(formDataNodeModel.value?.unitName) || '',
        excellentNum: formDataNodeModel.value?.excellentNum || 0,
        unitNum: formDataNodeModel.value?.unitNum || 0,
        digitizeTime: formDataNodeModel.value?.digitizeTime || 0,
        majorDataType: formDataNodeModel.value?.majorDataType || '',
        templateType:useAppState.contractInfo?.templateType,
    })
    //判断状态
    addNodeLoadingData.value = false
    if (!error && code === 200) {
        window?.$message?.success('新增成功')
        addNodeModalData.value = false
        window?.location?.reload() //刷新页面
    }
}
//删除节点
const delModalClick = () => {
    HcDelMsg(async (resolve) => {
        await removeContractTreeNode(false)
        resolve() //关闭弹窗的回调
    })
}
const removeContractTreeNode = async (isBatch) => {
    const loadingInstance = window.$loading.service({
        fullscreen: true,
        text: '删除节点中，请耐心等待...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const { error, code, msg } = await wbsApi.removeContractTreeNode({
        // ids: treeItemInfo.value?.primaryKeyId || '',
        ids: isBatch ? leftPid.value : treeItemInfo.value?.primaryKeyId || '', 
    })
    loadingInstance.close()
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        window?.location?.reload() //刷新页面
    } else {
        window?.$message?.error(msg || '操作失败')
    }
}

//批量删除
const batchDelLoading = ref(false)
const batchDelClick = ()=>{
    console.log('删除')
    HcDelMsg(async (resolve) => {
        await removeContractTreeNode(true)
        resolve() //关闭弹窗的回调
    })
    
}
const leftPid = ref('')
const leftCheckChange = (_, { checkedNodes }) => {
    if (checkedNodes && checkedNodes.length > 0) {
        // 获取所有选中节点的 primaryKeyId 并用逗号拼接
        leftPid.value = checkedNodes.map(node => node.primaryKeyId).filter(Boolean).join(',')
    } else {
        leftPid.value = ''
    }
}

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

//导入模板
const uploadRef = ref(null)
const importTempModal = ref(false)
const toImportTempClick = () => {
    importTempModal.value = true
    getContractInfoTreeApi()
}

//导入类型
const importRadio = ref(1)
const importRadioData = ref([
    { key: 1, name: '路基工程' },
    { key: 2, name: '路面工程' },
    { key: 3, name: '桥梁工程' },
    { key: 4, name: '机电工程' },
    { key: 5, name: '绿化工程' },
    { key: 6, name: '隧道工程' },
    { key: 7, name: '声屏障工程' },
    { key: 8, name: '交通与安全工程' },
    { key: 9, name: '特大斜拉桥、特大悬索桥' },
])
const isSplicingNumber = ref(0)

//上传文件被改变
const uploadFile = ref(null)
const uploadChange = (file) => {
    uploadFile.value = file
}

//上传中
const uploadLoading = ref(false)
const uploadprogress = (state) => {
    console.log(state)
    uploadLoading.value = state
}

//上传完成
const matchedData = ref([])
const unmatchedData = ref([])
const uploadFinished = ({ type, data }) => {
    uploadRef.value?.clearFiles()
    if (type === 'success') {
        uploadFile.value = null
        window?.$message?.success('导入成功')
        matchedData.value = getArrValue(data['matchedData'])
        unmatchedData.value = getArrValue(data['unmatchedData'])
    } else {
        uploadFile.value = null
        matchedData.value = []
        unmatchedData.value = []
    }
}

//关闭导入弹窗
const importTempModalClose = () => {
    uploadFile.value = null
    importTempModal.value = false
}

//确认导入
const importTempFolder = () => {
    if (uploadFile.value) {
        uploadRef.value?.submit()
    } else {
        window?.$message?.warning('请先选择文件')
    }
}

//关联被点击
const relationModal = ref(false)
const relationItemInfo = ref({})
const unmatchedTreeTap = ({ data }) => {
    relationItemInfo.value = data
    relationModal.value = true
}

//获取导入树
const unmatchedTreeData = ref([])
const getContractInfoTreeApi = async () => {
    const { error, code, data } = await divisionApi.getContractInfoTree({
        projectId: projectId.value,
        contractId: contractId.value,
        wbsId: '',
    })
    //判断状态
    if (!error && code === 200) {
        unmatchedTreeData.value = getArrValue(data)
    } else {
        unmatchedTreeData.value = []
    }
}

//关联树
const divisionTreeItemInfo = ref({})
const divisionTreeClick = ({ data }) => {
    divisionTreeItemInfo.value = data
}

//确认关联
const relationLoading = ref(false)
const relationSaveClick = () => {
    const item = relationItemInfo.value
    const info = divisionTreeItemInfo.value
    const primaryKeyId = info?.primaryKeyId ?? ''
    if (!primaryKeyId) {
        window?.$message?.warning('请先选择一个树节点')
    } else {
        setImportRelationApi({
            pKeyIdOld: info?.primaryKeyId,
            wbsTreeContractVO: {
                ...item,
                id: '',
            },
        })
    }
}

const setImportRelationApi = async (form) => {
    relationLoading.value = true
    const { error, code } = await divisionApi.setImportRelation(form)
    relationLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('关联成功')
        relationModal.value = false
    }
}



//返回上页
const toBackClick = () => {
    router.push({ path: '/data-fill/wbs' })
}

//添加独立表单
const addingFormModal = ref(false)
const addingFormClick = () => {
    const { isLeaf } = treeNodeInfo.value
    if (isLeaf) {
        addingFormLoading.value = false
        addingFormModal.value = true
        dialogTableData.value = []
        dialogTableRef.value?.clearSelection()
        selectItems.value = []
    } else {
        window?.$message?.warning('请先选择一个最子级的节点')
    }
}
//删除当前节点用表
const deltableexcel = async (row) => {
    console.log(row, 'row')
    if (row['isEle'] === 1) {
        if (row['pdfUrl']) {
            window?.$messageBox?.alert(
                '该表已填写数据' + ',请谨慎考虑后，确认是否需要删除？',
                '删除',
                {
                    showCancelButton: true,
                    confirmButtonText: '确认删除',
                    cancelButtonText: '取消',
                    callback: async (action) => {
                        if (action === 'confirm') {
                            const { error, code, msg }
                                = await divisionApi.removeWbsTreeContract({
                                    id: row.pkeyId,
                                    stats: 0,
                                })
                            if (!error && code === 200) {
                                window?.$message?.success('删除成功')
                                // window?.location?.reload()  //刷新页面
                                searchNodeAllTableApi(
                                    treeItemInfo.value['primaryKeyId'],
                                )
                            } else {
                                window?.$message?.error(msg || '操作失败')
                            }
                        }
                    },
                },
            )
        } else {
            const { error, code, msg }
                = await divisionApi.removeWbsTreeContract({
                    id: row.pkeyId,
                    stats: 0,
                })
            if (!error && code === 200) {
                window?.$message?.success('删除成功')
                searchNodeAllTableApi(treeItemInfo.value['primaryKeyId'])
                // window?.location?.reload()  //刷新页面
            } else {
                window?.$message?.error(msg || '操作失败')
            }
        }
    } else {
        window?.$message?.warning('该表不允许删除')
    }
}
//树配置
const addingFormTreeRef = ref(null)
const addingFormTreeProps = {
    label: 'title',
    children: 'children',
    isLeaf: 'isLeaf',
}

//树加载
const addingFormTreeLoadNode = async (node, resolve) => {
    if (node.level === 0) {
        const resData = await tabTypeLazyTree()
        resolve(resData?.data)
    } else {
        const resData = await tabTypeLazyTree(
            node?.data?.primaryKeyId,
            '',
            false,
            {
                current: 1,
                size: 2000,
            },
        )
        resolve(resData?.data)
    }
}

//树被点击
const addingFormTreeItem = ref({})
const selectItems = ref([])
const addingFormTreeClick = async (data, node) => {
    searchTreeTitle.value = ''
    addingFormTreeItem.value = data
    dialogTableData.value = []
    searchFormPage.value.current = 1
    console.log(
        addingFormTreeItem.value.primaryKeyId,
        'addingFormTreeItem.value',
    )
    if (node?.level === 1) {
        getDialogTableData().then()
    } else if (node?.level === 2) {
        searchFormPage.value.total = 1
        dialogTableData.value = [data]

        nextTick(() => {
            dialogTableRef.value?.toggleRowSelection(data, true)
        })
        selectItems.value.push(data)
    }
}

//搜索
const searchTreeTitle = ref('')
const querySearchTree = async (key, resolve) => {
    if (key) {
        const primaryKeyId = addingFormTreeItem.value?.primaryKeyId ?? ''
        const size = 100000
        const { data } = await divisionApi.tabTypeLazyTree({
            projectId: projectId.value,
            contractId: contractId.value,
            titleName: key,
            current: 1,
            size: 10000,
        })
        resolve(data?.records)
    } else {
        resolve([])
    }
}
const searchTreeSelect = (item) => {
    console.log('searchTreeSelect')
    dialogTableRef.value?.clearSelection()
    dialogTableKeys.value = []
    dialogTableData.value = [item]
    selectItems.value = [item]
    nextTick(() => {
        dialogTableRef.value?.toggleRowSelection(item, true)
    })
    searchFormPage.value.current = 1
    searchFormPage.value.total = 0
}

//分页
const searchFormPage = ref({ current: 1, size: 20, total: 0 })
const searchFormPageChange = ({ current, size }) => {
    searchFormPage.value.current = current
    searchFormPage.value.size = size
    getDialogTableData()
}

//表格数据
const dialogTableRef = ref(null)
const dialogTableColumn = ref([
    { key: 'title', name: '表单名称' },
    { key: 'tabType', name: '元素表类型' },
    { key: 'elementTotal', name: '元素总量' },
    { key: 'tabOwner', name: '所属方' },
    { key: 'fillRate', name: '填报率' },
])
const dialogTableData = ref([])

const dialogTableLoading = ref(false)
const getDialogTableData = async () => {
    //处理初始数据
    dialogTableLoading.value = true
    dialogTableRef.value?.clearSelection()
    dialogTableKeys.value = []
    const primaryKeyId = addingFormTreeItem.value?.primaryKeyId ?? ''
    const searchTitle = searchTreeTitle.value ?? ''
    //获取数据
    const resData = await tabTypeLazyTree(
        primaryKeyId,
        searchTitle,
        true,
        true,
    )
    const records = getArrValue(resData?.data)

    //处理返回的数据
    dialogTableData.value = records
    dialogTableLoading.value = false
    if (records.length > 0) {
        searchFormPage.value.total = resData.total || 0

        //表格勾选回显
        selectItems.value.forEach((item) => {
            dialogTableData.value.forEach((item1) => {
                if (item.id === item1.id) {
                    nextTick(() => {
                        dialogTableRef.value?.toggleRowSelection(item1, true)
                    })
                }
            })
        })
    } else {
        searchFormPage.value.total = 0
    }
}

//多选
const dialogTableKeys = ref([])

// 全选
const dialogTableSelectAll = (rows) => {
    if (rows.length) {
        /* 全选 */
        if (selectItems.value.length <= 0) {
            rows.forEach((row) => {
                selectItems.value.push(row)
            })
        } else {
            rows.forEach((row) => {
                const flag = selectItems.value.filter((e) => e.id === row.id)
                if (flag.length <= 0) {
                    selectItems.value.push(row)
                }
            })
        }
    } else {
        /* 反选-清空当前列表数据 */
        dialogTableData.value.forEach((row) => {
            // 取消选中时过滤
            selectItems.value = selectItems.value.filter(
                (e) => e.id !== row.id,
            )
        })
    }
}

const dialogTableSelect = ({ selection, row }) => {
    dialogTableKeys.value = selection
    const flag = selectItems.value.filter((e) => e.id === row.id)
    if (flag.length <= 0) {
        /* 不存在表示是选中，勾选时添加 */
        selectItems.value.push(row)
    } else {
        // 取消选中时过滤
        selectItems.value = selectItems.value.filter((e) => e.id !== row.id)
    }

    console.log(selectItems.value, 'dialogTableSelect selectItems')
}
//获取数据
const tabTypeLazyTree = async (
    parentId = '12345678910',
    titleName = '',
    search = false,
    form = {},
    size,
) => {
    let obj = {},
        searchObj = {}
    if (parentId) obj.parentId = parentId
    if (titleName) obj.titleName = titleName
    if (search) searchObj = searchFormPage.value
    //发起请求
    const { data } = await divisionApi.tabTypeLazyTree({
        projectId: projectId.value,
        contractId: contractId.value,
        ...obj,
        ...searchObj,
        ...form,
    })
    const records = getArrValue(data?.records)
    records.forEach((item) => {
        item.isLeaf = !item.hasChildren
    })
    return { data: records, total: data?.total }
}

//保存
const addingFormLoading = ref(false)
const addingFormSave = async () => {
    // const rows = dialogTableKeys.value
    console.log(dialogTableKeys.value, 'addingFormSave')
    const rows = selectItems.value
    console.log(rows, 'rows')
    if (rows.length > 0) {
        addingFormLoading.value = true
        const { primaryKeyId } = treeItemInfo.value
        const ids = arrToId(rows, 'primaryKeyId')
        const arrids = ids.split(',')
        let newStr = [...new Set(arrids)].join(',')
        // console.log(newStr,'ids');
        //发起请求
        const { error, code } = await divisionApi.addWbsContractInfo({
            projectId: projectId.value,
            contractId: contractId.value,
            nodeId: primaryKeyId,
            primaryKeyIds: newStr,
            // primaryKeyIds: ids
        })
        //处理结果
        addingFormLoading.value = false
        if (!error && code === 200) {
            window.$message?.success('操作成功')
            addingFormModal.value = false
            // window?.location?.reload()  //刷新页面
            searchNodeAllTableApi(treeItemInfo.value['primaryKeyId'])
        }
    } else {
        window.$message?.warning('请先勾选数据')
    }
}
//关闭
const addingFormClose = () => {
    addingFormModal.value = false
    dialogTableKeys.value = []
}

//左右拖动，改变树形结构宽度
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
    }
}
//节点划分
const divisionDialogShow = ref(false)
const divisionClick = async ()=>{
   
    await nextTick()
    divisionDialogShow.value = true
}
const divisionSaveClick = ()=>{
    divisionDialogShow.value = false
    window?.location?.reload() //刷新页面
}
// 添加一个定时器引用
const progressTimer = ref(null)
//是否可以点击节点导入
const isCanClickImport = ref(false)

const getIsImportData = async () => {
    const { error, code, data } = await divisionApi.getIsImport({
        projectId: projectId.value,
        contractId: contractId.value,
      
    })
    if (!error && code === 200) {
        isCanClickImport.value = data
        if (data) {
            getImportProgressData()
        }
    } else {
         isCanClickImport.value = false
    }
}
const progressData = ref(0)
const getImportProgressData = async () => {
    const { error, code, data } = await divisionApi.getImportProgress({
        projectId: projectId.value,
        contractId: contractId.value,
      
    })
    if (!error && code === 200) {
        progressData.value = Number(data)
           // 如果进度到达100%，清除定时器
        if (progressData.value >= 100) {
            clearProgressTimer()
            // 可以添加完成后的处理逻辑
            window.$message.success('导入完成')
            isCanClickImport.value = false
            divisionImportDialog.value = false
            setTimeout(() => {
              window.location.reload()
            }, 1000)
        }
    } else {
         progressData.value = 0
    }
}
//节点导入
const divisionImportDialog = ref(false)
// 修改 divisionImportDialog 的监听
watch(() => divisionImportDialog.value, (newVal) => {
  if (newVal && isCanClickImport.value) {
    // 弹窗打开且允许导入时,开启定时器
    startProgressTimer()
  } else {
    // 弹窗关闭时清除定时器
    clearProgressTimer()
  }
})
// 开启进度查询定时器
const startProgressTimer = () => {
  // 确保先清除可能存在的定时器
  clearProgressTimer()
  
  // 立即执行一次
  getImportProgressData()
  
  // 设置定时器,每5秒执行一次
  progressTimer.value = setInterval(() => {
    getImportProgressData()
  }, 5000)
}

// 清除定时器
const clearProgressTimer = () => {
  if (progressTimer.value) {
    clearInterval(progressTimer.value)
    progressTimer.value = null
  }
}
// 在组件销毁时清理定时器
onUnmounted(() => {
  clearProgressTimer()
})

//上传文件
const dialogUploadRef = ref(null)
const divisionImportClick = async ()=>{
   await getIsImportData()
   await nextTick()
    divisionImportDialog.value = true
    fileList.value = []
  
    
}
// 文件类型验证
const beforeUpload = (file) => {
  const extension = file.name.split('.').pop().toLowerCase()
  if (!['xls', 'xlsx'].includes(extension)) {
    window.$message.error('仅支持上传 .xls 或 .xlsx 格式的表格文件')
    return false
  }
  return true
}
// 添加以下数据和方法
const fileList = ref([])

const handleChange = (file, files) => {
    fileList.value = [file] // 由于限制为1个文件，直接替换
}

const handleRemove = (file) => {
    fileList.value = fileList.value.filter(item => item.uid !== file.uid)
    dialogUploadRef.value?.clearFiles()
}

const handleExceed = (files) => {
  dialogUploadRef.value.clearFiles()
  const file = files[0] 
  dialogUploadRef.value.handleStart(file)
}
//上传成功

const confirmLoading = ref(false)
const handleSuccess = (res) => {

    confirmLoading.value = false
    if (res.code === 200) {
        window.$message.success(res.msg || '上传成功')
      
        
    divisionImportDialog.value = false
  
//    setTimeout(()=>{
//     window?.location?.reload() //刷新页面
//    }, 1000)

    } else {
        window.$message.error(res.msg || '上传失败')
    }
}

//上传失败
const handleError = (error) => {
    confirmLoading.value = false
    const { msg } = !isNullES(error.message) ? JSON.parse(error.message) : {}
    if (isNullES(msg)) {
        window.$message.error('上传失败')
    } else {
        window.$message.error(msg)
    }
    fileList.value = []

}
const confirmTap = async ()=>{
    confirmLoading.value = true
    dialogUploadRef.value.submit()
    setTimeout(async ()=>{
          await getIsImportData()
            if ( isCanClickImport.value) {
                 startProgressTimer()
            } else {
                divisionSaveClick()
            }
    }, 3000)


    
}
//导入模板
const downLoadTemplate = async ()=>{
    downLoadTemplateLoading.value = true
    const { error, disposition, res, msg } = await divisionApi.downloadGongChengExcel()
    downLoadTemplateLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error(msg || '数据异常')
        }
    }
}
const downLoadTemplateLoading = ref(false)
//节点命名配置
const nodeNameDialogShow = ref(false) 
const editNamingConfigClick = async ()=>{
    const { primaryKeyId } = treeItemInfo.value
    if (!primaryKeyId) {
        window.$message.warning('请先选择一个节点')
        return 
}
    titleSetValue.value = []
    getTitleOptionsData().then()
    getNodeNameConfigData().then()
    await nextTick()
    nodeNameDialogShow.value = true
}
//获取节点命名配置
const getTitleOptionsData = async () => {
  const { data } = await getDictionary({ code:'name_rule' })
  titleOptions.value = getArrValue(data)
    
}
const titleSetValue = ref('')
const titleOptions = ref([])
const inputVal = ref('')

const getNodeNameConfigData = async () => {
  const { data } = await divisionApi.getNodeNameConfig({ pKeyId:treeItemInfo.value?.primaryKeyId, projectId: projectId.value })
  titleSetValue.value = getArrValue(data)
  if (titleSetValue.value.length > 0) {
    refreshName() //
  }
    
}
// 添加 firstTree ref
const firstTree = ref(null)
const refreshName = async ()=>{
 if (titleSetValue.value.length <= 0) {
    window.$message.warning('请先选择命名规则')
    return
 }
    const { code, error, msg, data } = await divisionApi.getNameRuleByRule({
        nameRule:titleSetValue.value.join('-'),
        pkeyId:  treeItemInfo.value?.primaryKeyId,
  
    })
    if (code === 200 && !error) {
    //  window.$message.success(msg)
     inputVal.value = data
    }
}
const saveNodeNmeClick = async () => {
    if (titleSetValue.value.length <= 0) {
        window.$message.warning('请先选择命名规则')
        return
    }
    
        const params = {
            nameRule: titleSetValue.value.join('-'), // 假设inputVal是输入框的值
            pkeyId: treeItemInfo.value?.primaryKeyId,
            projectId: projectId.value,
        }
        const { error, code, msg } = await divisionApi.saveContractNameRule(params)
        if (!error && code === 200) {
            window?.$message?.success(msg || '保存成功')
            refreshName() // 成功后调用refreshName
            nodeNameDialogShow.value = false
        } else {
            window?.$message?.error(msg || '保存失败')
        }
   
}
// 添加计算属性
const contentStyle = computed(() => ({
    '--project-info-height': !isTemplateType.value ? 'calc(100% - 238px)' : 'calc(100% - 298px)',
}))
const downloadLoading = ref(false)
const divisionExportClick = async ()=>{
     
    downloadLoading.value = true
    const { error, disposition, res } = await divisionApi.exportTree({
        contractId: contractId.value,
       
    })
    //处理数据
    downloadLoading.value = false
    if (!error) {
        if (disposition) {
            downloadBlob(res, disposition)
        } else {
            window.$message?.error('数据异常')
        }
    }
}
//导入划分模板
const divisionImportCodeClick = ()=>{
          HcUploadFileApi({
            url: '/api/blade-manager/wbsTreeContract/importPartitionCode',
            accept: '.xls,.xlsx,',
            accept_tip: 'Excel(xls、xlsx)<br/>',
      
            multiple: false,
           
            success: ({ echoParams }, { data }) => {
                window.$message.success(data?.msg || '上传成功')
            },
            error: () => {
                window.$message.error('上传失败')
            },
        })
}
const uploadProgress = ref(false)
</script>

<style lang="scss" scoped>
@import "../../styles/data-fill/division.scss";
</style>
