<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" class="page">
    <el-form ref="form" :model="form" label-width="80px" label-position="top" size="small">
      <page-module name="车卡文件上传" icon="folder">
        <div class="download-template-file">
          <span class="name">文件上传</span>
          <el-link type="primary" icon="el-icon-download" @click="downloadTemplateFile">下载模板</el-link>
        </div>
        <div class="file-upload-wrap">
          <div class="file-upload-l">
            <el-upload
              ref="upload"
              :limit="1"
              :data="upload.data"
              :headers="upload.headers"
              :file-list="form.fileList"
              :action="upload.action"
              :before-upload="onBefore"
              :on-remove="onRemove"
              :on-success	="onSuccess"
              :on-error	="onError"
              :on-exceed="onExceed"
              class="file-uploader"
              accept=".xls,.xlsx"
              name="file"
              multiple>
              <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
              <el-button :disabled="checkBtnStatus" style="margin-left: 8px;" size="small" type="primary" @click="checkVinData">校验数据</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件，文件大小不超过10MB，记录数不超过5000条</div>
            </el-upload>
          </div>
          <div class="file-upload-r"/>
        </div>
      </page-module>
      <page-module v-if="showCheckData" name="校验结果" icon="check">
        <div class="file-upload-check">
          <div v-if="form.checkData.failCount > 0" class="check-l fail"/>
          <div v-else class="check-l success"/>
          <div class="check-r">
            <template v-if="form.checkData.failCount > 0">
              <div class="info">{{ form.checkData.failCount }}条车卡数据验证{{ form.checkData.totalCount === form.checkData.failCount ? '全部' : '' }}失败</div>
              <div class="tips">异常数据不进入后续的实名认证环节</div>
              <div class="btns">
                <el-button type="primary" plain size="small" icon="el-icon-download" @click="downloadCheckFailFile">下载文件</el-button>
              </div>
            </template>
            <div v-else class="info">全部数据验证成功</div>
          </div>
        </div>
      </page-module>
    </el-form>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { verifyVinCardsTemplateUrl, postVinUpload, verifyVinCards, downloadFailFile } from '@/api/realname-car-enterprise'
export default {
  name: 'CarSimFile',
  components: {},
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      upload: {
        data: {
          rootPath: '',
          path: ''
        },
        headers: {
          'Authorization': `bearer ${getToken()}`
        },
        action: postVinUpload
      },
      form: {
        fileId: '',
        checkData: {},
        fileList: []
      }
    }
  },
  computed: {
    ...mapGetters(['dict']),
    checkBtnStatus() {
      return !this.form.fileId
    },
    showCheckData() {
      const keys = Object.keys(this.form.checkData)
      return keys.length > 0
    }
  },
  watch: {
    data() {
      this.updateInternalData()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.updateInternalData()
    },

    updateInternalData() {
      if (typeof this.data === 'object' && this.data !== null) {
        this.form = {
          fileId: this.data.fileId || '',
          checkData: this.data.checkData || {},
          fileList: this.data.fileList || []
        }
      } else {
        this.form = {
          fileId: '',
          checkData: {},
          fileList: []
        }
      }
    },

    /**
    * 上传前校验
    * @time 2021-12-06 10:02:49
    */
    onBefore(file) {
      const type1 = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const type2 = 'application/vnd.ms-excel'
      let isExcel = false
      if (file.type === type1 || file.type === type2) {
        isExcel = true
      }
      const isLt10M = file.size / 1024 / 1024 <= 10
      if (!isExcel) {
        this.$message.error('车卡信息文件只支持excel文件')
        return false
      }
      if (!isLt10M) {
        this.$message.error('车卡信息文件大小不能超过10MB')
        return false
      }
    },

    /**
    * 文件上传
    * @time 2021-12-06 10:02:33
    */
    onSuccess(json) {
      if (json.success) {
        this.$message.success('文件上传成功')
        const data = json.data || {}
        this.form.fileList = [{
          name: data.fileName,
          url: data.accessUrl,
          uuid: data.uuid
        }]
        this.form.fileId = data.uuid
      }
    },

    /**
    * 上传错误
    * @param  {Object} err 错误对象
    * @time 2021-12-15 14:14:49
    */
    onError() {
      this.$message.error('文件上传失败')
      this.$refs.upload.clearFiles()
      this.onRemove()
    },

    /**
    * 响应删除文件操作
    * @time 2021-12-09 09:52:56
    */
    onRemove(file, fileList) {
      this.form = {
        fileId: '',
        checkData: {},
        fileList: []
      }
      this.$emit('check', this.form)
    },

    /**
    * 上传数量限制
    * @time 2021-12-06 10:03:10
    */
    onExceed() {
      this.$message.error('最多上传1个excel文件')
    },

    /**
    * 校验车卡信息
    * @time 2022-04-23 14:27:21
    */
    checkVinData() {
      this.fullscreenLoading = true
      return verifyVinCards({ fileId: this.form.fileId	}).then(data => {
        this.fullscreenLoading = false
        this.form.checkData = data
        this.$emit('check', this.form)
      }).catch(() => {
        this.fullscreenLoading = false
        this.$emit('check', {})
      })
    },

    getFormData() {
      return this.form
    },

    // 获取待缓存数据
    getPendingCacheData() {
      return this.getFormData()
    },

    /**
    * 下载校验失败的文件
    * @time 2022-04-23 15:02:50
    */
    downloadCheckFailFile() {
      // location.href = `${process.env.VUE_APP_ROUTER}static/template.xlsx`
      this.fullscreenLoading = true
      return downloadFailFile({
        'uuid': this.form.checkData.fileId,
        'fileName': this.form.checkData.fileName
      }).then(() => {
        this.fullscreenLoading = false
      }).catch(() => {
        this.fullscreenLoading = false
      })
    },

    /**
    * 下载车卡模板文件
    * @time 2022-04-23 15:02:50
    */
    downloadTemplateFile() {
      location.href = verifyVinCardsTemplateUrl
    }
  }
}
</script>

<style scoped lang="scss">
.download-template-file {
  margin: 20px 0 0 0;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #71747B;
  .name {
    margin-right: 16px;
  }
}
.file-upload-wrap {
  margin: 10px auto 0;
  display: flex;
  justify-content: space-between;
  .file-upload-l {
    flex: 1;
  }
  .file-upload-r {
    width: 238px;
    height: 144px;
    background: url(../../../assets/image/file_upload.png) no-repeat 0 0 / 238px 144px;
  }
}
.file-upload-check {
  margin: 20px auto 0;
  display: flex;
  .check-l {
    width: 483px;
    height: 200px;
    flex: none;
    &.success {
      background: url(../../../assets/image/result_img_success.png) no-repeat 0 0;
    }
    &.fail {
      background: url(../../../assets/image/result_img_fail.png) no-repeat 0 0;
    }
  }
  .check-r {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    flex: 1;
    .info {
      font-size: 16px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #111;
    }
    .tips {
      margin: 8px auto 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(132, 133, 138, 0.7);
    }
  }
}
</style>
