<template>
  <basic-container>
    <div class="h-100p">
      <el-tabs
        v-model="activeType"
        :before-leave="beforeLeave"
      >
        <el-tab-pane
          label="项目基本信息"
          name="1"
          :disabled="btnLoad"
        >
          <div>
            <el-form
              :model="projectForm"
              :rules="projectRules"
              ref="projectForm"
              label-width="120px"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="项目名称"
                    prop="projectName"
                  >
                    <el-input v-model="projectForm.projectName"></el-input>
                  </el-form-item>
                  <el-form-item
                    label="项目别名"
                    prop="projectAlias"
                  >
                    <el-input v-model="projectForm.projectAlias"></el-input>
                  </el-form-item>
                  <el-form-item
                    label="项目编号"
                    prop="projectNumber"
                  >
                    <el-input v-model="projectForm.projectNumber"></el-input>
                  </el-form-item>
                  <el-form-item
                    label="公路等级"
                    prop="projectGrade"
                  >
                    <el-select
                      v-model="projectForm.projectGrade"
                      placeholder="请选择"
                      class="w-100p"
                    >
                      <el-option
                        v-for="item in highwayGradeList"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="计划开工日期"
                    prop="planStartTime"
                  >
                    <el-date-picker
                      v-model="projectForm.planStartTime"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="实际开工日期"
                    prop="actualStartTime"
                  >
                    <el-date-picker
                      v-model="projectForm.actualStartTime"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="项目预算投资"
                    prop="estimatedAmount"
                  >
                    <el-input v-model="projectForm.estimatedAmount">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item
                    label="施工文件后缀"
                    prop="sgSuffix"
                  >
                    <el-input v-model="projectForm.sgSuffix">
                    
                    </el-input>
                  </el-form-item>
                  <el-form-item
                    label="监理文件后缀"
                    prop="jlSuffix"
                  >
                    <el-input v-model="projectForm.jlSuffix">
                    </el-input>
                  </el-form-item>
                      <el-form-item
                      label="电签类别"
                      prop="remarkType"
                    >
                    <el-tooltip slot="label" effect="light" content="选择本项目所要应用的电签公司" placement="top">
                      <span>电签类别</span>
                    </el-tooltip>

                      <el-radio-group v-model="projectForm.remarkType">
                        <el-radio :label="1">安心签</el-radio>
                        <el-radio :label="2">（首讯）东方中讯</el-radio>
                        <el-radio :label="3">东方中讯</el-radio>
                      </el-radio-group>
                    </el-form-item>
                 
               
                  <el-form-item
                    label="电签方式"
                    prop="approvalType"
                  >
                  <el-tooltip slot="label" effect="light" content="平行审批只作用于质检系统，计量系统默认流程审批" placement="top">
                      <span>电签方式</span>
                    </el-tooltip>
                    <el-radio-group v-model="projectForm.approvalType">
                      <el-radio :label="1">流程审批</el-radio>
                      <el-radio :label="2">平行审批</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item
                    label="系统计量单元"
                    prop="projectGrade"
                  >
                    <el-select
                      v-model="projectForm.meterTemplateId"
                      placeholder="请选择"
                      class="w-100p"
                      clearable
                    >
                      <el-option
                        v-for="item in meterTemplateOption"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="项目状态"
                    prop="projectStatus"
                  >
                    <el-select
                      v-model="projectForm.projectStatus"
                      placeholder="请选择"
                      class="w-100p"
                      clearable
                    >
                     <el-option
                    v-for="item in proStatusItems"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="项目负责人"
                    prop="projectLeader"
                  >
                    <el-select
                      v-model="projectForm.projectLeader"
                      placeholder="请选择"
                      class="w-100p"
                      clearable
                      filterable

                    >
                     <el-option
                    v-for="item in createUserItems"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="项目概况"
                    prop="projectGist"
                  >
                    <el-input
                      v-model="projectForm.projectGist"
                      type="textarea"
                      :rows="7"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    label="内置里程"
                    prop="projectAllMileage"
                  >
                    <el-radio-group v-model="radioType">
                      <el-radio-button label="总里程"></el-radio-button>
                      <el-radio-button label="路面"></el-radio-button>
                      <el-radio-button label="路基"></el-radio-button>
                    </el-radio-group>
                    <el-input-number
                      v-model="projectForm.projectAllMileage"
                      v-show="radioType == '总里程'"
                      :min="0"
                      label="总里程"
                    ></el-input-number>
                    <el-input-number
                      v-model="projectForm.projectPavement"
                      v-show="radioType == '路面'"
                      :min="0"
                      label="路面"
                    ></el-input-number>
                    <el-input-number
                      v-model="projectForm.projectSubgrade"
                      v-show="radioType == '路基'"
                      :min="0"
                      label="路基"
                    ></el-input-number>
                    <span>公里(KM)</span>
                  </el-form-item>
                  <el-form-item
                    label="计划完工日期"
                    prop="planEndTime"
                  >
                    <el-date-picker
                      v-model="projectForm.planEndTime"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="实际完工日期"
                    prop="actualEndTime"
                  >
                    <el-date-picker
                      v-model="projectForm.actualEndTime"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item
                    label="开启随机数"
                    prop="isOpenRandomNumber"
                  >
                  <el-tooltip slot="label" effect="light" content="开启表单右键功能随机数生成" placement="top">
                      <span>开启随机数</span>
                    </el-tooltip>
                    <el-radio-group v-model="projectForm.isOpenRandomNumber">
                      <el-radio :label="0">不开启</el-radio>
                      <el-radio :label="1">开启</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item v-if="false"
                    label="是否为省级模板"
                    prop="isOpenRandomNumber"
                  >
                    <el-radio-group v-model="projectForm.isOpenRandomNumber" >
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item
                    label="模板引用"
                    prop="templateType"
                  >
                  <el-tooltip slot="label" effect="light" content="选择该项目引用后台项目WBS模版节点，或是让客户自行导入WBS引用底层节点" placement="top">
                      <span>模板引用</span>
                    </el-tooltip>
                    <el-radio-group v-model="projectForm.templateType">
                      <el-radio :label="1">模板节点</el-radio>
                      <el-radio :label="2">底层节点</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item
                    label="电签短信时效"
                    prop="msTime"
                  >
    
                     <el-input-number v-model="projectForm.msTime" controls-position="right" style="margin-right: 4px;"></el-input-number>小时
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane
          label="分配WBS模版"
          name="2"
          :disabled="btnLoad"
        >
          <div>
            <div class="text-align-c">
              <el-radio-group
                v-model="templateType"
                @change="templateTypeChange"
               
              >
                <el-radio :label="2">试验</el-radio>
                <el-radio :label="1">质检</el-radio>
                <el-radio :label="5">征拆</el-radio>
                <el-radio :label="3">计量</el-radio>
              
              </el-radio-group>
            </div>
            <div class="text-align-c mg-t-20" >
              <span class="mg-r-20">选择WBS</span>
              <el-select
                v-model="wbsId"
                @change='wbsChange'
                :disabled="iswbsselected"
                placeholder="请选择WBS"
                style="width:500px;"
              >
                <el-option-group
                  v-for="group in treeList"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="(item,index) in group.options"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </div>
            <tree-tree
              :left-tree-data="leftTreeData"
              scrollbarStyle="height:calc(100vh - 500px)"
              ref="treetotree"
              :show-all-check="true"
              @onAddTree="treeChang"
              @onDelTree="treeChang"
              @onCheckAll="treeChang"
              :leftloading="leftloading"
              :rightloading="rightloading"
            
            ></tree-tree>
          </div>
        </el-tab-pane>
        <el-tab-pane
          label="分配日志WBS"
          name="3"
          :disabled="btnLoad"
        >
          <div>
            <div class="text-align-c mg-t-20">
              <span class="mg-r-20">选择WBS</span>
              <el-select
                v-model="logWbsId"
                @change="logWbsChange"
                :disabled="selected"
                placeholder="请选择WBS"
                style="width:500px;"
              >
                <el-option-group
                  v-for="group in logTreeList"
                  :key="group.label"
                  :label="group.label"
                >
                  <el-option
                    v-for="(item,index) in group.options"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </div>
            <tree-tree
              :left-tree-data="logLeftTreeData"
              ref="treetotree2"
              :show-all-check="true"
              @onAddTree="treeChang3"
              @onDelTree="treeChang3"
              @onCheckAll="treeChang3"
              :leftloading="logleftloading"
              :rightloading="logrightloading"
              scrollbarStyle="height:calc(100vh - 500px)"
            ></tree-tree>
          </div>
        </el-tab-pane>
        <el-tab-pane
          label="分配系统维护人员"
          name="4"
          :disabled="btnLoad"
        >
          <div>
            <div class="flex jc-al-c">
              <span class="mg-r-10">项目名称</span>
              <el-input
                v-model="projectForm.projectName"
                disabled
                style="width:300px;margin-right:30px;"
              ></el-input>
              <span class="mg-r-10">合同段名称</span>
              <el-select
                v-model="cId"
                placeholder="请选择"
                @change="getUserByCondition"
              >
                <el-option
                  label="全部"
                  value=""
                ></el-option>
                <el-option
                  v-for="item in contractList"
                  :key="item.id"
                  :label="item.contractName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
            <el-divider></el-divider>
            <div class="flex jc-al-c mg-b-10">
              <span>维护人员角色</span>
              <avue-input-tree
                class="marleft10"
                :check-strictly="true"
                v-model="rId"
                placeholder="请选择"
                type="tree"
                :dic="roleList"
                :props="treeProps"
                @change="getUserByCondition"
              ></avue-input-tree>
              <!-- <el-select v-model="rId" clearable placeholder="请选择" @change="getUserByCondition">
                <el-option v-for="item in roleList" :key="item.id" :label="item.title"  :value="item.id"></el-option>
              </el-select> -->
            </div>
            <div>
              <el-table
                :data="contractUserList"
                border
                height="420"
                style="width: 100%"
              >
                <el-table-column
                  prop="name"
                  label="姓名"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="contractName"
                  label="合同段名称"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="postName"
                  label="岗位"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="phone"
                  label="电话"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="martop10 flexEnd">
              <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="pageindx"
                :page-size="pagesize"
                layout="total, prev, pager, next"
                :total="total"
              >
              </el-pagination>
            </div>
            <div class="flex jc-al-c mg-t-20">
              <span>添加系统内部人员</span>
              <el-select
                class="marleft10"
                v-model="userId"
                filterable
                placeholder="请输入搜索"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <el-button
                type="success"
                class="marleft10"
                @click="addUserToProject"
              >添加</el-button>
              <el-button
                type="primary"
                @click="rputerPush()"
              >创建新用户</el-button>
              <el-button
                type="danger"
                @click="handleDeletes"
              >全部删除</el-button>
            </div>
            <el-divider></el-divider>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="flexEnd">
        <el-button
          :type="activeType != 4?'info':'success'"
          size="medium"
          :disabled="saveBtnDisabled
          || leftloading || logleftloading
          || rightloading || logrightloading"
          :loading="saveBtnLoad"
          @click="saveQuit"
        >保存并退出</el-button>
        <el-button
          type="info"
          size="medium"
          :disabled="saveBtnBackDisabled
          || leftloading || logleftloading
          || rightloading || logrightloading"
          :loading="saveBtnBackLoad"
          v-if="activeType != 1"
          @click="saveNext('p')"
        >保存并返回上一步</el-button>
        <el-button
          type="success"
          size="medium"
          :disabled="saveBtnNextDisabled
          || leftloading || logleftloading
          || rightloading || logrightloading"
          :loading="saveBtnNextLoad"
          v-if="activeType != 4"
          @click="saveNext('n')"
        >保存并进入下一步</el-button>
      </div>
    </div>
  </basic-container>
