<template>
  <Page title="车卡信息" :show-operation="vinList.length > 0">
    <div class="page-rnr-main-card">
      <ScanCard :success-num="successNum" :fail-num="failNum" :total="vinList.length" @add="handleOpenVin" @scan="handleScanVin">
        <div v-if="vinList.length > 0" class="page-rnr-main-vin-wrapper" slot="content">
          <ErrorWrap v-for="(vin, index) in vinList" :key="vin.vin" :error="!vin.result" :error-message="vin.errorMsg">
            <van-field
              :value="vin.vin"
              :label="index + 1"
              readonly
              input-align="right"
              @click="handleEditVin(index)"
            >
              <template #button>
                <i class="imageicon imageicon-del" @click.stop="handleDeleteVin(index)" />
              </template>
            </van-field>
          </ErrorWrap>
        </div>
      </ScanCard>
    </div>
    <template #slot-operation>
      <van-button :loading="loading" type="primary" class="page-rnr-main-btn-next" round color="linear-gradient(120deg, #4F4CFB 0%, #376FF4 97%)" block @click="handleToNext">下一步</van-button>
    </template>
    <InputActionSheet :visible.sync="sheet.show" :title="sheet.title" :data="sheet.data" :rules="{ vin: 'vin' }" @submit="handleConfirmVin" />
  </Page>
</template>

<script>
import { SET_ENTERPRISE_CARD } from '@/store/modules/rnr'
import { checkVin } from '@/api/rnr'
import Page from '@/components/Page'
import ScanCard from '@/components/ScanCard'
import InputActionSheet from '@/components/InputActionSheet'
import { Toast } from 'vant'
import ErrorWrap from '@/components/ErrorWrap'

export default {
  name: 'RnrEnterpriseCard',
  components: { Page, ScanCard, InputActionSheet, ErrorWrap },
  data() {
    return {
      sheet: {
        show: false,
        title: '',
        data: ''
      },
      successNum: 0,
      failNum: 0,
      loading: false,
      showOperation: false,
      vinList: []
    }
  },
  methods: {
    /**
     * 打开vin码输入的弹框
     */
    handleOpenVin() {
      // 弹出框
      this.sheet.title = '添加VIN码'
      this.sheet.show = true
      this.sheet.data = ''
      this.sheet.vinIndex = -1
    },

    /**
     * 编辑当前vin码
     * @param index 当前vin码所处的索引
     */
    handleEditVin(index) {
      // 弹出框
      this.sheet.title = '修改VIN码'
      this.sheet.show = true
      this.sheet.vinIndex = index
      this.sheet.data = this.vinList[index].vin
    },

    /**
     * 删除指定所有的vin号
     * @param index 删除行数据
     */
    handleDeleteVin(index) {
      this.vinList.splice(index, 1)
    },

    /**
     * 跳转到下一页
     */
    async handleToNext() {
      // 展示loading框
      this.loading = true
      try {
        // iccid的集合
        const iccidList = []
        // 当前输入的vin码
        const vinList = this.vinList.map(vin => {
          // 重置校验结果
          vin.result = true
          vin.errorMsg = ''
          return vin.vin
        })
        // 开始校验数据
        const { checkList } = await checkVin({ vinList })
        // 校验失败的，将错误信息赋值给原来的组件
        const failVinList = checkList.filter(vin => {
          this.vinList.forEach(vinItem => {
            if (vinItem.vin === vin.vin) {
              vinItem.result = vin.checkResult
              vinItem.errorMsg = vin.errorMsg
              // 获取集合
              iccidList.push({
                vin: vin.vin,
                iccidList: vin.iccidList
              })
            }
          })
          return !vin.checkResult
        })
        // 校验失败的vin数量
        this.failNum = failVinList.length
        // 成功的vin数量
        this.successNum = vinList.length - this.failNum
        // 如果车卡关系校验有失败的
        if (failVinList.length > 0) {
          Toast('车卡关系校验不成功，请重新输入')
          this.loading = false
          return
        }
        // 将值保存到store中
        this.$store.commit(`rnr/${SET_ENTERPRISE_CARD}`, { vinList, iccidList })
        // 开始跳转页面
        this.$router.push({ name: 'RnrEnterpriseCert' })
      } catch (error) {
        console.error(error)
      }
      this.loading = false
    },

    /**
     * 扫码添加的vin码
     * @param vin 待添加的vin
     */
    handleScanVin(vin) {
      // 设置当前索引是-1
      this.sheet.vinIndex = -1
      // 添加一个vin
      this.handleConfirmVin(vin)
    },

    /**
     * 同步用户输入的vin码
     * @param vin 当前输入的vin码
     */
    handleConfirmVin(vin) {
      // 当前vin码集合
      const { vinIndex } = this.sheet
      // 如果当前是编辑
      if (vinIndex >= 0) {
        // 重新赋值
        this.vinList[vinIndex].vin = vin
        // 清空之前的校验
        this.vinList[vinIndex].result = true
        this.vinList[vinIndex].errorMsg = ''
      } else {
        this.vinList.push({
          result: true,
          vin,
          errorMsg: ''
        })
      }
    }
  }
}
</script>

<style lang="scss">
.page-rnr {
  .component-scan-code {
    .van-cell__title {
      padding-left: 32px;
    }
    .imageicon-del {
      margin-bottom: -6px;
      margin-left: 64px;
    }
  }
  .page-rnr-main-vin-wrapper {
    max-height: calc(100vh - 720px);
    overflow: auto;
  }
  .page-rnr-main-fixed-btn-group {
    .page-rnr-main-btn-next {
      height: 96px;
    }
  }
}
</style>
