<template>
  <div class="content">
    <div class="navBar">
      <van-nav-bar
          title="实名认证"
          left-arrow
          left-arrow-color="#FFFFFF"
          :border="false"
          :fixed="true"
          :safe-area-inset-top="true"
          @click-left="goListPage"
      />
    </div>
    <tip-bar :title="'应国家政策要求：从事货运行业的司机用户，身份证照片、驾驶证信息、行驶证信息、人车合影及承运资质信息必须进行实名认证。'"></tip-bar>
    <photo-item title="个人头像" v-if="type != 'simple'" :show="show" :left-url="form.icon ||headerUrl" @leftImg="headerHandler"></photo-item>
    <photo-item title="身份证正反面" :show="show" :left-url="form.identityCardFront || idFront" :right-url="form.identityCardContrary || idBack"
                @leftImg="idFrontHandler" @rightImg="idBackHandler" ></photo-item>
    <div class="carInfo">
      <div class="left_wrap title">
            <span class="mar_left">注册手机号</span>
             <div>
               <span class="star">*</span>
               <span>本人姓名</span>
             </div>
            <div>
              <span class="star">*</span>
              <span>本人性别</span>
            </div>
              <div>
                <span class="star">*</span>
                <span>本人身份证号</span>
              </div>
      </div>
      <div class="right_wrap">
        <span class="phone">{{form.phone}}</span>
        <input type="text" disabled placeholder="请输入持卡人姓名" v-model="form.name">
        <input type="text" disabled placeholder="请输入持卡人性别" v-model="form.sex">
        <input type="text" placeholder="请输入持卡人身份证号" v-model="form.identityCardNumber">
      </div>
    </div>
    <fixed-button title="实名认证" @myClick="goRealName" v-if="showFun() && !esignFlag"></fixed-button>
    <fixed-button @myClick="clickHandler" v-if="showFun() && esignFlag"></fixed-button>
<!--    <protocol-dialog></protocol-dialog>-->
  </div>
</template>

