// 上传设备
<template>
  <div class="upload-div">
    <a href="javascript:;" class="file"
      >批量导入<input
        type="file"
        name="file"
        ref="file"
        @change="uploadFun($event)"
    /></a>
    <!-- 批量注册人员-抽屉 -->
    <el-drawer
      :title="hasCompleted ? '导入已完成' : '正在处理中..'"
      :visible.sync="drawerVisible"
      :wrapper-closable="false"
      size="50%"
      direction="rtl"
    >
      <div style="padding: 50px">
        <div>
          已处理条数；{{ hasDealNumber }}; 待处理条数：{{ waitDealNumber }};
          总共条数：{{ allNumber }}
        </div>
        <el-progress
          :percentage="makePercent"
          :format="formatProgress"
          style="margin-top: 10px"
        />
        <el-table
          ref="batch_upload_result"
          v-loading="false"
          :data="batchUploadResultList"
          class="table"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          height="500"
        >
          <el-table-column label="错误序号" align="center" width="100px">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="错误描述" align="center">
            <template slot-scope="scope">
              {{ scope.row.err }}
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center; margin: 20px 0">
          <el-button type="primary" @click="drawerVisible = false">
            我已知晓
          </el-button>
          <el-button type="warning" @click="downloadBatchUploadErrorList">
            下载错误列表文件
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { batchAdd } from "@/api/tripartiteApi";
import BatchUpload from "@/components/BatchUpload";
import { readExcel } from "@/utils/getExcelList";

export default {
  components: { BatchUpload },
  props: {
    templateDataList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 批量注册-处理提示值
      hasDealNumber: 0,
      waitDealNumber: 0,
      allNumber: 0,
      hasCompleted: false,
      // 批量注册-抽屉控制值
      drawerVisible: false,
      batchUploadResultList: [],
    };
  },
  computed: {
    // 批量注册-返回向下取整，减少渲染次数
    makePercent() {
      return Math.floor((this.hasDealNumber / this.allNumber) * 100);
    },
  },
  watch: {},
  created() {},
  methods: {
    // 批量导入
    async uploadFun(e) {
      let files = e.currentTarget.files;
      if (!files.length) {
        return;
      }
      let data = await readExcel(files[0]); //file指的是获取的excel文件对象，如e.file
      let newData = [];
      data.forEach((i) => {
        for (let key in i) {
          if (i[key]) {
            newData.push(i);
            return;
          }
        }
      });
      data = newData;
      this.allNumber = data.length;
      this.batchUploadResultList=[]
      this.drawerVisible = true;
      this.doUploadAddUserInfo(0, data);
      e.target.value = "";
    },
    // 递归调用校验数据并请求
    async doUploadAddUserInfo(i, data) {
      if (i > data.length - 1) {
        this.hasCompleted = true;
        this.$emit("success",true);
        this.$message.success("导入已完成！");
        return;
      }
      let form = {};
      form.sn = data[i]["设备sn"];
      form.purchaserName = data[i]["购买方公司名称"];
      form.applicationType = data[i]["应用类型"];
      form.deviceModel = data[i]["设备型号"];
      await this.isPassFun(form, i).then(async (res) => {
        let timeout = 0;
        if (res.isOk) {
          await this.addUserInfo(data, form, i);
        } else {
          this.getFileList1(data, i, res, form);
          timeout = 0;
        }
        this.hasDealNumber = i + 1;
        this.waitDealNumber = data.length - (i + 1);
        setTimeout(() => {
          this.doUploadAddUserInfo(++i, data);
        }, timeout);
      });
    },
    // 校验模板数据内容
    async isPassFun(form, i) {
      let isPass = {
        isOk: true,
        incorrect: {
          name: `第${i + 1}行`,
          err: "",
        },
      };
      if (!form.sn) {
        isPass.incorrect.err = "设备sn为必填项";
        isPass.isOk = false;
        return isPass;
      }
      if (!form.purchaserName) {
        isPass.incorrect.err = "购买方公司名称为必填项";
        isPass.isOk = false;
        return isPass;
      }
      if (!form.applicationType) {
        isPass.incorrect.err = "应用类型为必填项";
        isPass.isOk = false;
        return isPass;
      }
      if (!form.deviceModel) {
        isPass.incorrect.err = "设备型号为必填项";
        isPass.isOk = false;
        return isPass;
      }
      return new Promise((resolve) => {
        resolve(isPass);
      });
    },
    // 批量导入-调用添加员工接口
    async addUserInfo(data, form, i) {
      await batchAdd(form)
        .then((res) => {})
        .catch((err) => {
          this.batchUploadResultList.push({ name: `第${i + 1}行`, err: err });
          this.makeScrollDown();
        });
    },
    // 批量导入-推入错误信息
    getFileList1(data, i, isPass) {
      this.batchUploadResultList.push(isPass.incorrect);
      this.makeScrollDown();
    },
    // 批量注册人员-保持滚动条在最底部
    makeScrollDown() {
      this.$nextTick(() => {
        this.$refs.batch_upload_result.$refs.bodyWrapper.scrollTop =
          this.$refs.batch_upload_result.$refs.bodyWrapper.scrollHeight;
      });
    },
    // 批量注册人员-返回进度条尾部显示值
    formatProgress(percent) {
      return percent === 100 ? "已完成" : "";
    },
    // 批量注册人员-导出错误名单
    downloadBatchUploadErrorList() {
      const list = this.batchUploadResultList;
      let string = "序号\t文件名\t错误原因\n";
      for (let i = 0; i < this.batchUploadResultList.length; i++) {
        string +=
          (i + 1).toString() +
          "\t" +
          list[i].name +
          "\t" +
          list[i].err +
          "\t" +
          "\n";
      }
      const blob = new Blob([string], { type: "text/plain;charset=utf-8" });
      const excel_url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = excel_url;
      link.download = "批量注册结果错误名单.xls";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
  },
};
</script>

<style scoped>
.upload-div{
  display: inline-block;
}
::v-deep .el-select {
  width: 100%;
}
.table {
  margin-top: 15px;
}
/*批量导入按钮*/
.file {
  margin: 10px 0 0 10px;
  position: relative;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 10px 20px;
  box-sizing: border-box;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
}
.file input {
  position: absolute;
  font-size: 14px;
  width: 106px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}

</style>
