<template>
    <div class="hc-page-layout-box">
        <div :style="`width:${leftWidth}px;`" class="hc-layout-left-box">
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="stack" />
                </div>
                <div class="ml-2 project-name-box">
                    <span class="text-xl text-cut project-alias">{{ projectInfo.projectAlias }}</span>
                    <div class="text-xs text-cut project-name">
                        {{ projectInfo.name }}
                    </div>
                </div>
            </div>
            <div v-loading="treeLoading" class="hc-tree-box" element-loading-text="加载中...">
                <el-scrollbar>
                    <HcLazyTree
                        :auto-expand-keys="treeAutoExpandKeys" is-counts is-type
                        :menus="ElTreeMenu" ui="page-division-tree" @load="treeLoadNode"
                        @menuTap="ElTreeMenuClick" @nodeLoading="treeNodeLoading" @nodeTap="wbsElTreeClick"
                    />
                </el-scrollbar>
            </div>
            <!-- 左右拖动 -->
            <div class="horizontal-drag-line" @mousedown="onmousedown" />
        </div>
        <div class="hc-page-content-box hc-division-page">
            <div class="basic-info">
                <HcCard title="当前节点基础信息">
                    <template #extra>
                        <el-checkbox
                            v-model="treeItemInfo.isConcealedWorksNode" :false-label="0"
                            :true-label="1" label="标记为隐蔽工程节点" size="large" @change="concealedChange"
                        />
                    </template>
                    <HcTable :column="tableBasicColumn" :datas="tableBasicData" :is-index="false" border>
                        <template #type="{ row }">
                            {{ getRowType(row.type) }}
                        </template>
                        <template #majorDataType="{ row }">
                            {{ getRowMajorType(row.majorDataType) }}
                        </template>
                    </HcTable>
                </HcCard>
            </div>
            <div class="project-info">
                <HcCard title="当前节点工程用表信息">
                    <template #extra>
                        <el-button hc-btn type="primary" @click="addingFormClick">
                            <HcIcon name="add" />
                            <span>引用元素表</span>
                        </el-button>
                    </template>
                    <HcTable :column="tableProjectColumn" :datas="tableProjectData" :is-index="false" border>
                        <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>
                </HcCard>
            </div>
            <div class="footer-box">
                <el-button hc-btn @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 @click="toBackClick">
                    <HcIcon name="arrow-go-back" />
                    <span>进入资料填报</span>
                </el-button>
            </div>
        </div>

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

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

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

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

        <!-- 导入划分模板 -->
        <HcDialog
            :show="importTempModal" title="导入划分模板" ui="hc-modal-table" widths="84%"
            @close="importTempModal = false"
        >
            <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" @relationTap="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>
        </HcDialog>

        <!-- 替换并关联节点 -->
        <HcDialog
            :loading="relationLoading" :show="relationModal" save-text="确认关联" title="替换并关联节点"
            ui="hc-modal-table"
            widths="47rem" @close="relationModal = false" @save="relationSaveClick"
        >
            <el-scrollbar>
                <DivisionTree :datas="unmatchedTreeData" @nodeTap="divisionTreeClick" />
            </el-scrollbar>
        </HcDialog>

        <!-- 添加独立表单 -->
        <HcDialog
            :loading="addingFormLoading" :padding="false" :show="addingFormModal" 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-check
                            @select="dialogTableSelect"
                            @select-all="dialogTableSelectAll"
                        />
                    </div>
                    <div class="dialog-pages">
                        <HcPages :pages="searchFormPage" @change="searchFormPageChange" />
                    </div>
                </div>
            </div>
        </HcDialog>
    </div>
</template>

