<template>
  <div class="page">
    <pageTitle title="车企实名认证" />
    <steps :data="dict.enterpriseRealnameSteps" :index="1" />
    <page-module name="基本信息" icon="info">
      <BaseInfo ref="baseInfo" :data="baseData" type="car-enterprise"/>
    </page-module>
    <page-module name="证件信息" icon="info">
      <CertInfo ref="certInfo" :data="certData"/>
    </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>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import BaseInfo from '../realname-enterprise/components/base-info'
import CertInfo from '../realname-enterprise/components/cert-info'
import Common from '@/components/Common'
export default {
  name: 'CarEnterpriseRealnameStep2',
  components: {
    BaseInfo,
    CertInfo
  },
  mixins: [Common],
  data() {
    return {
      pageData: {}
    }
  },
  computed: {
    ...mapGetters(['dict']),
    baseData() {
      return this.pageData.baseData || {}
    },
    certData() {
      return this.pageData.certData || {}
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getCacheData()
      if (this.$route.params.from === 'prev') {
        this.restoreCacheData()
      } else {
        this.resetStepData()
      }
    },

    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: {}
      }
    },

    onPrevStep() {
      this.$router.push({ name: 'CarEnterpriseRealnameStep1', params: { from: 'prev' }})
    },

    async onNextStep() {
      try {
        const valid = [
          this.$refs.baseInfo.validate(),
          this.$refs.certInfo.validate()
        ]
        await Promise.all(valid)

        const baseData = this.$refs.baseInfo.getPendingCacheData()
        const certData = this.$refs.certInfo.getPendingCacheData()
        this.cacheSetStepData(this.cacheKey, { baseData, certData })

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