<!--操作结果页面-->
<template>
  <div class="handle-result-container">
    <div class="payResult-header flex justify-content-c align-items-c p20 pt80"><img class="w60 h60 mt100" :src="srcSuccess" alt="" /></div>
    <div class="flex flex-direction-colunm text-center">
      <p class="mt15 mb20">已提交,待客户确认</p>
      <p class="gray fs14">修改完成，请让客户确认</p>
      <p class="gray fs14">如客户当天24:00前未确认提交，本次操作将自动取消</p>
    </div>

    <div class="bg-white bottom-btn"><van-button type="danger" size="large" @click="nextStep" v-no-more-click="2000">客户确认</van-button></div>

    <!-- 短信验证弹窗 -->
    <van-dialog v-model="isCaptchaModalShow" title="提示" show-cancel-button :before-close="onCaptchaConfirm" @cancel="onCaptchaCancel">
      <van-cell>
        <p class="fs14">为确保是您本人操作，短信验证码将发送至您手机号{{ encryptMobile }}，请您输入验证码以完成后续操作。</p>
      </van-cell>
      <van-field v-model="code" type="number" :maxlength="6" center clearable label="短信验证码" placeholder="请输入短信验证码">
        <template #button>
          <van-button size="small" type="danger" :disabled="countDownNum !== 0" @click="getCaptcha">{{
            countDownNum === 0 ? '获取验证码' : countDownNum | countDownText
          }}</van-button>
        </template>
      </van-field>
    </van-dialog>
  </div>
</template>

<script>
import { Field } from 'vant'
import utilsAge from '@/assets/js/utils/age'
import { getAuthCode, autchCodeCheck } from '@/api/ebiz/sale/sale'
import { getWhitelist } from '@/api/ebiz/whitelist'

