<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 :on-success="handleSuccess" :before-upload="beforeUpload" />
      <el-form :model="ruleForm" ref="ruleForm" :size="'mini'">
        <el-table
          :data="ruleForm.order_addr"
          border
          :size="'mini'"
          style="width: 100%"
          max-height="400px"
          row-key="key"
        >
          <el-table-column
            v-for="(si, sii) in postColumns"
            :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" label="操作">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="编辑" placement="top">
                <i
                  class="el-icon-edit tb-icon"
                  @click="openHouseModal(scope.$index)"
                ></i>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <i
                  class="el-icon-delete tb-icon"
                  @click="deleteRow(scope.$index, ruleForm.order_addr)"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!-- <addr-add-edit-modal
        :showModel="showAddrAddEditModal"
        :index="AddrAddEditModalIndex"
        :sitem="AddrAddEditModalSitem"
        @cancel="showAddrAddEditModal = false"
        :type="'1'"
        @refresh="showAddrAddEditModalRefresh"
      /> -->
      <div class="tr" style="padding: 10px 0 0 0">
        <el-button type="primary" size="small" @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 AddrAddEditModal from "@/components/addr-add-edit-modal";
import resToken from "@/mixins/resToken";
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: {},
      tableData: [],
      tableHeader: [],
      title: "",
      showModelThis: false,
      loading: false,
      newTime: 0,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date().valueOf();
        },
      },
      rulesThis: this.rules,
      ruleForm: {
        order_addr: [], //收货地址
      },
      rules: {
        receipt_quantity: [
          {
            required: true,
            validator: validateWeight,
            trigger: "blur",
          },
        ],

        contactor: [
          {
            required: true,
            trigger: "blur",
            message: "联系人不能为空",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatemobile,
            trigger: "blur",
          },
        ],
        addr_code: [
          {
            type: "array",
            required: true,
            message: "收货省市区不能为空",
            trigger: "change",
          },
        ],
        addr: [
          {
            required: true,
            message: "详细地址不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    showModel: function (val) {
      this.showModelThis = val;
      if (val) {
        this.initForm();
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit("cancel");
      }
    },
  },
  mounted() {
    // this.get_code();
  },
  methods: {
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
          this.$refs.ruleForm.clearValidate();
          this.ruleForm = {
            order_addr: [],
          };
        }
      });
    },
    // 省市区删除行操作
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    showAddrAddEditModalRefresh(e) {
      const { index, item } = e;

      if (index === -1) {
        this.ruleForm.order_addr.push(JSON.parse(JSON.stringify(item)));
      } else {
        const {
          receipt_quantity,
          contactor,
          mobile,
          addr_code,
          addr_code_name,
          addr,
          id,
        } = JSON.parse(JSON.stringify(item));
        this.ruleForm.order_addr[index].receipt_quantity = receipt_quantity;
        this.ruleForm.order_addr[index].contactor = contactor;
        this.ruleForm.order_addr[index].mobile = mobile;
        this.ruleForm.order_addr[index].addr_code = addr_code;
        this.ruleForm.order_addr[index].addr_code_name = addr_code_name;
        this.ruleForm.order_addr[index].addr = addr;
        this.ruleForm.order_addr[index].id = id;
      }
      this.$refs.ruleForm.validateField("order_addr");
    },
    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(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;
      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 = {
      //     receipt_quantity: b[0] + "",
      //     contactor: b[1] + "",
      //     mobile: b[2] + "",
      //     in_addr: b[3] + "/" + b[4] + "/" + b[5],
      //     addr_code_name: item.name + "",
      //     addr_code: item.code,
      //     addr: b[6] + "",
      //     edit: false,
      //   };
      //   this.ruleForm.order_addr.push(model);
      // });
      if (!tableOk) {
        this.$message.error("最晚收货日期不正确，请将表格格式转为文本上传！");
      }
    },
    openHouseModal(index) {
      this.AddrAddEditModalIndex = index;

      if (index === -1) {
        this.AddrAddEditModalSitem = {};
      } else {
        this.AddrAddEditModalSitem = JSON.parse(
          JSON.stringify(this.ruleForm.order_addr[index])
        );
      }
      this.showAddrAddEditModal = true;
      // let findex = this.ruleForm.order_addr.findIndex((v) => v.edit === true);
      // if (findex !== -1) {
      //   this.$message.warning("当前已有地址在编辑，请保存后再试！");
      //   return;
      // } else {
      //   this.ruleForm.order_addr[index].edit = true;
      // }
    },
    unique(arr) {
      let hash = [];
      for (let i = 0; i < arr.length; i++) {
        let index = hash.findIndex((v1) => v1.inv_number === arr[i].inv_number);
        if (index === -1) {
          hash.push(arr[i]);
        }
      }
      return hash;
    },
    setTime(time) {
      time = time.replace(/\//g, "-");
      time = time.replace(/\./g, "-");
      let key = new Date(time).valueOf() + "";
      if (key.length !== 13) {
        time = "";
      }
      return time;
    },
    async initForm() {
      this.rulesThis = this.rules;
      await this.resetForm();
      this.newTime = 0;
      this.loading = true;
      this.tableData = [];
      this.tableHeader = [];
      this.step = 1;
      this.title = "批量导入收货地址信息";

      this.changea();
      this.loading = false;
    },
    refreshAll() {
      this.showModelThis = false;
      this.$emit("refresh");
    },
    changea() {
      this.newTime = new Date().valueOf();
    },

    async submitForm() {
      if (!this.loading) {
        this.loading = true;
        const { order_addr } = this.ruleForm;
        if (order_addr.length < 1) {
          this.$message.error("导入数据不能为空！");
          this.loading = false;
          return;
        }
        let isEdit = false;
        order_addr.forEach((v) => {
          v.err = false;
          if (v.edit) {
            v.err = true;
            isEdit = true;
          }
        });
        if (isEdit) {
          this.$message.error("当前收货地址已在编辑，请保存后再试！");
          this.loading = false;
          return;
        }
        let cItem = null;
        order_addr.some((x, i) => {
          cItem = this.checkItem(x);
          if (!cItem.isok) {
            cItem.index = i;
            return true;
          }
        });
        if (cItem && !cItem.isok) {
          this.$message.error(`第${cItem.index + 1}行,${cItem.message}`);
          this.loading = false;
          return;
        }
        this.loading = false;
        this.showModelThis = false;
        let list = JSON.parse(JSON.stringify(order_addr));
        console.log(list);
        this.$emit("refresh", { list: list });
      }
    },
    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;
    },
    // get_code(name1, name2, name3) {
    //   let name = "",
    //     code = [];
    //   if (name1 && name2 && name3) {
    //     for (let x in province_list) {
    //       if (name1 === province_list[x]) {
    //         code.push(x);
    //         name += province_list[x];
    //         break;
    //       }
    //     }
    //     if (code.length === 1) {
    //       for (let y in city_list) {
    //         if (name2 === city_list[y]) {
    //           code.push(y);
    //           name += "/" + city_list[y];
    //           break;
    //         }
    //       }
    //     }
    //     if (code.length === 2) {
    //       for (let z in county_list) {
    //         if (name3 === county_list[z]) {
    //           code.push(z);
    //           name += "/" + county_list[z];
    //           break;
    //         }
    //       }
    //     }

    //     if (code.length === 3) {
    //       let str1 = "",
    //         str2 = "",
    //         isok = false;
    //       str1 = code[0].slice(0, 2);
    //       str2 = code[1].slice(2, 4);
    //       if (
    //         code[1].indexOf(str1) === 0 &&
    //         code[2].indexOf(str1) === 0 &&
    //         code[2].indexOf(str2) == 2
    //       ) {
    //         isok = true;
    //       }
    //       if (!isok) {
    //         name = "";
    //         code = [];
    //       }
    //     } else {
    //       name = "";
    //       code = [];
    //     }
    //   }
    //   return { name: name, code: code };
    // },
  },
};
</script>

   <style lang="scss" scoped>
.account {
  .gongshi {
    span {
      vertical-align: top;
      display: inline-block;
      color: #000;
    }
    .icon-span {
      padding: 0 5px;
      height: 40px;
      line-height: 40px;
      font-size: 20px;
      color: #606266;
      display: inline-block;
      // vertical-align: top;
      // display: inline-block;
    }
    .label {
      height: 40px;
      line-height: 40px;
    }
    .tuan {
      &.chu {
        width: 60px;
        height: 40px;
        display: inline-block;
        span {
          width: 60px;
          display: inline-block;
          line-height: 20px;
          text-align: center;
          font-size: 12px;
          height: 20px;
          &:last-child {
            border-top: 1px solid #606266;
          }
        }
      }
      &.cheng {
        .name {
          height: 40px;
          line-height: 40px;
        }
        .icon-span {
          line-height: 40px;
          font-size: 16px;
          padding: 0 1px;
        }
      }
    }
  }
}
</style>
