<template>
  <div class="signContract-container bg-white">
    <van-field readonly label-width="120px" label="销售人员姓名" v-model="agentInfo.name" />
    <van-field readonly label-width="120px" label="证件号码" v-model="agentInfo.idNo" />
    <van-field readonly label-width="120px" label="入司申请时间" v-model="agentInfo.createdDate" />
    <van-field readonly label-width="120px" label="所属分公司" rows="1" autosize type="textarea" v-model="referrerInfo.manageName" />
    <van-field readonly label-width="120px" label="所属团队" v-model="referrerInfo.orgLabel" />
    <div v-if="!isWeixin" class="mb10">
      <p class="p15 line-height">
        恭喜您的入司资料已经通过公司审核，<br />
        以下内容需要您按照顺序阅读并签字确认：
      </p>
      <div class="p15 line-height">
        需签署：
        <ul>
          <li class="flex" v-for="(sign, index) in agentSignList" :key="index">
            <div class="w240 blue">{{ sign.name }}</div>
            <div class="pt5 pb5">
              <van-icon v-if="sign.signState === '1'" color="green" name="checked" />
              <van-button
                v-if="sign.signState === '1' && agentInfo.audit == '04'"
                @click="changeSign(sign, '0')"
                v-no-more-click="1000"
                plain
                type="danger"
                round
                size="small"
                class="ml5"
                >重新签名</van-button
              >
            </div>
          </li>
        </ul>
        点击【开始】按钮，进行相关操作<br /><span class="red">温馨提示：请尽量使用正楷文字进行签名</span>
      </div>
      <div class="text-center mt20">
        <van-button @click="faceAuth('0')" v-no-more-click="1000" :disabled="isAgentSubmit" type="danger" size="normal" style="width: 30%">开始</van-button>
      </div>
    </div>
    <div class="ebizGuarantor">
      <van-field readonly label-width="120px" label="担保人" v-model="ebizGuarantor.name"></van-field>
      <p class="p15 line-height">以下内容需要您按照顺序阅读并签字确认：</p>
      <div class="p15 line-height">
        需签署：
        <ul>
          <li class="flex" v-for="(sign, index) in guaranteeSignList" :key="index">
            <div class="w240 blue">{{ sign.name }}</div>
            <van-icon v-if="sign.signState === '1'" color="green" name="checked" />
            <van-button
              v-if="sign.signState === '1' && agentInfo.audit == '04'"
              @click="changeSign(sign, '1')"
              v-no-more-click="1000"
              plain
              type="danger"
              round
              size="small"
              class="ml5"
              >重新签名</van-button
            >
          </li>
        </ul>
        点击【开始】或【分享】，进行相关操作<br /><span class="red">温馨提示：请尽量使用正楷文字进行签名</span>
      </div>
      <div v-if="!isInvalid" class="flex justify-content-a mb60 mt20">
        <van-button v-if="!isWeixin" @click="share" v-no-more-click="1000" type="danger" size="normal" style="width: 30%">分享</van-button>
        <van-button @click="faceAuth('1')" v-no-more-click="1000" :disabled="isguranteeSubmit" type="danger" size="normal" style="width: 30%">开始</van-button>
      </div>
      <div v-else class="ml15">操作时间已失效，请联系销售人员！</div>
    </div>

    <van-button
      v-if="isAgentSubmit && isguranteeSubmit && !isWeixin"
      class="fixed bottom0"
      type="danger"
      v-no-more-click="1000"
      @click="clickSubmit"
      size="large"
      >提交</van-button
    >

    <!-- 短信验证弹窗 -->
    <van-dialog v-model="isCaptchaModalShow" title="提示" show-cancel-button :before-close="onCaptchaConfirm" @cancel="onCaptchaCancel">
      <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, Icon, Button, Dialog } from 'vant'
