<template>
  <div class="orderImport pagePadding" v-loading="loading">
    <div v-if="tableData && tableData.length > 0" class="tr" style="padding: 10px 0 0 0">
      <el-button @click="cancel" :size="'mini'">取消</el-button>
      <el-button type="primary" @click="submit" :size="'mini'">提交</el-button>
    </div>
    <div v-else>
      <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
    </div>
    <div>
      <el-alert title="多物流单号请用逗号'，'隔开" type="warning" :closable="false">
      </el-alert>
    </div>
    <ex-table
      :columns="columns"
      :table="table"
      :data="tableData"
      style="margin: 15px 0 0 0"
    >
    </ex-table>
  </div>
</template>

<script>
import asyncRequest from "@/apis/service/sellOut/deliveryWorkOrder";
import resToken from "@/mixins/resToken";
import { sendOutOrderColumns, head } from "./columns";
import { isnumber, isNumeric } from "@/utils/validate";
export default {
  mixins: [resToken],
  name: "orderImport",
  data() {
    return {
      code_msg: "物流单号必传，且支持纯数字或字母数字组合(9~20位)!",
      ruleForm: {
        order_addr: [], //收货地址
      },
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        "max-height": "800px",
        // _defaultHeader_: ["setcol"],
      },
      tableData: [],
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      head,
      loading: false,
      // 表格 - 列参数
      columns: sendOutOrderColumns,

      //按钮锁
      btnFlag: false,

      //编辑全局锁
      editBtnFlag: false,
    };
  },
  mounted() {
    // alert(this.head.length)
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 < 500;
      if (isLt1M) {
        return true;
      }
      this.$message({
        message: "请不要上传大于500KB的文件.",
        type: "warning",
      });
      return false;
    },
    handleSuccess({ results, header }) {
      // alert(this.head.length, header.length)
      // console.log(results)
      if (!this.loading) {
        this.loading = true;
        if (results.length === 0) {
          this.$message.error("表格无有效数据！");
          this.loading = false;
          return;
        }

        console.log(this.head.length,header.length);
        if (this.head.length !== header.length) {
          this.$message.error("表头与导入模板不匹配！");
          this.loading = false;
          return;
        }
        let hederOk = true;
        this.head.forEach((v1, i1) => {
          if (v1 !== header[i1].replace(/\s*/g, "")) {
            console.log(v1 + "----" + header[i1]);
            hederOk = false;
          }
        });

        if (!hederOk) {
          this.$message.error("表头与导入模板不匹配！");
          this.loading = false;
          return;
        }
        this.tableData = [];
        let list = results;

        try {
          list.forEach((obj, index) => {
            let model = {};
            let arr = Object.values(obj);
            arr.forEach((key, ii) => {
              let key_n = (key ?? "") + "";
              key_n = key_n.replace(/\s+/g, "");
              const s = /\\|\/|\?|\?|\*|\"|\“|\”|\'|\‘|\’|\，|\；|\？|\<|\>|\{|\}|\[|\]|\[|\]|\:|\:|\.|\^|\$|\!|\~|\`|\|/g;

              Object.defineProperty(model, `value${ii}`, {
                value: ii === 28 ? key_n.replace(s, ",") : key_n,
              });
            });
            this.tableData.push(model);
            // console.log(this.tableData);
          });
        } catch (e) {
          console.log(e);
        }
        this.loading = false;
      }
    },
    //取消
    cancel() {
      this.tableData = [];
    },
    validateCode(str) {
      let arr = str.split(",");
      let isok = true;
      arr.forEach((value) => {
        const l = value.length;
        let res = true;
        // else if (value === "0") {//之前支持0
        //   res = true;
        // }
        if (value === "") {
          res = false;
        } else if (l >= 9 && l <= 20) {
          if (isnumber(value)) {
            res = true;
          } else if (!isNumeric(value)) {
            res = false;
          } else {
            res = true;
          }
        } else {
          isok = false;
        }
        if (!res) {
          isok = false;
        }
      });
      return isok;
    },

    //提交
    async submit() {
      if (!this.loading) {
        this.loading = true;
        if (this.tableData.length === 0) {
          this.$message.warning("导入数据不能为空");
          this.loading = false;
          return;
        }

        if(this.tableData.length > 100){
          this.$message.warning("导入数据最多不能超过100条");        
          this.loading = false
        }

        let isok = true,
          list = [],
          is_codeok = true;

        this.tableData.forEach((key, index) => {
          if (
            key["value0"] === "" ||
            key["value18"] === "" ||
            key["value19"] === "" ||
            key["value20"] === ""
          ) {
            isok = false;
          }
          let ketitem = {
            outChildCode: key["value0"],
            post_name: key["value18"],
            post_code: key["value19"],
            post_fee: key["value20"]
          };

          if (!this.validateCode(key["value19"])) {
            is_codeok = false;
          }

          list.push(ketitem);
        });
        if (!isok) {
          this.$notify.warning({
            title: "以下单号不能为空!",
            message:
              "发货工单号/发货工单物流公司/发货工单物流单号/发货工单物流费用",
          });
          this.loading = false;
          return;
        }
        if (!is_codeok) {
          this.$notify.warning({
            title: "部分物流单号不符合规则!",
            message: this.code_msg,
          });
          this.loading = false;
          return;
        }
        let model = {
          list: JSON.parse(JSON.stringify(list)),
        };

        const { code, data, message } = await asyncRequest.express(model);
        this.loading = false;
        if (code === 0) {
          this.$notify.success({
            title: "导入成功！",
            message: "",
          });
          this.tableData = [];
          // await this.routeReGoto("sellOutOrder", {});
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else if (code == 1003) {
          this.showal(data, message, "");
        } else if (code == 1005) {
          this.showal(data, message, "outCode");
        } else if (code == 1011) {
          this.showal(data, message, "outCode");
        } else {
          this.$message.warning(message);
        }
      }
    },
    showal(list, message, code) {
      let htmlList = "<ul>";
      list.forEach((v) => {
        htmlList += `<li>${code !== "" ? v[code] : v}</li>`;
      });
      htmlList += "</ul>";
      this.$notify({
        title: message,
        dangerouslyUseHTMLString: true,
        message: htmlList,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  // padding-top: 50px;
  box-sizing: border-box;
  // height: 100vh;
  // overflow: hidden;
  background: #fff;
}
.con {
  width: 100%;
  margin: 0px auto;
  background: #fff;
  // padding: 50px;
  box-sizing: border-box;

  h1 {
    margin-bottom: 20px;
    margin-top: 20px;
    font-size: 16px;
    color: #333;
  }
}
// .tab{
//   width: 100%;
//   overflow: hidden;
//   margin: auto;
//   box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
//   padding: 30px;

// }
.btn {
  width: 50%;
  margin: 50px auto 0;
  display: flex;
  justify-content: space-around;
}
</style>
