<template>
  <div class="page">
    <pageTitle title="企业实名认证" />
    <steps :data="dict.enterpriseRealnameSteps" :index="2" />
    <page-module name="责任人基本信息" icon="info">
      <CompBasicInfo ref="baseInfo" :data="baseData" type="enterprise" />
    </page-module>
    <page-module name="证件信息" icon="idcard">
      <CompCertificateInfo ref="certInfo" :data="certData" @read-cert="onReadCert" />
    </page-module>
    <page-module name="文件信息" icon="folder">
      <el-row>
        <el-col :span="12">
          <FileInfo ref="contractInfo" :sign="true" :data="contractData" :upload-type="['camera', 'sign']" :attachment-url="attachmentUrl" sign-key="companyAgreement" label="入网协议"/>
        </el-col>
        <el-col :span="12">
          <FileInfo ref="fileInfo" :data="fileData" label="企业实名认证授权书"/>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <FileInfo ref="dutyInfo" :sign="true" :data="dutyData" :upload-type="['camera', 'sign']" sign-key="realnameNotice" label="责任告知书"/>
        </el-col>
      </el-row>
    </page-module>
    <page-module name="联系信息" icon="tel">
      <CompConcatInfo ref="concatInfo" :data="concatData" />
    </page-module>
    <div class="next-step">
      <el-button size="small" plain @click="onPrevStep">上一步</el-button>
      <el-button size="small" type="primary" @click="onNextStep">下一步</el-button>
    </div>
    <CompAttachment :vin="attachment.vin" :file-id="attachment.fileId" @change="handleAttachmentChange" />
  </div>
</template>
<script>
import { checkSmsCaptcha } from '@/api/realname-person'
import { submitEnterpriseRnrWithFile, submitEnterpriseRnr } from '@/api/realname-enterprise'
import { mapGetters } from 'vuex'
import CompAttachment from '@/components/CompAttachment'
import CompBasicInfo from '@/components/CompBasicInfo'
import CompCertificateInfo from '@/components/CompCertificateInfo'
import CompConcatInfo from '@/components/CompConcatInfo'
import FileInfo from '@/components/FileInfo'
import Common from '@/components/Common'
export default {
  name: 'EnterpriseRealnameStep3',
  components: {
    CompAttachment,
    CompBasicInfo,
    CompCertificateInfo,
    FileInfo,
    CompConcatInfo
  },
  mixins: [Common],
  data() {
    return {
      pageData: {
        baseData: {},
        certData: {},
        fileData: {},
        contractData: {},
        dutyData: {},
        concatData: {}
      },
      attachment: {
        vin: [],
        fileId: ''
      },
      attachmentUrl: ''
    }
  },
  computed: {
    ...mapGetters(['dict', 'deviceType']),
    baseData() {
      return this.pageData.baseData || {}
    },
    certData() {
      return this.pageData.certData || {}
    },
    fileData() {
      return this.pageData.fileData || {}
    },
    dutyData() {
      return this.pageData.dutyData || {}
    },
    concatData() {
      return this.pageData.concatData || {}
    },
    contractData() {
      return this.pageData.contractData || {}
    }
  },
  created() {
    this.init()
  },
  activated() {
    this.$refs.baseInfo.clearValidate()
    this.$refs.certInfo.clearValidate()
    this.$refs.contractInfo.clearValidate()
    this.$refs.fileInfo.clearValidate()
    this.$refs.dutyInfo.clearValidate()
    this.$refs.concatInfo.clearValidate()
  },
  methods: {
    /**
     * 附件改变方法
     */
    handleAttachmentChange(val) {
      this.attachmentUrl = val
    },
    init() {
      this.getCacheData()
      if (this.$route.params.from === 'prev') {
        this.restoreCacheData()
      } else {
        this.resetStepData()
      }
      // 从缓存中取出数据
      const stepPad = this.cacheGetStepData('EnterpriseRealnameStepPad1') || {}
      const stepPc = this.cacheGetStepData('EnterpriseRealnameStep1') || {}
      this.attachment = {
        vin: stepPad.iccidList || [],
        fileId: stepPc.checkData ? stepPc.checkData.fileId : ''
      }
    },

    getCacheData() {
      this.cacheData = this.cacheGetStepData(this.cacheKey)
    },

    restoreCacheData() {
      if (this.isValidObject(this.cacheData)) {
        this.pageData = this.cloneObject(this.cacheData)
      } else {
        this.resetStepData()
      }
    },

    resetStepData() {
      this.pageData = {
        baseData: {},
        certData: {},
        fileData: {},
        dutyData: {},
        concatData: {},
        contractData: {}
      }
    },

    onReadCert(data) {
      this.$set(this.pageData.baseData, 'name', data.name)
      this.$set(this.pageData.baseData, 'sex', data.gender)
      this.$refs.baseInfo.validate()
    },

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

    getSubmitData() {
      const stepPad1Data = this.cacheGetStepData('EnterpriseRealnameStepPad1') || {}
      const step1Data = this.cacheGetStepData('EnterpriseRealnameStep1') || {}
      const step2Data = this.cacheGetStepData('EnterpriseRealnameStep2') || {}
      const step3Data = this.cacheGetStepData('EnterpriseRealnameStep3') || {}
      const ret = {
        companyName: step2Data.baseData.companyName,
        companyType: step2Data.baseData.companyType,
        industryType: step2Data.baseData.industryType,
        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),

        vinList: stepPad1Data.vinList ? stepPad1Data.vinList.map(vin => vin.vin) : '',

        fileId: step1Data.checkData ? step1Data.checkData.fileId : '',

        isVehicleCompany: 0
      }
      return ret
    },

    /**
    * 下一步
    * @time 2022-04-23 15:50:05
    */
    async onNextStep() {
      try {
        const valid = [
          this.$refs.baseInfo.validate(),
          this.$refs.certInfo.validate(),
          this.$refs.contractInfo.validate(),
          this.$refs.fileInfo.validate(),
          this.$refs.dutyInfo.validate(),
          this.$refs.concatInfo.validate()
        ]
        await Promise.all(valid)

        const baseData = this.$refs.baseInfo.getPendingCacheData()
        const certData = this.$refs.certInfo.getPendingCacheData()
        const contractData = this.$refs.contractInfo.getPendingCacheData()
        const fileData = this.$refs.fileInfo.getPendingCacheData()
        const dutyData = this.$refs.dutyInfo.getPendingCacheData()
        const concatData = this.$refs.concatInfo.getPendingCacheData()

        this.cacheSetStepData(this.cacheKey, { baseData, certData, fileData, contractData, dutyData, concatData })
        // 如果当前是平板
        if (window.OS.isTablet) {
          // 当前提交的数据
          const reqData = this.getSubmitData()
          // 提交接口
          const { h5LivenessUrl } = await (this.$store.getters.deviceType === 'aio' ? submitEnterpriseRnrWithFile : submitEnterpriseRnr)({
            ...(reqData || {}),
            source: 'PAD'
          })
          // 跳转到活体认证页面
          window.location.href = h5LivenessUrl
          return
        }

        // 校验手机号输入是否正确
        await checkSmsCaptcha({
          phone: concatData.phone,
          captcha: concatData.veCode
        })

        this.$router.push({ name: 'EnterpriseRealnameStep4' })
      } catch (e) {
        console.log(e)
        e.anchor()
      }
    }
  }
}
</script>
