<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" class="page">
    <pageTitle title="车企实名认证" />
    <steps :data="dict.enterpriseRealnameSteps" :index="3" />
    <PageModuleTabs
      :tabs="TABS"
      v-if="device.showTakePhoto"
      v-model="tabName"
    >
      <CompFaceRecognition ref="faceInfo" :type="livenessType" :take="tabName == 'carmer'" :data="faceData"/>
    </PageModuleTabs>
    <page-module v-else name="活体视频上传" icon="video">
      <CompFaceRecognition ref="faceInfo" :type="livenessType" :data="faceData"/>
    </page-module>
    <div class="next-step">
      <el-button size="small" plain @click="onPrevStep">上一步</el-button>
      <el-button size="small" type="primary" @click="onSubmit">提交</el-button>
    </div>
    <comp-confirm
      :show.sync="showSuccessConfirm"
      :desc="successConfirmDesc"
      :show-cancel-btn="false"
      type="success"
      @on-sure="onSure"
    />
    <comp-confirm
      :show.sync="showErrorConfirm"
      :desc="errorConfirmDesc"
    />
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getLivenessCode, carEnterpriseSubmitRnr } from '@/api/realname-car-enterprise'
import CompFaceRecognition from '@/components/CompFaceRecognition'
import PageModuleTabs from '@/components/PageModule/tabs'
import CompConfirm from '@/components/CompConfirm'
import Common from '@/components/Common'

const TABS = [
  {
    label: '活体视频上传',
    value: 'video',
    icon: require('@/assets/image/video@2x.png')
  },
  {
    label: '在线拍摄视频',
    value: 'carmer',
    icon: require('@/assets/image/icon_user@2x.png')
  }
]

export default {
  name: 'CarEnterpriseRealnameStep4',
  components: {
    CompFaceRecognition,
    CompConfirm,
    PageModuleTabs
  },
  mixins: [Common],
  data() {
    return {
      TABS,
      fullscreenLoading: false,
      showSuccessConfirm: false,
      successConfirmDesc: '',
      pageData: {},
      showErrorConfirm: false,
      livenessType: '',
      errorConfirmDesc: '',
      tabName: 'video'
    }
  },
  computed: {
    ...mapGetters(['dict', 'device']),
    faceData() {
      return this.pageData.faceData || {}
    }
  },
  created() {
    this.init()
  },
  methods: {
    errorTips(errMsg) {
      this.showErrorConfirm = true
      this.errorConfirmDesc = errMsg
    },
    successTips(msg) {
      this.showSuccessConfirm = true
      this.successConfirmDesc = msg
    },

    /**
    * 上一步
    * @time 2022-04-23 16:33:24
    */
    onPrevStep() {
      this.$router.push({ name: 'CarEnterpriseRealnameStep3', params: { from: 'prev' }})
    },

    getSubmitData() {
      const step1Data = this.cacheGetStepData('CarEnterpriseRealnameStep1')
      const step2Data = this.cacheGetStepData('CarEnterpriseRealnameStep2')
      const step3Data = this.cacheGetStepData('CarEnterpriseRealnameStep3')
      const ret = {
        companyName: step2Data.baseData.companyName,
        companyCertType: step2Data.certData.companyCertType,
        licenseImages: step2Data.certData.licenseImages.map(item => item.uuid),
        companyCertNumber: step2Data.certData.companyCertNumber,
        companyCertAddress: step2Data.certData.companyCertAddress,
        companyContactAddress: step2Data.certData.companyContactAddress,

        corporationName: step3Data.baseData.name,
        corporationGender: step3Data.baseData.sex,
        corporationCertType: step3Data.certData.type,
        corporationPhotoPic: step3Data.certData.photoUrls.filter(item => item.url.id !== null).map(item => item.url.id),
        corporationCertNumber: step3Data.certData.no,
        corporationCertAddress: step3Data.certData.address,
        corporationCertExpirationDate: step3Data.certData.validDate,
        corporationCertEffectiveDate: step3Data.certData.certEffectiveDate,
        corporationContactAddress: step3Data.certData.connectAddress,
        corporationPhone: step3Data.concatData.phone,
        verificationCode: step3Data.concatData.veCode,

        authorizationLetterPic: step3Data.fileData.fileList.map(item => item.uuid),

        dutyPic: step3Data.dutyData.fileList.map(item => item.uuid),

        contractPic: step3Data.contractData.fileList.map(item => item.uuid),

        liveVerificationVideo: this.$refs.faceInfo.getFormData().fileList[0].uuid,

        fileId: step1Data.checkData.fileId,

        requestId: this._remoteLiveData.requestId,

        isVehicleCompany: 1
      }
      return ret
    },

    async init() {
      this.fullscreenLoading = true
      this._remoteLiveData = await this.getLivenessCode()
      this.fullscreenLoading = false
      this.livenessType = this._remoteLiveData ? this._remoteLiveData.livenessType : ''
      this.pageData = {
        faceData: {
          number: this._remoteLiveData ? this._remoteLiveData.livenessCode : ''
        }
      }
    },

    async onSubmit() {
      if (this.faceData.number === '') {
        this.errorTips('获取活体数字验证码失败，请刷新页面重试')
        return
      }
      try {
        await this.$refs.faceInfo.validate()
        this.fullscreenLoading = true
        const respData = await this.carEnterpriseSubmitRnr(this.getSubmitData())
        this.fullscreenLoading = false
        if (!respData.isOk) {
          this.errorTips(respData.data.message || '实名认证失败')
          return
        }
        if (respData.data.verifyStatus === 0) {
          this.successTips('实名认证成功')
        } else if (respData.data.verifyStatus === 1) {
          this.successTips('已转入人工审核，请注意查询认证进度')
        } else {
          this.errorTips('实名认证失败')
        }
      } catch (e) {
        e.anchor()
      }
    },

    async getLivenessCode() {
      try {
        const ret = await getLivenessCode()
        return ret
      } catch (e) {
        return null
      }
    },

    async carEnterpriseSubmitRnr(params) {
      try {
        const respData = await carEnterpriseSubmitRnr({
          data: {
            ...params
          },
          hideToast: true
        })
        return {
          isOk: true,
          data: respData
        }
      } catch (e) {
        return {
          isOk: false,
          data: e
        }
      }
    },

    onSure() {
      sessionStorage.clear()
      this.$router.push({ name: 'HomePage' })
    }
  }
}
</script>
