<template>
  <basic-container>
    <el-row class="titlerow">
      <el-col style="margin-bottom: 0px; margin-top: 8px">
        <div style="position: relative">
          <!-- <el-button type="primary" size="medium" icon="el-icon-plus" class="mg-b-10" @click="addNodeHandle">新增节点</el-button>
                  <el-button type="primary" size="medium" icon="el-icon-edit-outline" class="mg-b-10" @click="editNodeHandle">编辑当前节点</el-button>
                  <el-button type="primary" size="medium" icon="el-icon-document-copy" class="mg-b-10" @click="copyNodeHandle">复制当前节点</el-button>
                  <el-button type="warning" size="medium" icon="el-icon-delete" class="mg-b-10" @click="delNodeHandle">删除当前节点</el-button> -->
          <el-button type="primary" size="medium" icon="el-icon-upload" v-show="curTreeNode && curTreeNode.level == 2"
            class="mg-b-10" @click="importTemplate(curTreeData, curTreeNode)">导入划分</el-button>
          <el-button class="mg-b-10" size="medium" icon="el-icon-s-grid" @click="eleFormulaHandle"
            v-if="leftType == 5">元素公式设置</el-button>
          <el-button class="mg-b-10" size="medium" icon="el-icon-s-grid" @click="eleHandle" v-else>元素设置</el-button>
          <el-button class="mg-b-10" size="medium" icon="el-icon-help" @click="nodeInfoHandle">节点参数设置</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="height: calc(100% - 34px);">
      <el-col :span="10" style="height: 85%">
        <div class="h-100p flex flex-d-c">
          <p>工程节点信息</p>
          <div class="flex" style="align-items: center; justify-content: space-between">
            <el-input placeholder="输入关键字进行搜索" v-model="filterText" clearable style="width: 70%; margin-right: 15px"
              @clear="clearSearch"></el-input>
            <el-switch v-model="searchType" active-value="1" inactive-value="2" inline-prompt active-text="按节点"
              inactive-text="按表名" />
            <el-button type="primary" @click="searchTreeClick">搜索</el-button>
          </div>
          <div class="flex1 ov-hidden" v-loading="treeLoad">
            <el-scrollbar class="h-100p">
              <div v-if="isShowTree">
                <el-tree v-show="!isSearch" class="filter-tree" lazy :load="loadNode" @node-click="getNodeDetail"
                  :props="defaultProps" :expand-on-click-node="false" highlight-current node-key="id" ref="tree"
                  :default-expanded-keys="defaultExpandedKeys" :data="treeData">
                  <span class="custom-tree-node" :class="data.moreShow ? 'show' : ''" slot-scope="{ node, data }"
                    @mouseleave="mouseout(data)">
                    <div class="pd-r-20">
                      {{ node.label }}
                      <div class="normal-black">
                        <!-- <el-link :underline="false">
                        <i class="el-icon-sort" @click="paixuMD(data)" v-if="node.level != 1" title="调整排序"></i>
                      </el-link> -->
                        <div>
                          <el-link :underline="false">
                            <i class="el-icon-menu" @click.stop="showMenu($event, data, node)"></i>
                          </el-link>

                          <!-- 因右键自定义菜单事件需要获取当前点击的位置，所以此处绑定动态样式来控制菜单实时跟踪鼠标右键点击位置 -->
                          <ul v-show="menuvisible" :style="{
                            left: menuleft + 'px',
                            top: menutop + 'px',
                          }" class="contextmenu">
                            <li v-for="item in menusData" :key="item" @click="menuClick($event, item, data, node)"
                              v-if="node.level !== 1">
                              <i :class="item.icon"></i>{{ item.label }}
                            </li>
                            <li v-for="item in menusData1" :key="item" @click="menuClick($event, item, data, node)"
                              v-if="node.level === 1">
                              <i :class="item.icon"></i>{{ item.label }}
                            </li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </span>
                </el-tree>
                <el-tree v-show="isSearch" :data="searchTreeData" @node-click="getNodeDetail" :props="defaultProps"
                  :expand-on-click-node="false" highlight-current node-key="id" :load="searchtreeLoad"
                  default-expand-all>
                  <span class="custom-tree-node" slot-scope="{ node, data }" :class="data.moreShow ? 'show' : ''"
                    @mouseleave="mouseout(data)">
                    <div class="pd-r-20">
                      {{ node.label }}
                      <div class="normal-black">
                        <div>
                          <el-link :underline="false">
                            <i class="el-icon-menu" @click.stop="showMenu($event, data, node)"
                              v-if="node.level != 1"></i>
                          </el-link>

                          <ul v-show="menuvisible" :style="{
                            left: menuleft + 'px',
                            top: menutop + 'px',
                          }" class="contextmenu">
                            <li v-for="item in menusData" :key="item" @click="menuClick($event, item, data, node)">
                              <i :class="item.icon"></i>{{ item.label }}
                            </li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </span>
                </el-tree>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </el-col>
      <el-col :span="14" class="h-100p flex flex-d-c">
        <!-- <div>
          <el-button type="primary" size="medium" icon="el-icon-plus" class="mg-b-10" @click="addNodeHandle">新增节点</el-button>
          <el-button type="primary" size="medium" icon="el-icon-edit-outline" class="mg-b-10" @click="editNodeHandle">编辑当前节点</el-button>
          <el-button type="primary" size="medium" icon="el-icon-document-copy" class="mg-b-10" @click="copyNodeHandle">复制当前节点</el-button>
          <el-button type="warning" size="medium" icon="el-icon-delete" class="mg-b-10" @click="delNodeHandle">删除当前节点</el-button>
          <el-button type="primary" size="medium" icon="el-icon-upload" v-show="curTreeNode && curTreeNode.level == 2" class="mg-b-10" @click="importTemplate(curTreeData,curTreeNode)">导入划分</el-button>
          <el-button class="el-btn-purple mg-b-10" type="primary" size="medium" icon="el-icon-s-grid" @click="eleFormulaHandle" v-if="leftType==5">元素公式设置</el-button>
          <el-button class="el-btn-purple mg-b-10" type="primary" size="medium" icon="el-icon-s-grid" @click="eleHandle" v-else>元素设置</el-button>
          <el-button class="el-btn-purple mg-b-10" type="primary" size="medium" icon="el-icon-help" @click="nodeInfoHandle">节点参数设置</el-button>
        </div> -->
        <template v-if="leftType == 5">
          <p class="mg-b-10">节点信息</p>
          <div>
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column align="center" prop="nodeName" label="当前节点"></el-table-column>
              <el-table-column align="center" prop="nodeType" :formatter="formatCat" label="节点类型"
                width="180"></el-table-column>
              <el-table-column align="center" prop="parentName" label="上级节点"></el-table-column>
            </el-table>
          </div>
          <div class="flex jc-sb">
            <p>
              <span>当前已创建的元素表</span>
              <el-button @click="showFormElement" type="text" icon="el-icon-circle-plus-outline"
                class="text-icon mg-l-10"></el-button>
              <el-button type="text" icon="el-icon-document-copy" class="text-icon"></el-button>
              <el-button type="text" icon="el-icon-edit-outline" class="text-icon"
                @click="editEditElementForm()"></el-button>
              <el-button type="text" icon="el-icon-sort" class="text-icon" @click="paixucc()"></el-button>
            </p>
            <div class="mg-t-10">
              <el-button :disabled="!canChooseForm" type="primary" size="mini" @click="chooseTable">选择表单</el-button>
            </div>
          </div>
          <div style="flex: 1; position: relative">
            <el-table :data="formData" border height="100%" style="width: 100%; position: absolute">
              <el-table-column align="center" prop="tableName" label="表单名称"></el-table-column>
              <el-table-column align="center" prop="elementTotal" label="元素总量"></el-table-column>
              <el-table-column align="center" prop="fillRate" label="填报率"></el-table-column>
              <el-table-column align="center" prop="tableType" :formatter="formatTableType"
                label="表单类型"></el-table-column>
              <el-table-column align="center" prop="tableOwner" :formatter="formatOwner" label="所属方"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
        <template v-if="leftType == 4">
          <div style="flex: 1; position: relative">
            <el-table :data="formData" border height="100%" style="width: 100%; position: absolute">
              <el-table-column align="center" prop="tableName" label="表单名称"></el-table-column>
              <el-table-column align="center" prop="elementTotal" label="元素总量"></el-table-column>
              <el-table-column align="center" prop="fillRate" label="填报率"></el-table-column>
              <el-table-column align="center" prop="tableType" :formatter="formatTableType"
                label="表单类型"></el-table-column>
              <el-table-column align="center" prop="tableOwner" :formatter="formatOwner" label="所属方"></el-table-column>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button size="mini" @click="handleEditFormula(scope.$index, scope.row)">编辑元素公式</el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-col>
    </el-row>

    <!-- 编辑元素表单信息 -->
    <el-dialog title="编辑元素表单信息" :visible.sync="editElementFormTag" width="60%" :modal-append-to-body="false">
      <div>
        <el-table :data="formDatass" border style="width: 100%">
          <el-table-column prop="tableName" label="表名">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tableName" placeholder="请输入表名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="tableType" label="表类型">
            <template slot-scope="scope">
              <el-select v-model="scope.row.tableType" placeholder="请选择">
                <el-option v-for="(item, key) in tableTypelist" :key="key" :label="item.dictValue"
                  :value="item.dictKey">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="tableOwner" label="所属方">
            <template slot-scope="scope">
              <el-select v-model="scope.row.tableOwner" placeholder="请选择">
                <el-option v-for="(item, key) in ownerTypeList" :key="key" :label="item.dictValue"
                  :value="item.dictKey">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="fillRate" label="填报率">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fillRate" placeholder="请输入填报率"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editElementFormTag = false">取 消</el-button>
        <el-button type="primary" @click="editeditElementFormMF()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 导入元素 -->
    <el-dialog title="导入元素" :visible.sync="ImportElementTag" width="30%" :modal-append-to-body="false"
      :before-close="ImportElementHandleClose">
      <div>
        <el-link type="primary" @click="xiazaielement">下载导入模版</el-link>
      </div>
      <el-upload class="upload-demo martop10" action="#" accept=".xlsx,.xls" :multiple="false" :limit="1"
        :auto-upload="false" :on-change="ElementChange" :file-list="ImportElementFile" :on-remove="ElementRemove">
        <el-button v-if="ImportElementFile.length === 0" size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx / xls文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ImportElementHandleClose()">取 消</el-button>
        <el-button type="primary" :disabled="loding" @click="pushImportElement">确 定</el-button>
      </span>
    </el-dialog>

    <!-- wbs树排序弹框 -->
    <el-dialog title="调整排序" :visible.sync="sortTag" width="50%" append-to-body>
      <ManualSorting v-if="sortTag2" @bianhua="bianhua()" :sort="sort" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="(sortTag = false), (sortTag2 = false)">取 消</el-button>
        <el-button type="primary" @click="editSort()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 元素表排序 -->
    <el-dialog title="调整排序" :visible="excelSortTag" width="50%" append-to-body>
      <ManualSorting v-if="excelSortTag2" @bianhua="bianhua2()" :sort="sort" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="excelSortTag = false">取 消</el-button>
        <el-button type="primary" @click="editExcelSort()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" append-to-body
      :close-on-click-modal="false" @closed="saveNodeLoading = false">
      <el-form ref="nodeDetail" :model="nodeDetail" :rules="rules" label-width="140px">
        <el-form-item label="节点名称" prop="nodeName">
          <div class="flex">
            <el-input v-model="nodeDetail.nodeName"></el-input>
            <el-button class="mg-l-10" type="primary" @click="aliasShow">添加别名</el-button>
          </div>
        </el-form-item>
        <el-form-item label="上级节点">
          <el-input v-model="nodeDetail.parentName" disabled></el-input>
        </el-form-item>
        <el-form-item label="节点类型" prop="nodeType">
          <el-select filterable v-model="nodeDetail.nodeType" placeholder="请选择" class="w-100p" @change="nodeTypeChange"
            clearable>
            <el-option v-for="item in nodeTypelist" :key="item.id" :label="item.dictValue"
              :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="划分编号" v-if="wbsType !== 2 && wbsType !== 5 && wbsType !== 3">
          <el-input v-model="nodeDetail.partitionCode"></el-input>
        </el-form-item>
        <!-- <el-form-item label="唯一编码" v-if="(wbsType !== 5) & (wbsType !== 3)">
          <el-input v-model="nodeDetail.uniqueCode"></el-input>
        </el-form-item> -->
        <el-form-item label="参数掩码" v-if="wbsType !== 5">
          <el-input v-model="nodeDetail.uniqueCode" placeholder="可填写分部评定权值/试验编号配置"></el-input>
        </el-form-item>
        <template v-if="nodeDetail.nodeType == 6 && wbsType !== 3">
          <el-form-item label="是否有混凝土">
            <el-radio-group v-model="nodeDetail.isConcrete" size="small">
              <el-radio :label="0" border>无</el-radio>
              <el-radio :label="1" border>有</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否试验节点">
            <el-radio-group v-model="nodeDetail.isExpernode" size="small">
              <el-radio :label="0" border>否</el-radio>
              <el-radio :label="1" border>是</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <el-form-item label="内业资料类型" prop="majorDataType" v-if="wbsType !== 2 && (wbsType !== 5) & (wbsType !== 3)">
          <el-select v-model="nodeDetail.majorDataType" placeholder="请选择" class="w-100p" clearable>
            <el-option v-for="item in majorDataTypeList" :key="item.id" :label="item.dictValue"
              :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="勾选相关联试验" prop="mixRatioTestIds" v-if="wbsType === 2 && nodeDetail.nodeType === 53">
          <div style="position: relative; height: 300px; border: 1px solid #dddfe6">
            <el-scrollbar class="h-100p">
              <div v-loading="testTreeLoad">
                <el-tree class="filter-tree" :data="testTreeData" :props="defaultProps" :expand-on-click-node="false"
                  highlight-current node-key="id" ref="treeall" show-checkbox :default-checked-keys="mixRatioTestIds"
                  @check="TestTreeCheckChange" />
              </div>
            </el-scrollbar>
          </div>
        </el-form-item>
        <el-form-item label="标准分类">
          <el-select v-model="nodeDetail.className" placeholder="请选择" class="w-100p" @change="changeStandType"
            clearable>
            <el-option v-for="item in standardTypeOptions" :key="item.id" :label="item.dictValue"
              :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元名称">
          <el-select v-model="nodeDetail.unitName" placeholder="请选择" class="w-100p" clearable>
            <el-option v-for="item in unitOptions" :key="item.id" :label="item.dictValue"
              :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNode" :loading="saveNodeLoading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="创建新的元素表" :visible.sync="eleVisible" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="eleDialog" :model="eleForm" :rules="eleRules" label-width="110px">
        <el-form-item label="表名" prop="nodeName">
          <el-input v-model="eleForm.nodeName"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="表类型" prop="tableType">
              <el-select v-model="eleForm.tableType" placeholder="请选择" class="w-100p">
                <el-option v-for="item in tableTypelist" :key="item.id" :label="item.dictValue"
                  :value="item.dictKey"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属方" prop="tableOwner">
              <el-select v-model="eleForm.tableOwner" placeholder="请选择" class="w-100p">
                <el-option v-for="item in ownerTypeList" :key="item.id" :label="item.dictValue"
                  :value="item.dictKey"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="填报率" prop="fillRate">
              <el-input v-model="eleForm.fillRate"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex jc-sb">
        <div></div>
        <div>
          <el-link type="primary" @click="importVisible = true">快捷导入</el-link>
          <el-link type="primary" class="mg-l-20" @click="downloadTmp">下载导入模版</el-link>
        </div>
      </div>
      <div class="border-grey">
        <p class="font-c-warning">编辑元素信息（请谨慎操作）</p>
        <el-table :data="eleForm.elementList" border style="width: 100%" height="400px">
          <el-table-column align="center" type="index" width="50"></el-table-column>
          <el-table-column align="center" prop="eName" label="元素名称">
            <template slot="header">
              <i class="required"></i>
              <span>元素名称</span>
            </template>
            <template slot-scope="scope">
              <el-input v-model="scope.row.eName" size="small" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="eType" label="数据类型" width="120">
            <template slot="header">
              <i class="required"></i>
              <span>数据类型</span>
            </template>
            <template slot-scope="scope">
              <el-select v-model="scope.row.eType" @change="setDefaultLength(scope.row)" size="small" placeholder="请选择">
                <el-option v-for="item in dataTypeList" :key="item.id" :label="item.dictValue"
                  :value="item.dictKey"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="eLength" label="长度" width="120">
            <template slot="header">
              <i class="required"></i>
              <span>长度</span>
            </template>
            <template slot-scope="scope">
              <el-input v-model="scope.row.eLength" size="small" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="eAllowDeviation" label="允许偏差值">
            <template slot-scope="scope">
              <div class="flex">
                <el-select v-model="scope.row.allow" :popper-append-to-body="false" size="small" placeholder="请选择"
                  style="width: 120px">
                  <el-option :key="1" label="-" value="-"></el-option>
                  <el-option :key="2" label=">" value=">"></el-option>
                  <el-option :key="3" label="<" value="<"></el-option>
                  <el-option :key="4" label="≥" value="≥"></el-option>
                  <el-option :key="5" label="≤" value="≤"></el-option>
                  <el-option :key="6" label="±" value="±"></el-option>
                  <el-option :key="7" label="【】" value="【】"></el-option>
                </el-select>
                <el-input v-model="scope.row.deviation" size="small" placeholder="请输入内容"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="eInspectionMethod" label="检查方法和频率">
            <template slot-scope="scope">
              <el-input v-model="scope.row.eInspectionMethod" size="small" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80">
            <template slot="header">
              <el-button @click="addEleRow(eleForm.elementList)" type="text" icon="el-icon-circle-plus-outline"
                class="text-icon"></el-button>
            </template>
            <template slot-scope="scope">
              <el-button icon="el-icon-remove-outline" type="text" @click="delEleRow(scope.$index, eleForm.elementList)"
                class="text-icon text-icon-danger"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveFormAndElementHandle">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="模版导入" :visible.sync="importVisible" width="50%" append-to-body :close-on-click-modal="false">
      <p>
        提示：必须按照系统要求的模版格式上传，否则系统识别无效
        <el-link type="primary" @click="downloadTmp">下载导入模版</el-link>
      </p>
      <div>
        <el-button size="small" type="primary" @click="fileClick2">本地上传</el-button>
        <input @change="tmpImport" type="file" hidden ref="file2" accept=".xls, .xlsx" />
      </div>
      <el-table :data="tempList" border style="width: 100%">
        <el-table-column align="center" prop="eName" label="元素名称">
        </el-table-column>
        <el-table-column align="center" prop="eType" label="数据类型" width="120">
        </el-table-column>
        <el-table-column align="center" prop="eLength" label="长度" width="120">
        </el-table-column>
        <el-table-column align="center" prop="eAllowDeviation" label="允许偏差值">
        </el-table-column>
        <el-table-column align="center" prop="eInspectionMethod" label="检查方法和频率">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">取 消</el-button>
        <el-button type="primary" @click="importHandle">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="(curEleTable.tableName ? curEleTable.tableName : '') + '  元素编辑'
      " :visible.sync="editEleVisible" width="80%" append-to-body :close-on-click-modal="false">
      <p class="font-c-warning">编辑元素信息（请谨慎操作）</p>
      <div style="display: flex; margin-bottom: 10px">
        <el-input placeholder="请输入你想编辑的元素名称" v-model="searchinput" :size="size" clearable @clear="clearsearchinput">
        </el-input>
        <el-button type="primary" icon="el-icon-search" size="small" @click="searchinputChange">搜索</el-button>
      </div>
      <el-table :data="editEleList" border style="width: 100%" height="400px" v-loading="editEleloading">
        <el-table-column align="center" type="index" width="50"></el-table-column>
        <el-table-column align="center" prop="eName" label="元素名称">
          <template slot="header">
            <i class="required"></i>
            <span>元素名称</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.eName" size="small" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="eType" label="数据类型" width="120">
          <template slot="header">
            <i class="required"></i>
            <span>数据类型</span>
          </template>
          <template slot-scope="scope">
            <el-select v-model="scope.row.eType" @change="setDefaultLength(scope.row)" size="small" placeholder="请选择">
              <el-option v-for="item in dataTypeList" :key="item.id" :label="item.dictValue"
                :value="item.dictKey"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="eLength" label="长度" width="120">
          <template slot="header">
            <i class="required"></i>
            <span>长度</span>
          </template>
          <template slot-scope="scope">
            <el-input v-model="scope.row.eLength" size="small" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="eAllowDeviation" label="允许偏差值">
          <template slot-scope="scope">
            <div class="flex">
              <el-select v-model="scope.row.allow" size="small" placeholder="请选择" style="width: 120px">
                <el-option :key="1" label="-" value="-"></el-option>
                <el-option :key="2" label=">" value=">"></el-option>
                <el-option :key="3" label="<" value="<"></el-option>
                <el-option :key="4" label="≥" value="≥"></el-option>
                <el-option :key="5" label="≤" value="≤"></el-option>
                <el-option :key="6" label="±" value="±"></el-option>
                <el-option :key="7" label="【】" value="【】"></el-option>
              </el-select>
              <el-input v-model="scope.row.deviation" size="small" placeholder="请输入内容"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="eInspectionMethod" label="检查方法和频率">
          <template slot-scope="scope">
            <el-input v-model="scope.row.eInspectionMethod" size="small" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="required" label="是否必填项" width="140">
          <template slot-scope="scope">
            <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.required"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="assist" label="是否公式辅助元素" width="140">
          <template slot-scope="scope">
            <el-checkbox :true-label="1" :false-label="0" v-model="scope.row.assist"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="dynamicDict" label="动态字典">
          <template slot="header">
            <span>动态字典</span>
          </template>
          <template slot-scope="scope">
            <el-select v-model="scope.row.dynamicDict" @change="setDefaultLength(scope.row)" filterable size="small"
              placeholder="请选择">
              <el-option v-for="item in dynamicDictList" :key="item.id" :label="item.dictValue"
                :value="item.dictKey"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120">
          <template slot="header">
            <el-button @click="addEleRow(editEleList)" type="text" icon="el-icon-circle-plus-outline"
              class="text-icon"></el-button>
          </template>
          <template slot-scope="scope">
            <el-button v-if="scope.row.id" icon="el-icon-remove-outline" type="text"
              @click="delEleRowHandle(scope.$index, editEleList)" class="text-icon text-icon-danger"></el-button>
            <div class="flex" v-else>
              <el-button @click="saveNewEle(scope.row)" type="mini">保存</el-button>
              <el-button icon="el-icon-remove-outline" type="text" @click="delEleRowHandle(scope.$index, editEleList)"
                class="text-icon text-icon-danger"></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editEleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEles" :loading="saveEleLoad">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="(curEleTable.tableName ? curEleTable.tableName : '') +
      '  元素公式(WBS级)'
      " :visible.sync="editEleFormulaVisible" width="800px" append-to-body :close-on-click-modal="false">
      <div class="flex mg-b-10">
        <el-input v-model="formulaInput" placeholder="请输入名称" size="samll" clearable
          @clear="searchFormulaName"></el-input>
        <el-button type="info" class="mg-l-10" @click="searchFormulaName">搜索</el-button>
      </div>
      <el-table :data="editEleListFilter" border style="width: 100%" height="400px">
        <el-table-column align="center" prop="eName" label="元素名称">
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-link :type="scope.row.globalFormula == 1 ? 'warning' : 'primary'"
              @click="toFormulaEdit(scope.row, 1)">全局公式</el-link>
            <el-link v-show="scope.row.hasPartFormula" class="mg-l-10"
              :type="scope.row.isSaveFormula == 1 ? 'warning' : 'primary'"
              @click="toFormulaEdit(scope.row, 2)">节点公式</el-link>
            <!-- <el-link
              class="mg-l-10"
              type="danger"
              @click="delEleRowHandle(scope.$index,editEleListFilter)"
            >删除元素</el-link> -->
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="导入划分" :visible.sync="importTemplateVisible" width="800px" append-to-body @close="daoruClose">
      <div v-loading="importLoading">
        <div>
          <el-link type="primary" @click="handleDownload">下载导入模版</el-link>
        </div>
        <div class="mg-t-20">
          <el-button type="primary" @click="fileClick">选择文件</el-button>
          <span v-if="upFile" class="mg-l-20">{{ upFile.name }}</span>
          <input @change="fileChange" type="file" hidden ref="file" accept=".xls, .xlsx" />
        </div>
        <div v-if="!upFile">当前还未选择文件，请选择需要导入的文件</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importTemplateVisible = false">取 消</el-button>
        <el-button type="primary" @click="importTemplateHandle" :loading="importLoading">导 入</el-button>
      </span>
    </el-dialog>

    <el-dialog title="节点参数" :visible.sync="nodeInfoVisible" width="800px" append-to-body class="jiedian"
      :close-on-click-modal="false" :show-close="false" @close="closenodeInfoVisible">
      <div>
        <el-button type="text" icon="el-icon-s-operation" class="right-btn" @click="setNodeParameters()"></el-button>
        <div class="flexEnd">
          <i class="el-icon-circle-plus marbottom10" @click="addNodeInfoTable()"
            style="font-size: 24px; color: rgb(37, 193, 99); cursor: pointer"></i>
          <i class="el-icon-refresh-right marbottom10" @click="refreshnfoTable()"
            style="font-size: 24px; color: rgb(37, 193, 99); cursor: pointer" v-loading="nodeInfoTableLoad"></i>
        </div>
        <el-table :data="nodeInfoTable" border style="width: 100%" height="400">
          <el-table-column align="center" prop="name" label="参数名称">
            <template slot-scope="scope">
              <el-select v-model="scope.row.k" placeholder="请选择" class="w-100p">
                <el-option v-for="item in namelist" :key="item.k" :label="item.name" :value="item.k"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="value" label="参数值设置">
            <template slot-scope="scope">
              <el-input v-model="scope.row.v"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="describe" label="描述">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" class="text-icon-primary" @click="linkEle(scope.row)">关联元素</el-button>
              <el-button type="text" size="small" class="text-icon-danger"
                @click="delNodeInfoss(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="nodeInfoVisible = false">取 消</el-button>
        <el-button type="primary" @click="nodeInfoSave()" :loading="nodeInfoSaveload">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="设置参数名称" :visible.sync="infoNameVisible" width="800px" append-to-body class="jiedian"
      :close-on-click-modal="false">
      <div>
        <div class="flexEnd">
          <i class="el-icon-circle-plus marbottom10" @click="setParameterName()"
            style="font-size: 24px; color: rgb(37, 193, 99); cursor: pointer"></i>
        </div>
        <el-table :data="namelists" border style="width: 100%" height="400">
          <el-table-column align="center" prop="name" label="参数名称">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="key" label="参数值KEY">
            <template slot-scope="scope">
              <el-input v-model="scope.row.k"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="describe" label="描述">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" class="text-icon-danger"
                @click="delNodeInfo(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParameterName()">保 存</el-button>
        <el-button @click="closeParameter()">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="节点参数设置-关联元素" :visible.sync="linkEleVisible" width="800px" append-to-body class="jiedian"
      :close-on-click-modal="false">
      <div>
        <el-table :data="linkEleTableList" border style="width: 100%" height="400">
          <el-table-column align="center" prop="tableName" label="元素表名">
          </el-table-column>
          <el-table-column align="center" prop="elementName" label="关联元素字段">
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template slot-scope="scope">
              <el-button v-if="!scope.row.mappingId" type="text" size="small" class="text-icon-primary"
                @click="tolinkEle(scope.row)">选择元素</el-button>
              <el-button v-if="!!scope.row.mappingId" type="text" size="small" class="text-icon-danger"
                @click="delLink(scope.row)">删除关联</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="saveLinks">保 存</el-button> -->
        <el-button @click="linkEleVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择关联元素" :visible.sync="linkCheckVisible" width="600px" append-to-body class="jiedian"
      :close-on-click-modal="false">
      <div>
        <div class="flex mg-b-20">
          <el-input v-model="linkEleKey" placeholder="请输入元素关键字搜索"></el-input>
          <el-link class="mg-l-20" :underline="false">
            <i class="el-icon-search" style="font-size: 20px" @click="searchEle"></i>
          </el-link>
        </div>
        <el-table :data="linkEleList" border style="width: 100%" height="400">
          <el-table-column align="center" prop="eName" label="元素名">
          </el-table-column>

          <el-table-column label="操作" width="55">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.checked"
                @change="(value) => linkEleCheck(value, scope.$index)"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveLinkEle">保 存</el-button>
        <el-button @click="linkCheckVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="别名" :visible.sync="aliasVisible" width="600px" append-to-body :close-on-click-modal="false">
      <div>
        <div class="flex">
          <el-input v-model="aliasInput" placeholder="请输入节点别名"></el-input>
          <el-button class="mg-l-20" type="primary" @click="addAlias">添加</el-button>
        </div>
        <div class="flex" style="flex-wrap: wrap">
          <div class="mg-t-10" v-for="(tag, index) in aliasArr" :key="index">
            <el-tag closable @close="delAlias(index)">
              {{ tag }}
            </el-tag>
            <span v-if="index != aliasArr.length - 1">、</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="aliasVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAliasHandle">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="" :visible.sync="formulaCompVisible" fullscreen append-to-body class="full-dialog"
      @close="closeformulaComp">
      <FormulaEdit :wbsid="id" :nodeid="curTreeData.id" :eleid="formulaCurRow.id" :globaltype="formulaCurRow.globaltype"
        @hideDialog="formulaCompVisible = false" v-if="formulaCompVisible" :fromcurNode="curTreeData" :iswbstype="1">
      </FormulaEdit>
    </el-dialog>

    <el-dialog title="" :visible.sync="formulaCompVisible1" fullscreen append-to-body class="full-dialog"
      @close="closeformulaComp1">
      <FormulaEditone :wbsid="id" :nodeid="curTreeData.id" :eleid="formulaCurRow.id"
        :elementType="formulaCurRow.elementType" :globaltype="formulaCurRow.globaltype"
        @hideDialog="formulaCompVisible1 = false" :fromcurNode="curEleTable" :iswbstype="1" v-if="formulaCompVisible1">
      </FormulaEditone>
    </el-dialog>
    <!-- 引入树形复制弹窗组件 -->
    <tree-copy-modal ref="treeCopyModal" :checkId="curTreeData.id" :source-id="id"
      :default-expanded-keys="defaultExpandedKeys" :user-info="userInfo" @close="handleModalClose"
      @link="handleLinkNodes" :linkLoading="linkLoading"></tree-copy-modal>

    <!-- 选择清表表单 -->
    <ChooseExcelTable ref="chooseExcelTableRef" :wbsId="id" :nodeId="curTreeData.id" @confirm="confirmChooseExcelTable">
    </ChooseExcelTable>
  </basic-container>
