<template>
  <div class="orderImport pagePadding" v-loading="loading">
  
    <div class="tr" style="padding: 10px 0 0 0"   v-if="tableData && tableData.length > 0">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :size="'mini'"
        :rules="rulesThis"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="导入目标平台" prop="platform_id">
              <search-terrace
                :value="ruleForm.platform_id"
                :disabled="false"
                :size="'mini'"
                :is_show="'1'"
                :isDetail="false"
                :placeholder="'导入目标平台'"
                @searchChange="platform_codesearchChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="16" class="tr">
            <el-button
              type="primary"
              @click="submit"
              :size="'mini'"
              class="fr"
              style="margin: 0 0 0 10px"
              >提交</el-button
            >
            <el-button
              @click="resetForm"
              :size="'mini'"
              class="fr"
              style="margin: 0 0 0 10px"
              >取消</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <div v-else>
      <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
    </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/orderEntry/orderImport";
import resToken from "@/mixins/resToken";
import { columns } from "./columns";

export default {
  mixins: [resToken],
  name: "orderImport",
  data() {
    return {
      ruleForm: {
        platform_id: "",
      },
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        "max-height": "800px",
        // _defaultHeader_: ["setcol"],
      },
      tableData: [],
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      rulesThis: this.rules,
      rules: {
        platform_id: [
          {
            required: true,
            message: "请选择导入目标平台",
            trigger: "change",
          },
        ],
      },
      loading: false,
      // 表格 - 列参数
      columns: columns,

      //按钮锁
      btnFlag: false,

      //编辑全局锁
      editBtnFlag: false,
    };
  },
  mounted() {
    this.resetForm();
  },
  methods: {
    async resetForm() {
      this.loading = false;
      this.rulesThis = this.rules;
      this.tableData = [];
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            platform_id: "", // 账号
          };
        }
      });
    },
    platform_codesearchChange(e) {
      const { id } = e;
      this.ruleForm.platform_id = id || "";
      this.$refs.ruleForm.validateField("platform_id");
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (isLt1M) {
        return true;
      }
      this.$message({
        message: "请不要上传大于1MB的文件.",
        type: "warning",
      });
      return false;
    },
    handleSuccess({ results, header }) {
      if (!this.loading) {
        this.loading = true;
        if (results.length === 0) {
          this.$message.error("表格无有效数据！");
          this.loading = false;
          return;
        }

        let head = [
          "平台订单号",
          "其他单号(不必填)",
          "平台下单时间",
          "销售渠道",
          "平台商品编号",
          "单价（元）",
          "数量",
          // "优惠前总金额",
          "订单总金额",
          // "商品优惠后金额",
          "优惠活动名称",
          "收费模式",
          "收货人",
          "联系电话",
          "联系地址",
          "订单备注",
        ];
        if (head.length !== header.length) {
          this.$message.error("表头与导入模板不匹配！");
          this.loading = false;
          return;
        }
        let hederOk = true;
        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((v1, index) => {
            let b = Object.values(v1);
            let model = {
              platform_code: b[0] + "",
              po_code: b[1] + "",
              platform_time: b[2],
              sale_source: b[3] + "",
              plat_code: b[4] + "",
              price: b[5] + "",
              num: b[6] + "",
              before_discount_all_price: b[7] + "",
              activity_name: b[8] + "",
              mode: b[9] + "",
              contactor: b[10] + "",
              mobile: b[11] + "",
              addr: b[12] + "",
              order_remark: b[13] + "",
            };

            this.tableData.push(model);
          });
        } catch (e) {}
        this.loading = false;
      }
      // console.log(this.tableData);
    },

    //提交
    async submit() {
      await this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true;
            if (this.tableData.length === 0) {
              this.$message.warning("导入数据不能为空");
              this.loading = false;
              return;
            }
            const { platform_id } = this.ruleForm;
            let list = JSON.parse(JSON.stringify(this.tableData));
            list.forEach((a) => {
              a.platform_id = platform_id;
            });
            let model = {
              list: list,
            };
            const { code, data, message } = await asyncRequest.orderimport(
              model
            );
            this.loading = false;
            if (code === 0) {
              this.$notify.success({
                title: "导入成功！",
                message: "",
              });
              await this.resetForm();
            } else if (code >= 100 && code <= 104) {
              await this.logout();
            } else {
              this.$message.warning(message);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</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>