</template>

<script>
import {
  submitProject, getProjectDeatil, findWbsTreeList, findProjectTree,
  submitWbsTreeInProject, getProjectDeatilWbsId, findLogWbsTreeList, submitLogWbsTreeInProject
} from "@/api/manager/projectinfo";
import {
  findContractByProjectId, saveUserInfoByProject, findUserListByCondition,
  findUserByName, removeUsersByIds
} from "@/api/manager/contractinfo";
import { getRoleTree } from "@/api/system/role";
import { getAlltree } from "@/api/manager/wbstree";
import { getDictionary } from "@/api/system/dict";
import { mapGetters } from "vuex";

import treeTree from "@/components/tree-tree/main"
import { findUserList } from "@/api/manager/contractinfo";
import { queryBusinessUserOpinionList } from "@/api/measure/template.js";
import {getList} from "@/api/system/user";
export default {
  components: {
    treeTree
  },
  data () {
    var checkDate = (rule, value, callback) => {
      if (value && this.projectForm.planStartTime) {
        if (Date.parse(value) < Date.parse(this.projectForm.planStartTime)) {
          callback(new Error('计划完工日期不能小于开工日期'));
        }
      }
      callback();
    };
    var checkDate2 = (rule, value, callback) => {
      if (value && this.projectForm.actualStartTime) {
        if (Date.parse(value) < Date.parse(this.projectForm.actualStartTime)) {
          callback(new Error('实际完工日期不能小于开工日期'));
        }
      }
      callback();
    };
    var checkIsNumber = (rule, value, callback) => {
      if (value != Number(value)) {
        callback(new Error('金额必须是数字'));
      }
      if (value && 999999999999999999 < Number(value)) {
        callback(new Error('数字过大'));
      }
      callback();
    };
    var checkMileage = (rule, value, callback) => {
      if (this.projectForm.projectPavement || this.projectForm.projectSubgrade) {
        if (this.projectForm.projectPavement) {
          if (this.projectForm.projectPavement > value) {
            callback(new Error('总里程必须是最大的'));
          }
        } else if (this.projectForm.projectSubgrade) {
          if (this.projectForm.projectSubgrade > value) {
            callback(new Error('总里程必须是最大的'));
          }
        }
        if (this.projectForm.projectPavement && this.projectForm.projectSubgrade) {
          if ((this.projectForm.projectPavement + this.projectForm.projectSubgrade) > value) {
            callback(new Error('总里程必须大于两项总和'));
          }
        }
      }
      callback();
    };

    return {
      //#region
      pageindx: 1,
      pagesize: 10,
      total: 0,
      //#endregion
      activeType: '1',
      typeChang: {
        1: false,
        2: false,
        3: false,
        4: false,
      },
      btnLoad: false,
      saveBtnLoad: false,
      saveBtnDisabled: false,
      saveBtnBackLoad: false,
      saveBtnBackDisabled: false,
      saveBtnNextLoad: false,
      saveBtnNextDisabled: false,
      id: '',
      highwayGradeList: [],
      meterTemplateOption:[],//计量单元列表
      radioType: '总里程',
      proStatusItems: [
          { type:'info', label: '未开始',value: 0 },
          { type: 'primary', label: '配置中' ,value: 1 },
          { type: 'warning', label: '进行中' ,value: 2 },
          { type: 'success', label: '已完成' ,value: 3 },
         
      ],
      projectForm: {
        estimatedAmount: 0,
        isOpenRandomNumber:1,
        approvalType:2,
        msTime:1

      },
      projectRules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
        ],
        projectAlias: [
          { required: true, message: '请输入项目别名', trigger: 'blur' },
        ],
        planStartTime: [{ required: true, message: '请选择计划开工日期', trigger: 'blur' },],
        planEndTime: [
          { validator: checkDate, trigger: 'blur' }
        ],
        actualEndTime: [
          { validator: checkDate2, trigger: 'blur' }
        ],
        estimatedAmount: [
          { validator: checkIsNumber, trigger: 'blur' }
        ],
        projectAllMileage: [
          { validator: checkMileage, trigger: 'blur' }
        ],
        remarkType: [
            { required: true, message: '请选择电签类别', trigger: 'blur' },
        ],
       
        templateType:[
            { required: true, message: '请选择是否模板引用', trigger: 'blur' },
        ],
        sgSuffix:[
            { required: true, message: '请输入施工文件后缀', trigger: 'blur' },
        ],
        jlSuffix:[
            { required: true, message: '请输入监理文件前缀', trigger: 'blur' },
        ],
         msTime:[
            { required: true, message: '请输入电签短信时效', trigger: 'blur' },
        ],  
        

      },

      contractList: [],
      cId: '',
      rId: '',
      roleList: [],
      userId: '',
      userList: [],
      contractUserList: [],

      treeProps: {
        label: "dictValue",
        value: "id"
      },

      templateType: 1,
      treeList: [],
      logTreeList: [],
      wbsId: '',
      iswbsselected:true,//右边有数据禁用下拉框选择
      logWbsId: '',
      selected: false,
      leftTreeData: [],
      logLeftTreeData: [],

      leftloading:false,
      rightloading:false,
      logleftloading:false,
      logrightloading:false,
      selectData:{},
      isFirst:false,
      rightTreeData:[],//存储右边的试验树数据
      rightTreeData1:[],//存储右边的质检树数据
      rightTreeData2:[],//存储征拆数据
      rightTreeData3:[],//存储计量数据
      rightObj:[
        
      ],
      rightObj1:[
       
      ],
      rightObj2:[
       
       ],
       rightObj3:[
       
       ],
      nowref:{},
      finalWbsid:'',
      finalIds:'',
      createUserItems:[]
     
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    projectForm: {
      immediate:false,
      handler: function () { // 此处注意，handler函数不能为箭头函数，this会取上下文，而不是组件里的this,此外，深度监听，必须为handler函数名，否则会无效果
        // this.typeChang['1'] = true;
        if(this.isFirst===false){
           this.typeChang['1'] = true;
        }
      },
      deep: true
    },
    activeType: function (newValue) {
    
      if (newValue == '4') {
        this.getContractList();
        this.getRoleList();
        this.getUserByCondition();
        this.getUserByName();
      } else if (newValue == '2') {
        this.treeInit();
     
      } else if (newValue == '3') {
        this.treeLogInit();
      }
    }
  },
  created () {
    this.init();
    //console.log(this.userInfo)
  },
  mounted () {
    this.$nextTick(() => {
      this.typeChang = {
        1: false,
        2: false,
        3: false,
        4: false,
      }
    })
  },
  methods: {
    getCreateUserItems(){
      getList(
        1,
        1000,
        {},

       '1536982621165592577',
     
      ).then(res => {
       
        
        this.createUserItems = res.data.data.records;
      })
    },
    //#region //后加分页
    handleSizeChange (val) {
      this.pagesize = val
      this.getUserByCondition();
    },
    handleCurrentChange (val) {
      this.pageindx = val
      this.getUserByCondition();
    },
    rputerPush () {
      this.$router.push({
        path: '/system/user',
        query: { tankai: true }
      })
    },
    //#endregion
    init () {
      this.getCreateUserItems();
      this.getHighwayGradeList();
      this.getMeterTemplateOption()
      this.id = this.$route.query.id;
      if (this.id) {
        this.getProjectDeatil();
      }
    },
    beforeLeave (activeName, oldActiveName) {
      return new Promise((resolve, reject) => {
        if (oldActiveName == '1' && !this.projectForm.id) {
          this.$message({
            type: "warning",
            message: "请先保存项目后，再进行项目的分配"
          });
          // reject();
        }

        if (this.typeChang[oldActiveName]) {
          this.$confirm('检测到新编辑内容, 是否保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '不用',
            type: 'warning'
          }).then(() => {
            switch (oldActiveName) {
              case '1':
                this.saveProject().then((res) => {
                  this.projectForm.id = res.data.data.id;
                  this.typeChang[oldActiveName] = false;

                  resolve();
                  this.$message({
                    type: "success",
                    message: "保存成功!"
                  });
                });
                break;
              case '2':
                this.saveWbsTree().then(() => {
                  this.typeChang[oldActiveName] = false;
                  resolve();
                  this.$message({
                    type: "success",
                    message: "保存成功!"
                  });
                }).catch(() => {
                  console.log("beforeLeave catch getRightTree")
                  this.getRightTree();
                  reject();
                })
                break;
            }
          }).catch(() => {
            this.typeChang[oldActiveName] = false;
            resolve();
          })
        } else {
          resolve();
        }
      })
    },

    getProjectDeatil () {
      getProjectDeatil(this.id).then((res) => {
        const data = res.data.data
        console.log(data)
        this.projectForm = data;
        this.isFirst=true;
        setTimeout(() => {
          this.isFirst=false;
        }, 1000);
        console.log(data,'data项目详情');
        this.selectData={
          referenceWbsTemplateId:data.referenceWbsTemplateId,//质检
          referenceWbsTemplateIdLar:data.referenceWbsTemplateIdLar,//征拆
          referenceWbsTemplateIdMeter:data.referenceWbsTemplateIdMeter,//计量
          referenceWbsTemplateIdTrial:data.referenceWbsTemplateIdTrial===-1?'':data.referenceWbsTemplateIdTrial//试验

        }
        if (Number(this.projectForm.estimatedAmount) < 0) {
          this.projectForm.estimatedAmount = 0
        }
        this.$nextTick(() => {
          this.typeChang['1'] = false;
        })
        let templateType = 'public';
        if (this.projectForm.referenceWbsTemplateType) {
          templateType = this.projectForm.referenceWbsTemplateType;
        }
        getProjectDeatilWbsId(this.id, this.projectForm.referenceWbsTemplateId, templateType).then((res) => {
          this.projectForm.wbsType = res.data.data.wbsType;
        })
      })
    },

    async saveQuit () {
      console.log('保存2',this.selectData);
      this.btnLoad = true;
      this.saveBtnLoad = true;
      this.saveBtnBackDisabled = true
      this.saveBtnNextDisabled = true
      try {
        if (this.activeType == '1') {
          await this.saveProject();
        } else if (this.activeType == '2') {
          await this.saveWbsTree();
        } else if (this.activeType == '3'){
          await this.saveLogWbsTree();
        }
      } catch (error) {
        this.btnLoad = false;
        this.saveBtnLoad = false;
        this.saveBtnBackDisabled = false
        this.saveBtnNextDisabled = false
        if(this.activeType == '2'){
          console.log("saveQuit getRightTree")
          this.getRightTree();
        }
        return;
      }

      this.$message({
        type: "success",
        message: "保存成功!"
      });
      this.btnLoad = false;
      this.saveBtnLoad = false;
      this.saveBtnBackDisabled = false
      this.saveBtnNextDisabled = false
      this.$router.go(-1);
    },
    async saveNext (type) {
         console.log('保存',this.activeType,this.selectData);
      this.btnLoad = true;
      if (type == 'n') {
        this.saveBtnNextLoad = true;
        this.saveBtnBackDisabled = true
        this.saveBtnDisabled = true
      } else if (type == 'p') {
        this.saveBtnBackLoad = true;
        this.saveBtnNextDisabled = true
        this.saveBtnDisabled = true
      

      }
      try {
        if (this.activeType == '1') {
          let res = await this.saveProject();
          this.projectForm.id = res.data.data.id;
        } else if (this.activeType == '2') {
  
          await this.saveWbsTree();
        } else if (this.activeType == '3'){
          await this.saveLogWbsTree();
          if(type == 'p'){
            console.log(this.wbsId,'wbsis');
          }
                

        }
      } catch (error) {
        this.btnLoad = false;
        if (type == 'n') {
          this.saveBtnNextLoad = false;
          this.saveBtnBackDisabled = false
          this.saveBtnDisabled = false
        } else if (type == 'p') {
          this.saveBtnBackLoad = false;
          this.saveBtnNextDisabled = false
          this.saveBtnDisabled = false
        }
        if(this.activeType == '2'){
          console.log("saveNext getRightTree")
          this.getRightTree();
          // this.templateType=1
        }
        return;
      }

      this.$message({
        type: "success",
        message: "保存成功!"
      });
      this.typeChang[this.activeType] = false;
      let num = Number(this.activeType);
      if (type == 'n') {
        num++;
      } else if (type == 'p') {
        num--;
      }

      this.activeType = num.toString();
      this.btnLoad = false;
      if (type == 'n') {
        this.saveBtnNextLoad = false;
        this.saveBtnBackDisabled = false
        this.saveBtnDisabled = false
      } else if (type == 'p') {
        this.saveBtnBackLoad = false;
        this.saveBtnNextDisabled = false
        this.saveBtnDisabled = false
      }
    },

    saveProject () {
         console.log('保存3',this.selectData);
      return new Promise((resolve, reject) => {
        this.$refs['projectForm'].validate((valid) => {
          if (valid) {
            resolve(submitProject(this.projectForm))
          } else {
            reject('验证失败')
          }
        })
      })
    },
    saveLogWbsTree() {
      let ids = this.$refs.treetotree2.getTreeAllId('rightTree');
      let obj = {
        wbsId: this.logWbsId,
        projectId: this.projectForm.id,
        wbsType: "4",
        wbsTreeIds: ids
      };
      return submitLogWbsTreeInProject(obj);
    },
    saveWbsTree () {
      let obj = {};
      let ids = this.$refs.treetotree.getTreeAllId('rightTree');
      // if(this.finalWbsid.length>0){
      //   this.wbsId=this.finalWbsid
      // }
      console.log(this.finalIds,'finalIds');
      obj = {
        wbsId: this.wbsId,
        projectId: this.projectForm.id,
        wbsType: this.templateType,
        wbsTreeIds: ids
      }
   
     
      console.log(this.wbsId,'this.wbsId最终');
      console.log(this.projectForm,'projectForm');
      if (this.wbsId.toString().indexOf(',') >= 0) {
        //私有库
        obj.referenceType = "private";
        let ids = this.wbsId.toString().split(',');
        // obj.wbsId = this.finalWbsid;
        obj.wbsId = ids[0];
        obj.referencePrivateWbsProjectId = ids[1];
        obj.primaryKeyId = this.leftTreeData[0].primaryKeyId;
      } else {
        //公有库
        obj.referenceType = "public";
         obj.wbsId = this.wbsId;
        // obj.wbsId = this.finalWbsid;
      }

      return submitWbsTreeInProject(obj);
    },

    addUserToProject () {
      if (!this.userId) {
        this.$message({
          type: "warning",
          message: "请先选择用户再进行添加"
        });
        return;
      }
      if (!this.rId) {
        this.$message({
          type: "warning",
          message: "请先选择维护人员角色再进行添加"
        });
        return;
      }
      let list = [{
        projectId: this.projectForm.id,
        contractId: this.cId ? this.cId : undefined,
        userId: this.userId,
        roleId: this.rId
      }];
      saveUserInfoByProject(list).then(() => {
        this.getUserByCondition();
      })
    },

    getUserByCondition () {
      findUserListByCondition({
        cId: this.cId,
        pId: this.projectForm.id,
        postId: '',
        rId: this.rId,
        size: this.pagesize,
        current: this.pageindx
      }).then((res) => {
        this.contractUserList = res.data.data.records;
        this.total = res.data.data.total
      })
    },

    getUserByName () {
      findUserList('').then((res) => {
        this.userList = res.data.data;
      })
    },

    handleDelete (index, row) {
      this.$confirm('是否将该用户移除出合同段', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeUsersByIds(row.id).then(() => {
          this.contractUserList.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
      })
    },
    handleDeletes () {
      this.$confirm('是否将所有用户移除出合同段', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = [];
        this.contractUserList.forEach((element) => {
          ids.push(element.id);
        })
        removeUsersByIds(ids.join(',')).then(() => {
          this.contractUserList = [];
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
      })
    },

    getHighwayGradeList () {
      if (this.highwayGradeList.length > 1) {
        return;
      }
      getDictionary({
        code: 'highway_grade'
      }).then((res) => {
        // res.data.data.forEach(element => {
        //   element.dictKey = Number(element.dictKey)
        // });
        this.highwayGradeList = res.data.data;
      })
    },
    getMeterTemplateOption(){
      queryBusinessUserOpinionList().then((res)=>{
        this.meterTemplateOption=res.data.data
      })
    },

    getContractList () {
      if (this.contractList.length < 1) {
        findContractByProjectId(this.projectForm.id).then((res) => {
          this.contractList = res.data.data;
        })
      }
    },

    getRoleList () {
      if (this.roleList.length > 1) {
        return;
      }

      getRoleTree().then((res) => {
        this.roleList = res.data.data
      })
    },
    logWbsChange(value){
      //公有库
      this.logleftloading = true;
      getAlltree(this.userInfo.tenant_id, '1', value).then((res) => {
        if (Array.isArray(res.data.data)) {
          this.logLeftTreeData = res.data.data;
        } else {
          this.logLeftTreeData = [];
        }
        this.logleftloading = false;
      })
    },
    wbsChange (value, flag) {
      console.log(value, 'WBS节点更换测试 value')
      this.iswbsselected=false
      if(this.templateType==1){
        this.selectData.referenceWbsTemplateId=value


      }else if(this.templateType==5){
        this.selectData.referenceWbsTemplateIdLar=value
      }
      else if(this.templateType==3){
        this.selectData.referenceWbsTemplateIdMeter=value
      }
      else{
          this.selectData.referenceWbsTemplateIdTrial=value
      }

      this.leftloading = true;
      if (value&&value.toString().indexOf(',') >= 0) {
        console.log('私有库');
         //私有库
          if(this.templateType==1){
            this.projectForm.referenceWbsTemplateType='private'
          }else if(this.templateType==5){
            this.projectForm.referenceWbsTemplateTypeLar='private'
          }
          else if(this.templateType==2){
            this.projectForm.referenceWbsTemplateTypeMeter='private'
          }
          else{
            this.projectForm.referenceWbsTemplateTypeTrial='private'
          }

        let ids = value.toString().split(',');
        console.log(ids,'ids');
        findProjectTree(ids[1], ids[0]).then((res) => {
          if (Array.isArray(res.data.data)) {
            this.leftTreeData = res.data.data;
          } else {
            this.leftTreeData = [];
          }
          this.leftloading = false;
        })
          this.getRightTree()
      } else {
        console.log('公有库');
        //公有库
        if(value&&value.length>0){
          if(this.templateType==1){
              this.projectForm.referenceWbsTemplateType='public'
          }
          else if(this.templateType==5){
            this.projectForm.referenceWbsTemplateTypeLar='public'
          }
          else if(this.templateType==2){
            this.projectForm.referenceWbsTemplateTypeMeter='public'
          }
          else{
              this.projectForm.referenceWbsTemplateTypeTrial='public'
            }
        }

        getAlltree(this.userInfo.tenant_id, '1', value).then((res) => {
          if (Array.isArray(res.data.data)) {
            this.leftTreeData = res.data.data;
            console.log("this.leftTreeData", this.leftTreeData)
          } else {
            this.leftTreeData = [];
          }
          this.leftloading = false;
        })
          this.getRightTree()
      }

      if (flag === undefined) { /* 下拉框切换的时候调用 */
        this.getRightTree();
      }
  
    },

    getLogTreeList(){
      return new Promise((resolve) => {
        if (this.logTreeList.length) {
          resolve();
        }
        findLogWbsTreeList().then((res) => {
          let arr = [{
            label: '公有库',
            options: [],
          }];
          let data = res.data.data;
          if (data && data.length) {
            data.forEach((element) => {
              element.label = element.wbsName;
              element.value = element.id;
            })
            arr[0].options = data;
          }
          this.logTreeList = arr;
        }).finally(() => {
          resolve();
        })
      })
    },

    getTreeList () {
      console.log('getTreeList');
      return new Promise((resolve) => {
        if (this.treeList.length) {
          resolve();
        }
        findWbsTreeList(this.templateType).then((res) => {
          let arr = [{
            label: '公有库',
            options: [],
          },
          {
            label: '私有库',
            options: [],
          }];
          let data = res.data.data;
          if (data.wbsInfos && data.wbsInfos.length) {
            data.wbsInfos.forEach((element) => {
              element.label = element.wbsName;
              element.value = element.id;
            })
            arr[0].options = data.wbsInfos;
          }
          if (data.wbsTreePrivates && data.wbsTreePrivates.length) {
            data.wbsTreePrivates.forEach((element) => {
              element.label = element.projectName;
              element.value = element.wbsId + ',' + element.projectId;
            })
            arr[1].options = data.wbsTreePrivates;
          }
          this.treeList = arr;

          // this.wbsChange(this.wbsId, true)
        }).finally(() => {
          resolve();
        })
      })
    },
//格式化wbsid
  formatWbsId(orid){
       let refId = orid;
      let WbsId=''
      if ((this.templateType == 1 && this.projectForm.referenceWbsTemplateType === 'private')
          || (this.templateType == 2 && this.projectForm.referenceWbsTemplateTypeTrial === 'private')
          || (this.templateType == 5 && this.projectForm.referenceWbsTemplateTypeLar === 'private')
          || (this.templateType == 3 && this.projectForm.referenceWbsTemplateTypeMeter === 'private')
         
           && refId != null && refId.toString().length > 0) {
          console.log(refId,'refId');
        // 私有库右边树形数据是通过 pkeyId 查询的
        let ids = refId.toString().split(",");
      console.log(ids,'ids');
        if (ids.length > 1) {
          refId = ids[0]
          console.log(refId,'refId');
            console.log(this.treeList,'treeList');
          let list = this.treeList[1].options;
          refId = list.filter(e => e.projectId == ids[1])[0].pkeyId;
           WbsId=refId
        }
      }else{
          console.log(3333333);
        WbsId=refId
      }

    return WbsId
   

  },
    treeChang () {
     let recordid= this.formatWbsId(this.wbsId)
     console.log(recordid,'recordid');
      if (this.templateType===2) {
        this.rightTreeData=this.$refs.treetotree.rightTreeData;
        // this.rightObj.push({
        //   wbsid:this.wbsId,objdata: this.rightTreeData
        // })
        this.rightObj.wbsId=recordid
        this.rightObj.objdata=this.rightTreeData
      }else if(this.templateType===5){
        this.rightTreeData2=this.$refs.treetotree.rightTreeData
          this.rightObj2.wbsId=recordid
          this.rightObj2.objdata=this.rightTreeData2
      }
      else if(this.templateType===3){//计量
        this.rightTreeData3=this.$refs.treetotree.rightTreeData
          this.rightObj3.wbsId=recordid
          this.rightObj3.objdata=this.rightTreeData3
      }
      else{
          this.rightTreeData1=this.$refs.treetotree.rightTreeData
          //  this.rightObj1.push({
          //   wbsid:this.wbsId,objdata: this.rightTreeData
          // })
          this.rightObj1.wbsId=recordid
          this.rightObj1.objdata=this.rightTreeData1
        
      }
    
      this.typeChang[2] = true;
    },

    treeChang3 () {
      this.typeChang[3] = true;
    },

    templateTypeChange () {
      findWbsTreeList(this.templateType).then((res) => {
        let arr = [
          {label: '公有库', options: []},
          {label: '私有库', options: []}
        ];
        let data = res.data.data;
        if (data.wbsInfos && data.wbsInfos.length) {
          data.wbsInfos.forEach((element) => {
            element.label = element.wbsName;
            element.value = element.id;
          })
          arr[0].options = data.wbsInfos;
        }
        if (data.wbsTreePrivates && data.wbsTreePrivates.length) {
          data.wbsTreePrivates.forEach((element) => {
            element.label = element.projectName;
            element.value = element.wbsId + ',' + element.projectId;
          })
          arr[1].options = data.wbsTreePrivates;
        }
        this.treeList = arr;

        this.wbsId = this.templateType == 1 ? this.selectData.referenceWbsTemplateId : this.selectData.referenceWbsTemplateIdTrial
        if(this.templateType===5){
          console.log('征拆选择');
          this.wbsId =this.selectData.referenceWbsTemplateIdLar
  
        }
        if(this.templateType===3){
          console.log('计量选择');
          this.wbsId =this.selectData.referenceWbsTemplateIdMeter
  
        }
        console.log(this.wbsId===-1);
        if(this.wbsId===-1){
          this.wbsId=''
        }
        this.wbsChange(this.wbsId, true)

        // if(this.treeList[0].options.length > 0){
        //   this.wbsId = this.treeList[0].options[0].value;
        //   this.wbsChange(this.wbsId)
        // }else if(this.treeList[1].options.length > 0){
        //   this.wbsId = this.treeList[1].options[0].value;
        //   this.wbsChange(this.wbsId)
        // }else{
        //   this.wbsId = '';
        //   this.leftTreeData = [];
        // }
      })

    },
    async treeLogInit(){
      let refId = this.projectForm.referenceLogWbsTemplateId;
      if(refId && refId > 0 && Number(this.projectForm.wbsType) > 0){
        await this.getLogTreeList();
        this.logWbsId = refId;

        this.logleftloading = true;
        let leftData = await getAlltree(this.userInfo.tenant_id, '1', refId);
        if (Array.isArray(leftData.data.data)) {
          this.logLeftTreeData = leftData.data.data;
        } else {
          this.logLeftTreeData = [];
        }
        this.logleftloading = false;

        this.logrightloading = true;
        let projectTree = await findProjectTree(this.projectForm.id, refId);
      
        this.$refs.treetotree2.setRightTree(Array.isArray(projectTree.data.data)?projectTree.data.data:[]);
        this.logrightloading = false;
      } else {
        await this.getLogTreeList();
      }
    },

        //初始化质量
    async treeInit () {
      console.log('------------------- treeInit ------------------------');
      let refId = this.selectData.referenceWbsTemplateId;

      console.log(refId, '------------------- treeInit.refId ------------------------');
  

      if (this.projectForm.referenceWbsTemplateType === 'private' && refId != null && refId.toString().length > 0) {
        // 私有库右边树形数据是通过 pkeyId 查询的
        let ids = refId.toString().split(",");
        if (ids.length > 1) {
          refId = ids[0]
          let list = this.treeList[1].options;
          refId = list.filter(e => e.projectId == ids[1])[0].pkeyId;
        }
      }

      //引用被删会出现 wbsType -1
      if (refId && refId > 0 && Number(this.projectForm.wbsType) > 0) {
        console.log('------------------- treeInit if------------------------');
        //有引用id，回显
        //this.selected = true;

        // this.templateType = this.projectForm.wbsType;
        await this.getTreeList();
        let priv = {};

        if (this.projectForm.referenceWbsTemplateType == 'private') {
          //私有
          let list = this.treeList[1].options;
          for (let i = 0; i < list.length; i++) {
            if (list[i].pkeyId == refId) {
              this.wbsId = list[i].wbsId + ',' + list[i].projectId;
              priv.wbsId = list[i].wbsId;
              priv.projectId = list[i].projectId;
              priv.value= list[i].value
              priv.pkeyId= list[i].pkeyId
              break;
            }
          }
        } else {
          //公有
          this.wbsId = refId;
        }

        if(this.templateType == 1){
          this.selectData.referenceWbsTemplateId =this.wbsId
        }else if(this.templateType==5){
          this.selectData.referenceWbsTemplateIdLar =this.wbsId
         
        }
        else if(this.templateType==3){
          this.selectData.referenceWbsTemplateIdMeter =this.wbsId
         
        }
        else{
          this.selectData.referenceWbsTemplateIdTrial=this.wbsId
        }
        this.nowref={
          value:priv.value,
          id:  priv.pkeyId 
        }
        let projectTree = await findProjectTree(this.projectForm.id, refId) //查询的右边的数据
           if (projectTree&&projectTree.data&&projectTree.data.data&&projectTree.data.data.length>0) {
            this.iswbsselected=true
          }else{
             this.iswbsselected=false
          }
        if (Array.isArray(projectTree.data.data)) {
          this.leftloading = true;
          this.rightloading = true;
          if (this.projectForm.referenceWbsTemplateType == 'private') {
            //私有
            let leftData = await findProjectTree(priv.projectId, priv.wbsId)
            if (Array.isArray(leftData.data.data)) {
              this.leftTreeData = leftData.data.data;
            } else {
              this.leftTreeData = [];
            }
            this.leftloading = false;
          } else {
            //公有
            let leftData = await getAlltree(this.userInfo.tenant_id, '1', refId)
            if (Array.isArray(leftData.data.data)) {
              this.leftTreeData = leftData.data.data;
            } else {
              this.leftTreeData = [];
            }
            this.leftloading = false;
          }

          this.$refs.treetotree.setRightTree(projectTree.data.data);
          console.log(projectTree.data.data,'projectTree.data.data');
         
          this.rightloading = false;
        }else{
          this.wbsId = '';
        }
      }
      else {
        console.log('------------------- treeInit else------------------------');
        this.getTreeList();
        this.iswbsselected=false
      }
      console.log(this.wbsId,'this.wbsId33333');
      this.treeInitTrial()
      this.treeInitLar()
      this.treeMeasure()
    },
    //初始化征拆
    async treeInitLar () {
      let refId = this.selectData.referenceWbsTemplateIdLar;
      console.log(refId,'refId');
      //引用被删会出现 wbsType -1
      if (refId && refId > 0 && Number(this.projectForm.wbsType) > 0) {
        //有引用id，回显
        //this.selected = true;

        findWbsTreeList(5).then((res) => {
          let arr = [{
            label: '公有库',
            options: [],
          },
          {
            label: '私有库',
            options: [],
          }];
          let data = res.data.data;
          if (data.wbsInfos && data.wbsInfos.length) {
            data.wbsInfos.forEach((element) => {
              element.label = element.wbsName;
              element.value = element.id;
            })
            arr[0].options = data.wbsInfos;
          }
          if (data.wbsTreePrivates && data.wbsTreePrivates.length) {
            data.wbsTreePrivates.forEach((element) => {
              element.label = element.projectName;
              element.value = element.wbsId + ',' + element.projectId;
            })
            arr[1].options = data.wbsTreePrivates;
          }

          let WbsId = 0;
          if (this.projectForm.referenceWbsTemplateTypeLar == 'private') {
            //私有
            let list = arr[1].options;
            console.log(list,'list');
            for (let i = 0; i < list.length; i++) {
              if (list[i].pkeyId == refId) {
                WbsId = list[i].wbsId + ',' + list[i].projectId;
                break;
              }
            }
          } else {
            console.log('共有',refId);
            //公有
            WbsId = refId;
          }

         this.selectData.referenceWbsTemplateIdLar = WbsId

          console.log("征拆", this.selectData)
        })

      } else {
        this.getTreeList();
      }
    },
    //初始化计量
    async treeMeasure () {
      let refId = this.selectData.referenceWbsTemplateIdMeter;
      console.log(refId,'refId');
      //引用被删会出现 wbsType -1
      if (refId && refId > 0 && Number(this.projectForm.wbsType) > 0) {
        //有引用id，回显
        //this.selected = true;

        findWbsTreeList(3).then((res) => {
          let arr = [{
            label: '公有库',
            options: [],
          },
          {
            label: '私有库',
            options: [],
          }];
          let data = res.data.data;
          if (data.wbsInfos && data.wbsInfos.length) {
            data.wbsInfos.forEach((element) => {
              element.label = element.wbsName;
              element.value = element.id;
            })
            arr[0].options = data.wbsInfos;
          }
          if (data.wbsTreePrivates && data.wbsTreePrivates.length) {
            data.wbsTreePrivates.forEach((element) => {
              element.label = element.projectName;
              element.value = element.wbsId + ',' + element.projectId;
            })
            arr[1].options = data.wbsTreePrivates;
          }

          let WbsId = 0;
          if (this.projectForm.referenceWbsTemplateTypeMeter == 'private') {
            //私有
            let list = arr[1].options;
            console.log(list,'list');
            for (let i = 0; i < list.length; i++) {
              if (list[i].pkeyId == refId) {
                WbsId = list[i].wbsId + ',' + list[i].projectId;
                break;
              }
            }
          } else {
            console.log('共有',refId);
            //公有
            WbsId = refId;
          }

         this.selectData.referenceWbsTemplateIdMeter = WbsId

          console.log("计两", this.selectData)
        })

      } else {
        this.getTreeList();
      }
    },
    //初始化试验
    async treeInitTrial () {
      console.log(this.wbsId,'wbsidshiyan');
      let refId = this.selectData.referenceWbsTemplateIdTrial;
      console.log(refId,'wbsidshiyan');
      //引用被删会出现 wbsType -1
      if (refId && refId > 0 && Number(this.projectForm.wbsType) > 0) {
        //有引用id，回显
        //this.selected = true;

        findWbsTreeList(2).then((res) => {
          let arr = [{
            label: '公有库',
            options: [],
          },
          {
            label: '私有库',
            options: [],
          }];
          let data = res.data.data;
          if (data.wbsInfos && data.wbsInfos.length) {
            data.wbsInfos.forEach((element) => {
              element.label = element.wbsName;
              element.value = element.id;
            })
            arr[0].options = data.wbsInfos;
          }
          if (data.wbsTreePrivates && data.wbsTreePrivates.length) {
            data.wbsTreePrivates.forEach((element) => {
              element.label = element.projectName;
              element.value = element.wbsId + ',' + element.projectId;
            })
            arr[1].options = data.wbsTreePrivates;
          }

          let WbsId = 0;
          if (this.projectForm.referenceWbsTemplateTypeTrial == 'private') {
            //私有
            let list = arr[1].options;
            for (let i = 0; i < list.length; i++) {
              if (list[i].pkeyId == refId) {
                WbsId = list[i].wbsId + ',' + list[i].projectId;
                break;
              }
            }
          } else {
            //公有
            WbsId = refId;
          }

         this.selectData.referenceWbsTemplateIdTrial = WbsId

          console.log("treeInitTrial", this.selectData)
        })

      } else {
        this.getTreeList();
      }
    },

    getRightTree() {
      this.rightloading = true;
       this.iswbsselected=true
      console.log(this.nowref,'nowrefId');

      let refId =  this.templateType === 1? this.selectData.referenceWbsTemplateId : this.selectData.referenceWbsTemplateIdTrial;
      if(this.templateType===5){
        console.log(this.selectData.referenceWbsTemplateIdLar,1111111111);
        refId=this.selectData.referenceWbsTemplateIdLar;
        // this.$refs.treetotree.setRightTree([]);
      }
      if(this.templateType===3){
        console.log(this.selectData.referenceWbsTemplateIdMeter,1111111111);
        refId=this.selectData.referenceWbsTemplateIdMeter;
        // this.$refs.treetotree.setRightTree([]);
      }
    
      console.log(refId,'refId');
      if(!refId){
        console.log('不存在refId');
         this.$refs.treetotree.setRightTree([]);
          this.iswbsselected=false
      }else{
              let WbsId=''
              if (this.projectForm.referenceWbsTemplateType === 'private'  && refId != null && refId.toString().length > 0&&this.templateType===1) {
                // 私有库右边树形数据是通过 pkeyId 查询的
                let ids = refId.toString().split(",");
                console.log(ids,'ids111111');
                this.finalIds=ids
                if (ids.length > 1) {
                  refId = ids[0]
                  let list = this.treeList[1].options;
                  refId = list.filter(e => e.projectId == ids[1])[0].pkeyId;
                  console.log(refId,'refId');
                
                }
              }
              if (this.projectForm.referenceWbsTemplateTypeTrial === 'private'  && refId != null && refId.toString().length > 0&&this.templateType===2) {
                // 私有库右边树形数据是通过 pkeyId 查询的
                let ids = refId.toString().split(",");
                console.log(ids,'试验');
                this.finalIds=ids
                if (ids.length > 1) {
                  refId = ids[0]
                  let list = this.treeList[1].options;
                  refId = list.filter(e => e.projectId == ids[1])[0].pkeyId;
                  console.log(refId,'refId');
                
                }
              }
              if (
              this.projectForm.referenceWbsTemplateTypeLar === 'private' && refId != null && refId.toString().length > 0 &&this.templateType===5) {
                // 私有库右边树形数据是通过 pkeyId 查询的
                let ids = refId.toString().split(",");
                console.log(ids,'征拆');
                this.finalIds=ids
                if (ids.length > 1) {
                  refId = ids[0]
                  let list = this.treeList[1].options;
                  refId = list.filter(e => e.projectId == ids[1])[0].pkeyId;
                  console.log(refId,'refId');
                
                }
              }
              if (
              this.projectForm.referenceWbsTemplateTypeMeter === 'private' && refId != null && refId.toString().length > 0 &&this.templateType===3) {
                // 私有库右边树形数据是通过 pkeyId 查询的
                let ids = refId.toString().split(",");
                console.log(ids,'计量');
                this.finalIds=ids
                if (ids.length > 1) {
                  refId = ids[0]
                  let list = this.treeList[1].options;
                  refId = list.filter(e => e.projectId == ids[1])[0].pkeyId;
                  console.log(refId,'refId');
                
                }
              }
              //引用被删会出现 wbsType -1
              if (refId && refId > 0) {
                let priv = {};
                if (this.projectForm.referenceWbsTemplateType == 'private'&&this.templateType===1
                ||this.projectForm.referenceWbsTemplateTypeLar === 'private' &&this.templateType===5
                ||this.projectForm.referenceWbsTemplateTypeMeter === 'private' &&this.templateType===3
                ||this.projectForm.referenceWbsTemplateTypeTrial === 'private'&&this.templateType===2) {
                  //私有
                  let list = this.treeList[1].options;
                  for (let i = 0; i < list.length; i++) {
                    if (list[i].pkeyId == refId) {
                      refId = list[i].wbsId + ',' + list[i].projectId;
                      priv.wbsId = list[i].wbsId;
                      priv.projectId = list[i].projectId;
                      priv.value= list[i].value
                      priv.pkeyId= list[i].pkeyId
                  
                      break;
                    }
                  }
                } else {
                  //公有
                  WbsId = refId;
                }


              if(this.nowref.value===refId){
                console.log(11111111111);
                WbsId=this.nowref.id
              }else{
                if (this.projectForm.referenceWbsTemplateType == 'private'&& refId != null && refId.toString().length > 0 &&this.templateType==1) {
                    WbsId = priv.pkeyId
                }
               else if (this.projectForm.referenceWbsTemplateTypeTrial == 'private'&& refId != null && refId.toString().length > 0 &&this.templateType==2) {
                    WbsId =priv.pkeyId
                }
               else if (this.projectForm.referenceWbsTemplateTypeLar === 'private'&& refId != null && refId.toString().length > 0&&this.templateType==5) {
                    WbsId = priv.pkeyId
                }
                else if (this.projectForm.referenceWbsTemplateTypeMeter === 'private'&& refId != null && refId.toString().length > 0&&this.templateType==3) {
                    WbsId = priv.pkeyId
                }
                else {//公有
                  WbsId=this.templateType === 1 ?this.selectData.referenceWbsTemplateId: this.selectData.referenceWbsTemplateIdTrial 
                  if(this.templateType===5){
                    WbsId=this.selectData.referenceWbsTemplateIdLar
                  }
                  if(this.templateType===3){
                    WbsId=this.selectData.referenceWbsTemplateIdMeter
                  }
                }
            }
            
            this.finalWbsid=WbsId
              console.log(WbsId,'WbsId'); 
              console.log( this.finalWbsid,' this.finalWbsid=');
         

            // findProjectTree(this.projectForm.id,  this.templateType === 1 ? WbsId : this.selectData.referenceWbsTemplateIdTrial).then((res) => {
            findProjectTree(this.projectForm.id, WbsId).then((res) => {
              if (this.rightTreeData.length>0&&this.templateType===2&&this.rightObj.wbsId==WbsId) {
                this.$refs.treetotree.setRightTree(this.rightTreeData);
              }else if(this.rightTreeData1.length>0&&this.templateType===1&&this.rightObj1.wbsId==WbsId){
                  this.$refs.treetotree.setRightTree(this.rightTreeData1);
              }else if(this.rightTreeData2.length>0&&this.templateType===5&&this.rightObj2.wbsId==WbsId){
                this.$refs.treetotree.setRightTree(this.rightTreeData2);
              }
              else if(this.rightTreeData3.length>0&&this.templateType===3&&this.rightObj3.wbsId==WbsId){
                this.$refs.treetotree.setRightTree(this.rightTreeData3);
              }
              else{
                if (Array.isArray(res.data.data)) {
                  if(res.data.data.length>0){
                    this.iswbsselected=true
                  }else{
                     this.iswbsselected=false
                  }
                 console.log(11111111111);
                  this.$refs.treetotree.setRightTree(res.data.data);
                } else {
                  this.$refs.treetotree.setRightTree([]);
                  this.iswbsselected=false
                }
              }
                
              
              })
            
              
              }
      }

      this.rightloading = false;
    },

  }
};
</script>

<style scoped lang="scss">
</style>
