<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" element-loading-spinner="page-loading" class="page">
    <pageTitle title="一车多卡绑定" />
    <steps :data="stepsData" :index="stepIndex" :margin="margin" />
    <page-module name="车卡信息" icon="car">
      <comp-car-card ref="compCarCard" :data="cacheData" souce-page="BIND" />
    </page-module>
    <div class="next-step">
      <el-button size="small" type="primary" @click="handleNext">下一步</el-button>
    </div>
  </div>
</template>

<script>
import Common from '@/components/Common'
import CompCarCard from '@/components/CompCarCard'
import { checkVinCard } from '@/api/iccid'

export default {
  name: 'CardBindingStepOne',
  components: {
    CompCarCard
  },
  mixins: [Common],
  data() {
    return {
      fullscreenLoading: false,
      stepsData: ['车卡信息录入', '客户确认'],
      stepIndex: 0,
      margin: '0 200px 0 200px',
      cacheData: null
    }
  },
  created() {
    this.init()
  },
  methods: {
    /**
    * 初始化
    * @time 2022-04-24 16:50:27
    */
    init() {
      if (this.$route.params.from) {
        // 表明是返回上一步 读缓存
        this.cacheData = this.cacheGetStepData(this.cacheKey)
      }
    },

    /**
    * 下一步操作
    * @time 2022-04-24 16:50:14
    */
    async handleNext() {
      try {
        await this.$refs.compCarCard.validate()
        const data = this.$refs.compCarCard.getPendingCacheData()
        // 校验车卡关系
        const verifyData = {
          iccidList: [],
          vin: data.vin,
          rnrId: data.data,
          businessType: 5
        }
        data.iccidList.forEach(item => {
          if (item.iccid !== '') {
            verifyData.iccidList.push(item.iccid)
          }
        })
        this.fullscreenLoading = true
        const retData = await checkVinCard(verifyData)
        let isAlert = false
        if (retData.iccidVerifyResults && retData.iccidVerifyResults.length > 0) {
          const resList = retData.iccidVerifyResults
          for (let i = 0; i < resList.length; i++) {
            if (!resList[i].exist) {
              // 车卡关系不正常
              isAlert = true
              break
            }
          }
        }
        this.fullscreenLoading = false
        if (isAlert) {
          this.$message.error('数据校验不通过')
          return false
        }
        // 写入缓存
        this.cacheSetStepData(this.cacheKey, {
          vin: data.vin,
          iccidList: data.iccidList
        })
        // 前往下一步
        this.$router.push({
          name: 'CardBindingStepTwo'
        })
      } catch (e) {
        this.fullscreenLoading = false
        if (e.anchor) {
          e.anchor()
        }
      }
    }
  }
}
</script>