<script setup>
import { nextTick, onActivated, onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { useRoute, 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 { arrIndex, arrToId, deepClone, formValidate, getArrValue, getObjValue } 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'

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

//全局变量
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const projectInfo = ref(useAppState.getProjectInfo)
const isCollapse = ref(useAppState.getCollapse)
const contractInfo = ref(useAppState.getContractInfo)
const { contractType } = contractInfo.value
const classifyType = ref(contractType === 2 ? '2' : '1')

//监听
watch(() => [
    useAppState.getCollapse,
], ([Collapse]) => {
    isCollapse.value = Collapse
})

//自动展开缓存
const treeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
//自动展开缓存
const TreeAutoExpandKeys = ref(getStoreValue('wbsTreeExpandKeys') || [])
//渲染完成
onMounted(() => {
    //setElTreeMenu()
    getWbsNodeTypeApi()
    getMajorDataTypeApi()
    getWbsNodeTableTypeApi()
    getTableOwnerTypeApi()
})
//缓存被激活时
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 treeLoadNode = async ({ node, item, level }, resolve) => {
    let contractIdRelation = '', parentId = '', primaryKeyId = ''
    if (level !== 0) {
        const nodeData = getObjValue(item)
        contractIdRelation = nodeData?.contractIdRelation || ''
        parentId = contractIdRelation ? nodeData?.primaryKeyId : nodeData?.id
        primaryKeyId = nodeData?.id || ''
    }
    //获取数据
    const { data } = await queryApi.queryWbsTreeData({
        contractId: contractId.value || '',
        contractIdRelation,
        primaryKeyId,
        parentId,
        classifyType: classifyType.value,
        tableOwner:'',
    })
    resolve(getArrValue(data))
}

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

//当前节点基础信息
const tableBasicColumn = ref([
    { key: 'title', name: '节点名称' },
    { key: 'partitionCode', name: '划分编号' },
    { key: 'type', 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?.warning(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 ElTreeMenuClick = async ({ key, node, data, keys }) => {
    treeNodeInfo.value = node
    treeItemInfo.value = data
    setStoreValue('wbsTreeExpandKeys', keys)
    TreeAutoExpandKeys.value = keys || []
    if (key === 'add') {
        addTreeNodeId.value = data?.primaryKeyId
        addTreeNodeOldId.value = data?.oldId
        addNodeLoading.value = false
        addNodeModal.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 }
        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) {
            delModalClick()
        } else {
            window?.$message?.warning('该节点已存在上报数据，不允许删除')
        }
    }
}

//编辑节点
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 } = formEditNodeModel.value
        const { error, code } = await wbsApi.wbsTreeUpdateNode({
            nodeName: title || '',
            pKeyId: primaryKeyId || '',
            partitionCode: partitionCode || '',
        })
        //处理数据
        editNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('修改成功')
            treeItemInfo.value['title'] = title || ''
            treeItemInfo.value['partitionCode'] = partitionCode || ''
            editNodeModal.value = false
            window?.location?.reload() //刷新页面
        }
    }
}

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

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

//复制节点变量
const copyNodeLoading = ref(false)
const formCopyNodeModel = ref({})
const copyNodeTable = ref([])
const 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 工序
//         //不能复制到本身节点下
//         //只能往上一级点击，不能跨层级点击
//         //已上报的工序节点不能点击选择
//         //如果选择的是父级节点，那不能复制到子级节点
    if (data['colorStatus'] === 2 || data['colorStatus'] == 1) {//已上报的工序不能点击
        if (data['id'] !== formCopyNodeModel.value.id) {//不能复制到本身节点下
            //只能往上一级点击，不能跨层级点击

                //如果选择的是父级节点，那不能复制到子级节点
                if (type === 6 && (data['type'] === 4 || data['type'] === 5 || data['type'] == 6)) {
                    setCopyNodeTable(data, title)
                }
                if (type === 5 && data['type'] === 4) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 4 && (data['type'] === 2 || data['type'] === 3)) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 3 && data['type'] === 2) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 2 && data['type'] === 1) {
                    setCopyNodeTable(data, title, partitionCode)
                }
                if (type === 1 && data['type'] === 1) {
                    setCopyNodeTable(data, title, partitionCode)
                }


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


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


    }
}

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

