import config from '../../config'
import {
  getOpenId,
  setOpenId,
  getSessionKey,
  setSessionKey,
} from '../../utils/auth'
import {
  getMaOpenId,
  getMaPhoneNumber,
} from '../../api/login'
import {
  findProjectInfo,
  registerSubDepts,
  registerSubDeptsUsers,
  findProSubDeptsUser,
  findProSubDeptsInfo,
  findProSubDeptsUserById
} from '../../api/project'
import {
  findBusExamInfos,
  findBusTrainingVideos,
  startPlayUserEduVideo,
  endPlayUserEduVideo,
  finishEduVideo,
  submitBusExamUser,
  submitUserSignets
} from '../../api/busEdu'
import {
  findDictCache
} from '../../api/publics'
import {
  securityFileUpload,
  securitySignFileUpload
} from '../../utils/request'
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      subDeptType: null,
      craftType: null,
      craftPost: null,
      user: {},
      leaderDegreeGrade: null,
      degreeGrade: null
    },
    parForm: {},
    limit: 1,
    maxDate: new Date(2088, 1, 1).getTime(),
    currentDate: new Date().getTime(),
    title: "",
    proId: null,
    userPost: null,
    initProject: {},
    userPhoneNumber: null,
    userPostList: [],
    deptTypeList: [{
      "id": "4",
      "text": "劳务分包"
    }, {
      "id": "5",
      "text": "专业分包"
    }],
    craftTypeList: [],
    craftPostList: [],
    craftPostAllOrginList: [],
    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'
      }]
    }],
    eduCationalType: [],
    showDetailsName: "",
    showDetailsPopup: false,
    mainActiveIndex: null,
    chidActiveIndex: null,
    imgBase: config.baseImgUrl,
    videoIdx: 0,
    videoUrl: "",
    videoTitle: "",
    eduVideoMenu: [],
    eduVideoItem: [],
    busExamInfos: {},
    busExamQuestions: [],
    time: 3600, // 初始倒计时为 3600 秒
    timer: null,
    timeStr: '',
    isPapers: false,
    fileForm: {},
    signTime: 180,
    signTimer: null,
    signPath: '',
    youWuList: [{
      "id": "0",
      "text": "无"
    }, {
      "id": "1",
      "text": "有"
    }],
    illnessStatus: '',
    supIllnessStatus: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    if (options && options.SIGID && options.QRPID) {
      this.getDictCache(options.SIGID);
      this.getMaOpenId();
      this.getProjectInfo(options.QRPID);
      if (options.PARID) {
        this.setData({
          "form.parId": options.PARID,
        });
        this.getProSubDeptsUser();
      }
      let title = "";
      let _userPostList = [];
      if (options.SIGID == '1') {
        title = "参建单位信息登记";
        _userPostList.push({
          "id": "1",
          "text": "委托代理人"
        });
      } else if (options.SIGID == '2' || options.SIGID == '3') {
        if (options.SIGID == '2') {
          _userPostList.push({
            "id": "2",
            "text": "项目经理"
          });
        } else {
          _userPostList.push({
            "id": "3",
            "text": "班组长"
          });
        }
        title = "参建单位管理人员信息登记";
      } else if (options.SIGID == '4') {
        title = "参建单位劳务人员信息登记";
        _userPost.push({
          "id": "4",
          "text": "劳务人员"
        });
      }
      this.setData({
        title,
        proId: options.QRPID,
        userPost: options.SIGID,
        "form.userPost": options.SIGID,
        userPostList: _userPostList,
        "form.projectId": options.QRPID,
      });
    } else {
      app.toast("请求参数异常,请重新扫码...");
      // wx.redirectTo({
      //     url: '/pages/login/index',
      // });
    }
  },

  /**
   * 获取字典缓存数据
   */
  getDictCache(signId) {
    if (signId == '3') {
      // 初始化工种类型
      findDictCache("pro_craft_type").then(res => {
        if (res.code == 200) {
          let craftTypeList = [];
          res.data.forEach(item => {
            if (item.dictValue != "3") {
              craftTypeList.push({
                "id": item.dictValue,
                "text": item.dictLabel
              });
            }
          })
          this.setData({
            craftTypeList
          });
        }
      })
      // 初始化工种岗位
      findDictCache("pro_craft_post").then(res => {
        if (res.code == 200) {
          this.setData({
            craftPostAllOrginList: res.data
          });
        }
      })
    }
    // 初始化学历类型
    findDictCache("educational_type").then(res => {
      if (res.code == 200) {
        let eduCationalType = [];
        res.data.forEach(item => {
          eduCationalType.push({
            "id": item.dictValue,
            "text": item.dictLabel
          });
        })
        this.setData({
          eduCationalType
        });
      }
    })
  },

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

  /**
   * 查询单位上级人员信息
   */
  getProSubDeptsUser() {
    findProSubDeptsUserById(this.data.form.parId).then(res => {
      if (res.code == 200) {
        this.setData({
          parForm: res.data
        });
      }
    });
  },

  /**
   * 获取手机号码
   * @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;
          //使用手机号码查询详情
          if (this.data.userPost == "1") {
            findProSubDeptsInfo(this.data.proId, phoneNumber).then(deptRes => {
              if (deptRes.code == 200 && deptRes.data) {
                deptRes.data.subDeptLeaderPhone = phoneNumber;
                deptRes.data.leaderDegreeGrade = deptRes.data.proProjectInfoSubdeptsUsers.degreeGrade;
                deptRes.data.eduFilePath = deptRes.data.proProjectInfoSubdeptsUsers.eduFilePath;
                deptRes.data.subStep = deptRes.data.proProjectInfoSubdeptsUsers.subStep;
                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.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.user) {
                  if (userRes.data.user.userInfos) {
                    let userInfosJSON = JSON.parse(userRes.data.user.userInfos);
                    userRes.data.user.phonenumber = userInfosJSON.phoneNumber;
                    userRes.data.user.nativePlace = userInfosJSON.nativePlace;
                    userRes.data.user.address = userInfosJSON.address;
                    userRes.data.user.emergencyContact = userInfosJSON.emergencyContact;
                    userRes.data.user.contactPhone = userInfosJSON.contactPhone;
                    userRes.data.user.bankName = userInfosJSON.bankName;
                    userRes.data.user.bankOffice = userInfosJSON.bankOffice;
                    userRes.data.user.bankCardNo = userInfosJSON.bankCardNo;
                  }
                  if (userRes.data.user.cardImgPos) {
                    userRes.data.user.cardImgPos = (this.data.imgBase + userRes.data.user.cardImgPos).split(',');
                  }
                  if (userRes.data.user.cardImgInv) {
                    userRes.data.user.cardImgInv = (this.data.imgBase + userRes.data.user.cardImgInv).split(',');
                  }
                  if (userRes.data.user.userPicture) {
                    userRes.data.user.userPicture = (this.data.imgBase + userRes.data.user.userPicture).split(',');
                  }
                  if (userRes.data.subDeptPowerPath) {
                    userRes.data.subDeptPowerPath = (this.data.imgBase + userRes.data.subDeptPowerPath).split(',');
                  }
                }
                this.setData({
                  form: userRes.data,
                  userPhoneNumber: phoneNumber,
                  "form.phoneNumber": phoneNumber,
                  active: userRes.data.subStep
                });
                if (userRes.data.subStep == 1) {
                  this.initBusEduVideos(false);
                } else if (userRes.data.subStep == 2) {
                  this.initBusEduQuestion(false);
                } else if (userRes.data.subStep == 3) {
                  this.startSignFile(false);
                }
              } 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.subStep > 1 || currentVideo >= videoSize) {
      this.initBusEduQuestion(true);
    } else {
      app.toast("请学习完所有视频后再进行考试。");
    }
  },

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

  /**
   * 初始化学习考试
   */
  initBusEduQuestion: function (skip) {
    this.setData({
      active: skip ? (this.data.active + 1) : this.data.active
    });
    clearInterval(this.data.timer);
    this.setData({
      time: 3600
    });
    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.userPost == 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 {
      _fileForm.fName = this.data.form.user.nickName;
      _fileForm.fCardId = this.data.form.user.cardCode;
      _fileForm.fSex = this.getGenderFromIdCard(this.data.form.user.cardCode);
      this.data.craftPostAllOrginList.forEach(item => {
        if (this.data.form.craftPost == item.dictValue) {
          _fileForm.fPost = item.dictLabel;
        }
      });
      _fileForm.fDate = currDate[0] + "年" + currDate[1] + "月" + currDate[2] + "日";
    }
    this.setData({
      active: skip ? (this.data.active + 1) : this.data.active,
      fileForm: _fileForm,
      signTime: 180
    })
    clearInterval(this.data.signTimer);
    this.startSignCountdown();
  },

  /**
   * 准备开始签名
   * 跳转签名页面
   */
  startSignFiles() {
    let {
      signTime,
      illnessStatus,
      supIllnessStatus
    } = this.data;
    if (signTime > 0) {
      app.toast("请仔细阅读各项承诺书及三级安全教育!");
      return false;
    }
    if (illnessStatus == "") {
      app.toast("请选择健康情况!");
      wx.pageScrollTo({
        scrollTop: 99999
      });
      return false;
    }
    if (supIllnessStatus == "") {
      app.toast("请选择严重疾病情况!");
      wx.pageScrollTo({
        scrollTop: 99999
      });
      return false;
    }
    let myCanvas = this.selectComponent(".myCanvas");
    myCanvas.showSign();
  },

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

  /**
   * 提交签名
   */
  submitSignFiles() {
    let {
      proId,
      signPath,
      userPhoneNumber,
      illnessStatus,
      supIllnessStatus
    } = this.data;
    if (illnessStatus == "") {
      app.toast("请选择身体健康情况!");
      return false;
    }
    if (supIllnessStatus == "") {
      app.toast("请选择身体严重疾病情况!");
      return false;
    }
    if (signPath == "") {
      app.toast("请填入受教育人手写签名!");
      return false;
    }
    if (proId && userPhoneNumber && signPath) {
      let that = this;
      //弹出确认
      wx.showModal({
        title: '提示',
        content: '是否确认提交文件签署信息?',
        success: function (sm) {
          if (sm.confirm) {
            that.submitSignFilesValues();
          }
        }
      })
    } else {
      app.toast("信息异常...请刷新页面后重新操作!");
      return false;
    }
  },

  /**
   * 提交文件签署表单
   */
  submitSignFilesValues() {
    let {
      proId,
      signPath,
      userPhoneNumber,
      illnessStatus,
      supIllnessStatus
    } = this.data;
    let param = {};
    param.proId = proId;
    param.userPhone = userPhoneNumber;
    param.imgPath = signPath;
    param.illnessStatus = illnessStatus;
    param.supIllnessStatus = supIllnessStatus;
    submitUserSignets(param).then(res => {
      if (res.code == 200) {
        this.setData({
          active: res.data.subStep,
          "form.subStep": res.data.subStep,
          "form.approveStatus": res.data.approveStatus,
          "form.eduFilePath": res.data.eduFilePath
        });
      }
    });
  },

  /**
   * 下载签名文件
   */
  downloadSignetFiles() {
    let that = this;
    wx.downloadFile({
      // 示例 url,并非真实存在
      url: config.baseUrl + '/file/NoSecurity/download?fileName=' + that.data.form.eduFilePath,
      success: function (res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },

  /**
   * 根据身份证号获取性别
   * @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);
  },

  /**
   * 授权登录
   */
  getProjectInfo: function (proId) {
    findProjectInfo(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
    })
  },

  /**
   * 负责人学历
   * @param {*} e 
   */
  onLeaderDegreeGrade(e) {
    this.setData({
      "form.leaderDegreeGrade": e.detail.id
    })
  },

  /**
   * 选中工种类型
   * @param {*} e 
   */
  onChageCraftType(e) {
    //设置工种岗位
    let craftPostList = [];
    console.log("this.data.craftPostAllOrginList", this.data.craftPostAllOrginList)
    this.data.craftPostAllOrginList.forEach(item => {
      if (item.remark == e.detail.id) {
        craftPostList.push({
          "id": item.dictValue,
          "text": item.dictLabel
        });
      }
    })
    this.setData({
      craftPostList,
      "form.craftType": e.detail.id,
      "form.craftPost": null
    })
  },

  /**
   * 选中工种岗位
   * @param {*} e 
   */
  onChageCraftPost(e) {
    this.setData({
      "form.craftPost": e.detail.id
    })
  },

  /**
   * 个人身份证正面照
   * @param {*} options 
   */
  fileUploadCardImgPos(options) {
    let file = options.detail;
    this.setData({
      "form.user.cardImgPos": file
    });
  },

  /**
   * 个人身份证反面照
   * @param {*} options 
   */
  fileUploadCardImgInv(options) {
    let file = options.detail;
    this.setData({
      "form.user.cardImgInv": file
    });
  },

  /**
   * 个人半身近照
   * @param {*} options 
   */
  fileUploadUserPicture(options) {
    let file = options.detail;
    this.setData({
      "form.user.userPicture": file
    });
  },

  /**
   * 单位委托书
   * @param {*} options 
   */
  fileUploadDeptPower(options) {
    let file = options.detail;
    this.setData({
      "form.subDeptPowerPath": file
    });
  },

  /**
   * 输入个人姓名
   * @param {*} e 
   */
  inputUserName(e) {
    this.setData({
      "form.user.nickName": e.detail.value
    })
  },

  /**
   * 输入个人身份证号
   * @param {*} e 
   */
  inputUserCode(e) {
    this.setData({
      "form.user.cardCode": e.detail.value
    })
  },

  /**
   * 个人籍贯民族
   * @param {*} e 
   */
  inputOriginNative(e) {
    this.setData({
      "form.user.nativePlace": e.detail.value
    })
  },
  /**
   * 个人籍贯地址
   * @param {*} e 
   */
  inputOriginAddress(e) {
    this.setData({
      "form.user.address": e.detail.value
    })
  },

  /**
   * 紧急联系人
   * @param {*} e 
   */
  inputUrgentUser(e) {
    this.setData({
      "form.user.emergencyContact": e.detail.value
    })
  },

  /**
   * 紧急联系人电话
   * @param {*} e 
   */
  inputUrgentUserPhone(e) {
    this.setData({
      "form.user.contactPhone": e.detail.value
    })
  },

  /**
   * 个人文化程度
   * @param {*} e 
   */
  onDegreeGrade(e) {
    this.setData({
      "form.degreeGrade": e.detail.id
    })
  },

  /**
   * 开户行名称
   * @param {*} e 
   */
  inputBankName(e) {
    this.setData({
      "form.user.bankName": e.detail.value
    })
  },

  /**
   * 开户行网点
   * @param {*} e 
   */
  inputBankOffice(e) {
    this.setData({
      "form.user.bankOffice": e.detail.value
    })
  },

  /**
   * 开户行卡号
   * @param {*} e 
   */
  inputBankCardNo(e) {
    this.setData({
      "form.user.bankCardNo": 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.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;
    }
    if (!form.leaderDegreeGrade) {
      app.toast("请选择委托人学历信息!");
      return false;
    }
    let that = this;
    //弹出确认
    wx.showModal({
      title: '提示',
      content: '是否确认保存参建单位信息登记?',
      success: function (sm) {
        if (sm.confirm) {
          that.submitSubDeptForm();
        }
      }
    })
  },

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

  /**
   * 单位人员信息验证
   */
  submitSubUserValues() {
    let {
      form,
      userPost
    } = this.data;
    debugger
    //数据效验
    if (userPost == '3') {
      if (!form.craftType) {
        app.toast("请选择工种类型!");
        return false;
      }
      if (!form.craftPost) {
        app.toast("请选择工种岗位!");
        return false;
      }
    }
    if (!form.user.cardImgPos || form.user.cardImgPos.length == 0) {
      app.toast("请上传身份证正面照!");
      return false;
    }
    if (!form.user.cardImgInv || form.user.cardImgInv.length == 0) {
      app.toast("请上传身份证反面照!");
      return false;
    }
    if (!form.user.userPicture || form.user.userPicture.length == 0) {
      app.toast("请上传进场半身近照!");
      return false;
    }

    if (!form.subDeptPowerPath || form.subDeptPowerPath.length == 0) {
      app.toast("请上传委托人单位委托书!");
      return false;
    }
    if (!form.user.nickName) {
      app.toast("请填写姓名!");
      return false;
    }
    if (!form.user.cardCode) {
      app.toast("请填写身份证号!");
      return false;
    }
    if (!form.phoneNumber) {
      app.toast("请填写联系电话!");
      return false;
    }
    if (!form.user.nativePlace) {
      app.toast("请填写籍贯民族!");
      return false;
    }
    if (!form.user.address) {
      app.toast("请填写籍贯地址!");
      return false;
    }
    if (!form.user.emergencyContact) {
      app.toast("请填写紧急联系人!");
      return false;
    }
    if (!form.user.contactPhone) {
      app.toast("请填写紧急联系人电话!");
      return false;
    }
    if (!form.degreeGrade) {
      app.toast("请选择文化程度!");
      return false;
    }
    if (userPost == '4') {
      if (!form.user.bankName) {
        app.toast("请填写开户银行名称!");
        return false;
      }
      if (!form.user.bankOffice) {
        app.toast("请填写开户银行网点!");
        return false;
      }
      if (!form.bankCardNo) {
        app.toast("请填写工资银行卡号!");
        return false;
      }
    }
    let that = this;
    //弹出确认
    wx.showModal({
      title: '提示',
      content: '是否确认保存单位人员信息登记?',
      success: function (sm) {
        if (sm.confirm) {
          that.submitSubUserForm();
        }
      }
    })
  },

  /**
   * 单位人员信息登记
   */
  submitSubUserForm() {
    let _form = {
      ...this.data.form
    };
    let userModel = {
      ..._form.user
    };
    let uploadFiles = [];
    if (userModel.cardImgPos && userModel.cardImgPos.length > 0) {
      uploadFiles.push({
        type: 'cardImgPos',
        path: userModel.cardImgPos[0]
      });
    }
    if (userModel.cardImgInv && userModel.cardImgInv.length > 0) {
      uploadFiles.push({
        type: 'cardImgInv',
        path: userModel.cardImgInv[0]
      });
    }
    if (userModel.userPicture && userModel.userPicture.length > 0) {
      uploadFiles.push({
        type: 'userPicture',
        path: userModel.userPicture[0]
      });
    }
    if (_form.subDeptPowerPath && _form.subDeptPowerPath.length > 0) {
      uploadFiles.push({
        type: 'subDeptPowerPath',
        path: _form.subDeptPowerPath[0]
      });
    }
    let that = this;
    let uploads = [];
    uploadFiles.forEach(async (item, idx) => {
      let obj;
      if (item.path.indexOf(this.data.imgBase) > -1) {
        obj = {
          data: {
            data: {
              url: item.path.replace(this.data.imgBase, "")
            }
          }
        }
      } else {
        //这里复杂的图片上传,改为同步上传,因为小程序只能上传一张图片
        obj = await that.syncUploadImage(item.path);
      }
      if (item.type == "cardImgPos") {
        userModel.cardImgPos = obj.data.data.url;
      }
      if (item.type == "cardImgInv") {
        userModel.cardImgInv = obj.data.data.url;
      }
      if (item.type == "userPicture") {
        userModel.userPicture = obj.data.data.url;
      }
      if (item.type == "subDeptPowerPath") {
        _form.subDeptPowerPath = obj.data.data.url;
      }
      uploads.push(obj.data.data.url);
      //验证图片上传完毕
      if (uploads.length == uploadFiles.length) {
        let userInfos = {};
        userInfos.phonenumber = _form.phoneNumber;
        userInfos.nativePlace = userModel.nativePlace;
        userInfos.address = userModel.address;
        userInfos.emergencyContact = userModel.emergencyContact;
        userInfos.contactPhone = userModel.contactPhone;
        userInfos.bankName = userModel.bankName;
        userInfos.bankOffice = userModel.bankOffice;
        userInfos.bankCardNo = userModel.bankCardNo;
        userModel.userInfos = JSON.stringify(userInfos);
        _form.user = userModel;
        registerSubDeptsUsers(_form).then(res => {
          if (res.code == 200) {
            this.setData({
              "form.id": res.data.id,
              "form.subStep": res.data.subStep
            });
            //跳转视频页面...
            this.initBusEduVideos(true);
          }
        });
      }
    });
  },

  /**
   * 委托人半身照
   * @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
    })
  },

  /**
   * 选中健康问题1
   * @param {*} e 
   */
  onChangeFileRadio1(e) {
    this.setData({
      illnessStatus: e.detail.id
    })
  },

  /**
   * 选中健康问题2
   * @param {*} e 
   */
  onChangeFileRadio2(e) {
    this.setData({
      supIllnessStatus: e.detail.id
    })
  },

  /**
   * 返回上一步
   */
  onClickPreviousNode() {
    if (this.data.active == 2) {
      this.initBusEduVideos(false);
    }
    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),
    });
  },

  /**
   * 这里考虑上传图片异步问题,封装为同步
   */
  syncUploadImage(file) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: config.baseUrl + "/file/NoSecurity/upload", // 上传的服务器接口地址
        filePath: file,
        header: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        name: "file", //上传的所需字段,后端提供
        formData: {},
        success: (res) => {
          // 上传完成操作
          const data = JSON.parse(res.data)
          resolve({
            data: data
          })
        },
        fail: (err) => {
          //上传失败:修改pedding为reject
          console.log("访问接口失败", err);
          wx.showToast({
            title: "网络出错,上传失败",
            icon: 'none',
            duration: 1000
          });
          reject(err)
        }
      });
    })
  },

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

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

  },

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

  },

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

  },

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