<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="8vh"
    width="1040px"
    :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="showModelThis = false"
    append-to-body
  >
    <el-card style="margin-top: -25px">
      <upload-excel
        v-show="!hasData"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      />
      <el-row v-show="hasData" :gutter="10" style="margin-bottom: 12px">
        <el-col :span="3" class="tr" style="height: 28px; line-height: 28px"
          >选择快递公司：</el-col
        >
        <el-col :span="8">
          <el-select
            v-model="express"
            style="width: 100%"
            :size="'mini'"
            placeholder="请选择快递公司"
          >
            <el-option
              v-for="item in options"
              :key="item.express_name + item.id"
              :label="item.express_name"
              :value="item.express_name"
            >
            </el-option> </el-select
        ></el-col>
        <el-col :span="3"
          ><el-button type="primary" :size="'mini'" @click="batch_set()"
            >批量设置快递公司</el-button
          ></el-col
        >
      </el-row>
      <el-form :model="ruleForm" ref="ruleForm" :size="'mini'">
        <el-table
          :data="order_addr"
          ref="multipleTable"
          @selection-change="handleSelectionChange"
          border
          :size="'mini'"
          style="width: 100%"
          max-height="400px"
          row-key="key"
        >
          <el-table-column align="center" type="selection" width="45">
          </el-table-column>
          <el-table-column
            v-for="(si, sii) in columns"
            :key="si.prop + sii"
            :prop="si.prop"
            :label="si.label"
            :width="si.width"
            :min-width="si['min-width']"
            show-overflow-tooltip
          />
          <el-table-column fixed="right" width="80">
            <template slot="header" slot-scope="scope">
              <span>操作</span>
              <el-tooltip
                effect="dark"
                class="fr"
                v-show="hasData"
                content="重新导入"
                placement="top"
              >
                <i
                  class="el-icon-brush tb-icon"
                  style="margin: 3px 0 0 0; font-size: 15px"
                  @click="resetForm"
                ></i>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="删除" placement="top">
                <i
                  class="el-icon-delete tb-icon"
                  @click="deleteRow(scope.$index, order_addr)"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="tr" style="padding: 10px 0 0 0">
        <el-button type="primary" :size="'mini'" @click="submitForm"
          >保 存
        </el-button>
      </div>
    </el-card>
  </el-dialog>
