<template>
  <basic-container>
    <div>
      <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-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-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"
                :disabled="selected"
              >
                <el-radio :label="2">试验</el-radio>
                <el-radio :label="1">质检</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="selected"
                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"
            ></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
                max-height="440"
                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"
          :loading="saveBtnLoad"
          @click="saveQuit"
        >保存并退出</el-button>
        <el-button
          type="info"
          size="medium"
          :disabled="saveBtnBackDisabled"
          :loading="saveBtnBackLoad"
          v-if="activeType != 1"
          @click="saveNext('p')"
        >保存并返回上一步</el-button>
        <el-button
          type="success"
          size="medium"
          :disabled="saveBtnNextDisabled"
          :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";
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: [],
      radioType: '总里程',

      projectForm: {
        estimatedAmount: 0
      },
      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' }
        ]
      },

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

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

      templateType: 1,
      treeList: [],
      logTreeList: [],
      wbsId: '',
      logWbsId: '',
      selected: false,
      leftTreeData: [],
      logLeftTreeData: [],

      leftloading:false,
      rightloading:false,
      logleftloading:false,
      logrightloading:false,
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    projectForm: {
      handler: function () { // 此处注意，handler函数不能为箭头函数，this会取上下文，而不是组件里的this,此外，深度监听，必须为handler函数名，否则会无效果
        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: {
    //#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.getHighwayGradeList();
      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(() => {
                  this.getRightTree();
                  reject();
                })
                break;
            }
          }).catch(() => {
            this.typeChang[oldActiveName] = false;
            resolve();
          })
        } else {
          resolve();
        }
      })
    },

    getProjectDeatil () {
      getProjectDeatil(this.id).then((res) => {
        this.projectForm = res.data.data;
        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 () {
      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'){
          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) {
      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();
        }
      } 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'){
          this.getRightTree();
        }
        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 () {
      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');
      obj = {
        wbsId: this.wbsId,
        projectId: this.projectForm.id,
        wbsType: this.templateType,
        wbsTreeIds: ids
      }
      if (this.wbsId.toString().indexOf(',') >= 0) {
        //私有库
        obj.referenceType = "private";
        let ids = this.wbsId.toString().split(',');
        obj.wbsId = ids[0];
        obj.referencePrivateWbsProjectId = ids[1];
        obj.primaryKeyId = this.leftTreeData[0].primaryKeyId;
      } else {
        //公有库
        obj.referenceType = "public";
      }

      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;
      })
    },

    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) {
      //console.log(value)
      this.leftloading = true;
      if (value.toString().indexOf(',') >= 0) {
        //私有库
        let ids = value.toString().split(',');
        findProjectTree(ids[1], ids[0]).then((res) => {
          if (Array.isArray(res.data.data)) {
            this.leftTreeData = res.data.data;
          } else {
            this.leftTreeData = [];
          }
          this.leftloading = false;
        })
      } else {
        //公有库
        getAlltree(this.userInfo.tenant_id, '1', value).then((res) => {
          if (Array.isArray(res.data.data)) {
            this.leftTreeData = res.data.data;
          } else {
            this.leftTreeData = [];
          }
          this.leftloading = false;
        })
      }

      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 () {
      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;
        }).finally(() => {
          resolve();
        })
      })
    },

    treeChang () {
      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;

        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(projectTree.data.data);
        this.logrightloading = false;
      } else {
        await this.getLogTreeList();
      }
    },
    async treeInit () {

      let refId = this.projectForm.referenceWbsTemplateId;
      //引用被删会出现 wbsType -1
      if (refId && refId > 0 && Number(this.projectForm.wbsType) > 0) {
        //有引用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;
              break;
            }
          }
        } else {
          //公有
          this.wbsId = refId;
        }

        let projectTree = await findProjectTree(this.projectForm.id, refId)
        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);
          this.rightloading = false;
        }
      } else {
        this.getTreeList();
      }
    },

    getRightTree() {
      this.rightloading = true;
      findProjectTree(this.projectForm.id, this.projectForm.referenceWbsTemplateId).then((res) => {
        if (Array.isArray(res.data.data)) {
          this.$refs.treetotree.setRightTree(res.data.data);
        }
        this.rightloading = false;
      })
    },

  }
};
</script>

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