<script>
  // import protocolDialog from "./component/protocolDialog";
  import fixedButton from "./component/fixedButton";
  import photoItem from "./component/photoItem";
  import tipBar from "./component/tipBar";
  import {
    ocrRecognize,
    driverInfoVerify,
    driverInfoVerifyDetail,
    driverRealName,
    infoVerifyProgress
  } from '@/api/authentication'
  import { leftCopy } from '@/utils/common.js'
  import { myMixins } from '@/utils/myMixins.js'
  // import {version} from "@/utils/baseUrl"
  export default {
    name: "personAudit",
    components: {
      tipBar,
      photoItem,
      fixedButton,
      // protocolDialog
    },
    mixins: [myMixins],
    data() {
      return {
        form: {
          phone: localStorage.getItem('phone'),
          name: '',
          sex: '',
          identityCardNumber: '',
          icon: '',
          identityCardFront: '',
          identityCardContrary: '',
					idCardAuthority: '',     // 发证机关
					idCardValidStartTime: '',    // 有效期开始
					idCardValidEndTime: '',      // 有效期结束
        },
        validPeriod: '',    // 有效期
        headerUrl: require('@/assets/authentication/person_header.png'),
        idFront: require('@/assets/authentication/person_idcard1.png'),
        idBack: require('@/assets/authentication/person_idcard2.png'),
        show: undefined,
        type:  'full',
        esignFlag: false,
      }
    },
    async mounted() {
      // 禁止双击放大
      let lastTouchEnd = 0;
      document.addEventListener('touchend', (event) => {
        const now = Date.now();
        if (now - lastTouchEnd <= 300) {
          event.preventDefault(); // 阻止双击放大
        }
        lastTouchEnd = now;
      }, { passive: false });

      this.show = true
        if( this.show ) {
          await this.getDetail()
        }
      const urlParams = new URLSearchParams(window.location.search);
      console.log('window.location',window.location)
      // console.log("urlParams",urlParams)
      console.log("decodeURIComponent(  window.location.href)",decodeURIComponent(  window.location.href))
      this.esignFlag = urlParams.get('esignFlag') || localStorage.getItem("esignFlag")
      if(window.location.search){
        console.log('有参数')
        this.esignFlag = localStorage.getItem("esignFlag") || urlParams.get('esignFlag')
      }else {
        console.log('无参数，说明认证成功')
        this.esignFlag =true
      }
      localStorage.setItem("esignFlag",this.esignFlag )
      console.log("this.esignFlag ",this.esignFlag )
    },
    methods: {
      async getDetail() {
        let res = await driverInfoVerifyDetail( {
          verifyType: 1
        })
        leftCopy(this.form, {...res?.data?.personalInfoData})
        let personAuditInfo=localStorage.getItem("personAuditInfo") ? JSON.parse(localStorage.getItem("personAuditInfo")) : ''
        if(!personAuditInfo){
          return
        }
        console.log('personAuditInfo.form',personAuditInfo.form)
        this.form={...personAuditInfo.form}
      },
      async headerHandler(data) {
        this.form.icon = data
      },
      async idFrontHandler(data) {      // 身份证正面
        this.form.identityCardFront = data
        await this.idOrcHandler(this.form.identityCardFront)
      },
      async idBackHandler(data) {
        this.form.identityCardContrary = data
        await this.idBackOrcHandler(this.form.identityCardContrary)
      },
      initForm() {
        this.form.name = ''
        this.form.sex = ''
        this.form.identityCardNumber = ''
      },
      backInit() {
        this.validPeriod = ''
      },
      async idBackOrcHandler(url) {
        let res = await ocrRecognize( {
          ocrType: 1,
          imageUrl: url
        });
        let idInfo = res?.data?.data?.back?.data
        let validPeriod = idInfo?.validPeriod;			// 有效期
				this.form.idCardAuthority = idInfo?.issueAuthority
				let dateArr = validPeriod.split('-');
				let startDate = dateArr[0];
				let endDate = dateArr[1];
				this.form.idCardValidStartTime = startDate.replace(/\./g, '/') + ' 00:00:00';
				if( endDate.indexOf('长期') != -1 ) {
					this.form.idCardValidEndTime = '2099/01/01 00:00:00'
				} else {
					this.form.idCardValidEndTime = endDate.replace(/\./g, '/') + ' 00:00:00';
				}
      },
      async idOrcHandler(url) {
        await this.initForm()
        let res = await ocrRecognize({
          ocrType: 1,
          imageUrl: url
        });
        let idInfo = res?.data?.data?.face?.data
        this.form.name = idInfo?.name
        this.form.sex = idInfo?.sex
        this.form.identityCardNumber = idInfo?.idNumber
      },
      async goRealName() {
        if (!this.form.identityCardContrary) {
          this.$toast('身份证反面照片未上传')
          return
        }
        if( !this.form.idCardValidStartTime ) {
          this.$toast('身份证反面识别错误')
          return
        }
        if (!this.form.identityCardFront) {
          this.$toast('身份证正面照片未上传')
          return
        }
        const urlParams = new URLSearchParams(window.location.search);
        let token = urlParams.get('token');
        if(this.form.name && this.form.identityCardNumber) {
          let res = await driverRealName( {
            phone: this.form.phone,
            name: this.form.name,
            idNo: this.form.identityCardNumber,
            token:token,
            jump:1
          })
          let info = res?.data
          console.log('info', info)
          localStorage.setItem("personAuditInfo",JSON.stringify({form:this.form}))
          window.location.href=info?.shortLink
        } else {
          this.$toast('身份证信息识别错误')
        }
      },
      async clickHandler() {
        if (!this.form.identityCardContrary) {
          this.$toast('身份证反面照片未上传')
          return
        }
        if( !this.form.idCardValidStartTime ) {
          this.$toast('身份证反面识别错误')
          return
        }
        if (!this.form.identityCardFront) {
          this.$toast('身份证正面照片未上传')
          return
        }
        if(this.form.name && this.form.identityCardNumber) {
         await driverInfoVerify( {
            verifyType: 1,
            type: this.type || 'full',
            ...this.form,
          })
          this.$toast('操作成功')
          await this.getRegisterInfo({
            verifyType: 1
          })
          localStorage.setItem("personAuditInfo",'')
          setTimeout(() => {
            this.goListPage()
          }, 100)
        } else {
          this.$toast('身份证信息识别错误')
        }
      },
      goListPage(){
        this.goPage('auditList',{
          token:localStorage.getItem('token')
        })
      },
      async getRegisterInfo(data) {
        let res = await infoVerifyProgress( data)
        localStorage.setItem('infoVerify', res?.data?.infoVerify?.code)
        localStorage.setItem('failReason', res?.data?.verifyRemark)
        localStorage.setItem('authIsSuccess', res?.data?.authIsSuccess)
        localStorage.setItem('name', res?.data?.name)
      },
    }
  }
</script>

<style lang="scss">
  @import "@/styles/common.scss";
  @import "@/styles/infoShow.scss";
  page {
    background: #F4F5F7;
  }
  .navBar{
    margin-bottom: 46px;
  }
  .empty{
    width: 100%;
    height:151px;
  }
  .content {
    padding-bottom: 86px;
    height: 90%;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* 启用iOS惯性滚动 */
    scroll-behavior: smooth; /* 平滑滚动（部分浏览器支持） */
  }
</style>
