<template>
    <div class="hc-page-layout-box">
        <div class="hc-layout-left-box" :style="'width:' + leftWidth + 'px;'">
            <div class="hc-project-box">
                <div class="hc-project-icon-box">
                    <HcIcon name="stack"/>
                </div>
                <div class="ml-2 project-name-box">
                    <span class="text-xl text-cut project-alias">{{projectInfo['projectAlias']}}</span>
                    <div class="text-xs text-cut project-name">{{projectInfo['name']}}</div>
                </div>
            </div>
            <div class="hc-tree-box">
                <el-scrollbar>
                    <WbsTree ui="page-division-tree" :menus="ElTreeMenu" :autoExpandKeys="treeAutoExpandKeys" :projectId="projectId" :contractId="contractId" isColor @nodeTap="wbsElTreeClick" @menuTap="ElTreeMenuClick"/>
                </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="当前节点基础信息">
                    <HcTable :column="tableBasicColumn" :datas="tableBasicData" :isIndex="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="当前节点工程用表信息">
                    <HcTable :column="tableProjectColumn" :datas="tableProjectData" :isIndex="false" border>
                        <template #tableType="{row}">{{getRowTableType(row['tableType'])}}</template>
                    </HcTable>
                </HcCard>
            </div>
            <div class="footer-box">
                <el-button hc-btn @click="downloadXlsx">
                    <HcIcon name="download-2"/>
                    <span>下载导入划分模板</span>
                </el-button>
                <el-button type="primary" hc-btn @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 :show="editNodeModal" title="编辑节点" widths="600px" :loading="editNodeLoading" @close="editNodeModal = false" @save="editNodeClick">
            <el-form ref="formEditNodeRef" :model="formEditNodeModel" :rules="formEditNodeRules" label-width="auto" size="large">
                <el-form-item label="节点名称" prop="title">
                    <el-input v-model="formEditNodeModel.title"  placeholder="请输入节点名称"/>
                </el-form-item>
                <el-form-item label="上级节点">
                    <el-input v-model="formEditNodeModel.parent.title" disabled/>
                </el-form-item>
                <el-form-item label="节点类型">
                    <el-select v-model="formEditNodeModel.type" block disabled>
                        <el-option v-for="item in nodeTypeData" :label="item['label']" :value="item['value']"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="划分编号">
                    <el-input v-model="formEditNodeModel.partitionCode" placeholder="请输入划分编号"/>
                </el-form-item>
            </el-form>
        </HcDialog>

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

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

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

        <!--导入划分模板-->
        <HcDialog :show="importTempModal" title="导入划分模板" widths="84%" ui="hc-modal-table" @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 class="hc-import-node-tree-box" v-loading="uploadLoading" 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" :contractId="contractId" :type="importRadio" :isSplicingNumber="isSplicingNumber" @change="uploadChange" @progress="uploadprogress" @finished="uploadFinished"/>
                    </div>
                    <div class="right flex">
                        <div class="mr-6">
                            <span class="text-grey">是否拼接划分编号：</span>
                            <el-switch v-model="isSplicingNumber" inline-prompt :active-value="1" active-text="是" :inactive-value="0" inactive-text="否" size="large"/>
                        </div>
                        <el-button size="large" @click="importTempModalClose">
                            <HcIcon name="close"/>
                            <span>取消</span>
                        </el-button>
                        <el-button type="primary" hc-btn :disabled="uploadLoading" :loading="uploadLoading" @click="importTempFolder">
                            <HcIcon name="folder-upload"/>
                            <span>导入模板</span>
                        </el-button>
                    </div>
                </div>
            </template>
        </HcDialog>

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

    </div>
</template>

<script setup>
import {ref,watch,onMounted} from "vue";
import {useAppStore} from "~src/store";
import {useRouter, useRoute} from 'vue-router'
import WbsTree from "./components/WbsTree.vue"
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 {isType, getIndex, deepClone, formValidate} from "vue-utils-plus"
import {getStoreData, setStoreData} from '~src/utils/storage'
import {HcIsButton} from "~src/plugins/IsButtons";
import {getDictionary} from "~api/other"
import wbsApi from "~api/data-fill/wbs";
import divisionApi from "~api/data-fill/division";
import Draggable from "vuedraggable";

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

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

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

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

