import {
  closeSecondaryScreen,
  openCycleSecondaryScreen,
  openSecondaryScreen,
  viceBroadcast
} from '../../utils/index/callAmpe'
import {
  receiptPrinting
} from '../../utils/index/receiptPrinting'
import {
  encryptAndSign
} from '../../utils/index/getSM4'
import {
  desensitization,
  getWaterDrop
} from '../../utils/index/index'
import {
  userInfoQuery,
} from '../../utils/api/api'
const app = getApp()
Page({
  data: {
    toTitleRef: null,
    result: '',
    timer: 5, // 顶部title定时器
    // 刷身份证信息
    brushingCardUserIInfo: {
      name: '',
      sex: '',
      nation: '',
      birthDate: '',
      address: '',
      idNum: '',
      photoBase64: '',
    },
    showFaceScan: false,
    signOffUserInfo: {}, // 签离成功信息
    printVisitorList: false,
    clickRetryNum: 0, //获取用户信息重试次数
    isShowRetry: false, //是否显示重试
    resultText: '', //结果页超时展示文本
  },
  onLoad(e) {
    my.hideBackHome();
    console.log(`resultPage进入页面===>${e.result}`);
    this.setData({
      result: e.result || '结果页超时',
      resultText: e.resultText || '请重试',
      clickRetryNum: app.data.clickRetryNum,
      isShowRetry: e.isShowRetry || false,
    })
    let resultTag = e.result || '';
    if (resultTag == '刷脸登记') {
      this.setData({
        showFaceScan: true,
        timer: app.globalData.snDisposition.faceTimeout
      })
      this.clickFaceScan()
      return;
    } else if (resultTag == '1:1比对') {
      console.log(e.type)
      let verifyType = 1;
      switch (e.type) {
        case '身份证1:1':
          verifyType = 3;
          break;
        case '手输1:1':
          verifyType = 15;
          break;
      }
      this.setData({
        showFaceScan: true,
        timer: app.globalData.snDisposition.oneToOneTimeout
      })
      this.getFaceInfoPersonCard({
        brushingCardUserIInfo: app.data.brushingCardUserIInfo,
        verifyType
      })
      return;
    } else if (resultTag == '联网查询') {
      console.log('联网查询');
      this.setData({
        timer: app.globalData.snDisposition.connectSearchTimeout
      })
      this.userInfoQuery()
      return;
    } else if (resultTag == '签离成功') {
      this.setData({
        signOffUserInfo: app.data.signOffMsg
      })
      return;
    } else if (resultTag == '首页刷证') {
      this.setData({
        timer: 15
      })
      this.showMsg(app.data.brushingCardUserIInfo)
      let _this = this;
      setTimeout(function () {
        //  是否人证比对
        if (app.globalData.snDisposition.usePersonCard) {
          console.log('1:1比对-首页刷证');
          _this.backToSpecifiedPage('/pages/resultPage/index?result=1:1比对&type=身份证1:1')
        } else {
          _this.getUserInfo({
            brushingCardUserIInfo: app.data.brushingCardUserIInfo,
            verifyType: 4  // 身份证
          })
        }
      }, 1000)
      return;
    } else if (resultTag == '登记成功') {
      switch (app.globalData.riskResult) {
        case 1:
          this.setData({
            printVisitorList: app.globalData.snDisposition.printVisitorList
          })
          if (app.globalData.snDisposition.printVisitorList) {
            this.printFun(app.data.visitoMsgData)
          }
          break;
        case 2:
          this.setData({
            result: '逃犯',
          })
          break;
        case 3:
          this.setData({
            result: '有前科',
          })
          break;
        default:
          break;
      }
      return;
    }
    this.setData({
      timer: e.timer ? parseInt(e.timer) : 5,
    })
  },
  clickAudio() {
    getWaterDrop()
  },
  // 刷脸登记
  clickFaceScan() {
    let that = this;
    let params1 = {
      "action": "getFaceInfo",
      "event": "open",
      "taskId": "2"
    }
    my.showLoading({
      mask:false
    });
    try {
      my.call("ampeHHCommunication", params1, res => {
        console.log(res.data);
        // 倒计时结束1004  点击关闭1003  没认出来1001
        my.hideLoading()
        that.data.showFaceScan = false
        if (res.success && res.data.idNum) {
          let form = {
            xm: res.data.name,
            sfzh: res.data.idNum,
            phone: res.data.mobile,
            avatar: res.data.photoBase64,
            verifyType: 2, // 支付宝人脸
            certContent: res.data // 身份证阅读器返回全部
          }
          app.data.userInfo = form
          viceBroadcast(app.globalData.snDisposition.successVoice)
          console.log(JSON.stringify(app.globalData.snDisposition));
          // 是否跳转到提示页
          let reminderAuth = app.globalData.snDisposition.reminderAuth;
          if (reminderAuth) {
            this.backToSpecifiedPage('/pages/tipsPage/index')
          } else {
            // 是否启用副屏处理中页面
            let processingPageSwitch = app.globalData.snDisposition.processingPageSwitch;
            if (app.data.isSecondaryScreenState && processingPageSwitch) {
              console.log('打开副屏', app.data.isSecondaryScreenState);
              closeSecondaryScreen()
              app.data.cycleIntervalSwitch = false
              openSecondaryScreen(app.globalData.snDisposition.processingPageImage || '')
            }
            this.backToSpecifiedPage('/pages/interviewee/index')
          }
        } else {
          if (!res.data || !res.data.originFaceInfo) {
            this.backToSpecifiedPage('/pages/resultPage/index?result=结果页超时&&timer=' + app.globalData.snDisposition.resultPageTimeout)
            return
          }
          let originFaceInfo = JSON.parse(res.data.originFaceInfo)
          console.log(originFaceInfo.code);
          // 1003关闭，1004超时
          if (originFaceInfo.code == '1003' || originFaceInfo.code == '1004') {
            this.backToSpecifiedPage('/pages/home/index')
          } else {
            // 启用无证登记和刷脸失败跳转手输，跳转输入身份证页面
            if (app.globalData.snDisposition.faceFailHandInput && app.globalData.snDisposition.noIdcardRegister) {
              this.backToSpecifiedPage('/pages/inputIDCard/index')
            } else {
              viceBroadcast(app.globalData.snDisposition.failVoice)
              this.backToSpecifiedPage('/pages/resultPage/index?result=结果页超时&&timer=' + app.globalData.snDisposition.resultPageTimeout)
            }
          }
        }

      });
    } catch (error) {
      my.hideLoading()
      this.backToSpecifiedPage('/pages/home/index')
      that.setData({
        showFaceScan: false
      })
    }
  },
  saveRef(ref) {
    // 将ref存起来，在想要调用的地方使用
    this.toTitleRef = ref
  },
  /**
   * 跳转指定页面 并清除顶部计时器
   */
  backToSpecifiedPage(url = '/pages/home/index') {
    this.toTitleRef && this.toTitleRef.clearIntervalAll()
    my.reLaunch({
      url: url,
    })
  },
  // 联网查询获取用户信息
  async userInfoQuery() {
    const that = this;
    viceBroadcast(app.globalData.snDisposition.connectSearchVoice)
    try {
      that.handleValue(app.data.userInfo.xm)
    } catch (error) {
      console.log(error);
    }
  },

  handleValue(val) {
    let that = this;
    if (val) {
      let form = {
        name: app.data.userInfo.xm,
        idNum: app.data.userInfo.sfzh,
        photoBase64: app.data.userInfo.avatar,
      }
      app.data.brushingCardUserIInfo = form
      console.log('1:1比对-联网查询', val);
      that.backToSpecifiedPage('/pages/resultPage/index?result=1:1比对&type=手输1:1')
    } else {
      setTimeout(function () {
        // 捕获到联网查询错误，跳转到重试页面
        if (app.data.isNetworkQueryError == false) {
          let resultText = app.data.clickRetryNum == 0 ? '查询超时，可点击重试' : '查询超时~'
          that.backToSpecifiedPage('/pages/resultPage/index?result=结果页超时&timer=' + app.globalData.snDisposition.resultPageTimeout + '&resultText=' + resultText + '&isShowRetry=' + true)
        } else {
          that.handleValue(app.data.userInfo.xm)
        }
      }, 1000)
    }
  },
  // 重试
  retryFun() {
    this.getRetryUserInfo()
    app.data.clickRetryNum = app.data.clickRetryNum + 1
    app.data.isNetworkQueryError = null
    this.backToSpecifiedPage('/pages/resultPage/index?result=联网查询&timer=' + app.globalData.snDisposition.connectSearchTimeout)
  },
  // 重试-联网查询用户信息
  async getRetryUserInfo() {
    try {
      let appKey = app.globalData.appKey
      let appSecret = app.globalData.appSecret
      let privateKey = app.globalData.privateKey
      let content = {
        sfzh: app.data.inputIdCard
      }
      content = JSON.stringify(content)
      let sm4 = encryptAndSign(appKey, appSecret, privateKey, content, "encrypted")
      // console.log(sm4);
      let data = {
        "appId": app.globalData.appId,
        "bizContent": sm4.encrypted,
        "reqTimestamp": sm4.timestamp,
        "sign": sm4.sign
      }
      let res = await userInfoQuery(data)
      app.data.isNetworkQueryError = true
      // 解密
      let decryptedData = encryptAndSign(appKey, appSecret, privateKey, res.data.bizContent, "decrypt")
      if (!decryptedData.decrypted) {
        return
      }
      let decrypted = JSON.parse(decryptedData.decrypted)
      app.data.userInfo = decrypted
      app.data.userInfo.avatar = decrypted.xp
    } catch (error) {
      app.data.isNetworkQueryError = false
    }
  },

  // 身份证信息展示
  showMsg(data) {
    let brushingCardUserIInfo = JSON.parse(JSON.stringify(data))
    brushingCardUserIInfo.sex = brushingCardUserIInfo.sex[0]
    const fruits = brushingCardUserIInfo.birthDate.split(".");
    brushingCardUserIInfo.year = fruits[0]
    brushingCardUserIInfo.month = fruits[1]
    brushingCardUserIInfo.day = fruits[2]
    app.data.brushingCardUserIInfo = brushingCardUserIInfo
    this.setData({
      brushingCardUserIInfo
    })
  },
  // 1:1比对
  getFaceInfoPersonCard({
                          brushingCardUserIInfo,
                          verifyType // 识别类型
                        }) {
    let params1 = {
      "action": "getFaceInfoPersonCard",
      "event": "open",
      "taskId": "7",
      "params": {
        "certName": brushingCardUserIInfo.name,
        "certNo": brushingCardUserIInfo.idNum,
        "certPhotoBase64Str": brushingCardUserIInfo.photoBase64
      }
    }
    let that = this
    console.log(params1.params);
    try {
      my.call('ampeHHCommunication', params1, res => {
        // console.log(res.data);
        that.setData({
          showFaceScan: false
        })
        if (res.success) {
          that.getUserInfo({
            brushingCardUserIInfo: res.data,
            verifyType
          })
        } else {
          if (!res.data || !res.data.originFaceInfo) {
            that.backToSpecifiedPage('/pages/resultPage/index?result=结果页超时&&timer=' + app.globalData.snDisposition.resultPageTimeout)
            return
          }
          let originFaceInfo = JSON.parse(res.data.originFaceInfo)
          console.log(originFaceInfo);
          if (originFaceInfo.code == '1001' || originFaceInfo.code == '2006') {
            that.backToSpecifiedPage('/pages/resultPage/index?result=结果页超时&&timer=' + app.globalData.snDisposition.resultPageTimeout)
          } else {
            that.backToSpecifiedPage('/pages/home/index')
            my.showToast({
              content: (originFaceInfo && originFaceInfo.subMessage) ? originFaceInfo.subMessage : '请重试',
              duration: 2000
            });
          }
        }
      });
    } catch (error) {
      that.backToSpecifiedPage('/pages/home/index')
      that.setData({
        showFaceScan: false
      })
    }
  },
  // 用户信息赋值
  getUserInfo({brushingCardUserIInfo, verifyType}) {
    console.log('用户信息赋值', brushingCardUserIInfo, verifyType)
    app.data.userInfo.avatar = brushingCardUserIInfo.photoBase64 || '';
    app.data.userInfo.xm = brushingCardUserIInfo.name;
    app.data.userInfo.sfzh = brushingCardUserIInfo.idNum;
    app.data.userInfo.verifyType = verifyType;
    app.data.userInfo.certContent = brushingCardUserIInfo; // 身份证阅读器返回全部
    // 是否跳转到提示页
    let reminderAuth = app.globalData.snDisposition.reminderAuth;
    if (reminderAuth) {
      this.backToSpecifiedPage('/pages/tipsPage/index')
    } else {
      // 是否启用副屏处理中页面
      let processingPageSwitch = app.globalData.snDisposition.processingPageSwitch;
      if (app.data.isSecondaryScreenState && processingPageSwitch) {
        console.log('打开副屏', app.data.isSecondaryScreenState);
        closeSecondaryScreen()
        app.data.cycleIntervalSwitch = false
        openSecondaryScreen(app.globalData.snDisposition.processingPageImage || '')
      }
      this.backToSpecifiedPage('/pages/interviewee/index')
    }
  },

  // 打印小票
  printFun(form) {
    if (form.name) {
      form.name = desensitization(form.name, 1, 2)
    }
    if (form.phone) {
      form.phone = desensitization(form.phone, 3, 7)
    }
    let data = receiptPrinting(form)
    if (app.data.visitoMsgData.commonQrCode) {
      data.printList.push({
        "text": " " + app.globalData.snDisposition.generalQrcodeTitle,
        "textSize": 25,
        "bold": false,
        "algin": "center"
      }, {
        "width": 376,
        "height": 376,
        "qrCodeText": app.data.visitoMsgData.commonQrCode
      })
    }
    if (app.globalData.snDisposition.ethQrcode && app.data.visitoMsgData.ladderQrCode) {
      data.printList.push({
        "text": " " + app.globalData.snDisposition.ethQrcodeTitle,
        "textSize": 25,
        "bold": false,
        "algin": "center"
      }, {
        "width": 376,
        "height": 376,
        "qrCodeText": app.data.visitoMsgData.ladderQrCode
      })
    }
    let params = {
      "action": "receiptPrinting",
      "event": "open",
      "taskId": "10",
      "params": data
    }
    console.log(params);
    try {
      my.call('ampeHHCommunication', params, res => {
        console.log(res);
        if (!res.success) {
          my.showToast({
            content: res.message ? res.message : '打印失败，请重试',
            duration: 2000
          });
        }
      })
    } catch (error) {
      my.showToast({
        content: res.message ? res.message : '打印失败，请重试',
        duration: 2000
      });
    }
  },
  // 倒计时结束
  finish(e) {
    let {
      result
    } = this.data
    // 操作超时
    if (result == '扫码签离' || result == '刷身份证' || result == '联网查询' || result == '1:1比对') {
      this.backToSpecifiedPage('/pages/resultPage/index?result=结果页超时&&timer=' + app.globalData.snDisposition.resultPageTimeout);
      return;
    }
    // 结果页自动退回首页
    if (result == '签离成功' || result == '签离失败' || result == '结果页超时' || result == '逃犯' || result == '有前科' || result == '登记成功') {
      this.backToSpecifiedPage('/pages/home/index');
      return;
    }
    //未知操作，回到首页
    this.backToSpecifiedPage('/pages/home/index');
  },

  sure() {
    this.backToSpecifiedPage('/pages/home/index')
  },
});
