<template>
  <div class="orderImport pagePadding">
    <div style="padding: 10px 0 0 0">
      <div
        v-if="addrForm && addrForm.order_addr && addrForm.order_addr.length > 0"
        class="tr"
      >
        <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 style="padding: 10px 0 0 0">
        <el-form
          :model="addrForm"
          ref="addrForm"
          :size="'mini'"
          v-loading="loading"
        >
          <el-table
            :data="addrForm.order_addr"
            border
            :size="'mini'"
            style="width: 100%"
            max-height="800px"
            row-key="key"
          >
            <el-table-column type="index" fixed="left" show-overflow-tooltip />
            <el-table-column
              prop="platform_code"
              label="平台订单号"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'platform_code'"
                  :rules="addrRules.platform_code"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.platform_code"
                    placeholder="平台订单号"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{
                  scope.row.platform_code
                }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="sale_source"
              label="销售渠道"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'sale_source'"
                  :rules="addrRules.sale_source"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.sale_source"
                    placeholder="销售渠道"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{
                  scope.row.sale_source
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="mode"
              label="收费模式"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'mode'"
                  :rules="addrRules.mode"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-select v-model="scope.row.mode" placeholder="收费模式">
                    <el-option
                      v-for="(item, i) in options"
                      :key="item + i"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.mode }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="plat_code"
              label="平台商品编号"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'plat_code'"
                  :rules="addrRules.plat_code"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.plat_code"
                    placeholder="平台商品编号"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.plat_code }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="num"
              label="数量"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'num'"
                  :rules="addrRules.num"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <digital-input
                    :values="scope.row.num"
                    :placeholder="'数量'"
                    :min="0"
                    :newTime="scope.row.newTime"
                    :disabled="!scope.row.edit"
                    :max="100000000000"
                    :position="'right'"
                    :precision="0"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, scope.$index, 'num')"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.num }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              label="单价（元）"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'price'"
                  :rules="addrRules.price"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <digital-input
                    :values="scope.row.price"
                    :placeholder="'单价（元'"
                    :min="0"
                    :newTime="scope.row.newTime"
                    :disabled="!scope.row.edit"
                    :max="100000000000"
                    :position="'right'"
                    :precision="2"
                    :size="'mini'"
                    :controls="false"
                    :append="''"
                    @reschange="number_change($event, scope.$index, 'price')"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="before_discount_all_price"
              label="订单总金额"
              min-width="110"
              show-overflow-tooltip
            />

            <el-table-column
              prop="contactor"
              label="收货人"
              min-width="110"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'contactor'"
                  :rules="addrRules.contactor"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.contactor"
                    placeholder="收货人"
                    maxlength="20"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.contactor }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="mobile"
              label="联系电话"
              min-width="130"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'mobile'"
                  :rules="addrRules.mobile"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.mobile"
                    placeholder="联系电话"
                    maxlength="11"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.mobile }}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="addr"
              label="联系地址"
              min-width="170"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'addr'"
                  :rules="addrRules.addr"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.addr"
                    placeholder="联系地址"
                    maxlength="200"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.addr }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="order_remark"
              label="订单备注"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'order_remark'"
                  :rules="addrRules.order_remark"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.order_remark"
                    placeholder="订单备注"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{
                  scope.row.order_remark
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="activity_name"
              label="优惠活动名称"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'activity_name'"
                  :rules="addrRules.activity_name"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.activity_name"
                    placeholder="优惠活动名称"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{
                  scope.row.activity_name
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="po_code"
              label="其他单号"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'po_code'"
                  :rules="addrRules.po_code"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-input
                    v-model="scope.row.po_code"
                    placeholder="其他单号"
                    maxlength="100"
                    :disabled="!scope.row.edit"
                  />
                </el-form-item>
                <span v-show="!scope.row.edit">{{ scope.row.po_code }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="platform_time"
              label="平台订单下单时间"
              min-width="125"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-form-item
                  v-show="scope.row.edit"
                  :prop="'order_addr.' + scope.$index + '.' + 'platform_time'"
                  :rules="addrRules.platform_time"
                  :size="'mini'"
                  :style="{ marginBottom: scope.row.edit ? '13px' : '0' }"
                >
                  <el-date-picker
                    v-model="scope.row.platform_time"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions"
                    type="datetime"
                    placeholder="平台订单下单时间号"
                    :disabled="!scope.row.edit"
                  >
                  </el-date-picker>
                  <!-- <el-input
                    v-model="scope.row.platform_time"
                    placeholder="平台订单下单时间号"
                    maxlength="100"
                   
                  /> -->
                </el-form-item>
                <span v-show="!scope.row.edit">{{
                  scope.row.platform_time
                }}</span>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              width="80"
              show-overflow-tooltip
              label="操作"
            >
              <template slot-scope="scope">
                <el-tooltip
                  effect="dark"
                  content="编辑"
                  v-show="!scope.row.edit"
                  placement="top"
                >
                  <i
                    class="el-icon-edit tb-icon"
                    @click="openHouseModal(scope.$index)"
                  ></i>
                </el-tooltip>

                <el-tooltip
                  effect="dark"
                  content="保存"
                  v-show="scope.row.edit"
                  placement="top"
                >
                  <i
                    class="el-icon-circle-check tb-icon"
                    @click="checkRow(scope.$index)"
                  ></i>
                </el-tooltip>

                <el-tooltip effect="dark" content="删除" placement="top">
                  <i
                    class="el-icon-delete tb-icon"
                    @click="deleteRow(scope.$index, addrForm.order_addr)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import asyncRequest from "@/apis/service/orderEntry/orderImport";
import resToken from "@/mixins/resToken";
import { isMobile } from "@/utils/validate";
export default {
  mixins: [resToken],
  name: "orderImport",
  data() {
    const validatemobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空！"));
      } else {
        if (!isMobile(value)) {
          callback(new Error("手机号格式不正确！"));
        } else {
          callback();
        }
      }
    };
    const validate_num = (rule, value, callback) => {
      const { required } = rule;
      if (required && value === "") {
        callback(new Error("不能为空！"));
      } else {
        callback();
      }
    };
    const validate_num_0 = (rule, value, callback) => {
      const { required } = rule;
      if (required && value === "") {
        callback(new Error("不能为空！"));
      } else if (
        required &&
        (value === "0" ||
          value === "0." ||
          value === "0.0" ||
          value === "0.00" ||
          value === "0.000")
      ) {
        callback(new Error("不能为零！"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      options: ["卡券支付", "现金支付", "混合支付"],
      addrForm: {
        order_addr: [], //收货地址
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 1000 * 60 * 60 * 24;
        },
      },
      addrRules: {
        platform_code: {
          required: true,
          trigger: "blur",
          message: "平台订单号不能为空",
        },
        sale_source: {
          required: true,
          trigger: "blur",
          message: "销售渠道不能为空",
        },
        mode: {
          required: true,
          trigger: "change",
          message: "收费模式不能为空",
        },
        plat_code: {
          required: true,
          trigger: "blur",
          message: "平台商品编号不能为空",
        },
        num: {
          required: true,
          validator: validate_num_0,
          trigger: "blur",
        },
        price: {
          required: true,
          validator: validate_num,
          trigger: "blur",
        },

        contactor: {
          required: true,
          trigger: "blur",
          message: "联系人不能为空",
        },
        mobile: {
          required: true,
          validator: validatemobile,
          trigger: "blur",
        },

        addr: {
          required: true,
          message: "联系地址不能为空",
          trigger: "blur",
        },
        order_remark: {
          required: true,
          message: "订单备注不能为空",
          trigger: "blur",
        },
        activity_name: {
          required: false,
        },
        po_code: {
          required: false,
        },
        platform_time: {
          required: false,
        },
      },
    };
  },
  mounted() {},
  methods: {
    //取消
    cancel() {
      this.addrForm.order_addr = [];
    },
    //省市区保存某一行
    async checkRow(rowIndex) {
      console.log(this.addrForm.order_addr[rowIndex]);
      await this.$refs.addrForm.validate(async (valid) => {
        if (valid) {
          this.addrForm.order_addr[rowIndex].edit = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async number_change(e, index, key) {
      this.addrForm.order_addr[index][key] = e + "" || "0";
      this.addrForm.order_addr[index].newTime = new Date().valueOf() + "";
    },
    // 删除收货地址操作
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    //日期转换
    formatDate(numb) {
      const date = new Date(numb);
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      // var h = date.getHours() + ':';
      // var m = date.getMinutes() + ':';
      // var s = date.getSeconds();
      return Y + M + D;
    },
    //提交
    async submit() {
      if (this.btnFlag) {
        console.log("拦截点击");
        return;
      }
      const { order_addr } = this.addrForm;
      const model = {
        list: order_addr,
      };
      if (model.list.length <= 0) {
        this.$message.warning("导入数据不能为空");
        return;
      }
      let obj = [
        { name: "平台订单号", str: "platform_code" },
        { name: "销售渠道", str: "sale_source" },
        { name: "平台商品编号", str: "plat_code" },
        { name: "单价（元）", str: "price" },
        { name: "数量", str: "num" },
        { name: "收费模式", str: "mode" },
        { name: "订单备注", str: "order_remark" },
        { name: "收货人", str: "contactor" },
        { name: "联系电话", str: "mobile" },
        { name: "联系地址", str: "addr" },
      ];
      let flag = true;
      let platform_code_arr = [];
      try {
        model.list.forEach((item, index) => {
          platform_code_arr.push(item.platform_code);
          //必填判断
          if (flag) {
          } else {
            throw Error();
          }

          if (item.price == 0 || item.num == 0) {
            this.$message.warning(`表格第${index + 1}行，单价,数量的值不能为0`);
            flag = false;
            throw Error();
          }

          if (
            !isNaN(item.price) &&
            !isNaN(item.num) &&
            !isNaN(item.before_discount_all_price)
          ) {
          } else {
            this.$message.warning(
              `表格第${index + 1}行，单价,数量，总金额必须是数字`
            );
            flag = false;
            throw Error();
          }

          if (!Number.isInteger(Number(item.num))) {
            this.$message.warning(`表格第${index + 1}行,数量必须是整数`);
            flag = false;
            throw Error();
          }

          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;
              throw Error();
            } else {
              flag = true;
            }
          }
        });
      } catch {}

      //去重锁
      if (
        platform_code_arr.length !=
        Array.from(new Set(platform_code_arr)).length
      ) {
        this.$message.warning(`平台订单号不能重复`);
        return;
      }
      if (flag) {
        //按钮锁开启
        this.btnFlag = true;
        this.submitHttp(model);
      }
    },
    openHouseModal(index) {
      let findex = this.addrForm.order_addr.findIndex((v) => v.edit === true);
      if (findex !== -1) {
        this.$message.warning("当前已有地址在编辑，请保存后再试！");
        return;
      } else {
        this.addrForm.order_addr[index].edit = true;
        this.addrForm.order_addr[index].newTime = new Date().valueOf() + "";
      }
    },
    async submitHttp(model) {
      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);
      }
      //关闭按钮锁
      this.btnFlag = false;
    },
    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.addrForm.order_addr = [];
      let list = results;
      // let r = /^\+?[1-9][0-9]*$/;
      // let tableOk = true;
      this.addrForm.order_addr = [];

      try {
        list.forEach((v1, index) => {
          let b = Object.values(v1);
          // let numFlag = false;

          // 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] + "",
            activity_name: b[8] + "",
            mode: b[9] + "",
            contactor: b[10] + "",
            mobile: b[11] + "",
            addr: b[12] + "",
            order_remark: b[13] + "",
            //编辑锁
            newTime: new Date().valueOf() + "",
            edit: false,
          };
          this.addrForm.order_addr.push(model);
        });
      } catch (e) {}
    },
  },
};
</script>

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