<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="1000px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="closeModel"
  >
    <el-card style="margin-top: -25px">
      <upload-excel-component
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      />
      <el-table
        :data="tableData"
        size="mini"
        border
        max-height="400px"
        highlight-current-row
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="invNo" label="发票编号" width="180" />
        <el-table-column prop="inv_type_name" label="发票类型" width="150" />
        <el-table-column prop="inv_code" label="发票代码" />
        <el-table-column prop="inv_number" label="发票号码" />
        <el-table-column prop="inv_total" label="发票金额" width="130" />
        <el-table-column prop="createtime" label="开票日期" width="150" />
      </el-table>
      <div class="tr" style="padding: 10px 0 0 0">
        <el-button type="primary" size="small" @click="submitForm"
          >保 存
        </el-button>
      </div>
    </el-card>
  </el-dialog>
</template>
<script>
import UploadExcelComponent from "@/components/UploadExcel/index.vue";
import asyncRequest from "@/apis/service/InvoiceSales/orderBatchBilling";
export default {
  name: "invoiceApply",
  props: ["showModel"],
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: [],
      title: "",
      showModelThis: false,
      loading: false,
      newTime: 0,
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (isLt1M) {
        return true;
      }

      this.$message({
        message: "请不要上传大于1MB的文件.",
        type: "warning",
      });
      return false;
    },
    handleSuccess({ results, header }) {
      let head = [
        "发票编号",
        "发票类型",
        "发票代码",
        "发票号码",
        "发票金额",
        "开票日期",
      ];
      if (head.length !== header.length) {
        this.$message.error("表头与导入模板不匹配！");
        return;
      }
      let hederOk = true;
      head.forEach((v1, i1) => {
        if (v1 !== header[i1].replace(/\s*/g, "")) {
          hederOk = false;
        }
      });

      if (!hederOk) {
        this.$message.error("表头与导入模板不匹配！");
        return;
      }
      this.tableHeader = header;
      this.tableData = [];
      let list = results;
      let tableOk = true;
      this.tableData = [];
      list.forEach((v1) => {
        let b = Object.values(v1);
        let time = this.setTime((b[5] + "").replace(/^\s*|\s*$/g, ""));
        let inv_type = this.get_inv_type(b[1] + "");
        if (inv_type === -1) {
          tableOk = false;
        }
        let model = {
          invNo: b[0] + "",
          inv_type_name: inv_type === -1 ? "" : b[1] + "",
          inv_type: inv_type === -1 ? "" : inv_type,
          inv_code: b[2] + "",
          inv_number: b[3] + "",
          inv_total: b[4] + "",
          createtime: time,
        };
        this.tableData.push(model);
      });
      if (!tableOk) {
        this.$message.error("发票类型不正确，请将表格格式转为文本上传！");
      }
    },
    unique(arr) {
      let hash = [];
      for (let i = 0; i < arr.length; i++) {
        let index = hash.findIndex((v1) => v1.inv_number === arr[i].inv_number);
        if (index === -1) {
          hash.push(arr[i]);
        }
      }
      return hash;
    },
    setTime(time) {
      time = time.replace(/\//g, "-");
      time = time.replace(/\./g, "-");
      let key = new Date(time).valueOf() + "";
      if (key.length !== 13) {
        time = "";
      }
      return time;
    },
    closeModel() {
      console.log("closeModel!!");
    },
    dropzoneS(file) {
      console.log(file);
      this.$message({ message: "Upload success", type: "success" });
    },
    dropzoneR(file) {
      console.log(file);
      this.$message({ message: "Delete success", type: "success" });
    },
    async initForm() {
      this.newTime = 0;
      this.loading = true;
      this.tableData = [];
      this.tableHeader = [];
      this.step = 1;
      this.title = "批量导入开票信息";

      this.changea();
      this.loading = false;
    },
    refreshAll() {
      this.showModelThis = false;
      this.$emit("refresh");
    },
    changea() {
      this.newTime = new Date().valueOf();
    },

    async submitForm() {
      if (!this.loading) {
        if (this.tableData.length < 1) {
          this.$message.error("导入数据不能为空！");
          this.loading = false;
          return;
        }
        let arr = this.unique(this.tableData);
        if (arr.length !== this.tableData.length) {
          this.$message.error("发票号码不可以重复出现！");
          this.loading = false;
          return;
        }

        this.loading = true;
        let isok = true;
        let list = [];
        this.tableData.forEach((v1, i1) => {
          let model = Object.assign({}, v1);
          delete model["inv_type_name"];
          for (let key in model) {
            if (model[key] === "") {
              isok = false;
            }
          }
          list.push(model);
        });
        if (!isok) {
          this.$message.error("导入数据不能出现空值！");
          this.loading = false;
          return;
        }
        const res = await asyncRequest.receiptimport({ data: list });
        this.loading = false;
        if (res && res.code === 0) {
          this.showModelThis = false;
          this.$emit("refresh");
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else if (res && res.code === 1005) {
          this.$message.error(res.message);
        } else {
          console.log("其他错误");
        }
      }
    },
    get_inv_type(type) {
      let list = [
        {
          id: "1",
          name: "增值税专用发票",
        },
        {
          id: "2",
          name: "增值税普通发票",
        },
        {
          id: "3",
          name: "增值税电子专用发票",
        },
        {
          id: "4",
          name: "增值税电子普通发票",
        },
      ];
      let index = list.findIndex((v1) => v1.name === type.replace(/\s*/g, ""));
      if (index !== -1) {
        index === list[index].id;
      }
      return index;
    },
  },
};
</script>

   <style lang="scss" scoped>
