<template>
  <el-dialog
    :title="'兑换链接导入'"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    @close="showModelThis = false"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    append-to-body
  >
    <el-card style="margin-top: -20px">
      <div class="orderImport pagePadding" v-loading="loading" style="padding-top: 0">
        <div v-if="tableData && tableData.length > 0" class="tr" style="padding: 0 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>
    </el-card>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/youzan/luckDrawGood";
import resToken from "@/mixins/resToken";
import { tHeader, filterVal } from "./columns";
import { validURL } from "@/utils/validate";
export default {
  mixins: [resToken],
  name: "orderImport",
  props: ["showModel"],
  data() {
    return {
      showModelThis: this.showModel,
      code_msg: "物流单号必传，且支持纯数字或字母数字组合(9~20位)!",
      tHeader,
      filterVal,
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        "max-height": "500px",
        // _defaultHeader_: ["setcol"],
      },
      tableData: [],
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      loading: false,
      // 表格 - 列参数
      columns: [],
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  methods: {
    async initForm() {
      this.loading = true;

      this.columns = [];
      tHeader.forEach((e, i) => {
        this.columns.push({
          prop: filterVal[i],
          label: e,
          minWidth: "100px",
        });
      });

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

        if (tHeader.length !== header.length) {
          this.$message.error("表头与导入模板不匹配！");
          this.loading = false;
          return;
        }
        let hederOk = true;
        tHeader.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) => {
              Object.defineProperty(model, filterVal[ii], {
                value: key,
              });
            });
            this.tableData.push(model);
            // console.log(this.tableData);
          });
        } catch (e) {
          console.log(e);
        }
        this.loading = false;
      }
    },
    //取消
    cancel() {
      this.tableData = [];
    },

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

        let isUrl = true,
          web_url = [];

        this.tableData.forEach((key, index) => {
          // if (!validURL(key["act_good_url"])) {
          //   isUrl = false;
          // }
          let model = {
            act_good_id: key["act_good_id"],
            act_good_url: key["act_good_url"],
          };
          web_url.push(model);
        });
        // if (!isUrl) {
        //   this.$message.warning("部分兑换链接不合法!");
        //   this.loading = false;
        //   return;
        // }

        const { code, data, message } = await asyncRequest.batchImport({
          web_url,
        });
        this.loading = false;
        if (code === 0) {
          this.$notify.success({
            title: "兑换链接导入成功！",
            message: "",
          });
          this.tableData = [];
          this.$emit("refresh");
        } 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>
