<template>
  <basic-container>
    <div>
      <el-tabs
        v-model="activeType"
        :before-leave="beforeLeave"
      >
        <!-- 合同段信息 -->
        <el-tab-pane
          label="合同段信息"
          name="1"
          :disabled="btnLoad"
        >
          <div>
            <el-form
              :model="contractForm"
              :rules="contractRules"
              ref="contractForm"
              label-width="140px"
            >
              <el-form-item label="项目名称">
                <el-input
                  v-model="projectInfo.projectName"
                  disabled
                ></el-input>
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="合同段类型"
                    prop="contractType"
                  >
                    <el-select
                      :disabled="contractForm.id?true:false"
                      v-model="contractForm.contractType"
                      placeholder="请选择"
                      class="w-100p"
                    >
                      <el-option
                        v-for="item in contractTypeList"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="合同段编号"
                    prop="contractNumber"
                  >
                    <el-input v-model="contractForm.contractNumber"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="合同段名称"
                    prop="contractName"
                  >
                    <el-input v-model="contractForm.contractName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="参与方进场日期"
                    prop="contractorJoinTime"
                  >
                    <el-date-picker
                      v-model="contractForm.contractorJoinTime"
                      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>
              <div class="flexBetween">
                <el-form-item
                  style="width:25%;"
                  label="是否开启电签"
                  prop="isElectronicSignature"
                >
                  <el-radio-group v-model="contractForm.isElectronicSignature">
                    <el-radio :label="0">关闭</el-radio>
                    <el-radio :label="1">开启</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  style="width:25%;"
                  label="是否开启试验模块"
                  prop="isTestModule"
                >
                  <el-radio-group v-model="contractForm.isTestModule">
                    <el-radio :label="0">关闭</el-radio>
                    <el-radio :label="1">开启</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  style="width:25%;"
                  label="是否引用编号"
                  prop="isReferenceNumber"
                >
                  <el-radio-group v-model="contractForm.isReferenceNumber">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  style="width:25%;"
                  label="是否开启复制数据"
                  prop="isCopyData"
                  v-if="contractForm.contractType==1"
                >
                  <el-radio-group v-model="contractForm.isCopyData">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <div v-else style="width:25%;">

                </div>
              </div>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="计划开工日期"
                    prop="planStartTime"
                  >
                    <el-date-picker
                      v-model="contractForm.planStartTime"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="计划完工日期"
                    prop="planEndTime"
                  >
                    <el-date-picker
                      v-model="contractForm.planEndTime"
                      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-row>
                <el-col :span="12">
                  <el-form-item
                    label="实际开工日期"
                    prop="actualStartTime"
                  >
                    <el-date-picker
                      v-model="contractForm.actualStartTime"
                      type="date"
                      format="yyyy 年 MM 月 dd 日"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="实际完工日期"
                    prop="actualEndTime"
                  >
                    <el-date-picker
                      v-model="contractForm.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-row>
                <el-col :span="12">
                  <el-form-item
                    label="业主单位名称"
                    v-if="contractForm.contractType==1"
                    prop="contractorUnitName"
                  >
                    <el-input v-model="contractForm.contractorUnitName"></el-input>
                  </el-form-item>
                  <el-form-item
                    v-if="contractForm.contractType==2"
                    label="监理单位名称"
                    prop="supervisionUnitName"
                  >
                    <el-input v-model="contractForm.supervisionUnitName"></el-input>
                  </el-form-item>
                  <el-form-item
                    v-if="contractForm.contractType==3"
                    label="建设单位名称"
                    prop="supervisionUnitName"
                  >
                    <el-input v-model="contractForm.supervisionUnitName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="合同金额"
                    prop="contractAmount"
                  >
                    <el-input v-model="contractForm.contractAmount">
                      <template slot="append">万元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="contractForm.contractType==1">
                <el-col :span="12">
                  <el-form-item
                    label="施工单位名称"
                    prop="constructionUnitName"
                  >
                    <el-input v-model="contractForm.constructionUnitName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="上传开工令"
                    prop="startFileUrl"
                  >
                    <template v-if="isBackShow">
                      <el-link
                        type="primary"
                        @click="downloadFile"
                      >开工令
                      </el-link>
                      <el-button
                        @click="delFile"
                        class="mg-l-10"
                        style="color:red"
                        type="text"
                        icon="el-icon-circle-close"
                      ></el-button>
                    </template>
                    <template v-else>
                      <el-upload
                        action="/api/blade-resource/oss/endpoint/put-file-attach"
                        :on-remove="handleRemove"
                        :limit="1"
                        :headers=headers
                        :on-exceed="handleExceed"
                        :on-success="handleSuccess"
                        :file-list="fileList"
                      >
                        <el-button
                          size="small"
                          type="primary"
                        >点击上传
                        </el-button>
                      </el-upload>
                    </template>

                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="contractForm.contractType==1">
                <el-col :span="12">
                  <el-form-item
                    label="监理单位名称"
                    prop="supervisionUnitName"
                  >
                    <el-input v-model="contractForm.supervisionUnitName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="试验室名称"
                    prop="laboratoryName"
                  >
                    <el-input v-model="contractForm.laboratoryName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-divider></el-divider>
              <el-row :gutter="20">
                <el-col
                  :span="12"
                  v-show="contractForm.contractType!=1"
                >
                  <div class="head-font">合同段权限配置</div>
                  <el-checkbox-group
                    v-model="idList"
                    class="martop15"
                  >
                    <el-checkbox
                      :label="item.contractId"
                      :key="key"
                      v-for="(item,key) in checkList"
                    >{{ item.contractName }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-col>
                <el-col :span="12">
                  <div class="head-font">组卷归档默认信息</div>
                  <el-row class="martop15">
                    <el-col :span="12">
                      <el-form-item
                        label="立卷人"
                        prop="filer"
                      >
                        <el-input v-model="contractForm.filer"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="保管期限"
                        prop="storagePeriod"
                      >
                        <el-select
                          v-model="contractForm.storagePeriod"
                          placeholder="请选择"
                          class="w-100p"
                        >
                          <el-option
                            v-for="item in storagePeriodList"
                            :key="item.id"
                            :label="item.dictValue"
                            :value="item.dictKey"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item
                        label="审核人"
                        prop="reviewer"
                      >
                        <el-input v-model="contractForm.reviewer"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="保管密级"
                        prop="securityLevel"
                      >
                        <el-select
                          v-model="contractForm.securityLevel"
                          placeholder="请选择"
                          class="w-100p"
                        >
                          <el-option
                            v-for="item in securityLevelList"
                            :key="item.id"
                            :label="item.dictValue"
                            :value="item.dictKey"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item
                        label="档案前缀"
                        prop="prefix"
                      >
                        <el-input v-model="contractForm.prefix"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">

                    </el-col>
                  </el-row>
                </el-col>
                <el-col
                  :span="12"
                  v-if="contractForm.contractType==1"
                >
                  <div class="head-font">附加信息</div>
                  <el-form-item
                    label="项目地址"
                    prop="projectPlace"
                  >
                    <!-- <el-input v-model="contractForm.projectPlace" placeholder="点击后面地图选取地址">
                        <el-button slot="append" icon="el-icon-map-location" @click="mapDialogVisible = true"></el-button>
                      </el-input> -->
                    <avue-input-map
                      :params="params"
                      placeholder="请选择地图"
                      v-model="flageData"
                      @change="mapChange"
                    ></avue-input-map>
                  </el-form-item>
                  <el-form-item
                    label="起始桩号"
                    prop="startStation"
                  >
                    <el-input v-model="contractForm.startStation"></el-input>
                  </el-form-item>
                  <el-form-item
                    label="结束桩号"
                    prop="endStation"
                  >
                    <el-input v-model="contractForm.endStation"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-if="contractForm.contractType == 1"
          label="分配WBS"
          name="2"
          :disabled="btnLoad"
        >
          <div>
            <div
              v-if="!wbsId"
              class="text-align-c"
            >项目暂未分配wbs树
            </div>
            <tree-tree
              :left-tree-data="leftTreeData"
              ref="treetotree"
              @onAddTree="treeChang"
              @onDelTree="treeChang"
              :leftloading="leftloading"
              :rightloading="rightloading"
            ></tree-tree>
          </div>
        </el-tab-pane>
        <el-tab-pane
          label="分配项目人员"
          name="3"
          :disabled="btnLoad"
        >
          <div>
            <div class="flex jc-al-c">
              <span class="mg-r-10">项目名称</span>
              <el-input
                v-model="projectInfo.projectName"
                disabled
                style="width:300px;margin-right:30px;"
              ></el-input>
              <span class="mg-r-10">合同段名称</span>
              <el-input
                v-model="contractForm.contractName"
                disabled
                style="width:300px;"
              ></el-input>
            </div>
            <el-divider></el-divider>
            <div class="flex jc-al-c mg-b-10">
              <div>
                <span class="mg-r-10">角色方</span>
                <el-radio-group v-model="rId">
                  <el-radio-button
                    v-for="(item,key) in roleList"
                    :label="item.id"
                    :key="key"
                  >{{ item.roleName }}
                  </el-radio-button>
                </el-radio-group>
              </div>
              <div>
                <span class="mg-r-10 mg-l-20">请选择岗位</span>
                <el-select
                  v-model="postId"
                  filterable
                  placeholder="请输入搜索"
                >
                  <el-option
                    v-for="item in postList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <!-- table表 -->
            <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="account"
                  label="登录账号"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="password"
                  label="密码"
                  align="center"
                ></el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-link
                      class="mg-r-20"
                      type="primary"
                      @click="copyAccPas(scope.row)"
                    >复制
                    </el-link>
                    <el-link
                      class="mg-r-20"
                      type="primary"
                      @click="resetPassword(scope.row)"
                    >重置密码
                    </el-link>
                    <el-link
                      type="danger"
                      @click="handleDelete(scope.$index, scope.row)"
                    >删除
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
              <el-input
                v-model="copyText"
                ref="copyInput"
                type="textarea"
                style='opacity: 0;position: absolute;height:1px;overflow:hidden;'
              ></el-input>
            </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
                class="marleft10"
                type="success"
                @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 marbottom20">
        <el-button
          :type="activeType != 3?'info':'success'"
          size="medium"
          :disabled="saveBtnDisabled || leftloading || rightloading"
          :loading="saveBtnLoad"
          @click="saveQuit"
        >保存并退出</el-button>
        <el-button
          type="info"
          size="medium"
          :disabled="saveBtnBackDisabled || leftloading || rightloading"
          :loading="saveBtnBackLoad"
          v-if="activeType != 1"
          @click="saveNext('p')"
        >保存并返回上一步</el-button>
        <el-button
          type="success"
          size="medium"
          :disabled="saveBtnNextDisabled || leftloading || rightloading"
          :loading="saveBtnNextLoad"
          v-if="activeType != 3"
          @click="saveNext('n')"
        >保存并进入下一步</el-button>
      </div>
    </div>
  </basic-container>
</template>

<script>
import {getProjectDeatil, findProjectTree, treeAllConstruction, getContractRelation} from "@/api/manager/projectinfo";
import {
  submitContractInfo,
  getContractInfo,
  getContractInfo2,
  delFileFromUrl,
  searchRole,
  findAllUserByCondition,
  findUserList,
  saveUserInfoByProjectTow,
  removeUsersByIds,
  resetPasswordByUserId,
  submitWbsTreeInContract,
  getContractInfoTree
} from "@/api/manager/contractinfo";
import {getDictionary} from "@/api/system/dict";
import {getDictionary as getDictbiz} from "@/api/system/dictbiz";
import {remove as removeFile} from "@/api/resource/attach";
import website from '@/config/website';
import {Base64} from 'js-base64';
import {getToken} from '@/util/auth';
import {mapGetters} from "vuex";

import treeTree from "@/components/tree-tree/main"

export default {
  components: {
    treeTree
  },
  data() {
    var checkPlace = (rule, value, callback) => {
      if (this.flageData && this.flageData.length > 2 && this.flageData[2]) {
        callback();
      } else {
        callback(new Error('请选取项目地址'));
      }
    }
    var checkDate = (rule, value, callback) => {
      if (value && this.contractForm.planStartTime) {
        if (Date.parse(value) < Date.parse(this.contractForm.planStartTime)) {
          callback(new Error('计划完工日期不能小于开工日期'));
        }
      }
      callback();
    };
    var checkDate2 = (rule, value, callback) => {
      if (value && this.contractForm.actualStartTime) {
        if (Date.parse(value) < Date.parse(this.contractForm.actualStartTime)) {
          callback(new Error('实际完工日期不能小于开工日期'));
        }
      }
      callback();
    };
    var checkIsNumber = (rule, value, callback) => {
      if (value != Number(value)) {
        callback(new Error('金额必须是数字'));
      }
      callback();
    };
    return {
      idList: [],
      checkList: [],
      postIdss: '',
      //#region
      pageindx: 1,
      pagesize: 10,
      total: 0,
      //#endregion
      activeType: '1',
      typeChang: {
        1: false,
        2: false,
        3: false,
      },
      btnLoad: false,
      saveBtnLoad: false,
      saveBtnDisabled: false,
      saveBtnBackLoad: false,
      saveBtnBackDisabled: false,
      saveBtnNextLoad: false,
      saveBtnNextDisabled: false,

      pid: '',
      cid: '',
      projectInfo: {},

      contractTypeList: [],
      storagePeriodList: [],//保管期限
      securityLevelList: [],//保管密级
      fileList: [],
      headers: {},
      isBackShow: false,

      contractForm: {
        contractType: 1,
        contractAmount: 0,
        isElectronicSignature: 0,
        isTestModule: 0,
        isReferenceNumber: 0,
        isCopyData: 0,
      },
      contractRules: {
        contractName: [
          {required: true, message: '请输入合同段名称', trigger: 'blur'},
        ],
        contractType: [
          {required: true, message: '请选择合同段类型', trigger: 'change'}
        ],
        contractNumber: [
          {required: true, message: '请输入合同段编号', trigger: 'blur'},
        ],
        isElectronicSignature: [
          {required: true, message: '请设置电签状态', trigger: 'change'},
        ],
        isTestModule: [
          {required: true, message: '请设置试验模块状态', trigger: 'change'},
        ],
        isReferenceNumber: [
          {required: true, message: '请设置是否引用编号', trigger: 'change'},
        ],
        isCopyData: [
          {required: true, message: '请设置是否复制数据', trigger: 'change'},
        ],
        contractorUnitName: [
          {required: true, message: '请输入业主单位名称', trigger: 'blur'},
        ],
        constructionUnitName: [
          {required: true, message: '请输入施工单位名称', trigger: 'blur'},
        ],
        supervisionUnitName: [
          {required: true, message: '请输入监理单位名称', trigger: 'blur'},
        ],
        startStation: [
          {required: true, message: '请输入起始桩号', trigger: 'blur'},
        ],
        endStation: [
          {required: true, message: '请输入结束桩号', trigger: 'blur'},
        ],
        projectPlace: [
          {required: true, validator: checkPlace, trigger: 'blur'},
        ],
        planEndTime: [
          {validator: checkDate, trigger: 'blur'},
        ],
        actualEndTime: [
          {validator: checkDate2, trigger: 'blur'},
        ],
        contractAmount: [
          {validator: checkIsNumber, trigger: 'blur'}
        ]
      },

      mapDialogVisible: false,
      params: {
        zoom: 10,
        // zoomEnable: false,
        // dragEnable: false,
      },
      flageData: [],

      rId: '',
      roleList: [],
      postId: '',
      postList: [],
      contractUserList: [],
      userId: '',
      userList: [],
      copyText: '',

      wbsId: '',
      leftTreeData: [],
      leftloading:false,
      rightloading:false,
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  watch: {
    contractForm: {
      handler: function () { // 此处注意，handler函数不能为箭头函数，this会取上下文，而不是组件里的this,此外，深度监听，必须为handler函数名，否则会无效果
        this.typeChang['1'] = true;
      },
      deep: true
    },
    activeType: async function (newValue) {
      if (newValue == '3') {
        this.getUserByName();
        this.searchRole()
      } else if (newValue == '2') {
        await this.getLeftTree();
        this.getRightTree();
      }
    },
    rId: function () {
      this.postIdss = ''
      this.postId = ''
      this.contractUserList = [];//从超级管理员，切到其他角色，不会清空列表
      this.roleList.forEach(val => {
        if (val.id === this.rId) {
          if (val.children) {
            this.postList = val.children
            this.postId = this.postList[0].id;//切换的时候默认选中第一个岗位
          } else {
            this.postList = []
          }
          if (val.roleName === '超级管理员') {
            this.postIdss = this.rId
            this.findAllUserByCondition(this.rId)
          }
        }
      })
    },
    postId: function (newValue) {
      if (newValue) {
        this.findAllUserByCondition();
      } else {
        this.contractUserList = [];
      }
    },
    'contractForm.contractType'(newValue) {
      if (newValue != 1) {
        this.treeAllConstruction()
      }
    }
  },
  created() {
    this.init();
    //console.log(this.userInfo)
  },
  mounted() {
    this.$nextTick(() => {
      this.typeChang = {
        1: false,
        2: false,
        3: false,
      }
    })
  },
  methods: {
    //#region //后加分页
    handleSizeChange(val) {
      this.pagesize = val
      this.findAllUserByCondition()
    },
    handleCurrentChange(val) {
      this.pageindx = val
      this.findAllUserByCondition()
    },
    rputerPush() {
      this.$router.push({
        path: '/system/user',
        query: {tankai: true}
      })
    },
    //#endregion

    //#region 甘云杰
    async searchRole() {
      const {data: res} = await searchRole()
      console.log(res);
      if (res.code === 200) {
        this.roleList = res.data
      }
    },
    async init() {
      this.pid = this.$route.query.pid;
      this.cid = this.$route.query.cid;
      if (!this.cid) {
        this.contractForm.pid = this.pid;
      } else {
        if (this.$route.query.contractType == 1) {
          await this.getContractInfo();//获取合同段基本信息
        } else if (this.$route.query.contractType == 2 || this.$route.query.contractType == 3) {
          await this.getContractInfo2()
          await this.getContractRelation(); //监理、业主关联施工
        }
      }
      await this.getProjectDeatil();//获取项目详情
      if (this.$route.query.type) {
        console.log(this.$route.query.type);
        this.activeType = this.$route.query.type;
      }
      this.getContractTypeList();//获取合同类型
      this.getStoragePeriodList();//获取业务字典
      this.getSecurityLevelList();//获取安全等级
      this.setHeaders();
    },
    beforeLeave(activeName, oldActiveName) {
      return new Promise((resolve, reject) => {
        if (oldActiveName == '1' && !this.contractForm.id) {
          this.$message({
            type: "warning",
            message: "请先保存合同段后，再进行合同段的分配"
          });
          reject();
        }

        if (this.typeChang[oldActiveName]) {
          this.$confirm('检测到新编辑内容, 是否保存?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '不用',
            type: 'warning'
          }).then(() => {
            switch (oldActiveName) {
              case '1':
                this.savecontract().then((res) => {
                  this.contractForm.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() {
      return new Promise((resolve) => {
        getProjectDeatil(this.pid).then((res) => {
          this.projectInfo = res.data.data;
          this.wbsId = this.projectInfo.referenceWbsTemplateId;
          resolve();
        }).finally(() => {
          resolve();
        })
      })
    },
    getContractRelation() {
      return new Promise((resolve) => {
        getContractRelation(this.cid).then((res) => {
          console.log("ids", res)
          this.idList = res.data.data && res.data.data.map(item => {
            return item.id
          })
          resolve();
        }).finally(() => {
          resolve();
        })
      })
    },
    getContractInfo() {
      return new Promise((resolve) => {
        getContractInfo(this.cid).then((res) => {
          this.contractForm = res.data.data;
          if (this.contractForm.startFileUrl) {
            this.isBackShow = true;
          }
          if (this.contractForm.projectPlace) {
            this.flageData = ['', '', this.contractForm.projectPlace]
          }
          if (Number(this.contractForm.contractAmount) < 0) {
            this.contractForm.contractAmount = 0;
          }
          if (Number(this.contractForm.securityLevel) < 0) {
            this.contractForm.securityLevel = 0;
          }
          if (Number(this.contractForm.storagePeriod) < 0) {
            this.contractForm.storagePeriod = 0;
          }
          this.$nextTick(() => {
            this.typeChang['1'] = false;
          })
        }).finally(() => {
          resolve();
        })
      })
    },
    getContractInfo2() {
      return new Promise((resolve) => {
        getContractInfo2({id: this.cid, contractType: this.contractType}).then((res) => {
          this.contractForm = res.data.data.contractInfo
          if (res.data.data.wbsTreeContractList.length > 0) {
            this.idList = []
            res.data.data.wbsTreeContractList.forEach(val => {
              if (val.contractIdRelation) {
                this.idList.push(val.contractIdRelation)
              }
            })
          }

          if (this.contractForm.startFileUrl) {
            this.isBackShow = true;
          }
          if (this.contractForm.projectPlace) {
            this.flageData = ['', '', this.contractForm.projectPlace]
          }
          if (Number(this.contractForm.contractAmount) < 0) {
            this.contractForm.contractAmount = 0;
          }
          if (Number(this.contractForm.securityLevel) < 0) {
            this.contractForm.securityLevel = 0;
          }
          if (Number(this.contractForm.storagePeriod) < 0) {
            this.contractForm.storagePeriod = 0;
          }
          this.$nextTick(() => {
            this.typeChang['1'] = false;
          })
        }).finally(() => {
          resolve();
        })
      })
    },
    async saveQuit() {
      this.btnLoad = true;
      this.saveBtnLoad = true;
      this.saveBtnBackDisabled = true
      this.saveBtnNextDisabled = true
      try {
        if (this.activeType == '1') {
          await this.savecontract();
        } else if (this.activeType == '2') {
          await this.saveWbsTree();
        }
      } 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.savecontract();
          this.contractForm.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 (this.contractForm.contractType == 1) {
        if (type == 'n') {
          num++;
        } else if (type == 'p') {
          num--;
        }
      } else {
        if (type == 'n') {
          num = num + 2;
        } else if (type == 'p') {
          num = num - 2
        }
      }
      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
      }
    },
    getIds() {

    },

    savecontract() {
      return new Promise((resolve, reject) => {
        this.$refs['contractForm'].validate((valid) => {
          if (valid) {
            if (this.flageData.length == 3) {
              this.contractForm.projectPlace = this.flageData[2];
            }
            let das = this.contractForm
            if (this.contractForm.contractType != 1) {
              delete das.startStation
              delete das.endStation
              delete das.projectPlace
              das.idList = []
              this.idList.forEach(val => {
                das.idList.push({contractId: val})
              })
              resolve(submitContractInfo(das))
              this.btnLoad = false
            } else {
              resolve(submitContractInfo(das))
              this.btnLoad = false
            }
          } else {
            reject('验证失败')
            this.btnLoad = false
          }
        })
      })
    },

    handleRemove(file) {
      //console.log(file, fileList);
      removeFile(file.response.data.attachId).then(() => {
        this.contractForm.startFileUrl = '';
      })
    },
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件，请先移除后，再次上传`);
    },
    handleSuccess(res) {
      this.contractForm.startFileUrl = res.data.link;
    },
    setHeaders() {
      this.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
      this.headers[website.tokenHeader] = 'bearer ' + getToken()
    },

    downloadFile() {
      window.open(this.contractForm.startFileUrl);
    },
    delFile() {
      this.$confirm('是否删除该文件?', '删除开工令', {
        distinguishCancelAndClose: true,
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(() => {
        delFileFromUrl(this.contractForm.startFileUrl).then(() => {
          this.isBackShow = false;
          this.contractForm.startFileUrl = '';
        })
      })
    },

    addUserToProject() {
      if (!this.userId) {
        this.$message({
          type: "warning",
          message: "请先选择用户再进行添加"
        });
        return;
      }
      let roleId = ''
      if (!this.postIdss) {
        if (!this.postId) {
          this.$message({
            type: "warning",
            message: "请先选择岗位再进行添加"
          });
          return;
        } else {
          roleId = this.postId
        }
      } else {
        roleId = this.postIdss
      }

      let list = [{
        projectId: this.pid,
        contractId: this.contractForm.id,
        userId: this.userId,
        roleId: roleId,
      }];
      saveUserInfoByProjectTow(list).then(() => {
        this.findAllUserByCondition(this.rId);
      })
    },

    findAllUserByCondition(val) {
      let rId
      if (this.postId) {
        rId = this.postId
      } else {
        rId = val
      }
      findAllUserByCondition({
          cId: this.contractForm.id,
          pId: this.pid,
          // "postId": this.postId,
          rId: rId,
        },
        this.pagesize,
        this.pageindx,
      ).then((res) => {
        this.contractUserList = res.data.data.records;
        this.total = res.data.data.total
      })
    },

    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: "删除成功!"
          });
        })
      })
    },

    copyAccPas(row) {
      this.copyText = `姓名：${row.name}
账号：${row.account}
密码：${row.password}`;
      this.$nextTick(() => {
        this.$refs.copyInput.select()
        document.execCommand('copy')
        this.$message({
          type: "success",
          message: "成功复制在剪贴板!"
        });
      })

    },

    resetPassword(row) {
      this.$confirm('是否将用户【' + row.name + '】密码重置为123456', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPasswordByUserId(row.uid).then(() => {
          row.password = '123456';
          this.$message({
            type: "success",
            message: "重置成功!"
          });
        })
      })
    },

    getContractTypeList() {
      if (this.contractTypeList.length > 1) {
        return;
      }
      getDictionary({
        code: 'contract_type'
      }).then((res) => {
        res.data.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.contractTypeList = res.data.data;
      })
    },


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

    getLeftTree() {
      return new Promise((resolve) => {
        if (!this.leftTreeData.length) {
          this.leftloading = true;
          findProjectTree(this.projectInfo.id, this.wbsId).then((res) => {
            if (Array.isArray(res.data.data)) {
              this.leftTreeData = res.data.data;
            } else {
              this.leftTreeData = [];
            }
            resolve();
          }).finally(() => {
            this.leftloading = false;
            resolve();
          })
        }
        resolve();
      })
    },
    getRightTree() {
      console.log(this.wbsId, this.projectInfo.id, this.contractForm.id);
      this.rightloading = true;
      getContractInfoTree(this.wbsId, this.projectInfo.id, this.contractForm.id).then((res) => {
        if (Array.isArray(res.data.data)) {
          this.$refs.treetotree.setRightTree(res.data.data);
        }
        this.rightloading = false;
      })
    },
    saveWbsTree() {
      let obj = {};
      let ids = this.$refs.treetotree.getTreeAllId('rightTree');
      obj = {
        wbsId: this.wbsId,
        projectId: this.projectInfo.id,
        contractId: this.contractForm.id,
        wbsTreeIds: ids
      }
      return submitWbsTreeInContract(obj);
    },

    treeChang() {
      this.typeChang[2] = true;
    },

    mapChange() {
      this.$refs['contractForm'].validateField('projectPlace');
    },

    getStoragePeriodList() {
      if (this.storagePeriodList.length > 1) {
        return;
      }
      getDictbiz({
        code: 'storage_period'
      }).then((res) => {
        res.data.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.storagePeriodList = res.data.data;
      })
    },
    getSecurityLevelList() {
      if (this.securityLevelList.length > 1) {
        return;
      }
      getDictbiz({
        code: 'security_level'
      }).then((res) => {
        res.data.data.forEach(element => {
          element.dictKey = Number(element.dictKey)
        });
        this.securityLevelList = res.data.data;
      })
    },
    //#endregion

    //#region 合同段信息
    async treeAllConstruction() {
      const {data: res} = await treeAllConstruction({projectId: this.$route.query.pid})
      console.log(res);
      if (res.code == 200) {
        this.checkList = res.data
      }
    },
    //#endregion
  }
};
</script>

<style scoped lang="scss">
.bm-view {
  width: 100%;
  height: 300px;
}

.head-font {
  font-size: 20px;
  font-weight: bold;
}
</style>
