<template>
  <vxe-modal v-model="show" id="importExcelFailModel" width="800" height="600" title="B2B订单导入" @hide="hide" resize
    transfer show-footer v-loading="load">
    <div class="upload" v-if="!uploadRes">
      <div class="upload-name">{{ value.name }}</div>
      <div class="upload-btn" @click="importOrder">{{ value.name ? '重新上传' : '上传' }}</div>
    </div>
    <div class="upload-module" v-if="!uploadRes" @click="loadDownExcel">下载excel模版</div>
    <div class="shop-result" v-if="uploadRes">
      <div class="success">成功：{{ uploadRes.successCount }}</div>
      <div class="err">异常：{{ uploadRes.failureCount }}</div>
    </div>
    <div v-if="uploadRes && uploadRes.failureCount > 0">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column v-for="(val, key) in tableData[0]" v-if="key === '订单编号' || key === '是否成功' || key === '操作信息'"
          :key="key" :prop="key" :label="key === '操作信息' ? '异常原因' : key" show-overflow-tooltip
          :width="key === '操作信息' ? '' : '120'" />
      </el-table>

      <el-pagination @current-change="handleCurrentChange" v-model:current-page="currentPage" :page-size="pageSize"
        :total="total" layout="prev, pager, next, jumper" style="margin-top: 20px; text-align: right" />
    </div>
    <template #footer>
      <div class="btn">
        <el-button type="primary" size="small" @click="uploadErr"
          v-if="uploadRes && uploadRes.failureCount > 0">下载异常数据</el-button>
        <el-button type="primary" size="small" @click="btn" v-if="!uploadRes">完成上传</el-button>
        <el-button plain size="small" @click="show = false">关闭</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { importExc, loadDownModule } from '@/api/omsOrder'
import ExcelHelper from '@/benyun/utils/excelHelper'
// 处理成 table 能用的结构
@Component({ components: {} })
export default class ImportExcelFailModel extends Vue {
  show: boolean = false;
  value: any = {}
  load: boolean = false;
  uploadRes: any = null;
  tableData: any = [];
  currentPage = 1;
  pageSize = 10;
  total = this.tableData.length;
  setShow(v: boolean) {
    this.show = v;
  }
  hide() {
    if (this.uploadRes && this.uploadRes.successCount > 0) {
      this.$emit('handleSuccess')
    }
    this.value = {};
    this.uploadRes = null;
  }
  //下载模版
  loadDownExcel() {
    loadDownModule().then((res: any) => {
      let url = window.URL.createObjectURL(new Blob([res]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", '订单导入模版.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      this.$message({
        message: '下载成功！',
        type: 'success'
      })
    }).catch(() => { })
  }
  //导入
  importOrder() {
    const accept = '.xlsx'
    let input = document.createElement('input')
    input.style.display = 'none'
    input.type = 'file'
    input.accept = accept
    document.body.appendChild(input);
    const that = this;
    input.addEventListener('change', function (e: any) {
      let txt = e.target.files[0];
      let s = txt.name.split('.');
      let suffix = '.' + s[s.length - 1];
      if (accept.indexOf(suffix) == -1) {
        that.$message({ message: '不支持该类型文件上传！' })
        return
      }
      that.value = txt;
    })
    input.click();
    document.body.removeChild(input);
  }
  btn() {
    if (!this.value.name) {
      this.$message('请选择文件！');
      return
    }
    let data = new FormData();
    data.append('file', this.value);
    this.load = true;
    importExc(data).then(res => {
      this.uploadRes = res.data;
      this.tableData = this.transformFailureList(res.data.failureList);
      this.total = this.tableData.length;
      this.currentPage = 1;
      this.tableData = this.pagedData()
      this.load = false;
    }).catch(err => {
      this.load = false;
      if (err && err.msg) {
        this.$message({
          showClose: true,
          message: err.msg,
          type: 'error'
        })
      }
    })
  }
  pagedData() {
    const start = (this.currentPage - 1) * this.pageSize;
    this.tableData = this.transformFailureList(this.uploadRes.failureList);
    return this.tableData.slice(start, start + this.pageSize);
  }
  handleCurrentChange(val: number) {
    this.currentPage = val;
    this.tableData = this.pagedData();
  }
  transformFailureList(failureList) {
    if (!failureList || failureList.length < 2) return [];
    const headers = failureList[0];
    return failureList.slice(1).map(row => {
      const obj = {};
      headers.forEach((h, i) => {
        obj[h] = row[i];
      });
      return obj;
    });
  }
  uploadErr() {
    let ExcelHead: Array<any> = [];
    let data: Array<any> = []
    // let arr=['orderCode','plantTime','sProvince','sCity','sCounty','address','sName','sTel','orderDate','buyId','orderRmk','lineRmk','productCode','productType','mProductCode','mProductName','mTypeCode','isGift','num','basePrice','price','rmk','isSuccess','info']

    this.uploadRes.failureList.forEach((item: any, index: any) => {
      let obj: any = {}
      item.forEach((ele: any, dex: any) => {
        if (index === 0) {
          let excelHeadConfig = {
            text: ele,
            value: 'a' + dex,
            width: '200'
          }
          ExcelHead.push(excelHeadConfig)
        } else {
          obj['a' + dex] = ele;
        }
      });
      if (index !== 0) {
        data.push(obj)
      }
    });

    const excelHelper = new ExcelHelper()
    excelHelper.success = () => {
      this.$message({
        message: '下载成功！',
        type: 'success'
      });
      this.show = false;
    }
    excelHelper.toExcel({
      fileName: 'B2B异常数据（仅供参考，请误上传）.xlsx',
      data: data,
      otherData: { ExcelHead }
    })

  }
}
</script>

<style lang="scss" scoped>
.upload {
  width: 100%;
  display: flex;
  height: 40px;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
  margin-top: 32px;
  margin-bottom: 8px;

  .upload-name {
    height: 32px;
    width: 400px;
    border-radius: 5px;
    background-color: #F7F8FA;
    box-sizing: border-box;
    padding: 0 16px;
    font-size: 14px;
    color: #333;
    line-height: 32px;
  }

  .upload-btn {
    height: 32px;
    width: 70px;
    background-color: #0581FF;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #FFF;
    font-size: 14px;
    border-radius: 5px;
    margin-left: 8px;
    cursor: pointer;
  }
}

.upload-module {
  color: #0581FF;
  font-size: 14px;
  text-align: center;
  width: 100%;
  cursor: pointer;
}

.shop-result {
  width: 100%;
  padding-top: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;

  .success {
    color: #0581FF;
    padding-right: 24px;
  }

  .err {
    color: #F00;
    padding-left: 24px;
  }
}
</style>