</template>

<script>
import ManualSorting from "@/components/WbsTree/ManualSorting";
import FormulaEdit from "@/views/formula/edit.vue";
import FormulaEditone from "@/views/formula/edit1.vue";
import TreeCopyModal from './components/TreeCopyModal.vue';
import ChooseExcelTable from "./components/ChooseExcelTable.vue";
import {
  getLazytree,
  getDetail,
  update,
  selectByNodeTable,
  getParamElements,
  delParamElements,
  specifiedParamElements,
  getAlltree,
  saveFormAndElement,
  selectFormElements,
  removeTableById,
  findWbsTreeSameLevel,
  wbsTreeSort,
  findWbsTreeTableSameLevel,
  wbsTreeTableSort,
  parameters,
  saveOrUpdateBatch,
  keymap,
  importwbsTreeFormBatch,
  exportBatchTemplate,
  updateBatchNodeTableInfo,
  importWbsTree,
  exportTemplate,
  remove as removeTreeNode,
  submitFullName,
  refrehPram,
  getQueryValueByType,
} from "@/api/manager/wbstree";

import {
  saveElement,
  remove as removeElement,
  updateBatchElements,
  getTemplate,
  importWbsElement,
  copyNode
} from "@/api/manager/wbsformelement";
import { getDictionary, getChildList } from "@/api/system/dict";
import { mapGetters } from "vuex";
import { getStore, setStore } from "@/util/store";
export default {
  components: {
    ManualSorting,
    FormulaEdit,
    FormulaEditone,
    TreeCopyModal,
    ChooseExcelTable
  },
  data() {
    var checkMajorDataType = (rule, value, callback) => {
      //console.log(this.nodeDetail.nodeType)
      //console.log(this.nodeDetail.majorDataType)
      if (this.nodeDetail.nodeType == 6) {
        if (!this.nodeDetail.majorDataType) {
          callback(new Error("工序节点必须选择内业资料类型"));
        }
      }

      callback();
    };

    return {
      loding: false,
      nodeInfoTableLoad: false,

      formDatass: [],
      editElementFormTag: false,
      ImportElementdata: {},
      ImportElementFile: [], //导入元素file文件
      ImportElementTag: false,
      jiedianId: "",
      excelSortTag: false,
      excelSortTag2: false,
      sortTag2: false,
      sortTag: false,
      sort: [],
      id: "",
      filterText: "",
      isSearch: false,
      treeData: [],
      searchTreeData: [],
      searchtreeLoad: false,
      searchType: "1", //搜索类型
      treeLoad: false,
      menuShow: false,
      defaultProps: {
        children: "children",
        label: "title",
        isLeaf: function (data) {
          if (data.hasChildren && data.isExistForm != 1) {
            return false;
          } else if (data.hasChildren && data.isExistForm == 1) {
            return true;
          } else {
            return true;
          }
        },
      },
      leftType: 5,
      curTreeData: {},
      curTreeNode: {},
      tableData: [],
      nodeDetail: {},
      formData: [],
      editType: 1,

      dialogVisible: false,
      saveNodeLoading: false,
      nodeTypelist: [],
      majorDataTypeList: [],
      rules: {
        nodeName: [
          { required: true, message: "请输入节点名称", trigger: "blur" },
        ],
        nodeType: [
          { required: true, message: "请选择节点类型", trigger: "change" },
        ],
        majorDataType: [{ validator: checkMajorDataType, trigger: "change" }],
      },

      eleVisible: false,
      tableTypelist: [],
      dataTypeList: [],
      ownerTypeList: [],
      eleForm: {
        elementList: [],
      },
      eleRules: {
        nodeName: [
          { required: true, message: "请输入表名称", trigger: "blur" },
        ],
        tableType: [
          { required: true, message: "请选择表类型", trigger: "change" },
        ],
        tableOwner: [
          { required: true, message: "请选择所属方", trigger: "change" },
        ],
      },

      importVisible: false,
      tempList: [],
      checkRow: {},
      curEleTable: {},
      editEleVisible: false,
      saveEleLoad: false,
      editEleList: [],
      eleReg: /(-|>|<|≥|≤|±|【】)?([^≥≤±【】]*)/,

      editEleFormulaVisible: false,
      formulaInput: "",
      editEleListFilter: [],
      editEleListAll: [],

      importTemplateVisible: false,
      fileUrl: "",
      upFile: null,
      importLoading: false,

      nodeInfoVisible: false,
      nodeInfoTable: [],
      namelist: [],
      namelists: [],
      infoNameVisible: false,
      delids: [],
      //数据类型的默认长度
      dataTypeDefaultMap: {
        1: 250, //字符串
        2: 50, //整数
        3: 50, //小数
        4: 50, //日期
        5: 50, //数值
        6: 50, //签名
        7: 100, //文件
      },

      //节点参数，关联元素
      curParam: {}, //当前节点参数
      linkEleVisible: false,
      linkEleTableList: [], //元素表数组
      curLinkEleTable: {}, //当前元素表
      linkCheckVisible: false, //关联弹框
      linkEleList: [], //元素数组
      linkEleKey: "", //搜索关键字

      defaultExpandedKeys: [],
      expandName: this.$route.fullPath,

      aliasVisible: false, //别名
      aliasInput: "",
      aliasArr: [],

      formulaCompVisible: false, //公式弹框
      formulaCompVisible1: false,
      formulaCurRow: {}, //当前元素
      testTreeLoad: false,
      testTreeData: [],
      mixRatioTestIds: [],
      searchinput: "",
      editEleloading: false,

      menuvisible: false, //右键菜单
      menuleft: 20,
      menutop: 0,
      menusData: [
        { icon: "el-icon-plus", label: "新增节点", key: "add" },
        { icon: "el-icon-s-promotion", label: "编辑节点", key: "edit" },
        { icon: "el-icon-sort", label: "排序节点", key: "sort" },
        { icon: "el-icon-document-copy", label: "复制节点", key: "copy" },

        { icon: "el-icon-delete", label: "删除节点", key: "del" },
      ], //树组件操作菜单
      menusData1: [{ icon: "el-icon-plus", label: "新增节点", key: "add" }],
      menuKey: "",
      nodeInfoSaveload: false,
      dynamicDictList: [],
      standardTypeOptions: [], //标准分类
      unitOptions: [], //单位名称
      copyDialogVisible: false, //复制节点弹框
      linkLoading: false, //复制节点加载
      isShowTree: true, //是否显示树组件



    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    dialogTitle: function () {
      let text = "节点";
      if (this.leftType == 1) {
        text = "新增" + text;
      } else if (this.leftType == 2) {
        text = "编辑" + text;
      }
      return text;
    },
    canChooseForm() {
      const { hasChildren, isExistForm } = this.curTreeData;
      // 有节点 && (无子节点 或 有子节点且存在表单)
      return Object.keys(this.curTreeData).length > 0 && (!hasChildren || isExistForm);
    }
  },
  created() {
    this.init();
    //console.log(this.userInfo)
  },
  methods: {
    // 选择表单=======start
    async chooseTable() {
      console.log(this.$refs.chooseExcelTableRef)
      await this.$refs.chooseExcelTableRef.show()
    },
    confirmChooseExcelTable() {
      this.updateTreeNewNode();
      this.updateNodeTable(); //更新元素表
    },
    // 选择表单=======end
    //#region 排序
    paixuMD(data) {
      this.sortTag = true;
      this.sortTag2 = true;
      this.curTreeData = data;
      this.findWbsTreeSameLevel(data.parentId);
    },
    bianhua() {
      this.sortTag2 = false;
      this.$nextTick(() => {
        this.sortTag2 = true;
      });
    },
    editSort() {
      //修改排序
      this.wbsTreeSort();
    },
    async wbsTreeSort() {
      //修改排序
      const { data: res } = await wbsTreeSort(this.sort);
      //console.log(res);
      if (res.code == 200) {
        this.sortTag = false;
        this.sortTag2 = false;
        this.updateTreeNewNode();
      }
    },
    async findWbsTreeSameLevel(parentId) {
      //查询当前节点的同级节点
      const { data: res } = await findWbsTreeSameLevel({ parentId });
      //console.log(res);
      if (res.code === 200) {
        this.sort = res.data;
      }
    },
    async getLazytree() {
      //冲洗获取wbs树
      const { data: res } = await getLazytree(
        this.id,
        0,
        this.userInfo.tenant_id
      );
      //console.log(res);
      if (res.code == 200) {
        this.treeData = res.data;
      }
    },
    bianhua2() {
      this.excelSortTag2 = false;
      this.$nextTick(() => {
        this.excelSortTag2 = true;
      });
    },
    editExcelSort() {
      //确定按钮
      this.wbsTreeTableSort();
    },
    paixucc() {
      if (this.curTreeData.value) {
        this.excelSortTag = true;
        this.excelSortTag2 = true;
        this.findWbsTreeTableSameLevel(this.curTreeData.value);
      } else {
        this.$message({
          type: "warning",
          message: "请先选择需要排序的节点",
        });
      }
    },
    async findWbsTreeTableSameLevel(id) {
      //查询表单
      const { data: res } = await findWbsTreeTableSameLevel({ id });
      //console.log(res);
      if (res.code == 200) {
        this.sort = res.data;
      }
    },
    async wbsTreeTableSort() {
      //表单排序
      const { data: res } = await wbsTreeTableSort(this.sort);
      //console.log(res);
      if (res.code == 200) {
        this.excelSortTag = false;
        this.excelSortTag2 = false;
        this.updateNodeTable(); //更新元素表
      }
    },
    //#endregion

    //#region 甘云杰
    init() {
      //this.id = this.$route.params.id;
      const { id, type } = this.$route.query;
      this.id = id;
      this.wbsType = Number(type);
      this.getNodeTypelist();
      this.getTableTypelist();
      this.getDataTypelist();
      this.getOwnerTypelist();
      this.getDictTypelist();
      this.getStandardTypeOptions();
      this.defaultExpandedKeys = getStore({ name: this.expandName });
    },
    loadNode(node, resolve) {
      let pid = 0;
      if (node.level != 0) {
        pid = node.data.id;
      }
      getLazytree(this.id, pid, this.userInfo.tenant_id).then((res) => {
        let arr = [];
        if (Array.isArray(res.data.data)) {
          arr = res.data.data;
        }
        return resolve(arr);
      });
    },
    //搜索树
    searchTreeClick() {
      this.searchtreeLoad = true;

      if (this.filterText.length > 0) {
        this.isSearch = true;
        getQueryValueByType({
          queryValue: this.filterText,
          type: this.searchType,
          wbsId: this.id,
          projectId: "",
        }).then((res) => {
          let arr = [];
          if (Array.isArray(res.data.data)) {
            arr = res.data.data;
            this.searchTreeData = arr;
          } else {
            this.searchTreeData = [];
          }
        });
      } else {
        this.isSearch = false;
      }

      this.searchtreeLoad = false;
    },
    clearSearch() {
      this.isSearch = false;
    },

    getNodeDetail(data, node) {
      console.log('getNodeDetail', data, node);
      let parentName = "";
      if (node.parent.data) {
        parentName = node.parent.data.title;
      }
      this.curTreeData = data;
      this.curTreeNode = node;
      this.curTreeData.parentName = parentName;
      getDetail(data.id).then((res) => {
        res.data.data.parentName = parentName;
        this.tableData = [res.data.data];
        this.nodeDetail = Object.assign({}, res.data.data);

        if (this.menuKey === "add") {
          this.nodeDetail.nodeName = "";
          this.nodeDetail.className = "";
          this.nodeDetail.unitName = "";
          this.nodeDetail.partitionCode = "";

          this.nodeDetail.uniqueCode = "";
        }
      });
      this.updateNodeTable();

      //获取节点展开路径
      this.getExpandedKeys(node);
    },

    saveNode() {
      const type = this.wbsType;
      this.$refs["nodeDetail"].validate((valid) => {
        if (valid) {
          const { mixRatioTestIds, nodeType } = this.nodeDetail;
          if (type === 2 && nodeType === 53) {
            if (mixRatioTestIds) {
              if (this.editType == 1) {
                this.addNode();
              } else if (this.editType == 2) {
                this.updateNode();
              }
            } else {
              this.$message({
                type: "error",
                message: "请先选择节点",
              });
              return false;
            }
          } else {
            if (this.editType == 1) {
              this.addNode();
            } else if (this.editType == 2) {
              this.updateNode();
            }
          }
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },
    addNode() {
      this.saveNodeLoading = true;
      let subobj = this.nodeDetail;
      subobj.id = "";
      subobj.parentId = this.curTreeData.id;
      subobj.parentName = this.curTreeData.title;

      update(subobj).then(() => {
        this.updateTreeNewNode();
        this.dialogVisible = false;
        this.$message({
          type: "success",
          message: "新增成功!",
        });
      });
    },
    updateNode() {
      console.log("编辑节点");

      update(this.nodeDetail).then(() => {
        let node = this.tableData[0];
        node.nodeName = this.nodeDetail.nodeName;
        node.nodeType = this.nodeDetail.nodeType;
        this.curTreeData.title = this.nodeDetail.nodeName;
        this.dialogVisible = false;
        this.$message({
          type: "success",
          message: "修改成功!",
        });
      });
    },
    toSplit(val) {
      return val ? String(val).split(",") : "";
    },
    setLeftType(type, data, node) {
      this.jiedianId = data.id;
      if (type == 4 || type == 5) {
        this.leftType = type;
      }
      this.curTreeData = data;
      this.curTreeNode = node;
      this.$refs.tree.setCurrentKey(data.id);
      this.mixRatioTestIds = [];
      if (type == 1 || type == 2) {
        this.getMajorDataTypeList();

        this.dialogVisible = true;
        this.editType = type;
      }
      getDetail(data.id).then((res) => {
        let parentName = "";
        if (node.parent.data) {
          parentName = node.parent.data.title;
        }
        res.data.data.parentName = parentName;
        this.tableData = [res.data.data];

        if (type === 1) {
          this.nodeDetail = {
            parentId: res.data.data.id,
            parentName: data.title,
          };
          console.log(this.nodeDetail, " this.nodeDetail");
        } else {
          this.nodeDetail = Object.assign({}, res.data.data);
          this.mixRatioTestIds = this.toSplit(res.data.data.mixRatioTestIds);
        }
        this.nodeDetail.type = 1; //	'1'节点 '2'表单
        this.nodeDetail.wbsId = this.id;
        this.nodeDetail.tenantId = this.userInfo.tenant_id;
        this.changeStandType(this.nodeDetail.className);
      });
      if (this.leftType == 4) {
        selectByNodeTable(data.id).then((res) => {
          if (res.data.data.length) {
            this.formData = res.data.data;
          } else {
            this.formData = [];
          }
        });
      }

      //获取节点展开路径
      this.getExpandedKeys(node);
    },

    deleNode(data, node) {
      this.$confirm(
        "此操作将删除节点【" + data.title + "】, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          removeTreeNode(data.id).then(() => {
            this.$refs.tree.remove(node);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => { });
    },

    showFormElement() {
      if (!this.nodeDetail.id) {
        this.$message({
          type: "warning",
          message: "请先选择在哪个节点下创建表",
        });
        return;
      }
      this.eleForm = {
        elementList: [],
      };
      this.eleVisible = true;
    },

    addEleRow(list) {
      list.push({});
    },
    delEleRow(index, list) {
      list.splice(index, 1);
    },
    saveFormAndElementHandle() {
      this.$refs["eleDialog"].validate((valid) => {
        if (valid) {
          this.eleForm.wbsId = this.id;
          this.eleForm.tenantId = this.userInfo.tenant_id;
          this.eleForm.nodeType = -1;
          this.eleForm.type = 2; //	'1'节点 '2'表单
          this.eleForm.parentId = this.nodeDetail.id;
          for (let i = 0; i < this.eleForm.elementList.length; i++) {
            if (!this.eleForm.elementList[i].eName) {
              this.$message({
                type: "warning",
                message: "请填写第" + (i + 1) + "条元素名称",
              });
              return;
            }
            if (!this.eleForm.elementList[i].eType) {
              this.$message({
                type: "warning",
                message: "请选择第" + (i + 1) + "条数据类型",
              });
              return;
            }
            if (!this.eleForm.elementList[i].eLength) {
              this.$message({
                type: "warning",
                message: "请填写第" + (i + 1) + "条长度",
              });
              return;
            }
          }
          this.eleForm.elementList.forEach((element) => {
            element.eAllowDeviation =
              (element.allow ? element.allow : "") +
              (element.deviation ? element.deviation : "");
            // if (element.eType == 4) {
            //   this.$set(element, 'eLength', 0);
            //   //element.eLength = 0;
            // }
          });
          saveFormAndElement(this.eleForm).then(() => {
            //console.log(res)
            //this.updateTreeNewNode();
            this.updateNodeTable();
            this.eleVisible = false;
            this.$message({
              type: "success",
              message: "新增成功!",
            });
          });
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },

    updateTreeNewNode() {
      let detail = this.nodeDetail.parentId
        ? this.nodeDetail
        : this.curTreeData;
      getLazytree(this.id, detail.parentId).then((res) => {
        let node = this.$refs.tree.getNode(detail.parentId);
        node.isLeaf = false;
        node.isLeafByUser = false;
        //console.log(node)
        this.$refs.tree.updateKeyChildren(detail.parentId, res.data.data);
      });
    },

    updateNodeTable() {
      selectByNodeTable(this.curTreeData.id).then((res) => {
        if (res.data.data && res.data.data.length) {
          this.formData = res.data.data;
        } else {
          this.formData = [];
        }
      });
    },

    importHandle() { },
    //获取编辑元素表格数据
    getSelectFormElements() {
      this.editEleloading = true;
      selectFormElements(this.curEleTable.id, {
        type: 1,
        search: this.searchinput,
      }).then((res) => {
        res.data.data.forEach((element) => {
          this.eleReg.exec(element.eAllowDeviation);
          element.allow = RegExp.$1 ? RegExp.$1 : "";
          element.deviation = RegExp.$2 ? RegExp.$2 : "";
        });
        this.editEleloading = false;
        this.editEleList = res.data.data;
      });
    },
    //编辑元素搜索相关
    clearsearchinput() {
      this.getSelectFormElements();
    },
    searchinputChange() {
      this.getSelectFormElements();
    },
    handleEdit(index, row) {
      this.curEleTable = row;
      // selectFormElements(this.curEleTable.id,{type:1}).then((res) => {
      //   res.data.data.forEach((element) => {
      //     this.eleReg.exec(element.eAllowDeviation);
      //     element.allow = RegExp.$1 ? RegExp.$1 : '';
      //     element.deviation = RegExp.$2 ? RegExp.$2 : '';
      //   })
      //   this.editEleList = res.data.data;
      // })
      this.getSelectFormElements();
      this.editEleVisible = true;
    },
    handleDelete(index, row) {
      this.$confirm("是否删除  " + row.tableName + "  ?", "删除元素表", {
        distinguishCancelAndClose: true,
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      }).then(() => {
        removeTableById(row.id).then((res) => {
          //console.log(res)
          if (res.data.success) {
            this.formData.splice(index, 1);
            //this.updateTreeNewNode();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.msg,
            });
          }
        });
      });
    },

    handleEditFormula(index, row) {
      console.log(row, 'row');
      this.checkRow = row;
      this.curEleTable = row;
      selectFormElements(this.curEleTable.id, { type: 1 }).then((res) => {
        this.editEleListFilter = res.data.data;
        this.editEleListAll = [].concat(this.editEleListFilter);
      });
      this.editEleFormulaVisible = true;
    },

    //搜索 筛选
    searchFormulaName() {
      this.editEleListFilter = this.editEleListAll.filter((ele) => {
        return ele.eName.indexOf(this.formulaInput) > -1;
      });
    },

    saveNewEle(row) {
      if (!row.eName) {
        this.$message({
          type: "warning",
          message: "请填写元素名称",
        });
        return;
      }
      if (!row.eType) {
        this.$message({
          type: "warning",
          message: "请选择数据类型",
        });
        return;
      }

      row.eAllowDeviation =
        (row.allow ? row.allow : "") + (row.deviation ? row.deviation : "");
      row.fId = this.curEleTable.initTableId;
      row.initTableName = this.curEleTable.initTableName;
      // if (row.eType == 4) {
      //   this.$set(row, 'eLength', 0);
      //   //row.eLength = 0;
      // } else
      if (!row.eLength) {
        this.$message({
          type: "warning",
          message: "请填写长度",
        });
        return;
      }

      saveElement(row).then((res) => {
        if (res.data.data) {
          this.$set(row, "id", res.data.data.id);
          this.$set(row, "ekey", res.data.data.ekey);
          this.$message({
            type: "success",
            message: "保存成功!",
          });
        }
      });
    },
    delEleRowHandle(index, list) {
      let row = list[index];
      if (row.id) {
        //有id需要请求删除
        this.$confirm("是否确认删除?", "删除元素", {
          distinguishCancelAndClose: true,
          confirmButtonText: "删除",
          cancelButtonText: "取消",
        }).then(() => {
          removeElement(row.id, this.curEleTable.initTableName, row.ekey).then(
            () => {
              list.splice(index, 1);
            }
          );
          this.curEleTable.elementTotal--;
        });
      } else {
        list.splice(index, 1);
      }
    },
    saveEles() {
      for (let i = 0; i < this.editEleList.length; i++) {
        if (!this.editEleList[i].id) {
          this.$message({
            type: "warning",
            message: "请先将新增的元素点击保存",
          });
          return;
        }
        if (!this.editEleList[i].eName) {
          this.$message({
            type: "warning",
            message: "请填写第" + (i + 1) + "条元素名称",
          });
          return;
        }
        if (!this.editEleList[i].eType) {
          this.$message({
            type: "warning",
            message: "请选择第" + (i + 1) + "条数据类型",
          });
          return;
        }
        if (!this.editEleList[i].eLength) {
          this.$message({
            type: "warning",
            message: "请填写第" + (i + 1) + "条长度",
          });
          return;
        }
      }
      if (this.editEleList.length > 0) {
        this.editEleList.forEach((element) => {
          element.eAllowDeviation =
            (element.allow ? element.allow : "") +
            (element.deviation ? element.deviation : "");
          // if (element.eType == 4) {
          //   this.$set(element, 'eLength', 0);
          //   //element.eLength = 0;
          // }
        });
        this.saveEleLoad = true
        updateBatchElements(
          this.editEleList,
          this.curEleTable.initTableName
        ).then(() => {
          this.saveEleLoad = false
          this.editEleVisible = false;
          this.updateNodeTable();
          this.$message({
            type: "success",
            message: "保存成功!",
          });
        });
      } else {
        this.editEleVisible = false;
        this.updateNodeTable();
        this.$message({
          type: "success",
          message: "保存成功!",
        });
      }
    },
    nodeTypeChange(val) {
      if (val === 53) {
        if (this.testTreeData.length > 0) {
          return;
        }
        this.testTreeLoad = true;
        getAlltree(this.userInfo.tenant_id, 1, this.id).then((res) => {
          this.testTreeLoad = false;
          this.testTreeData = res.data.data;
        });
      }
    },
    //根据逗号联合
    toJoin(arr) {
      return arr ? arr.join() : "";
    },
    TestTreeCheckChange(_, { checkedKeys, halfCheckedKeys }) {
      // const newarr = [...checkedKeys, ...halfCheckedKeys]
      const newarr = [...checkedKeys];
      this.nodeDetail.mixRatioTestIds = this.toJoin(newarr);
    },
    // filterChange () {
    //   if (this.treeData.length > 0) {
    //     this.$refs.treeall.filter(this.filterText);
    //     return;
    //   }
    //   this.treeLoad = true;
    //   getAlltree(this.userInfo.tenant_id, 1, this.id).then((res) => {
    //     this.treeLoad = false;
    //     this.treeData = res.data.data;
    //     this.$nextTick(() => {
    //       this.$refs.treeall.filter(this.filterText);
    //     })
    //   })
    // },

    importTemplate(data) {
      this.importTemplateVisible = true;
      this.curTreeData = data;
    },
    daoruClose() {
      this.upFile = null;
    },
    importTemplateHandle() {
      if (!this.upFile) {
        this.$message({
          type: "warning",
          message: "请先选择文件再进行导入",
        });
        return;
      }
      let forms = new FormData();
      forms.append("excelFile", this.upFile);
      let wbsTreeFu = {
        wbsId: this.id,
        parentId: this.curTreeData.id,
        // ancestors:'0,'+this.curTreeData.id,
      };
      let json = JSON.stringify(wbsTreeFu);
      let blob = new Blob([json], { type: "application/json" });
      forms.append("wbsTreeFu", blob);
      this.importLoading = true;
      importWbsTree(forms)
        .then(() => {
          //this.$router.go(0)
          let node = this.$refs.tree.getNode(this.curTreeData.id);
          node.isLeaf = false;
          this.importTemplateVisible = false;
          this.upFile = null;
        })
        .finally(() => {
          this.importLoading = false;
        });
    },

    handleDownload() {
      //WBS划分模板
      exportTemplate().then((res) => {
        this.downloadExcel(res.data, "WBS划分模板");
      });
    },

    fileClick() {
      this.$refs.file.click();
    },

    fileChange(e) {
      const file = e.target.files[0];
      if (!file) {
        // 如果用户没有选择图片,只是点了文件上传这个按钮
        return;
      }
      //console.log(file)
      this.upFile = file;
    },
    downloadTmp() {
      getTemplate().then((res) => {
        //console.log(res)
        this.downloadExcel(res.data, "元素模板");
      });
    },

    fileClick2() {
      this.$refs.file2.click();
    },
    tmpImport(e) {
      const file = e.target.files[0];
      const formData = new FormData();
      formData.append("file", file);
      //console.log(file.name)
      importWbsElement(formData)
        .then((res) => {
          res.data.data.forEach((element) => {
            element.eName = element.elementName;
            element.eLength = element.elementLength;
            element.eType = Number(element.elementType);
            element.eAllowDeviation = element.elementAllowDeviation;
            element.eInspectionMethod = element.elementInspectionMethod;
            if (element.eAllowDeviation.indexOf(",") > 0) {
              element.allow = "【】";
              element.deviation = element.eAllowDeviation;
            } else {
              this.eleReg.exec(element.eAllowDeviation);
              // console.log(RegExp.$1)
              // console.log(RegExp.$2)
              element.allow = RegExp.$1 ? RegExp.$1 : "";
              element.deviation = RegExp.$2 ? RegExp.$2 : "";
            }
          });
          this.eleForm.elementList = res.data.data;
          this.importVisible = false;
        })
        .finally(() => {
          e.target.value = "";
        });
    },

    visiblechange(value, data) {
      this.$set(data, "moreShow", value);
    },

    downloadExcel(data, filename = "") {
      let blob = new Blob([data], {
        type: "application/vnd.ms-excel",
      });
      //console.log(blob)
      if (!filename) {
        filename = Date.parse(new Date());
      }
      filename = filename + ".xls";
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10
        window.navigator.msSaveBlob(blob, filename);
      } else {
        //  兼容chrome/firefox
        let aTag = document.createElement("a");
        aTag.download = filename;
        aTag.href = window.URL.createObjectURL(blob);
        aTag.click();
        URL.revokeObjectURL(aTag.href);
      }
    },

    toFormulaEdit(row, type) {
      // this.$router.push({
      //   path: '/formula/edit',
      //   query: {
      //     wbsid: this.id,
      //     eleid: row.id,
      //     nodeid:this.curTreeData.id
      //   }
      // });
      //this.editEleFormulaVisible = false;
      this.curEleTable = row;
      this.formulaCurRow = row;
      this.formulaCurRow.globaltype = type;
      if (type === 1) {
        this.formulaCompVisible1 = true;
        this.formulaCurRow.elementType = false;
      } else {
        this.formulaCompVisible = true;
      }
    },
    //关闭公式弹窗
    closeformulaComp() {
      console.log(this.checkRow, '  this.checkRow');

      console.log("关闭");
      selectFormElements(this.checkRow.id, { type: 1 }).then((res) => {
        this.editEleListFilter = res.data.data;
        this.editEleListAll = [].concat(this.editEleListFilter);
      });
    },
    //关闭公式弹窗
    closeformulaComp1() {
      console.log("关闭");
      selectFormElements(this.checkRow.id, { type: 1 }).then((res) => {
        this.editEleListFilter = res.data.data;
        this.editEleListAll = [].concat(this.editEleListFilter);
      });
    },
    getNodeTypelist() {
      const type = this.wbsType;
      console.log(this.nodeTypelist, "this.nodeTypelist");
      if (this.nodeTypelist.length > 1) {
        return;
      }
      let code = "";
      if (type === 5) {
        code = "lar_node_type"; //征拆
      } else if (type === 2) {
        code = "trial_node_type"; //试验
      } else if (type === 3) {
        code = "meter_node_type"; //计量
      } else {
        {
          code = "wbs_node_type"; //质检
        }
      }

      getDictionary({
        code,
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.nodeTypelist = res.data.data;
      });
    },
    getMajorDataTypeList() {
      getDictionary({
        code: "major_data_type",
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.majorDataTypeList = res.data.data;
      });
    },
    getStandardTypeOptions() {
      getDictionary({
        code: "classification",
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        // 定义要过滤的 dictKey 值
        const targetKeys = [1, 2, 3, 4, 5];
        // 过滤数组
        const filteredOptions = res.data.data.filter((item) =>
          targetKeys.includes(item.dictKey)
        );

        this.standardTypeOptions = filteredOptions;
      });
    },
    changeStandType(val) {
      let parentId = "";
      this.standardTypeOptions.forEach((item) => {
        if (item.dictKey == val) {
          parentId = item.id; // 找到匹配项，提取 parentId
        }
      });

      getChildList(1, 10000, parentId).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.unitOptions = res.data.data;
        this.unitOptions = this.unitOptions.filter(
          (item) => item.dictKey != -1
        );
      });
    },
    getTableTypelist() {
      const type = this.wbsType;
      if (this.tableTypelist.length > 1) {
        return;
      }
      let code = "";
      if (type === 5) {
        code = "table_type"; //征拆
      } else if (type === 2) {
        code = "trial_table_type"; //试验
      } else {
        code = "table_type"; //质检
      }
      getDictionary({
        // code: "table_type",

        code: code,
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.tableTypelist = res.data.data;
      });
    },
    getDataTypelist() {
      if (this.dataTypeList.length > 1) {
        return;
      }
      getDictionary({
        code: "data_type",
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.dataTypeList = res.data.data;
      });
    },
    getDictTypelist() {
      if (this.dynamicDictList.length > 1) {
        return;
      }
      getDictionary({
        code: "land_field_dict",
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.dynamicDictList = res.data.data;
      });
    },
    getOwnerTypelist() {
      if (this.ownerTypeList.length > 1) {
        return;
      }
      getDictionary({
        code: "owner_type",
      }).then((res) => {
        res.data.data.forEach((element) => {
          element.dictKey = Number(element.dictKey);
        });
        this.ownerTypeList = res.data.data;
      });
    },

    formatCat(row, column, cellValue) {
      for (let i = 0; i < this.nodeTypelist.length; i++) {
        if (this.nodeTypelist[i].dictKey == cellValue) {
          return this.nodeTypelist[i].dictValue;
        }
      }
      return cellValue;
      //console.log(cellValue)
    },
    formatTableType(row, column, cellValue) {
      for (let i = 0; i < this.tableTypelist.length; i++) {
        if (this.tableTypelist[i].dictKey == cellValue) {
          return this.tableTypelist[i].dictValue;
        }
      }
      return cellValue;
      //console.log(cellValue)
    },
    formatOwner(row, column, cellValue) {
      for (let i = 0; i < this.ownerTypeList.length; i++) {
        if (this.ownerTypeList[i].dictKey == cellValue) {
          return this.ownerTypeList[i].dictValue;
        }
      }
      return cellValue;
      //console.log(cellValue)
    },
    formatdataType(row, column, cellValue) {
      for (let i = 0; i < this.dataTypeList.length; i++) {
        if (this.dataTypeList[i].dictKey == cellValue) {
          return this.dataTypeList[i].dictValue;
        }
      }
      return cellValue;
      //console.log(cellValue)
    },

    // filterNode (value, data) {
    //   //console.log(value)
    //   if (!value) return true;
    //   return data.title.indexOf(value) !== -1;
    // },

    getReturnNode(node, _array, value) {
      let isPass =
        node.data && node.data.title && node.data.title.indexOf(value) !== -1;
      isPass ? _array.push(isPass) : "";
      if (!isPass && node.level != 1 && node.parent) {
        this.getReturnNode(node.parent, _array, value);
      }
    },

    filterNode(value, data, node) {
      if (!value) {
        return true;
      }
      let level = node.level;
      let _array = []; //这里使用数组存储 只是为了存储值。
      this.getReturnNode(node, _array, value);
      let result = false;
      _array.forEach((item) => {
        result = result || item;
      });
      return result;
    },
    //修改数据类型，给个默认值
    setDefaultLength(row) {
      this.$set(row, "eLength", this.dataTypeDefaultMap[row.eType]);
    },

    //#endregion

    //#region 节点参数
    nodeInfo(data) {
      //节点参数按钮
      this.keymap();
      this.jiedianId = data.id;
      this.parameters(data.id);
      this.nodeInfoVisible = true;
    },
    closenodeInfoVisible() {
      this.nodeInfoTable = [];
      this.nodeInfoVisible = false;
    },
    addNodeInfoTable() {
      //添加节点参数数据
      this.nodeInfoTable.unshift({
        k: "",
        v: "",
        remark: "",
        nodeId: this.jiedianId,
        type: 1,
      });
    },
    refreshnfoTable() {
      //刷新表格
      let prams = {
        nodeId: this.jiedianId,
        type: 0,
      };
      this.nodeInfoTableLoad = true;
      refrehPram(prams).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          this.nodeInfoTableLoad = false;
          this.$message.success("刷新成功");
        }
      });
    },
    delNodeInfo(key, obj) {
      //设置参数名称中的删除按钮
      this.delids.push(obj.id);
      this.namelists.splice(key, 1);
    },
    delNodeInfoss(key, obj) {
      //节点参数
      this.delids.push(obj.id);
      this.nodeInfoTable.splice(key, 1);
    },
    setNodeParameters() {
      //打开设置节点参数弹框按钮
      this.infoNameVisible = true;
      this.namelists = [...this.namelist];
    },
    async setParameterName() {
      //设置参数名称中添加节点参数按钮
      // wbsId: this.jiedianId
      this.namelists.unshift({
        name: "",
        remark: "",
        k: "",
        type: 0,
        nodeId: this.jiedianId,
      });
    },
    async nodeInfoSave() {
      //节点参数弹框保存按钮
      if (this.nodeInfoTable) {
        // if(this.nodeInfoTable.length == 0){
        //   await this.saveOrUpdateBatch({projectId:this.projectid,nodeId:this.jiedianId,type:1,delIds:this.delids,wps:[
        //     {
        //       nodeId: this.jiedianId,
        //       type: -1,
        //     },
        //   ]})
        //   this.delIds=[];
        //   this.nodeInfoVisible = false
        //   this.$message({
        //     type: "success",
        //     message: "保存参数节点成功!"
        //   })
        //   return;
        // }

        let tag = true;
        this.nodeInfoTable.forEach((val) => {
          if (!val.k | !val.v) {
            return (tag = false);
          }

          //if(!val.name){
          for (let i = 0; i < this.namelist.length; i++) {
            if (this.namelist[i].k == val.k) {
              val.name = this.namelist[i].name;
              return;
            }
          }
          //}
        });
        if (tag) {
          this.nodeInfoSaveload = true;
          await this.saveOrUpdateBatch({
            scopeType: 1,
            projectId: this.projectid,
            nodeId: this.jiedianId,
            wps: this.nodeInfoTable,
            type: 1,
            delIds: this.delids,
          });
          this.delIds = [];
          this.$message({
            type: "success",
            message: "设置参数节点成功!",
          });
          this.nodeInfoSaveload = false;
          // this.nodeInfoVisible = false;
          this.parameters(this.jiedianId);
        } else {
          this.$message({
            type: "error",
            message: "请填写所有的参数名称和参数值!",
          });
        }
      } else {
        this.$message({
          type: "error",
          message: "请先设置参数节点!",
        });
      }
    },
    async addParameterName() {
      //设置参数名称中的保存按钮
      if (this.namelists.length) {
        let tag = true;
        this.namelists.forEach((val) => {
          if (!val.name || !val.k) {
            return (tag = false);
          }
        });
        if (tag) {
          await this.saveOrUpdateBatch({
            scopeType: 1,
            projectId: this.projectid,
            nodeId: this.jiedianId,
            wps: this.namelists,
            type: 0,
            delIds: this.delids,
          }); //保存设置参数
          this.infoNameVisible = false;
          this.delIds = [];
          this.keymap();
        } else {
          this.$message({
            type: "error",
            message: "请填写所有的参数名称和参数值KEY!",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先添加参数",
        });
      }
    },
    closeParameter() {
      //设置参数名称，关闭按钮
      this.namelists = [];
      this.infoNameVisible = false;
    },
    async parameters(wbsId) {
      //获取接待你参数列表
      const { data: res } = await parameters({ wbsId });
      console.log(res);
      if (res.code == 200) {
        if (Array.isArray(res.data)) {
          this.nodeInfoTable = res.data;
        }
      }
    },
    async saveOrUpdateBatch(da) {
      //保存
      const { data: res } = await saveOrUpdateBatch(da);
      this.delids = [];
      //console.log(res);
    },
    async keymap() {
      //节点参数枚举
      const { data: res } = await keymap();
      //console.log(res);
      if (res.code == 200) {
        this.namelist = res.data;
      }
    },
    //#endregion

    //#region 导入元素
    ImportElement(data) {
      //导入元素按钮
      console.log(data);
      this.ImportElementdata.ancestors = data.ancestors;
      this.ImportElementdata.id = data.id;
      this.ImportElementTag = true;
    },
    async pushImportElement() {
      //确定按钮
      if (this.ImportElementFile.length > 0) {
        let formData = new FormData();
        formData.append("wbsId", this.$route.params.id);
        formData.append("ancestors", this.ImportElementdata.ancestors);
        formData.append("id", this.ImportElementdata.id);
        formData.append("tenantId", this.userInfo.tenant_id);
        formData.append("excelFile", this.ImportElementFile[0].raw);
        await this.importwbsTreeFormBatch(formData);
        this.ImportElementFile = [];
        this.ImportElementTag = false;
      }
    },
    ImportElementHandleClose() {
      //关闭弹框事件
      this.ImportElementTag = false;
      this.loding = false;
      this.ImportElementFile = [];
    },
    ElementChange(file, fileList) {
      //文件上传时的钩子
      //console.log(fileList);
      if (this.ImportElementFile.length == 0) {
        this.ImportElementFile = fileList;
      }
    },
    ElementRemove(file, fileList) {
      this.ImportElementFile = fileList;
    },
    async importwbsTreeFormBatch(da) {
      this.loding = true;
      try {
        const { data: res } = await importwbsTreeFormBatch(da);
        console.log(res);
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "导入成功!",
          });
        }
        this.loding = false;
      } catch (error) {
        this.loding = false;
      }
    },
    async exportBatchTemplate() {
      const res = await exportBatchTemplate();
      //console.log(res);
      if (res.status == 200) {
        this.downloadExcel(res.data, "导入元素模板");
      }
    },
    xiazaielement() {
      this.exportBatchTemplate();
    },
    //#endregion

    //#region 元素表单信息
    editEditElementForm() {
      //标记元素
      if (this.formData.length) {
        let da = [];
        this.formDatass = [...this.formData];
        this.formDatass.forEach((val) => {
          da.push({
            tableType: val.tableType - 0,
            tableOwner: val.tableOwner - 0,
            id: val.id,
            tableName: val.tableName,
            fillRate: val.fillRate,
          });
        });
        this.formDatass = da;
        this.editElementFormTag = true;
      }
    },
    editeditElementFormMF() {
      //保存按钮
      let da = [];
      let tag = true;
      this.formDatass.forEach((val) => {
        if (!val.tableName || !val.tableType || !val.tableOwner) {
          tag = false;
          return;
        } else {
          da.push({
            id: val.id,
            nodeName: val.tableName,
            tableType: val.tableType,
            tableOwner: val.tableOwner,
            fillRate: val.fillRate,
          });
        }
      });
      if (tag) {
        this.updateBatchNodeTableInfo(da);
      } else {
        this.$message({
          type: "success",
          message: "请填写完整元素表单的所有信息!",
        });
      }
    },
    async updateBatchNodeTableInfo(da) {
      //共有编辑元素
      const { data: res } = await updateBatchNodeTableInfo(da);
      //console.log(res);
      if (res.code == 200) {
        this.editElementFormTag = false;
        this.updateNodeTable();
      }
    },
    //#endregion

    //获取节点展开路径
    getExpandedKeys(node) {
      //console.log(node)
      let expandedKeys = [];
      while (node.parent) {
        expandedKeys.push(node.data.id);
        node = node.parent;
      }
      setStore({
        name: this.expandName,
        content: expandedKeys,
        type: true, //sessionStorage
      });
      //console.log(expandedKeys)
    },

    //节点参数 关联元素
    linkEle(row) {
      if (!row.id) {
        this.$message.warning("请先保存数据，再点击关联元素");
      } else {
        this.linkEleVisible = true;
        this.curParam = row;
        getParamElements({
          nodeId: this.jiedianId,
          paramId: row.id,
          scopeType: 1,
        }).then((res) => {
          if (res.data.data.length) {
            this.linkEleTableList = res.data.data;
          } else {
            this.linkEleTableList = [];
          }
        });
      }
    },

    //保存关联
    saveLinks() { },

    //删除关联
    delLink(data) {
      this.$confirm("删除关联, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(data);
          delParamElements(data).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });

            getParamElements({
              nodeId: this.jiedianId,
              paramId: this.curParam.id,
              scopeType: 1,
            }).then((res) => {
              if (res.data.data.length) {
                this.linkEleTableList = res.data.data;
              } else {
                this.linkEleTableList = [];
              }
            });
          });
        })
        .catch(() => { });
    },

    //关联元素弹框
    tolinkEle(row) {
      this.curLinkEleTable = row;
      this.linkCheckVisible = true;
      selectFormElements(row.id, { nodeId: this.jiedianId, type: 5 }).then(
        (res) => {
          res.data.data.forEach((ele) => {
            ele.checked = false;
            ele.show = true;
          });
          this.linkEleList = res.data.data;
          this.linkEleListAll = [].concat(this.linkEleList);
        }
      );
    },

    linkEleCheck(value, index) {
      //console.log(value)
      if (value) {
        this.linkEleList.forEach((ele, i) => {
          if (i != index) {
            ele.checked = false;
          }
        });
      }
    },

    //关联元素
    saveLinkEle() {
      let target = {};
      this.linkEleList.forEach((e) => {
        if (e.checked == true) {
          target = { elementId: e.id, paramId: this.curParam.id };
        }
      });
      if (JSON.stringify(target) !== "{}") {
        specifiedParamElements(target).then((data) => {
          this.linkCheckVisible = false;
          getParamElements({
            nodeId: this.jiedianId,
            paramId: this.curParam.id,
            scopeType: 1,
          }).then((res) => {
            if (res.data.data.length) {
              this.linkEleTableList = res.data.data;
            } else {
              this.linkEleTableList = [];
            }
          });
        });
      } else {
        this.$message.warning("请先选择关联元素");
      }
    },

    //筛选元素
    searchEle() {
      this.linkEleList = this.linkEleListAll.filter((ele) => {
        return ele.eName.indexOf(this.linkEleKey) > -1;
      });
    },

    //触发节点参数
    nodeInfoHandle() {
      if (!this.curTreeData.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }

      this.nodeInfo(this.curTreeData);
    },

    eleFormulaHandle() {
      if (!this.curTreeData.id || !this.curTreeNode.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }
      this.setLeftType(4, this.curTreeData, this.curTreeNode);
    },

    addNodeHandle() {
      if (!this.curTreeData.id || !this.curTreeNode.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }
      if (
        this.curTreeData.nodeType == 6 ||
        this.curTreeData.isExistForm == 1 ||
        this.curTreeData.unitName ||
        this.curTreeData.className
      ) {
        this.$message({
          type: "warning",
          message: "该节点下无法新增节点",
        });
        return;
      }
      this.mixRatioTestIds = [];
      this.setLeftType(1, this.curTreeData, this.curTreeNode);
    },

    editNodeHandle() {
      if (!this.curTreeData.id || !this.curTreeNode.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }
      this.nodeTypeChange(53);
      this.setLeftType(2, this.curTreeData, this.curTreeNode);
    },
    copyNodeHandle() {
      if (!this.curTreeData.id || !this.curTreeNode.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }
    },
    delNodeHandle() {
      if (!this.curTreeData.id || !this.curTreeNode.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }
      if (this.curTreeNode.level == 1) {
        this.$message({
          type: "warning",
          message: "当前节点无法删除",
        });
        return;
      }
      this.deleNode(this.curTreeData, this.curTreeNode);
    },

    eleHandle() {
      if (!this.curTreeData.id || !this.curTreeNode.id) {
        this.$message({
          type: "warning",
          message: "请先选择节点",
        });
        return;
      }

      this.setLeftType(5, this.curTreeData, this.curTreeNode);
    },

    //显示别名弹窗
    aliasShow() {
      this.aliasVisible = true;
      if (this.nodeDetail.fullName) {
        this.aliasArr = this.nodeDetail.fullName.split(",");
      } else {
        this.aliasArr = [];
      }
      this.aliasInput = "";
    },

    addAlias() {
      if (this.aliasInput) {
        this.aliasArr.push(this.aliasInput);
        this.aliasInput = "";
      }
    },
    delAlias(index) {
      this.aliasArr.splice(index, 1);
    },

    saveAliasHandle() {
      this.nodeDetail.fullName = this.aliasArr.join(",");
      if (this.editType == 1) {
        //新增
        this.aliasVisible = false;
      } else if (this.editType == 2) {
        //编辑 公有
        submitFullName(this.nodeDetail.id, this.nodeDetail.fullName).then(
          () => {
            this.$message({
              type: "success",
              message: "保存成功",
            });
            this.aliasVisible = false;
          }
        );
      }
    },
    //树形控件菜单相关方法
    mouseout() {
      this.menuvisible = false;
    },
    //展示菜单
    showMenu(e, data, node) {
      e.preventDefault();
      console.log(e, "e");
      var x = e.pageX; //这个应该是相对于整个浏览器页面的x坐标，左上角为坐标原点（0,0）
      var y = e.pageY; //这个应该是相对于整个浏览器页面的y坐标，左上角为坐标原点（0,0）
      this.menutop = y;
      this.menuleft = x;
      this.menuvisible = true;
    },
    menuClick(e, item, data, node) {

      this.curTreeData = data; //当前节点数据
      this.curTreeNode = node; //当前节点数据


      this.menuKey = "";
      e.preventDefault();
      if (item.key === "add") {
        this.addNodeHandle();
        this.menuKey = "add";
      } else if (item.key === "edit") {
        this.editNodeHandle();
        this.menuKey = "edit";
      } else if (item.key === "del") {
        this.menuKey = "del";
        this.delNodeHandle();
      } else if (item.key === "copy") {

        this.$refs.treeCopyModal.show();
      } else if (item.key === "sort") {
        this.menuKey = "sort";
        this.paixuMD(data);
      }
    },
    handleModalClose() {
      console.log('树形复制弹窗已关闭');
      // 可以在这里处理弹窗关闭后的逻辑
      this.reloadTree();
    },
    reloadTree() {
      this.isShowTree = false;
      setTimeout(() => {
        this.isShowTree = true;
      }, 100);
    },

    // 处理节点关联
    async handleLinkNodes(linkData, callback) {
      console.log('准备关联的节点数据:', linkData);

      this.linkLoading = true;
      try {
        const { data: res } = await copyNode({
          leftIds: linkData.sourceNodes,
          rightIds: linkData.targetNodes,
        });

        console.log(res);
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          });
          // 调用回调函数通知成功
          if (callback) callback(true);
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
          if (callback) callback(false);
        }
      } catch (error) {
        console.error('关联节点失败:', error);
        // this.$message({
        //   type: 'error',
        //   message: '关联失败，请重试'
        // });
        if (callback) callback(false);
      } finally {
        this.linkLoading = false;
      }
    }
    //表单排序

  },
};
</script>