//渲染完成
onMounted(() => {
    setElTreeMenu()
    getWbsNodeTypeApi()
    getMajorDataTypeApi()
    getWbsNodeTableTypeApi()
})

//获取节点类型
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 = getIndex(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 = getIndex(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 = getIndex(nodeData, 'dictKey', type)
        return nodeData[index]?.dictValue ?? type
    } else {
        return ''
    }
}


//树被点击
const treeItemInfo = ref({})
const treeNodeInfo = ref({})
const wbsElTreeClick = ({node, data, keys}) => {
    treeNodeInfo.value = node
    treeItemInfo.value = data
    tableBasicData.value = [data]
    setStoreData('wbsTreeExpandKeys',keys)
    treeAutoExpandKeys.value = keys || []
    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 tableProjectColumn = ref([
    {key:'nodeName', name: '工程用表名称'},
    {key:'tableType', name: '用表类型'},
    {key:'taskStatusStr', name: '用表单位'},
    {key:'fillRate', name: '填报完整率'}
])
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([])
const setElTreeMenu = () => {
    let newArr = [];
    if (HcIsButton('wbs_tree_add')) {
        newArr.push({icon: 'add-circle', label: '新增节点', key: "add"})
    }
    if (HcIsButton('wbs_tree_copy')) {
        newArr.push({icon: 'file-copy-2', label: '复制节点', key: "copy"})
    }
    if (HcIsButton('wbs_tree_edit')) {
        newArr.push({icon: 'draft', label: '修改节点', key: "edit"})
    }
    if (HcIsButton('wbs_tree_sort')) {
        newArr.push({icon: 'sort-asc', label: '调整排序', key: "sort"})
    }
    if (HcIsButton('wbs_tree_del')) {
        newArr.push({icon: 'delete-bin', label: '删除节点', key: "del"})
    }
    ElTreeMenu.value = newArr
}

//树菜单被点击
const ElTreeMenuClick = async ({key,node,data}) => {
    treeNodeInfo.value = node
    treeItemInfo.value = data
    if (key === 'add') {
        addTreeNodeId.value = data?.id
        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()
    }
}

//编辑节点
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 copyNodeElTreeClick = ({data}) => {
    const TabKey = copyNodeTabKey.value;
    const {title, type} = formCopyNodeModel.value;
    if (TabKey === '2') {
        //1 单位工程，2 分部工程，3 子分部工程，4 分项工程， 5 子分项工程，6 工序
        if (type === 6 && (data['type'] === 4 || data['type'] === 5 || data['type'] === 6)) {
            setCopyNodeTable(data, title)
        }
        if (type === 5 && data['type'] === 4) {
            setCopyNodeTable(data, title)
        }
        if (type === 4 && (data['type'] === 2 || data['type'] === 3)) {
            setCopyNodeTable(data, title)
        }
        if (type === 3 && data['type'] === 2) {
            setCopyNodeTable(data, title)
        }
        if (type === 2 && data['type'] === 1) {
            setCopyNodeTable(data, title)
        }
        if (type === 1 && data['type'] === 1) {
            setCopyNodeTable(data, title)
        }
    } else if (TabKey === '3') {
        if (data['notExsitChild']) {
            setCopyNodeTable(data, data?.title)
        }
    }
}

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

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

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

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

//新增节点
const addNodeLoading = ref(false)
const addNodeClick = async () => {
    const keys = allSelectedList.value || []
    if (keys.length <= 0) {
        window?.$message?.warning('请先选择节点')
    } else {
        //发起请求
        addNodeLoading.value = true
        const primaryKeyId = 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 {error, code} = await wbsApi.removeContractTreeNode({
        ids: treeItemInfo.value?.primaryKeyId || ''
    })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
        window?.location?.reload()  //刷新页面
    }
}

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

//导入模板
const 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/20220928/46c85506c6719b70cfbd192f59fe95b6.xlsx','_blank')
}

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

//左右拖动，改变树形结构宽度
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>
