import config from '../../config'
import {
  getOpenId,
  setOpenId,
  getSessionKey,
  setSessionKey,
} from '../../utils/auth'
import {
  getMaOpenId,
  getMaPhoneNumber,
} from '../../api/login'
import {
  getProjectInfo,
  registerSubDepts,
  findProSubDeptsUser,
  findProSubDeptsInfo
} from '../../api/project'
import {
  findBusExamInfos,
  findBusTrainingVideos,
  startPlayUserEduVideo,
  endPlayUserEduVideo,
  finishEduVideo,
  submitBusExamUser,
  submitUserSignets
} from '../../api/busEdu'
import {
  securityFileUpload
} from '../../utils/request'
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      subDeptType: null,
      craftType: null,
      craftPost: '1',
    },
    limit: 1,
    maxDate: new Date(2088, 1, 1).getTime(),
    currentDate: new Date().getTime(),
    title: "",
    proId: null,
    signType: null,
    initProject: {},
    userPhoneNumber: null,
    deptTypeList: [{
      "id": "4",
      "text": "劳务分包"
    }, {
      "id": "5",
      "text": "专业分包"
    }],
    craftPostList: [{
      "id": "23",
      "text": "项目经理"
    }],
    flowNodes: [{
      "id": "1",
      "name": "信息登记",
      "text": "信息登记"
    }, {
      "id": "2",
      "name": "视频学习",
      "text": "视频学习"
    }, {
      "id": "3",
      "name": "在线考试",
      "text": "在线考试"
    }, {
      "id": "4",
      "name": "文件签署",
      "text": "文件签署"
    }],
    active: 0,
    posDataList: [{
      'id': 1,
      'text': '测试',
      'children': [{
        'id': '2',
        'text': '测试111'
      }, {
        'id': '3',
        'text': '测试222'
      }]
    }],
    showDetailsName: "",
    showDetailsPopup: false,
    mainActiveIndex: null,
    chidActiveIndex: null,
    imgBase: config.baseImgUrl,
    videoIdx: 0,
    videoUrl: "",
    videoTitle: "",
    eduVideoMenu: [],
    eduVideoItem: [],
    busExamInfos: {},
    busExamQuestions: [],
    radio: '1',
    time: 3600, // 初始倒计时为 3600 秒
    timer: null,
    timeStr: '',
    isPapers: false,
    fileForm: {},
    signTime: 5,
    signTimer: null,
    signPath: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    if (options && options.signType && options.QRPID) {
      //this.getMaOpenId();
      this.findProjectInfo(options.QRPID);
      let title = "";
      if (options.signType == '1') {
        title = "参建单位信息注册";
      } else if (options.signType == '2' || options.signType == '3') {
        this.setData({
          "form.subDeptId": options.KeyId,
          "form.craftPost": options.signType == '2' ? '23' : null,
        });
        title = "参建单位管理人员信息注册";
      } else if (options.signType == '4') {
        this.setData({
          "form.subDeptId": options.KeyId
        });
        title = "参建单位劳务人员信息注册";
      }
      this.setData({
        title,
        proId: options.QRPID,
        signType: options.signType,
        "form.projectId": options.QRPID,
      });
      this.getPhoneNumber({
        'data': '18189138536'
      });
    } else {
      app.toast("请求参数异常,请重新扫码...");
      // wx.redirectTo({
      //     url: '/pages/login/index',
      // });
    }
  },

  /**
   * 授权登录
   */
  getMaOpenId: function () {
    wx.login({
      success: res => {
        getMaOpenId({
          'code': res.code
        }).then(response => {
          setOpenId(response.data.openid);
          setSessionKey(response.data.sessionKey);
        });
      }
    })
  },

  /**
   * 获取手机号码
   * @param {*} e 
   */
  getPhoneNumber(e) {
    // if (e.detail.code) {
    //   let data = {
    //     openId: getOpenId(),
    //     sessionKey: getSessionKey(),
    //     iv: e.detail.iv,
    //     encryptedData: e.detail.encryptedData
    //   }
    //   getMaPhoneNumber(data).then(res => {
    //     if (res.code == 200) {
    //let phoneNumber = res.data;
    let phoneNumber = e.data;
    //使用手机号码查询详情
    if (this.data.signType == "1") {
      findProSubDeptsInfo(this.data.proId, phoneNumber).then(deptRes => {
        if (deptRes.code == 200 && deptRes.data) {
          deptRes.data.subDeptLeaderPhone = phoneNumber;
          if (deptRes.data.subDeptInfos) {
            let subDeptInfosJSON = JSON.parse(deptRes.data.subDeptInfos);
            deptRes.data.subDeptInfos = subDeptInfosJSON;
            if (deptRes.data.subDeptInfos.legalPersonCardImgPos) {
              deptRes.data.subDeptInfos.legalPersonCardImgPos = (this.data.imgBase + deptRes.data.subDeptInfos.legalPersonCardImgPos).split(',');
            }
            if (deptRes.data.subDeptInfos.legalPersonCardImgInv) {
              deptRes.data.subDeptInfos.legalPersonCardImgInv = (this.data.imgBase + deptRes.data.subDeptInfos.legalPersonCardImgInv).split(',');
            }
          }
          if (deptRes.data.proProjectInfoSubdeptsUsers && deptRes.data.proProjectInfoSubdeptsUsers.user) {
            if (deptRes.data.proProjectInfoSubdeptsUsers.user.cardImgPos) {
              deptRes.data.leaderCardImgPos = (this.data.imgBase + deptRes.data.proProjectInfoSubdeptsUsers.user.cardImgPos).split(',');
            }
            if (deptRes.data.proProjectInfoSubdeptsUsers.user.cardImgInv) {
              deptRes.data.leaderCardImgInv = (this.data.imgBase + deptRes.data.proProjectInfoSubdeptsUsers.user.cardImgInv).split(',');
            }
            if (deptRes.data.proProjectInfoSubdeptsUsers.user.userPicture) {
              deptRes.data.leaderUserPicture = (this.data.imgBase + deptRes.data.proProjectInfoSubdeptsUsers.user.userPicture).split(',');
            }
            if (deptRes.data.proProjectInfoSubdeptsUsers.subDeptPowerPath) {
              deptRes.data.subDeptLeaderPowerPath = (this.data.imgBase + deptRes.data.proProjectInfoSubdeptsUsers.subDeptPowerPath).split(',');
            }
            if (deptRes.data.businessLicensePath) {
              deptRes.data.businessLicensePath = (this.data.imgBase + deptRes.data.businessLicensePath).split(',');
            }
          }
          this.setData({
            form: deptRes.data,
            userPhoneNumber: phoneNumber,
            active: deptRes.data.proProjectInfoSubdeptsUsers.subStep
          });
          if (deptRes.data.proProjectInfoSubdeptsUsers.subStep == 1) {
            this.initBusEduVideos(false);
          } else if (deptRes.data.proProjectInfoSubdeptsUsers.subStep == 2) {
            this.initBusEduQuestion(false);
          } else if (deptRes.data.proProjectInfoSubdeptsUsers.subStep == 3) {
            this.startSignFile(false);
          }
        } else {
          this.setData({
            userPhoneNumber: phoneNumber,
            "form.subDeptLeaderPhone": phoneNumber,
          });
        }
      });
    } else {
      findProSubDeptsUser(this.data.proId, phoneNumber).then(userRes => {
        if (userRes.code == 200 && userRes.data) {
          if (userRes.data.subDeptInfos) {
            let subDeptInfosJSON = JSON.parse(userRes.data.subDeptInfos);
            userRes.data.subDeptInfos = subDeptInfosJSON;
          }
          this.setData({
            form: userRes.data,
            userPhoneNumber: phoneNumber,
            "form.leaderCardImgPos": userRes.data.proProjectInfoSubdeptsUsers.user.cardImgPos,
            "form.leaderCardImgInv": userRes.data.proProjectInfoSubdeptsUsers.user.cardImgInv,
            "form.leaderUserPicture": userRes.data.proProjectInfoSubdeptsUsers.user.userPicture,
            "form.phoneNumber": phoneNumber,
            active: userRes.data.proProjectInfoSubdeptsUsers.subStep
          });
        } else {
          this.setData({
            userPhoneNumber: phoneNumber,
            "form.phoneNumber": phoneNumber,
          });
        }
      });
    }
    //     }
    //   })
    // } else {
    //   //用户决绝授权
    //   app.toast("请允许微信手机号一键登录");
    // }
  },

  /**
   * 初始化学习视频
   */
  initBusEduVideos: function (skip) {
    this.setData({
      active: skip ? (this.data.active + 1) : this.data.active
    })
    findBusTrainingVideos(this.data.proId, this.data.userPhoneNumber).then(res => {
      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          let videoMenus = [];
          let videoItems = [];
          res.data.forEach(menuItem => {
            videoMenus.push({
              'menuId': menuItem.menuId,
              'menuName': menuItem.menuName
            });
            menuItem.busTrainingVideos.forEach(videoItem => {
              videoItem.menuId = menuItem.menuId;
              videoItem.menuName = menuItem.menuName;
              videoItems.push(videoItem);
            });
          });
          startPlayUserEduVideo(videoItems[0].remark);
          this.setData({
            videoActive: res.data[0].menuId,
            eduVideoMenu: videoMenus,
            eduVideoItem: videoItems,
            videoIdx: 0,
            videoUrl: this.data.imgBase + videoItems[0].trainFilePath,
            videoTitle: videoItems[0].trainTitle,
          });
        } else {
          //没有视频时跳过学习...
          this.initBusEduQuestion();
        }
      }
    });
  },

  /**
   * 上一个学习视频
   */
  onClickPrevsVideo: function () {
    if (this.data.videoIdx == 0) {
      app.toast("播放失败,这已经是第一个视频了。");
    } else {
      this.setData({
        videoIdx: this.data.videoIdx - 1
      });
      this.data.eduVideoItem.forEach((item, idx) => {
        if (this.data.videoIdx == idx) {
          this.setData({
            videoActive: item.menuId,
            videoUrl: this.data.imgBase + item.trainFilePath,
            videoTitle: item.trainTitle
          });
        }
      });
    }
  },

  /**
   * 下一个学习视频
   */
  onClickAfterVideo: function (event) {
    let videoSize = this.data.eduVideoItem.length;
    let currentVideo = this.data.videoIdx + 1;
    if (currentVideo >= videoSize) {
      finishEduVideo(this.data.eduVideoItem[this.data.videoIdx].remark);
      //视频学习完成...
      app.toast("学习完成,您可以开始考试了。");
    } else {
      endPlayUserEduVideo(this.data.eduVideoItem[this.data.videoIdx].remark);
      startPlayUserEduVideo(this.data.eduVideoItem[currentVideo].remark);
      let msg = "正在学习第 " + currentVideo + "个视频,还有 " + (videoSize - currentVideo) + "个视频待学习。";
      app.toast(msg);
      this.setData({
        videoIdx: this.data.videoIdx + 1
      });
      this.data.eduVideoItem.forEach((item, idx) => {
        if (this.data.videoIdx == idx) {
          this.setData({
            videoActive: item.menuId,
            videoUrl: this.data.imgBase + item.trainFilePath,
            videoTitle: item.trainTitle
          });
        }
      });
    }
  },

  /**
   * 初始化学习考试
   */
  startBusEduExamNode: function () {
    let videoSize = this.data.eduVideoItem.length;
    let currentVideo = this.data.videoIdx + 1;
    if (this.data.form.proProjectInfoSubdeptsUsers.subStep > 1 || currentVideo >= videoSize) {
      this.initBusEduQuestion(true);
    } else {
      app.toast("请学习完所有视频后再进行考试。");
    }
  },

  /**
   * 重新开始考试
   */
  anewBusEduQuestion() {
    this.setData({
      isPapers: false
    })
  },

  /**
   * 初始化学习考试
   */
  initBusEduQuestion: function (skip) {
    this.setData({
      active: skip ? (this.data.active + 1) : this.data.active
    })
    this.startCountdown(); // 页面加载时开始倒计时
    findBusExamInfos(this.data.proId, this.data.userPhoneNumber).then(res => {
      if (res.code == 200) {
        if (res.data && res.data && res.data.busExamUserResultList) {
          res.data.busExamUserResultList.forEach(item => {
            item.questionOption = JSON.parse(item.questionOption);
          });
          this.setData({
            busExamInfos: res.data,
            busExamQuestions: res.data.busExamUserResultList
          });
        } else {
          //没有答题时跳过学习...
          //this.initBusEduQuestion();
        }
      }
    });
  },

  /**
   * 选中单选框
   * @param {*} e 
   */
  toggleRadio(e) {
    if (!this.data.isPapers) {
      let idxs = e.currentTarget.dataset.id.split('_');
      let _busExamQuestions = this.data.busExamQuestions;
      _busExamQuestions[idxs[0]].questionOption.forEach(item => {
        item.selected = false;
      })
      _busExamQuestions[idxs[0]].questionOption[idxs[1]].selected = true;
      this.setData({
        busExamQuestions: _busExamQuestions
      });
    }
  },

  /**
   * 选中复选框
   * @param {*} e 
   */
  toggleCheckbox(e) {
    if (!this.data.isPapers) {
      let idxs = e.currentTarget.dataset.id.split('_');
      let _busExamQuestions = this.data.busExamQuestions;
      _busExamQuestions[idxs[0]].questionOption[idxs[1]].selected = !_busExamQuestions[idxs[0]].questionOption[idxs[1]].selected;
      this.setData({
        busExamQuestions: _busExamQuestions
      });
    }
  },

  /**
   * 提交试卷
   */
  submitThePapers(skip) {
    let _busExamQuestions = this.data.busExamQuestions;
    for (let i = 0; i < _busExamQuestions.length; i++) {
      let ck = false;
      let _userAnswer = [];
      for (let y = 0; y < _busExamQuestions[i].questionOption.length; y++) {
        if (_busExamQuestions[i].questionOption[y].selected) {
          ck = true;
          _userAnswer.push(_busExamQuestions[i].questionOption[y].opt);
        }
      }
      if (!ck) {
        if (skip == "skip") {
          _busExamQuestions[i].userAnswer = "";
        } else {
          app.toast("第" + (i + 1) + "题还未答,请完成考试后再提交试卷!");
          return false;
        }
      } else {
        _busExamQuestions[i].userAnswer = _userAnswer.toString();
      }
    }
    this.setData({
      busExamQuestions: _busExamQuestions
    });
    let that = this;
    //弹出确认
    wx.showModal({
      title: '提示',
      content: '是否确认提交试卷信息?',
      success: function (sm) {
        if (sm.confirm) {
          that.submitThePapersValues();
        }
      }
    })
  },

  /**
   * 提交试卷答案
   */
  submitThePapersValues() {
    let examForm = this.data.busExamInfos;
    let busExamQuestions = this.data.busExamQuestions;
    busExamQuestions.forEach(item => {
      item.questionOption = null;
    });
    examForm.busExamUserResultList = busExamQuestions;
    submitBusExamUser(examForm).then(res => {
      this.setData({
        isPapers: true,
        busExamInfos: res.data
      });
      wx.pageScrollTo({
        scrollTop: 0
      });
    });
  },

  /**
   * 开始签署文件
   * @param {*} skip 
   */
  startSignFile(skip) {
    let _fileForm = {};
    let currDate = new Date().toLocaleString().substring(0, 10).split("/");
    if (this.data.signType == 1) {
      _fileForm.fName = this.data.form.subDeptLeaderName;
      _fileForm.fCardId = this.data.form.subDeptLeaderCode;
      _fileForm.fSex = this.getGenderFromIdCard(this.data.form.subDeptLeaderCode);
      _fileForm.fPost = "委托人";
      _fileForm.fDate = currDate[0] + "年" + currDate[1] + "月" + currDate[2] + "日";
    } else {
      // let fPost = "";
      // this.data.craftPostList.forEach(item =>{
      //   if(item.id==this.data.form.)
      // })
    }
    this.setData({
      active: skip ? (this.data.active + 1) : this.data.active,
      fileForm: _fileForm
    })
    this.startSignCountdown();
  },

  /**
   * 准备开始签名
   * 跳转签名页面
   */
  startSignFiles() {
    let myCanvas = this.selectComponent(".myCanvas");
    myCanvas.showSign();
  },

  /**
     * 确认签名
     */
    sign(e){
      wx.pageScrollTo({
        scrollTop: 99999
      });
      let tempFilePath = e.detail
      securityFileUpload(tempFilePath).then(res =>{
        if(res.code==200){
          this.setData({
            signPath:res.data.url
          });
        }
      });
  },

  /**
   * 提交签名
   */
  submitSignFiles() {
    let param = {};
    param.proId = this.data.proId;
    param.userPhone = this.data.phoneNumber;
    param.imgPath = this.data.signPath;
    if(param.proId && param.userPhone && param.imgPath){
      submitUserSignets(param).then(res =>{
        if(res.code==200){
          this.setData({
            active:100
          });
        }
      });
    }else{
      app.toast("信息异常...请刷新页面后重新操作!");
      return false;
    }
  },

  /**
   * 根据身份证号获取性别
   * @param {*} idCard 
   */
  getGenderFromIdCard: function (idCard) {
    // 先判断是否是有效的身份证号码(18位或15位)
    const isValid = this.validateIdCard(idCard);
    if (!isValid) {
      return "未知";
    }
    // 如果是18位身份证,倒数第二位是性别标志
    const genderDigit = idCard.length === 18 ? parseInt(idCard.charAt(16)) : parseInt(idCard.charAt(14));
    // 根据性别标志判断男女
    if (genderDigit % 2 === 0) {
      return "女"; // 偶数为女性
    } else {
      return "男"; // 奇数为男性
    }
  },

  // 验证身份证号码是否有效(15位或18位)
  validateIdCard: function (idCard) {
    const reg15 = /^[1-9]\d{14}$/; // 15位身份证号的正则
    const reg18 = /^[1-9]\d{17}(\d|X|x)$/; // 18位身份证号的正则
    return reg15.test(idCard) || reg18.test(idCard);
  },

  /**
   * 授权登录
   */
  findProjectInfo: function (proId) {
    getProjectInfo(proId).then(res => {
      let list = [];
      list.push({
        'id': res.data.id,
        'text': res.data.projectName
      });
      app.globalData.projectInfoList = list;
      app.globalData.useProjectId = res.data.id;
      app.globalData.useProjectName = res.data.projectName;
      this.setData({
        initProject: {
          'id': res.data.id,
          'text': res.data.projectName
        }
      });
    });
  },

  /**
   * 选中单位类型
   * @param {*} e 
   */
  onSubDeptType(e) {
    this.setData({
      "form.subDeptType": e.detail.id
    })
  },

  /**
   * 参建单位名称
   * @param {*} e 
   */
  onSubDeptName(e) {
    this.setData({
      "form.subDeptName": e.detail.value
    })
  },

  /**
   * 社会信用代码
   * @param {*} e 
   */
  onSubDeptCode(e) {
    this.setData({
      "form.subDeptCode": e.detail.value
    })
  },

  /**
   * 营业执照副本
   * @param {*} options 
   */
  fileUpload0(options) {
    let file = options.detail;
    this.setData({
      "form.businessLicensePath": file
    });
  },

  /**
   * 法人身份证正面
   * @param {*} options 
   */
  fileUpload1(options) {
    let file = options.detail;
    this.setData({
      "form.subDeptInfos.legalPersonCardImgPos": file
    });
  },

  /**
   * 法人身份证反面
   * @param {*} options 
   */
  fileUpload2(options) {
    let file = options.detail;
    this.setData({
      "form.subDeptInfos.legalPersonCardImgInv": file
    });
  },

  /** 单位法人姓名 */
  inputInfoslegalPerson(e) {
    this.setData({
      "form.subDeptInfos.legalPerson": e.detail.value
    })
  },

  /** 单位法人身份证号 */
  inputInfoslegalPersonCard(e) {
    this.setData({
      "form.subDeptInfos.legalPersonCard": e.detail.value
    })
  },

  /** 合同约定的承包范围 */
  inputContractInfos(e) {
    this.setData({
      "form.contractInfos": e.detail.value
    })
  },

  /** 进入场地时间 */
  onInputTime0(e) {
    this.setData({
      "form.useDates": e.detail
    })
  },

  /** 计划开工时间 */
  onInputTime1(e) {
    this.setData({
      "form.startWorkDates": e.detail
    })
  },

  /** 计划完工时间 */
  onInputTime2(e) {
    this.setData({
      "form.endWorkDates": e.detail
    })
  },

  /**
   * 委托人身份证反面
   * @param {*} options 
   */
  fileUpload3(options) {
    let file = options.detail;
    this.setData({
      "form.leaderCardImgPos": file
    });
  },

  /**
   * 委托人身份证反面
   * @param {*} options 
   */
  fileUpload4(options) {
    let file = options.detail;
    this.setData({
      "form.leaderCardImgInv": file
    });
  },

  /**
   * 委托人半身照
   * @param {*} options 
   */
  fileUpload5(options) {
    let file = options.detail;
    this.setData({
      "form.leaderUserPicture": file
    });
  },

  /**
   * 委托人委托书
   * @param {*} options 
   */
  fileUpload6(options) {
    let file = options.detail;
    this.setData({
      "form.subDeptLeaderPowerPath": file
    });
  },

  /**
   * 输入负责人姓名
   * @param {*} e 
   */
  inputLeaderName(e) {
    this.setData({
      "form.subDeptLeaderName": e.detail.value
    })
  },

  /**
   * 输入负责人身份证号
   * @param {*} e 
   */
  inputLeaderCode(e) {
    this.setData({
      "form.subDeptLeaderCode": e.detail.value
    })
  },

  /**
   * 输入负责人联系电话
   * @param {*} e 
   */
  subDeptLeaderPhone(e) {
    this.setData({
      "form.subDeptLeaderPhone": e.detail.value
    })
  },

  /**
   * 委托代理提交参建单位信息
   */
  submitSubDeptValues() {
    let {
      form
    } = this.data;
    let subDeptInfos = form.subDeptInfos;
    if (!subDeptInfos) {
      subDeptInfos = {};
    }
    //数据效验
    if (!form.subDeptType) {
      app.toast("请选择单位类型!");
      return false;
    }
    if (!form.subDeptName) {
      app.toast("请填写单位名称!");
      return false;
    }
    if (!form.subDeptCode) {
      app.toast("请填写单位社会信用代码!");
      return false;
    }
    if (!form.businessLicensePath || form.businessLicensePath.length == 0) {
      app.toast("请上传营业执照副本!");
      return false;
    }
    if (!subDeptInfos.legalPersonCardImgPos || subDeptInfos.legalPersonCardImgPos.length == 0) {
      app.toast("请上传法人身份证正面照!");
      return false;
    }
    if (!subDeptInfos.legalPersonCardImgInv || subDeptInfos.legalPersonCardImgInv.length == 0) {
      app.toast("请上传法人身份证反面照!");
      return false;
    }
    if (!subDeptInfos.legalPerson) {
      app.toast("请填写法人姓名!");
      return false;
    }
    if (!subDeptInfos.legalPersonCard) {
      app.toast("请填写法人身份证号!");
      return false;
    }
    if (!form.contractInfos) {
      app.toast("请填写合同约定的承包范围!");
      return false;
    }
    if (!form.startWorkDates) {
      app.toast("请选择计划开工时间!");
      return false;
    }
    if (!form.endWorkDates) {
      app.toast("请选择计划完工时间!");
      return false;
    }
    if (!form.leaderCardImgPos || form.leaderCardImgPos.length == 0) {
      app.toast("请上传委托人身份证正面照!");
      return false;
    }
    if (!form.leaderCardImgInv || form.leaderCardImgInv.length == 0) {
      app.toast("请上传委托人身份证反面照!");
      return false;
    }
    if (!form.leaderUserPicture || form.leaderUserPicture.length == 0) {
      app.toast("请上传委托人半身近照!");
      return false;
    }
    if (!form.subDeptLeaderPowerPath || form.subDeptLeaderPowerPath.length == 0) {
      app.toast("请上传委托人单位委托书!");
      return false;
    }
    if (!form.subDeptLeaderName) {
      app.toast("请填写委托人姓名!");
      return false;
    }
    if (!form.subDeptLeaderCode) {
      app.toast("请填写委托人身份证号!");
      return false;
    }
    if (!form.subDeptLeaderPhone) {
      app.toast("请填写委托人联系电话!");
      return false;
    }
    let that = this;
    //弹出确认
    wx.showModal({
      title: '提示',
      content: '是否确认保存参建单位信息?',
      success: function (sm) {
        if (sm.confirm) {
          that.submitSubDeptForm();
        }
      }
    })
  },

  /**
   * 委托代理提交参建单位表单
   */
  submitSubDeptForm() {
    let {
      form
    } = this.data;
    let subDeptInfos = form.subDeptInfos;
    let uploadFiles = [];
    if (form.businessLicensePath && form.businessLicensePath.length > 0) {
      uploadFiles.push({
        type: 'businessLicensePath',
        path: form.businessLicensePath[0]
      });
    }
    if (subDeptInfos.legalPersonCardImgPos && subDeptInfos.legalPersonCardImgPos.length > 0) {
      uploadFiles.push({
        type: 'legalPersonCardImgPos',
        path: subDeptInfos.legalPersonCardImgPos[0]
      });
    }
    if (subDeptInfos.legalPersonCardImgInv && subDeptInfos.legalPersonCardImgInv.length > 0) {
      uploadFiles.push({
        type: 'legalPersonCardImgInv',
        path: subDeptInfos.legalPersonCardImgInv[0]
      });
    }
    if (form.leaderCardImgPos && form.leaderCardImgPos.length > 0) {
      uploadFiles.push({
        type: 'leaderCardImgPos',
        path: form.leaderCardImgPos[0]
      });
    }
    if (form.leaderCardImgInv && form.leaderCardImgInv.length > 0) {
      uploadFiles.push({
        type: 'leaderCardImgInv',
        path: form.leaderCardImgInv[0]
      });
    }
    if (form.leaderUserPicture && form.leaderUserPicture.length > 0) {
      uploadFiles.push({
        type: 'leaderUserPicture',
        path: form.leaderUserPicture[0]
      });
    }
    if (form.subDeptLeaderPowerPath && form.subDeptLeaderPowerPath.length > 0) {
      uploadFiles.push({
        type: 'subDeptLeaderPowerPath',
        path: form.subDeptLeaderPowerPath[0]
      });
    }
    uploadFiles.forEach(async (item, idx) => {
      let obj;
      if (item.path.indexOf(this.data.imgBase) > -1) {
        obj = {
          data: {
            url: item.path.replace(this.data.imgBase, "")
          }
        }
      } else {
        //这里复杂的图片上传,改为同步上传,因为小程序只能上传一张图片
        obj = await securityFileUpload(item.path);
      }
      if (item.type == "businessLicensePath") {
        this.setData({
          "form.businessLicensePath": obj.data.url
        })
      }
      if (item.type == "legalPersonCardImgPos") {
        subDeptInfos.legalPersonCardImgPos = obj.data.url;
      }
      if (item.type == "legalPersonCardImgInv") {
        subDeptInfos.legalPersonCardImgInv = obj.data.url;
      }
      if (item.type == "leaderCardImgPos") {
        this.setData({
          "form.leaderCardImgPos": obj.data.url
        })
      }
      if (item.type == "leaderCardImgInv") {
        this.setData({
          "form.leaderCardImgInv": obj.data.url
        })
      }
      if (item.type == "leaderUserPicture") {
        this.setData({
          "form.leaderUserPicture": obj.data.url
        })
      }
      if (item.type == "subDeptLeaderPowerPath") {
        this.setData({
          "form.subDeptLeaderPowerPath": obj.data.url
        })
      }
      //验证图片上传完毕
      if ((idx + 1) == uploadFiles.length) {
        this.setData({
          "form.subDeptInfos": JSON.stringify(subDeptInfos)
        })
        registerSubDepts(form).then(res => {
          if (res.code == 200) {
            //跳转视频页面...
            this.initBusEduVideos(true);
          }
        });
      }
    });
  },

  /**
   * 单位人员信息验证
   */
  submitSubUserValues() {
    let {
      form,
      signType
    } = this.data;
    //数据效验
    if (signType != '4') {
      if (!form.craftPost) {
        app.toast("请选择岗位类型!");
        return false;
      }
    }
    if (!form.leaderCardImgPos && form.leaderCardImgPos.length > 0) {
      app.toast("请上传委托人身份证正面照!");
      return false;
    }
    if (!form.leaderCardImgInv && form.leaderCardImgInv.length > 0) {
      app.toast("请上传委托人身份证反面照!");
      return false;
    }
    if (!form.leaderUserPicture && form.leaderUserPicture.length > 0) {
      app.toast("请上传委托人半身近照!");
      return false;
    }

    if (!form.subDeptLeaderPowerPath && form.subDeptLeaderPowerPath.length > 0) {
      app.toast("请上传委托人单位委托书!");
      return false;
    }
    if (!form.subDeptLeaderName) {
      app.toast("请填写委托人姓名!");
      return false;
    }
    if (!form.subDeptLeaderCode) {
      app.toast("请填写委托人身份证号!");
      return false;
    }
    if (!form.subDeptLeaderPhone) {
      app.toast("请填写委托人联系电话!");
      return false;
    }
    let that = this;
    //弹出确认
    wx.showModal({
      title: '提示',
      content: '是否确认提交参建单位信息?',
      success: function (sm) {
        if (sm.confirm) {
          that.submitSubDeptForm();
        }
      }
    })
  },

  /**
   * 委托人半身照
   * @param {*} options 
   */
  fileUpload7(options) {
    let file = options.detail;
    this.setData({
      "form.leaderUserPicture": file
    });
  },

  /**
   * 委托人委托书
   * @param {*} options 
   */
  fileUpload8(options) {
    let file = options.detail;
    this.setData({
      "form.subDeptLeaderPowerPath": file
    });
  },

  //显示选择
  onShowPopup(e) {
    this.setData({
      showDetailsPopup: true
    })
  },

  //关闭选择
  onClosePopup(e) {
    this.setData({
      showDetailsPopup: false
    })
  },

  /**
   * 栏目触发事件
   */
  onClickNav(e) {
    this.setData({
      chidActiveIndex: null,
      mainActiveIndex: e.detail.index
    })
  },

  /**
   * 选项触发事件
   */
  onClickItem(e) {
    this.setData({
      chidActiveIndex: e.detail.id,
      showDetailsName: e.detail.detailName
    })
  },

  /**
   * 返回上一步
   */
  onClickPreviousNode() {
    if (this.data.active == 2) {
      this.initBusEduVideos(true);
    } else {
      this.setData({
        active: this.data.active - 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  // 启动倒计时
  startCountdown() {
    let that = this;
    this.setData({
      timer: setInterval(() => {
        let {
          time
        } = this.data;
        let minutes = Math.floor(time / 60);
        let seconds = time % 60;
        if (minutes < 10) minutes = "0" + minutes;
        if (seconds < 10) seconds = "0" + seconds;
        if (time > 0) {
          time--;
          this.setData({
            time,
            timeStr: minutes + ' 分钟 ' + seconds + ' 秒'
          });
        } else {
          clearInterval(this.data.timer); // 倒计时结束,清除定时器
          //考试结束...
          that.submitThePapers("skip");
        }
      }, 1000),
    });
  },

  // 启动签署时
  startSignCountdown() {
    this.setData({
      signTimer: setInterval(() => {
        let {
          signTime
        } = this.data;
        if (signTime > 0) {
          signTime--;
          this.setData({
            signTime
          });
        } else {
          clearInterval(this.data.signTimer); // 倒计时结束,清除定时器
        }
      }, 1000),
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);
    clearInterval(this.data.signTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  }
})