<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" class="page-person-real-step3">
    <page-title title="完成人脸识别"/>
    <steps :data="stepData" :index="2"/>
    <PageModuleTabs
      :tabs="TABS"
      v-if="device.showTakePhoto"
      v-model="tabName"
    >
      <CompFaceRecognition ref="face" :type="livenessType" :take="tabName == 'carmer'" :data="faceData"/>
    </PageModuleTabs>
    <page-module v-else name="活体视频上传" icon="video">
      <CompFaceRecognition ref="face" :type="livenessType" :data="faceData"/>
    </page-module>
    <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"
    />
    <comp-confirm
      :show.sync="showSuccessConfirm"
      :desc="successConfirmDesc"
      type="success"
      @on-sure="successSureHandler"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import PageModuleTabs from '@/components/PageModule/tabs'
import { submitPersonRealNameAuth, getLivenessCode } from '@/api/realname-person'
import PageTitle from '@/components/PageTitle'
import Steps from '@/components/Steps'
import Common from '@/components/Common'
import CompConfirm from '@/components/CompConfirm'
import CompFaceRecognition from '@/components/CompFaceRecognition'
import ValidateStep from './components/validate-step'
import SelfCommon 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: 'PersonRealnameStep3',
  components: {
    PageTitle,
    Steps,
    CompConfirm,
    CompFaceRecognition,
    PageModuleTabs
  },
  mixins: [Common, SelfCommon, ValidateStep],
  data() {
    return {
      fullscreenLoading: false,
      showErrorConfirm: false,
      errorConfirmDesc: '',
      showSuccessConfirm: false,
      successConfirmDesc: '',
      stepData: ['车卡信息录入', '填写客户信息', '完成人脸识别'],
      livenessType: '',
      pageData: {},
      tabName: 'video',
      TABS
    }
  },
  computed: {
    ...mapGetters(['device']),
    faceData() {
      return this.pageData.faceData || {}
    }
  },
  methods: {
    errorTips(errMsg) {
      this.showErrorConfirm = true
      this.errorConfirmDesc = errMsg
    },
    successTips(msg) {
      this.showSuccessConfirm = true
      this.successConfirmDesc = msg
    },

    async init() {
      this.fullscreenLoading = true
      this._remoteLiveData = await this.getLivenessCode()
      this.fullscreenLoading = false

      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() {
      this.pageData = this.makeEmptyPageDataTemplate()
      this.livenessType = this._remoteLiveData ? this._remoteLiveData.livenessType : ''
      this.pageData.faceData = {
        number: this._remoteLiveData ? this._remoteLiveData.livenessCode : ''
      }
    },
    // 从缓存恢复数据
    restorePageDataFromCache() {
      const step3CachePageData = this._step3CachePageData
      if (this.isValidObject(step3CachePageData)) {
        this.pageData = this.cloneObject(step3CachePageData)
      } else {
        this.initEmptyPageData()
      }
    },
    updateDepData() {
      // todo
    },

    // 获取缓存的 step page data
    initStepCachePageData() {
      this._step1CachePageData = this.cacheGetStepData('PersonRealnameStep1')
      this._step2CachePageData = this.cacheGetStepData('PersonRealnameStep2')
      this._step3CachePageData = this.cacheGetStepData(this.cacheKey)
    },
    // 是否可以进入当前页检查
    async canEnter() {
      const step1IsOk = await this.step1Validate(this._step1CachePageData)
      const step2IsOk = await this.step2Validate(this._step2CachePageData)
      return step1IsOk && step2IsOk
    },

    // 上一步
    clickPrevStep() {
      this.$router.push({
        name: 'PersonRealnameStep2',
        params: {
          from: 'prev'
        }
      })
    },
    // 下一步
    async clickNextStep() {
      if (this.faceData.number === '') {
        this.errorTips('获取活体数字验证码失败，请刷新页面重试')
        return
      }
      try {
        await this.$refs.face.validate()
        this.clickNextStepHandler()
      } catch (e) {
        e.anchor()
      }
    },
    async clickNextStepHandler() {
      const submitData = {
        step1Data: this._step1CachePageData,
        step2Data: this._step2CachePageData,
        step3Data: {
          fileData: this.$refs.face.getFormData(),
          number: this.faceData.number,
          requestId: this._remoteLiveData.requestId
        }
      }
      this.fullscreenLoading = true
      const respData = await this.submitPersonRealNameAuth(this.getSubmitPersonRealNameAuthParams(submitData))
      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('实名认证失败')
      }
    },
    successSureHandler() {
      this.$router.push({
        name: 'Home'
      })
    },

    makeEmptyPageDataTemplate() {
      return {
        faceData: null
      }
    },

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

  }
}
</script>

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