<template>
  <div class="page-person-real-step2">
    <page-title title="填写客户信息"/>
    <steps :data="stepData" :index="1"/>
    <div v-if="pageData.userType === 'new'" key="newUser">
      <div v-if="!pageData.isDelegate" key="self">
        <page-module name="基本信息" icon="info">
          <comp-basic-info ref="masterBasicInfo" :data="masterBasicInfoData"/>
        </page-module>
        <page-module name="证件信息" icon="idcard">
          <comp-certificate-info ref="masterCertInfo" :data="masterCertInfoData" @read-cert="(data)=> onReadCert(data, 'master')"/>
        </page-module>
        <page-module name="文件信息" icon="folder">
          <CompMasterFileInfo ref="masterFileInfo" :data="masterFileInfoData" :type="pageData.userType" :attachment-url="attachmentUrl" />
        </page-module>
        <page-module name="联系信息" icon="tel">
          <comp-concat-info ref="masterConcatInfo" :data="masterConcatInfoData"/>
        </page-module>
      </div>
      <div v-else key="delegate">
        <page-module name="车主基本信息" icon="info">
          <comp-basic-info ref="masterBasicInfo" :data="masterBasicInfoData"/>
        </page-module>
        <page-module name="车主证件信息" icon="idcard">
          <comp-certificate-info ref="masterCertInfo" :data="masterCertInfoData" @read-cert="(data)=> onReadCert(data, 'master')"/>
        </page-module>
        <page-module name="车主文件信息" icon="folder">
          <CompMasterFileInfo ref="masterFileInfo" :data="masterFileInfoData" :type="pageData.userType" :attachment-url="attachmentUrl" />
        </page-module>
        <page-module name="车主联系信息" icon="tel">
          <comp-concat-info ref="masterConcatInfo" :data="masterConcatInfoData" :need-vcode="false"/>
        </page-module>

        <page-module name="代办人基本信息" icon="info">
          <comp-basic-info ref="delegateBasicInfo" :data="delegateBasicInfoData" :show-vin="false"/>
        </page-module>
        <page-module name="代办人证件信息" icon="idcard">
          <comp-certificate-info ref="delegateCertInfo" :data="delegateCertInfoData" @read-cert="(data)=> onReadCert(data, 'delegate')"/>
        </page-module>
        <page-module name="代办人文件信息" icon="folder">
          <file-info
            ref="delegateFileInfo"
            :limit="1"
            :file-size="10"
            :data="delegateFileInfoData"
            label="委托书"
            placeholder="上传文件"
          />
        </page-module>
        <page-module name="代办人联系信息" icon="tel">
          <comp-concat-info ref="delegateConcatInfo" :data="delegateConcatInfoData" />
        </page-module>
      </div>
    </div>
    <div v-else key="oldUser">
      <div v-if="!pageData.isDelegate" key="self">
        <page-module name="基本信息" icon="info">
          <comp-basic-info ref="masterBasicInfo" :data="masterBasicInfoData"/>
        </page-module>
        <page-module name="证件信息" icon="idcard">
          <comp-certificate-info ref="masterCertInfo" :data="masterCertInfoData" @read-cert="(data)=> onReadCert(data, 'master')"/>
        </page-module>
        <page-module name="文件信息" icon="folder">
          <CompMasterFileInfo ref="masterFileInfo" :data="masterFileInfoData" :type="pageData.userType" :attachment-url="attachmentUrl" />
        </page-module>
        <page-module name="联系信息" icon="tel">
          <comp-concat-info ref="masterConcatInfo" :data="masterConcatInfoData"/>
        </page-module>
      </div>
      <div v-else key="delegate">
        <page-module name="车主基本信息" icon="info">
          <comp-basic-info ref="masterBasicInfo" :data="masterBasicInfoData"/>
        </page-module>
        <page-module name="车主证件信息" icon="idcard">
          <comp-certificate-info ref="masterCertInfo" :data="masterCertInfoData" @read-cert="(data)=> onReadCert(data, 'master')"/>
        </page-module>
        <page-module name="车主文件信息" icon="folder">
          <CompMasterFileInfo ref="masterFileInfo" :data="masterFileInfoData" :type="pageData.userType" :attachment-url="attachmentUrl" />
        </page-module>
        <page-module name="车主联系信息" icon="tel">
          <comp-concat-info ref="masterConcatInfo" :data="masterConcatInfoData" :need-vcode="false"/>
        </page-module>

        <page-module name="代办人基本信息" icon="info">
          <comp-basic-info ref="delegateBasicInfo" :data="delegateBasicInfoData" :show-vin="false"/>
        </page-module>
        <page-module name="代办人证件信息" icon="idcard">
          <comp-certificate-info ref="delegateCertInfo" :data="delegateCertInfoData" @read-cert="(data)=> onReadCert(data, 'delegate')"/>
        </page-module>
        <page-module name="代办人文件信息" icon="folder">
          <file-info
            ref="delegateFileInfo"
            :limit="1"
            :file-size="10"
            :data="delegateFileInfoData"
            label="委托书"
            placeholder="上传文件"
          />
        </page-module>
        <page-module name="代办人联系信息" icon="tel">
          <comp-concat-info ref="delegateConcatInfo" :data="delegateConcatInfoData" />
        </page-module>
      </div>
    </div>
    <div class="next-step">
      <el-button size="small" plain @click.stop="clickPrevStep">上一步</el-button>
      <el-button size="small" type="primary" @click.stop="clickNextStep">下一步</el-button>
    </div>
    <comp-confirm
      :show.sync="showErrorConfirm"
      :desc="errorConfirmDesc"
    />
    <CompAttachment :vin="attachment.vin" :iccid="attachment.iccid" @change="handleAttachmentChange" />
  </div>