</template>
<script>
// import resToken from "@/mixins/resToken";
// import { province_list, city_list, county_list } from "@/assets/js/area-data";
import { isnumber, isMobile } from "@/utils/validate";
import asyncRequest from "@/apis/service/mobile/order";
// import AddrAddEditModal from "@/components/addr-add-edit-modal";
import resToken from "@/mixins/resToken";
import { postColumns } from "./columns";
export default {
  name: "inAddrModel",
  props: ["showModel", "id", "sitem"],
  mixins: [resToken],
  // components: { AddrAddEditModal },
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("联系电话不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("联系电话格式不正确！"));
        } else {
          callback();
        }
      }
    };
    const validateWeight = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("收货总数不能为空!"));
      } else {
        if (!isnumber(value)) {
          callback(new Error("收货总数仅支持整数!"));
        } else {
          callback();
        }
      }
    };
    return {
      showAddrAddEditModal: false,
      AddrAddEditModalIndex: -1,
      AddrAddEditModalSitem: {},
      options: [],
      express: "",
      tableData: [],
      tableHeader: [],
      hasData: false,
      title: "批量发货",
      showModelThis: false,
      loading: false,
      multipleSelection: [],
      columns: postColumns,
      rulesThis: this.rules,
      order_addr: [], //收货地址
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  mounted() {},
  methods: {
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.order_addr = [];
          this.hasData = false;
          this.express = "";
        }
      });
    },
    // 删除行操作
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    //选择数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    batch_set() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择要设置的订单！");
        return;
      }
      if (this.express === "") {
        this.$message.warning("请选择快递公司！");
        return;
      }
      this.multipleSelection.forEach((a) => {
        let findex = this.order_addr.findIndex((b) => b.value1 === a.value1);
        if (findex !== -1) {
          this.order_addr[findex].value0 = this.express;
          this.$set(this.order_addr, findex, this.order_addr[findex]);
        }
      });
    },
    // 刷新快递公司
    async get_express() {
      this.options = [];
      let model = {
        status: "1",
        code: "",
        express_name: "",
        page: 1,
        size: 10000,
      };
      const { code, data, message } = await asyncRequest.expresslist(model);
      if (code === 0) {
        const { list } = data;
        console.log(list);
        this.options = list;
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },

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

      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;
      this.order_addr = [];
      let resList = [];
      let repeatList = [];
      list.forEach((a) => {
        let Okey = Object.values(a);
        if (resList.length === 0) {
          resList.push(Okey[0]);
        } else {
          let findex = resList.findIndex((b) => b === Okey[0]);
          if (findex === -1) {
            resList.push(Okey[0]);
          } else {
            repeatList.push(Okey[0]);
          }
        }
      });
      const result = Array.from(new Set(repeatList));
      if (result.length !== 0) {
        this.show_p(result, "以下订单出现重复！不允许导入！");
        return;
      }
      await this.get_express();
      list.forEach((v1) => {
        let b = Object.values(v1);
        let item = {
          value0: "",
        };
        for (let key = 0; key < b.length; key++) {
          if (key === 5) {
            item.value6 = this.setTime(b[key]);
          } else {
            item[`value${key + 1}`] = b[key];
          }

          if (key === 7) {
            item.value0 =
              (this.options.find((item) => item.express_name === b[key]) || {})
                .express_name || "";
          }
        }

        this.order_addr.push(item);
      });
      this.hasData = this.order_addr.length !== 0;
    },

    setTime(tkey) {
      let time = tkey;
      time = (time + "").replace(/\//g, "-");
      time = (time + "").replace(/\./g, "-");
      let key = new Date(time).valueOf() + "";
      console.log(time, key);
      if (key.length !== 13) {
        time = "";
      }
      return time;
    },
    show_p(result, title) {
      let html = `<ul>`;
      result.forEach((c) => {
        html += `<li>${c}</li>`;
      });
      html += "</ul>";
      this.$notify({
        title: title,
        dangerouslyUseHTMLString: true,
        message: html,
      });
    },
    async initForm() {
      this.rulesThis = this.rules;
      await this.resetForm();
      this.loading = true;
      this.tableData = [];
      this.tableHeader = [];
      this.step = 1;
      this.loading = false;
    },
    refreshAll() {
      this.showModelThis = false;
      this.$emit("refresh");
    },

    async submitForm() {
      if (!this.loading) {
        this.loading = true;
        if (this.order_addr.length === 0) {
          this.$message.error("导入数据不能为空！");
          this.loading = false;
          return;
        }
        let isEdit = false,
          list = [];
        this.order_addr.forEach((v) => {
          let item = {
            order_sn: v.value1, //订单编号
            order_num: v.value2, //订单数量
            delivery_time: v.value6, //发货时间
            post_name: v.value0, //快递公司
            post_code: v.value7, //快递编号
          };
          if (v.value0 === "" || v.value7 === "") {
            isEdit = true;
          }
          list.push(item);
        });
        if (isEdit) {
          this.$message.error("部分订单未匹配到快递公司,物流编号为空！");
          this.loading = false;
          return;
        }
        let model = {
          list: list,
        };
        console.log(model);
        const { code, data, msg } = await asyncRequest.updateOrder(model);
        this.loading = false;
        if (code === 0) {
          this.$notify.success({
            title: `批量提交成功!`,
            message: "",
          });
          this.showModelThis = false;
          this.$emit("refresh");
        } else if (code === 1005 || code === 1006) {
          this.show_p(data, msg);
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(msg);
        }
        // 批量导入物流信息
      }
    },
    checkItem(sitem) {
      let model = {
        isok: true,
        message: "",
      };
      const {
        arrive_time,
        receipt_quantity,
        contactor,
        mobile,
        addr_code,
        addr,
      } = sitem;
      if (receipt_quantity === "" && model.isok) {
        model.isok = false;
        model.message = "收货总数不能为空!";
      }
      if (!isnumber(receipt_quantity) && model.isok) {
        model.isok = false;
        model.message = "收货总数仅支持整数!";
      }
      if (arrive_time === "" && model.isok) {
        model.isok = false;
        model.message = "最晚收货日期不能为空!";
      }

      if (contactor === "" && model.isok) {
        model.isok = false;
        model.message = "收货联系人不能为空!";
      }
      if (mobile === "" && model.isok) {
        model.isok = false;
        model.message = "收货联系电话不能为空!";
      }
      if (!isMobile(mobile) && model.isok) {
        model.isok = false;
        model.message = "收货联系电话格式不正确!";
      }
      if (addr_code.length !== 3 && model.isok) {
        model.isok = false;
        model.message = "收货省市区不能为空!";
      }
      if (addr === "" && model.isok) {
        model.isok = false;
        model.message = "详细地址不能为空!";
      }
      return model;
    },
  },
};
</script>

   <style lang="scss" scoped>
</style>
