<template>
  <div class="box">
    <div class="con">
      
      <div class="tab">
        <h1></h1>
          <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
      <h1 style="color: #0099ff"></h1>
        <ex-table :columns="columns" :table="table" :data="tableData"> </ex-table>
        <div class="btn">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
      </div>
      
    </div>
    
  </div>
</template>

<script>
import asyncRequest from "@/apis/service/orderEntry/orderImport";
import resToken from "@/mixins/resToken";
import { province_list, city_list, county_list } from "@/assets/js/area-data";
import { columns } from "./columns";
import { set } from 'js-cookie';
export default {
  mixins: [resToken],
  data() {
    return {
      ruleForm: {
        order_addr: [], //收货地址
      },
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        // _defaultHeader_: ["setcol"],
      },
      tableData: [],
      tableHeader: [],
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: columns,
    };
  },
  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 }) {
      console.log("表格导入数据", results, "表格表头", header);
      if (results.length === 0) {
        this.$message.error("表格无有效数据！");
        return;
      }
      let head = [
        "平台订单号",
        "其他单号(不必填)",
        "平台下单时间",
        "销售渠道",
        "平台商品编号",
        "单价（元）",
        "数量",
        // "优惠前总金额",
        "订单总金额",
        // "商品优惠后金额",
        "优惠活动名称",
        "收费模式",
        "收货人",
        "联系电话",
        "联系地址",
        "订单备注",
      ];
      if (head.length !== header.length) {
        // console.log("自定义head长度",head.length)
        // console.log("表格内数据长度：",header.length)
        this.$message.error("表头与导入模板不匹配！");
        return;
      }
      let hederOk = true;
      head.forEach((v1, i1) => {
        if (v1 !== header[i1].replace(/\s*/g, "")) {
          console.log(v1);
          console.log(header[i1]);
          hederOk = false;
        }
      });

      if (!hederOk) {
        console.log(hederOk);
        this.$message.error("表头与导入模板不匹配！");
        return;
      }
      this.tableHeader = header;
      this.tableData = [];
      let list = results;
      // let tableOk = true;
      this.ruleForm.order_addr = [];
      list.forEach((v1) => {
        let b = Object.values(v1);

        // let item = this.get_code(b[3], b[4], b[5]);
        let model = {
          platform_code: b[0] + "",
          po_code: b[1] + "",
          platform_time: this.formatDate(b[2], "/") + "",
          sale_source: b[3] + "",
          plat_code: b[4] + "",
          price: b[5] + "",
          num: b[6] + "",
          // before_discount_all_price: b[7] + "",
          discount_price: b[7] + "",
          // after_price: b[9] + "",
          activity_name: b[8] + "",
          mode: b[9] + "",
          contactor: b[10] + "",
          mobile: b[11] + "",
          addr: b[12] + "",
          order_remark: b[13] + "",
        };

        this.tableData.push(model);
      });

      console.log(this.tableData);
    },
    //取消
    cancel() {
      this.tableData = [];
    },
    //日期转换
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1);
      time.setYear(time.getFullYear() - 70);
      const year = time.getFullYear() + "";
      const month = time.getMonth() + 1 + "";
      const date = time.getDate() + "";
      if (format && format.length === 1) {
        return year + format + month + format + date;
      }
      return (
        year +
        (month < 10 ? "0" + month : month) +
        (date < 10 ? "0" + date : date)
      );
    },
    //提交
    async submit() {
      const model = {
        list: this.tableData,
      };
    
      let obj = [
        { name: "平台订单号", str: "platform_code" },
        { name: "销售渠道", str: "sale_source" },
        { name: "平台商品编号", str: "plat_code" },
        { name: "单价（元）", str: "price" },
        { name: "收货人", str: "contactor" },
        { name: "联系电话", str: "mobile" },
        { name: "联系地址", str: "addr" },
      ];
      let flag = true;
      let platform_code_arr = [];
      model.list.forEach((item, index) => {
        platform_code_arr.push(item.platform_code)
        //必填判断
        if (flag) {
        } else {
          return;
        }
        for (let i = 0; i < obj.length; i++) {
          let txt = item[obj[i].str].trim();
          if (txt == "") {
            this.$message.warning(`第${index + 1}行的${obj[i].name}不能为空`);
            flag = false;
            break;
          } else {
            flag = true;
          }
        }
      });

      //去重锁
      if(platform_code_arr.length != Array.from(new Set(platform_code_arr)).length){
        this.$message.warning(`平台订单号不能重复`);
        return;
      }
      if(flag){
        this.submitHttp(model)
      }
    },
    async submitHttp(model) {
      
      if(model.list.length<=0){
        this.$message.warning("导入数据不能为空");
        return;
      }
     
      const res = await asyncRequest.orderimport(model);
      if (res && res.code === 0) {
        this.$notify.success({
          title: "成功！",
          message: "",
        });

        this.tableData = [];
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  padding-top: 50px;
  box-sizing: border-box;
  height: 100vh;
  // overflow: hidden;
  background: #f7f7f7e1;
}
.con {
  width: 95%;
  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>