</template>

<script>
import { submitPersonRealNameAuthH5, checkSmsCaptcha } from '@/api/realname-person'
import CompAttachment from '@/components/CompAttachment'
import PageTitle from '@/components/PageTitle'
import Steps from '@/components/Steps'
import Common from '@/components/Common'
import CompBasicInfo from '@/components/CompBasicInfo'
import CompCertificateInfo from '@/components/CompCertificateInfo'
import CompConcatInfo from '@/components/CompConcatInfo'
import CompMasterFileInfo from '@/components/CompMasterFileInfo'
import FileInfo from '@/components/FileInfo'
import ValidateStep from './components/validate-step'
import SelfCommon from './components/common'
import CompConfirm from '@/components/CompConfirm'

export default {
  name: 'PersonRealnameStep2',
  components: {
    PageTitle,
    Steps,
    CompBasicInfo,
    CompCertificateInfo,
    CompMasterFileInfo,
    FileInfo,
    CompConcatInfo,
    CompConfirm,
    CompAttachment
  },
  mixins: [Common, SelfCommon, ValidateStep],
  data() {
    return {
      stepData: ['车卡信息录入', '填写客户信息', '完成人脸识别'],
      pageData: {
        userType: '',
        isDelegate: false,
        vin: '',
        masterData: {
          basicInfoData: {
            vin: ''
          }
        },
        delegateData: {
          basicInfoData: {}
        }
      },
      attachment: {
        vin: '',
        iccid: []
      },
      attachmentUrl: '',
      showErrorConfirm: false,
      errorConfirmDesc: ''
    }
  },
  computed: {
    masterData() {
      return this.pageData.masterData || {}
    },
    masterBasicInfoData() {
      return this.masterData.basicInfoData || {}
    },
    masterCertInfoData() {
      return this.masterData.certInfoData || {}
    },
    masterFileInfoData() {
      return this.masterData.fileInfoData || {}
    },
    masterConcatInfoData() {
      return this.masterData.concatInfoData || {}
    },

    delegateData() {
      return this.pageData.delegateData || {}
    },
    delegateBasicInfoData() {
      return this.delegateData.basicInfoData || {}
    },
    delegateCertInfoData() {
      return this.delegateData.certInfoData || {}
    },
    delegateFileInfoData() {
      return this.delegateData.fileInfoData || {}
    },
    delegateConcatInfoData() {
      return this.delegateData.concatInfoData || {}
    }
  },
  methods: {
    /**
     * 附件变化方法
     */
    handleAttachmentChange(val) {
      this.attachmentUrl = val
    },

    errorTips(errMsg) {
      this.showErrorConfirm = true
      this.errorConfirmDesc = errMsg
    },

    async init() {
      this.initStepCachePageData()
      const canEnter = await this.canEnter()
      if (!canEnter) {
        this.$router.replace({
          name: 'PersonRealnameStep1'
        })
      } else {
        this.initRenderPage()
      }
    },
    async show() {
      this.initStepCachePageData()
      const canEnter = await this.canEnter()
      if (!canEnter) {
        this.$router.replace({
          name: 'PersonRealnameStep1'
        })
      } else {
        // 更新依赖数据
        this.updateDepData()
      }
    },

    // 初始化空页面数据
    initEmptyPageData() {
      const step1CachePageData = this._step1CachePageData
      this.pageData = this.makeEmptyPageDataTemplate()
      this.pageData.userType = (step1CachePageData.busTypeData || {}).userType
      this.pageData.isDelegate = !!((step1CachePageData.busTypeData || {}).isDelegate)
      this.pageData.vin = (step1CachePageData.carCardData || {}).vin || ''
      this.pageData.masterData.basicInfoData.vin = this.pageData.vin
    },
    // 从缓存恢复数据
    restorePageDataFromCache() {
      const step2CachePageData = this._step2CachePageData
      if (this.isValidObject(step2CachePageData)) {
        this.pageData = this.cloneObject(step2CachePageData)
      } else {
        this.initEmptyPageData()
      }
    },
    // 更新依赖前一步的数据
    updateDepData() {
      const step1CachePageData = this._step1CachePageData
      this.pageData.userType = (step1CachePageData.busTypeData || {}).userType
      this.pageData.isDelegate = !!((step1CachePageData.busTypeData || {}).isDelegate)
      this.pageData.vin = (step1CachePageData.carCardData || {}).vin || ''
      if (this.isValidObject(this.pageData.masterData) && this.isValidObject(this.pageData.masterData.basicInfoData)) {
        this.pageData.masterData.basicInfoData.vin = this.pageData.vin
      }
    },

    // 获取缓存的 step page data
    initStepCachePageData() {
      this._step1CachePageData = this.cacheGetStepData('PersonRealnameStep1')
      this._step2CachePageData = this.cacheGetStepData(this.cacheKey)

      if (this._step1CachePageData) {
        const carCardData = this._step1CachePageData.carCardData || {}
        this.attachment = {
          vin: carCardData.vin,
          iccid: carCardData.iccidList.filter(item => item.iccid !== '').map(item => item.iccid)
        }
      }
    },
    // 是否可以进入当前页检查
    async canEnter() {
      const step1CachePageData = this._step1CachePageData
      const result = await this.step1Validate(step1CachePageData)
      return result
    },

    // 上一步
    clickPrevStep() {
      this.$router.push({
        name: 'PersonRealnameStep1',
        params: {
          from: 'prev'
        }
      })
    },
    // 下一步
    async clickNextStep() {
      try {
        const validateList = [
          this.$refs.masterBasicInfo.validate(),
          this.$refs.masterCertInfo.validate(),
          this.$refs.masterFileInfo.validate(),
          this.$refs.masterConcatInfo.validate()
        ]
        if (this.pageData.isDelegate) {
          validateList.push(...[
            this.$refs.delegateBasicInfo.validate(),
            this.$refs.delegateCertInfo.validate(),
            this.$refs.delegateFileInfo.validate(),
            this.$refs.delegateConcatInfo.validate()
          ])
        }
        await Promise.all(validateList)

        // 校验车主和委托人证件信息
        if (this.pageData.isDelegate) {
          const masterCertInfo = this.$refs.masterCertInfo.getPendingCacheData()
          const delegateCertInfo = this.$refs.delegateCertInfo.getPendingCacheData()
          if (masterCertInfo.type === delegateCertInfo.type && masterCertInfo.no === delegateCertInfo.no) {
            this.errorTips('车主证件信息与委托代办人证件信息一致，请更换')
            return
          }
        }
        // 手机号校验成功，则跳转下一步
        this.clickNextStepHandler()
      } catch (e) {
        console.error('校验错误：', e)
        e.anchor()
      }
    },
    async clickNextStepHandler() {
      const step2CachePageData = this.makeEmptyPageDataTemplate()

      step2CachePageData.userType = this.pageData.userType
      step2CachePageData.isDelegate = this.pageData.isDelegate
      step2CachePageData.vin = this.pageData.vin

      const masterBasicInfoData = this.$refs.masterBasicInfo.getPendingCacheData()
      const masterCertInfoData = this.$refs.masterCertInfo.getPendingCacheData()
      const masterFileInfoData = this.$refs.masterFileInfo.getPendingCacheData()
      const masterConcatInfoData = this.$refs.masterConcatInfo.getPendingCacheData()

      step2CachePageData.masterData = {
        basicInfoData: masterBasicInfoData,
        certInfoData: masterCertInfoData,
        fileInfoData: masterFileInfoData,
        concatInfoData: masterConcatInfoData
      }

      // 校验参数
      let phoneValidParams = {
        phone: masterConcatInfoData.phone,
        captcha: masterConcatInfoData.veCode
      }

      if (this.pageData.isDelegate) {
        const delegateBasicInfoData = this.$refs.delegateBasicInfo.getPendingCacheData()
        const delegateCertInfoData = this.$refs.delegateCertInfo.getPendingCacheData()
        const delegateFileInfoData = this.$refs.delegateFileInfo.getPendingCacheData()
        const delegateConcatInfoData = this.$refs.delegateConcatInfo.getPendingCacheData()

        step2CachePageData.delegateData = {
          basicInfoData: delegateBasicInfoData,
          certInfoData: delegateCertInfoData,
          fileInfoData: delegateFileInfoData,
          concatInfoData: delegateConcatInfoData
        }

        phoneValidParams = {
          phone: delegateConcatInfoData.phone,
          captcha: delegateConcatInfoData.veCode
        }
      }

      this.cacheSetStepData(this.cacheKey, step2CachePageData)
      // 如果当前是平板下，调用h5的接口，跳转腾讯活体
      if (window.OS.isTablet) {
        // 请求入参
        const reqData = this.getSubmitPersonRealNameAuthParams({
          step1Data: this.cacheGetStepData('PersonRealnameStep1'),
          step2Data: this.cacheGetStepData('PersonRealnameStep2')
        })
        // 开始提交接口
        const { h5LivenessUrl } = await submitPersonRealNameAuthH5({
          ...(reqData || {}),
          source: 'PAD'
        })
        // 跳转去活体
        window.location.href = h5LivenessUrl
        return
      }

      // 校验手机号输入是否正确
      await checkSmsCaptcha(phoneValidParams)

      this.$router.push({
        name: 'PersonRealnameStep3'
      })
    },

    makeEmptyPageDataTemplate() {
      return {
        userType: '',
        isDelegate: false,
        vin: '',
        masterData: {
          basicInfoData: {
            vin: ''
          }
        },
        delegateData: {
          basicInfoData: {}
        }
      }
    },

    onReadCert(data, type) {
      if (type === 'master') {
        this.$set(this.pageData.masterData.basicInfoData, 'name', data.name)
        this.$set(this.pageData.masterData.basicInfoData, 'sex', data.gender)
        this.$refs.masterCertInfo.validate()
      } else {
        this.$set(this.pageData.delegateData.basicInfoData, 'name', data.name)
        this.$set(this.pageData.delegateData.basicInfoData, 'sex', data.gender)
        this.$refs.delegateCertInfo.validate()
      }
      this.$refs.masterBasicInfo.validate()
    }
  }
}
</script>

<style lang="scss">
.page-person-real-step2 {
  padding-bottom: 64px;
  .next-step {
    z-index: 5;
  }
}
</style>