.orderBatchBilling {
  .activity-upload {
    position: relative;
    .img-list-main {
      position: relative;
      width: auto;
      border-left: 1px solid rgb(220, 223, 230);
      .img-item {
        float: left;
        width: 254px;
        height: 164px;
        border: 1px solid rgb(220, 223, 230);
        border-left: 0;
        position: relative;
        &.error {
          border: 1px solid #c03639;
          .error-m {
            position: absolute;
            background: #f2f2f2;
            left: 0;
            top: 0;
            z-index: 20;
            width: 250px;
            height: 160px;
            line-height: 160px;
            text-align: left;
            display: flex;
            align-items: center;
            padding: 16px;
            box-sizing: border-box;

            li {
              width: 100%;
              padding: 5px 0;
              max-height: 160px;
              color: #c03639;
              text-align: center;
              box-sizing: border-box;
            }
            &.show {
              opacity: 1;
              transition: opacity 0.3s;
            }
            &.close {
              opacity: 0;
              transition: opacity 0.3s;
            }
          }
        }
        img {
          display: inline-block;
          width: 100%;
          height: 100%;
        }
        i {
          position: absolute;
          right: 6px;
          font-size: 16px;
          top: 6px;
          z-index: 30;
          color: #909399;
          &:hover {
            cursor: pointer;
            color: rgb(56, 193, 231);
          }
        }
      }
    }
    .btnupload {
      float: left;
      border: 1px solid rgb(220, 223, 230);
      border-left: 0;
      box-sizing: border-box;
      width: 254px;
      height: 164px;
      line-height: 164px;
      text-align: center;
    }
    .Upload {
      width: 254px;
      height: 164px;
      line-height: 164px;
      text-align: center;
      position: absolute;
      line-height: 0px;
      top: 0;
      left: 0;
      z-index: 2;
      line-height: 164px;
    }
    .fileUp {
      vertical-align: top;
    }
    .avatar {
      width: 254px;
      height: 164px;
      line-height: 164px;
      text-align: center;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 33px;
      color: #8c939d;
      width: 50px;
      height: 50px;
      line-height: 50px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
    .txt-tips {
      display: inline-block;
      font-size: 13px;
      color: #606266;
      padding: 15px 0 0 15px;
      p {
        margin: 0;
        line-height: 30px;
        span {
          padding: 0 15px 0 0;
        }
      }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  }
}
</style>