//节点表单
const formCopyNodeModelRef = ref(null)
const formCopyNodeModelRules = {
    title: {
        required: true,
        trigger: 'blur',
        message: '请输入节点名称',
    },
}
//表格节点表单
const copyNodeTableRef = ref(null)
const copyNodeTableRules = {
    nodeName: {
        required: true,
        trigger: 'blur',
        message: '请输入节点名称',
    },
}
//删除选中的节点
const copyNodeTableDel = (index) => {
    copyNodeTable.value.splice(index, 1)
}
//复制节点
//复制节点
const copyNodeClick = async () => {
    const type = copyNodeTabKey.value
    const form = formCopyNodeModel.value
    const table = copyNodeTable.value
    let classify = ''
    let arr = []
    if (classifyList.value.length > 0) {
        classifyList.value.forEach((item) => {
            if (item === '施工') {
                arr.push(1)
            } else if (item === '监理') {
                arr.push(2)
            }
        })
        classify = arr.join(',')
    }
    //isSameNode 是否同节点 1=同节点，0=跨节点
    if (table.length > 0) {
        table.forEach((ele) => {
            if (ele.parentId === formCopyNodeModel.value.parentId || ele.id === formCopyNodeModel.value.parentId) {
                ele.isSameNode = 1
            } else {
                ele.isSameNode = 0
            }
        })
    }
  if (isCopyData.value === 1) {
    if (classify) {
        //效验数据
        if (type === '1') {
            const validate = await formValidate(formCopyNodeModelRef.value)
            if (validate) await copyContractTreeNode(type, form, [], classify)
        } else if (type === '2') {
            if (table.length > 0) {
                const validate = await formValidate(copyNodeTableRef.value)
                if (validate) await copyContractTreeNode(type, form, table, classify)
            } else {
                window?.$message?.warning('请先在左侧选择要复制到的节点')
            }
        }
    } else {
        window?.$message?.warning('请选择所属方')
    }
  } else {
    if (type === '1') {
            const validate = await formValidate(formCopyNodeModelRef.value)
            if (validate) await copyContractTreeNode(type, form, [], classify)
    } else if (type === '2') {
            if (table.length > 0) {
                const validate = await formValidate(copyNodeTableRef.value)
                if (validate) await copyContractTreeNode(type, form, table, classify)
            } else {
                window?.$message?.warning('请先在左侧选择要复制到的节点')
            }
     }
  }
}
const copyContractTreeNode = async (type, form, table, classify) => {
    copyNodeLoading.value = true
    if (type === '1') {
        const { error, code } = await wbsApi.copyContractTreeNode({
            copyType: type,
            needCopyNodeName: form?.title || '',
            partitionCode: form?.partitionCode || '',
            needCopyPrimaryKeyId: form?.primaryKeyId || '',
            parentPrimaryKeyId: form?.parent?.primaryKeyId || '',
            copyBatchToPaths: table,
            classifyType: classify,
            isCopyData:isCopyData.value,
        })
        //判断状态
        copyNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('复制成功')
            copyNodeModal.value = false
            window?.location?.reload() //刷新页面
        }
    } else {
        const { error, code } = await wbsApi.copyContractTreeNode({
            copyType: type,
            needCopyNodeName: form?.title || '',
            needCopyPrimaryKeyId: form?.primaryKeyId || '',
            parentPrimaryKeyId: form?.parent?.primaryKeyId || '',
            copyBatchToPaths: table,
            classifyType: classify,
            isCopyData:isCopyData.value,
        })
        //判断状态
        copyNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('复制成功')
            copyNodeModal.value = false
            window?.location?.reload() //刷新页面
        }
    }
}

//复制数据
const copyContractNodeSubmitBusinessData = async (form, table, classify) => {
    copyNodeLoading.value = true
    const { error, code } = await wbsApi.copyContractNodeSubmitBusinessData({
        needCopyPrimaryKeyId: form?.primaryKeyId || '',
        copyBatchToPaths: table,
        classify: classify,
    })
    //判断状态
    copyNodeLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('复制成功')
        copyNodeModal.value = false
        window?.location?.reload() //刷新页面
    }
}

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

//选中的节点
const allSelectedList = ref([])
const halfSelectedList = ref([])
const addTreeNodeCheckChange = (nodes) => {
    let NodesArr = [], halfArr = []
    //全选数据
    const keys = nodes.checkedNodes || []
    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 } = await wbsApi.saveContractTreeNode({
            projectId: projectId.value,
            contractId: contractId.value,
            saveType: addTreeNodeType.value,
            allSelectedList: allSelectedList.value,
            halfSelectedList: halfSelectedList.value,
            currentNodePrimaryKeyId: primaryKeyId,
        })
        //判断状态
        addNodeLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success('新增成功')
            addNodeModal.value = false
            window?.location?.reload() //刷新页面
        }
    }
}

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

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

//导入模板
const 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 downloadXlsx = () => {
    window.open('https://bladex-test-info.oss-cn-chengdu.aliyuncs.com//upload/20221017/854463fdfdf90843e6783fbcb4d7d00c.xlsx', '_blank')
}

//返回上页
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?.warning(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?.warning(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 selectItem = ref({})
const selectIds = 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
    }
}
</script>

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