<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" class="page">
    <pageTitle title="车企实名认证" />
    <steps :data="dict.carEnterpriseRealnameSteps" :index="2" />
    <page-module name="责任人信息" icon="info">
      <FlowPersonInfo ref="personInfo" :data="personData"/>
    </page-module>
    <page-module name="文件信息" icon="folder">
      <el-row>
        <el-col :span="12">
          <FileInfo ref="contractInfo" :data="contractData" :upload-type="['camera', 'sign']" sign-key="companyAgreement" mode="preview" label="入网协议"/>
        </el-col>
        <el-col :span="12">
          <FileInfo ref="fileInfo" :data="fileData" mode="preview" label="企业实名认证授权书"/>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <FileInfo ref="dutyInfo" :data="dutyData" :upload-type="['camera', 'sign']" sign-key="realnameNotice" mode="preview" label="责任告知书"/>
        </el-col>
      </el-row>
    </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 FlowPersonInfo from './components/flow-person-info'
import FileInfo from '@/components/FileInfo'
import Common from '@/components/Common'
import CompConfirm from '@/components/CompConfirm'
import { queryCarEnterpriseDetail, submitRnrFollowUp } from '@/api/realname-car-enterprise'

export default {
  name: 'CarEnterpriseRealnameFlow3',
  components: {
    FlowPersonInfo,
    FileInfo,
    CompConfirm
  },
  mixins: [Common],
  data() {
    return {
      fullscreenLoading: false,
      pageData: {
        fileData: {},
        contractData: {},
        dutyData: {}
      },
      showSuccessConfirm: false,
      successConfirmDesc: '',
      showErrorConfirm: false,
      errorConfirmDesc: ''
    }
  },
  computed: {
    ...mapGetters(['dict']),
    personData() {
      return this.pageData.personData || {}
    },
    fileData() {
      return this.pageData.fileData || {}
    },
    dutyData() {
      return this.pageData.dutyData || {}
    },
    contractData() {
      return this.pageData.contractData || {}
    }
  },
  created() {
    this.getBaseInfo()
    // 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 = {
    //     personData: {},
    //     fileData: {}
    //   }
    // },

    errorTips(errMsg) {
      this.showErrorConfirm = true
      this.errorConfirmDesc = errMsg
    },
    successTips(msg) {
      this.showSuccessConfirm = true
      this.successConfirmDesc = msg
    },

    getBaseInfo() {
      this.fullscreenLoading = true
      return queryCarEnterpriseDetail({}).then(data => {
        this.pageData = {
          personData: {
            name: data.corporationName,
            phone: data.corporationPhone
          },
          fileData: {
            fileList: data.authorizationLetterPic.map(item => {
              return {
                accessUrl: `data:image/png;base64,${item}`
              }
            })
          },
          dutyData: {
            fileList: data.dutyPic.map(item => {
              return {
                accessUrl: `data:image/png;base64,${item}`
              }
            })
          },
          contractData: {
            fileList: data.contractPic.map(item => {
              return {
                accessUrl: `data:image/png;base64,${item}`
              }
            })
          }
        }
        this._submitData = data
        this.fullscreenLoading = false
      }).catch(() => {
        this.fullscreenLoading = false
      })
    },

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

    /**
    * 下一步
    * @time 2022-04-23 15:50:05
    */
    async onSubmit() {
      try {
        await Promise.all([
          this.$refs.personInfo.validate(),
          this.$refs.dutyInfo.validate(),
          this.$refs.fileInfo.validate(),
          this.$refs.contractInfo.validate()
        ])
        const flowStep1Data = this.cacheGetStepData('CarEnterpriseRealnameFlow1')
        // 提交数据
        this.fullscreenLoading = true
        const respData = await this.carEnterpriseSubmitRnr({
          fileId: flowStep1Data.checkData.fileId,
          vehicleEnterpriseId: this._submitData.vehicleEnterpriseId
          // liveVerificationVideo: this._submitData.liveVerificationVideo
        })
        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 carEnterpriseSubmitRnr(params) {
      try {
        const respData = await submitRnrFollowUp({
          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>