<style scoped lang="scss">
//树结构超长后产生滚动条
.el-tree>.el-tree-node {
  min-width: 100%;
  display: inline-block;
}

.font-s-12 ::v-deep .iconfont {
  font-size: 12px;
}

.el-popper[x-placement^="bottom"] {
  margin-top: -6px;
}

.right-btn {
  position: absolute;
  right: 20px;
  top: 10px;
  font-size: 20px;
}

.custom-tree-node {
  .normal-black {
    display: none;
  }

  &:hover {
    .normal-black {
      display: inline-block;
    }
  }

  &.show .normal-black {
    display: inline-block;
  }
}

.jiedian {
  ::v-deep.el-dialog__body {
    padding: 10px 20px !important;
  }
}

.filter-tree {
  min-width: 100%;
  display: inline-block;
}

.full-dialog {
  ::v-deep .el-dialog__body {
    padding-bottom: 0;
  }

  ::v-deep .basic-container {
    height: calc(100vh - 60px);
  }
}

.titlerow {
  // float: right;
  background-color: rgba(31, 34, 41, 0.8);
  padding-left: 10px;
  padding-right: 10px;
  text-align: right;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

// 树形控件菜单样式
.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 1000;
  position: fixed; //关键样式设置固定定位
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
}

.contextmenu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
}

.contextmenu li:hover {
  background: #eee;
}
</style>