export default {
  name: 'HandleResult',
  components: {
    [Field.name]: Field
  },
  data() {
    return {
      // 人脸验证次数
      faceAuthCount: 0,
      isCaptchaModalShow: false,
      code: '',
      sid: '',
      countDownNum: 0,
      countDownTimer: null,
      path: '', //页面跳转路径
      srcSuccess: this.$assetsUrl + 'images/success.png',
      entry: '',
      signInvalid: '',
      surrenderType: '',
      customerInfo: {},
      policy: {}
    }
  },
  computed: {
    encryptMobile() {
      if (this.customerInfo && this.customerInfo.preferredPhoneNum) {
        return this.customerInfo.preferredPhoneNum.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
      }
      return ''
    }
  },
  created() {
    this.entry = this.$route.query.entry
    if (localStorage['preserve-customerInfo']) {
      this.customerInfo = JSON.parse(localStorage['preserve-customerInfo'])
    }
    if (localStorage['preserve-policy']) {
      this.policy = JSON.parse(localStorage['preserve-policy'])
    }
    // 此处处理 this.path
    switch (this.entry) {
      case 'BB':
        this.path = `/preserve/BB/ContactConfirmation?entry=${this.entry}`
        break
      case 'BC':
        this.path = `/preserve/BC/BeneficiaryConfirmation?entry=${this.entry}`
        break
      case 'PC':
        this.path = `/preserve/pc/renewalConfirmation?entry=${this.entry}`
        break
      case 'CT':
        this.path = `/preserve/ct/surrenderConfirmation?entry=${this.entry}`
        break
      case 'WT':
        this.path = `/preserve/wt/wsurrenderConfirmation?entry=${this.entry}`
        break
      default:
        this.path = ''
        break
    }
  },
  mounted() {
    document.getElementsByTagName('body')[0].classList.add('bg-white')
  },
  destroyed() {
    document.getElementsByTagName('body')[0].classList.remove('bg-white')
  },
  methods: {
    async onCaptchaConfirm(action, done) {
      if (!this.sid) {
        done(false)
        return
      }
      if (!this.code.trim()) {
        done(false)
        return this.$toast('请输入验证码')
      }
      try {
        let res = await autchCodeCheck({
          smsId: this.sid,
          code: this.code
        })
        console.log(this.sid, this.code)
        if (res.result === '0') {
          this.jumpNextPage(this.path)
        } else {
          this.$toast(res.resultMessage)
        }
      } catch (error) {
        this.$toast('网络异常')
        console.log(error)
      }
      this.onCaptchaCancel()
      done()
    },
    onCaptchaCancel() {
      this.isCaptchaModalShow = false
      clearInterval(this.countDownTimer)
      this.countDownTimer = null
      this.countDownNum = 0
      this.sid = ''
      this.code = ''
    },
    async getCaptcha() {
      let data = {
        operateType: 'appntInfoEntry',
        type: 'H5',
        operateCode: this.customerInfo.preferredPhoneNum,
        system: 'agentApp',
        operateCodeType: '0'
      }
      //获取验证码
      try {
        let res = await getAuthCode(data)
        console.log(res)
        if (res.result === '0') {
          this.$toast(res.resultMessage)
          this.sid = res.sessionId
          this.countDownNum = 60
          this.countDownTimer = setInterval(() => {
            this.countDownNum--
            if (this.countDownNum <= 0) {
              clearInterval(this.countDownTimer)
              this.countDownTimer = null
            }
          }, 1000)
        } else {
          this.$toast(res.resultMessage)
        }
      } catch (error) {
        console.log(error)
        this.$toast('网络异常')
      }
    },
    nextStep() {
      if (this.entry != 'BC') {
        // 如果 保全项不是 受益人变更、则 在证件类型为身份证时 直接接入人脸识别
        if (this.customerInfo.idType != '1') {
          // 如果证件类型不是身份证
          // 直接跳过人脸识别
          this.jumpNextPage(this.path)
        } else {
          this.toFace({
            number: this.customerInfo.idNo, //身份证号码
            name: this.customerInfo.customerName, //姓名
            businessSource: '4', //业务来源:1-电投，2-入司，3-理赔，4-保全
            orderNo: this.$CacheUtils.getLocItem('orderNo') //订单号
          })
        }
      } else if (this.entry == 'BC') {
        /* 如果 保全项是 受益人变更，则进行特殊判断
         若被保险人≥18周岁，人脸识别录入被保人本人
         若被保险人＜18周岁，被保险人与投保人为子女关系，人脸识别录入未成年人父亲或母亲*/
        let age = utilsAge.getAge(this.policy.insuredInfo.insuredBirthday, new Date())
        if (age >= 18) {
          if (this.policy.insuredInfo.idType != '0') {
            // 如果证件类型不是身份证——直接跳过人脸识别
            this.jumpNextPage(this.path)
          } else {
            this.toFace({
              number: this.policy.insuredInfo.idNo, //身份证号码
              name: this.policy.insuredInfo.insuredName, //姓名
              businessSource: '4', //业务来源:1-电投，2-入司，3-理赔，4-保全
              orderNo: this.$CacheUtils.getLocItem('orderNo') //订单号
            })
          }
        } else {
          if (this.policy.appntInfo.idType != '0') {
            // 如果证件类型不是身份证——直接跳过人脸识别
            this.jumpNextPage(this.path)
          } else {
            this.toFace({
              number: this.policy.appntInfo.idNo, //身份证号码
              name: this.policy.appntInfo.appntName, //姓名
              businessSource: '4', //业务来源:1-电投，2-入司，3-理赔，4-保全
              orderNo: this.$CacheUtils.getLocItem('orderNo') //订单号
            })
          }
        }
      }
    },
    jumpNextPage(path) {
      this.$jump({
        flag: 'h5',
        extra: {
          url: location.origin + '/#' + path
        },
        routerInfo: {
          path: path
        }
      })
    },
    async toFace(config) {
      const res = await getWhitelist({
        idNo: this.customerInfo.idNo,
        name: this.customerInfo.customerName,
        whiteType: 'edor_face_show'
      })
      if (res.result === '0') {
        // 用户在白名单内
        if (res.content && res.content.length) {
          this.jumpNextPage(this.path)
          return
        }
      } else {
        this.$toast(res.resultMessage)
      }
      if (this.faceAuthCount < 3) {
        // eslint-disable-next-line no-undef
        EWebBridge.webCallAppInJs('face_auth', config)
          // 跳过人脸识别
          // new Promise(resolve => {
          //   console.log('--跳过人脸识别--返回识别成功')
          //   resolve(JSON.stringify({ state: '0' }))
          // })
          .then((data) => {
            if (JSON.parse(data).state == '1') {
              this.jumpNextPage(this.path)
            } else {
              // eslint-disable-next-line no-undef
              EWebBridge.webCallAppInJs('webview_toast', '人脸检测失败')
              this.faceAuthCount++
            }
          })
      } else {
        this.isCaptchaModalShow = true
      }
    }
  },
  filters: {
    countDownText(val) {
      if (isNaN(parseFloat(val))) {
        return val
      } else {
        return `${val} s`
      }
    }
  }
}
</script>

<style></style>