import { agreementQuery, signAgreement } from '@/api/ebiz/agentEenter/agentEenter.js'
import { checkSignInvalid, getSignInvalid, getAuthCode, autchCodeCheck } from '@/api/ebiz/sale/sale'
import { getWhitelist } from '@/api/ebiz/whitelist'
import { filtSignList } from './js/methods'
export default {
  data() {
    let isWeixin = this.$utils.device().isWeixin //判断环境
    return {
      // 人脸验证次数
      faceAuthCount: 0,
      isCaptchaModalShow: false,
      code: '',
      sid: '',
      countDownNum: 0,
      countDownTimer: null,
      authCode: '',
      // 是否在微信
      isWeixin,
      // 微信分享链接是否失效 false 为未失效 true为已失效
      isInvalid: false,
      // 微信分享校验值
      signInvalid: '',
      agentInfo: {
        name: '',
        idNo: '',
        createdDate: ''
      },
      referrerInfo: {
        orgLabel: ''
      },
      signList: [],
      agentSignList: [], //申请人所需阅读签署文档集合
      guaranteeSignList: [], //担保人所需阅读签署文档集合
      isAgentSubmit: false,
      isguranteeSubmit: false,
      ebizGuarantor: {} //担保人信息
    }
  },
  created() {
    this.init()
  },
  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.goUrl(this.authCode)
        } 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.agentInfo.mobile,
        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('网络异常')
      }
    },
    //初始化信息
    async init() {
      if (this.isWeixin) {
        if (this.$route.query.token) {
          window.localStorage.setItem('token', this.$route.query.token)
        }
        if (this.$route.query.signInvalid) {
          sessionStorage.setItem('signInvalid', this.$route.query.signInvalid)
        }
        let signInvalid = sessionStorage.getItem('signInvalid')
        await this.agreementQuery()
        let rs = await this.checkSignInvalid(signInvalid)
        if (rs == '1') {
          this.isInvalid = false
        } else {
          this.isInvalid = true
        }
        if (this.$route.query.dialogFlag) {
          Dialog.alert({
            message: '签名成功，请联系申请人进行后续操作！'
          }).then(() => {})
        }
      } else {
        await this.agreementQuery()
        this.getSignInvalid()
      }
    },

    //获取签署协议人信息
    agreementQuery() {
      let data = {}
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '加载中……'
      })
      return new Promise((resolve) => {
        agreementQuery(data).then((res) => {
          if (res.result == '0') {
            this.$toast.clear()
            this.agentInfo = res.content.ebizEnterCustomerDto
            this.referrerInfo = res.content.ebizReferrerDto
            this.signList = res.content.ebizAgreementDtoList
            this.ebizGuarantor = res.content.ebizGuarantorDto
            localStorage.idNoD = this.ebizGuarantor.idNo
            localStorage.idNameD = this.ebizGuarantor.name
            this.agentInfo.createdDate = this.agentInfo.createdDate.substring(0, 10)
            this.agentSignList = filtSignList(this, this.signList).agentSignList
            this.guaranteeSignList = filtSignList(this, this.signList).guaranteeSignList
            this.isAgentSubmit = this.agentSignList.every((item) => {
              return item.signState == '1'
            })
            this.isguranteeSubmit = this.guaranteeSignList.every((item) => {
              return item.signState == '1'
            })
            resolve()
          } else {
            this.$toast(res.resultMessage)
          }
        })
      })
    },
    //担保人分享到微信空签
    share() {
      EWebBridge.webCallAppInJs('bridge', {
        flag: 'share',
        extra: {
          title: '国富人寿入司申请（担保人签字）',
          content: '签字进行',
          url: location.origin + '/#/agentEenter/signContract?token=' + localStorage.token + '&signInvalid=' + this.signInvalid,
          img: this.$assetsUrl + 'images/logo.png'
        }
      })
    },

    getSignInvalid() {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '加载中……'
      })
      let data = {}
      getSignInvalid(data).then((res) => {
        if (res.result == '0') {
          this.$toast.clear()
          this.signInvalid = res.content.sign
        }
      })
    },
    //修改签名
    changeSign(v, code) {
      localStorage.idNo = this.agentInfo.idNo
      localStorage.idName = this.agentInfo.name
      this.$jump({
        flag: 'h5',
        extra: {
          url: `${location.origin}/#/agentEenter/${v.path}?code=${code}&isChange=0`
        },
        routerInfo: {
          path: `/agentEenter/${v.path}?code=${code}&isChange=0`
        }
      })
    },
    //判断微信分享链接是否失效
    async checkSignInvalid(signInvalid) {
      let that = this
      this.$toast.loading({
        duration: 0, // 持续展示 toast

        forbidClick: true, // 禁用背景点击

        loadingType: 'spinner',

        message: '加载中……'
      })
      let data = {
        sign: signInvalid
      }
      return new Promise((resolve) => {
        checkSignInvalid(data).then((res) => {
          if (res.result == '0') {
            that.$toast.clear()
            let status = res.content.status
            resolve(status)
          }
        })
      })
    },
    async faceAuth(code) {
      this.authCode = code
      localStorage.idNo = this.agentInfo.idNo
      localStorage.idName = this.agentInfo.name

      if (code == '0') {
        if (this.agentInfo.idType == '1') {
          this.goUrl(code)
          // 人脸识别次数小于3次
          this.$toast.loading({
            duration: 0, // 持续展示 toast
            forbidClick: true, // 禁用背景点击
            loadingType: 'spinner',
            message: '加载中……'
          })
          // 判断是否在白名单, 在白名单无需人脸
          const res = await getWhitelist({
            idNo: this.agentInfo.idNo,
            name: this.agentInfo.name,
            whiteType: 'enter_agent_face_show'
          })
          console.log(res.content)
          if (res.result === '0') {
            // 用户在白名单内
            if (res.content && res.content.length) {
              this.goUrl(code)
            }
            // 不再白名单内
            else {
              if (this.faceAuthCount < 3) {
                try {
                  // eslint-disable-next-line no-undef
                  const authRes = await EWebBridge.webCallAppInJs('face_auth', {
                    businessSource: '2', //业务来源:1-电投，2-入司，3-理赔，4-保全
                    number: this.agentInfo.idNo, //身份证号码
                    name: this.agentInfo.name, //姓名
                    orderNo: this.$CacheUtils.getLocItem('orderNo') //订单号
                  })
                  // const authRes = await this.fakeFaceAuth(true)
                  console.log(authRes)
                  if (JSON.parse(authRes).state == '1') {
                    this.goUrl(code)
                  } else {
                    // 人脸验证失败更新faceAuthCount
                    this.faceAuthCount++
                  }
                } catch (error) {
                  console.log(error)
                }
              } else {
                this.isCaptchaModalShow = true
              }
            }
          } else {
            this.$toast(res.resultMessage)
          }
        } else {
          this.goUrl(code)
        }
      } else {
        this.goUrl(code)
      }
    },
    fakeFaceAuth(expect) {
      console.log('模拟调用人脸识别')
      return new Promise(function (resolve, reject) {
        setTimeout(() => {
          console.log('模拟人脸识别完成')
          if (expect) {
            resolve({ state: '0' })
          } else {
            reject({ state: '0' })
          }
        }, 2000)
      })
    },
    goUrl(code) {
      let path = ''
      if (code == '0') {
        path = this.agentSignList.filter((v) => {
          return v.signState == '0'
        })[0].path
      } else if (code == '1') {
        path = this.guaranteeSignList.filter((v) => {
          return v.signState == '0'
        })[0].path
      }
      this.$jump({
        flag: 'h5',
        extra: {
          url: `${location.origin}/#/agentEenter/${path}?code=${code}`
        },
        routerInfo: {
          path: `/agentEenter/${path}?code=${code}`
        }
      })
    },
    clickSubmit() {
      let data = {
        submitFlag: '1'
      }
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '加载中……'
      })
      signAgreement(data).then((res) => {
        console.log(res)
        if (res.result == '0') {
          this.$toast.clear()
          this.$jump({
            flag: 'h5',
            extra: {
              url: location.origin + `/#/agentEenter/agentEenterResult`,
              forbidSwipeBack: '1',
              backToFirst: '1'
            },
            routerInfo: {
              path: `/agentEenter/agentEenterResult`
            }
          })
        } else {
          this.$toast(res.resultMessage)
        }
      })
    }
  },
  components: {
    [Field.name]: Field,
    [Icon.name]: Icon,
    [Button.name]: Button
  },
  filters: {
    countDownText(val) {
      if (isNaN(parseFloat(val))) {
        return val
      } else {
        return `${val} s`
      }
    }
  }
}
</script>

<style lang="scss" scoped>
#app .van-cell:not(:last-child)::after {
  border: none;
}
.signContract-container {
  height: 100%;
}
.ebizGuarantor {
  /deep/ .van-field__body {
    .van-field__control {
      color: #e9332e;
    }
  }
}
</style>
