<template>
  <el-dialog center width="1024px" title="导入采销订单补录" :visible="innerVisible" :close-on-click-modal="false"
    @close="innerVisible = false; tableData = []">
    <!-- <div style="margin-bottom:20px;display:flex;align-items:center">
      <span style="color:red">*</span>
      <p style="width:80px">业务经理:</p>

    </div> -->

    <div v-if="tableData && tableData.length > 0" style="width:100%;display: flex;align-items: center;">

      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" style="width:100%">
        <el-row>
          <el-col :span="10">
            <el-form-item label="业务经理" prop="managerid">
              <project-manager size="mini" :isDetail="true" :value="ruleForm.managerid" @searchChange="managerChange" />
            </el-form-item>
          </el-col>

          <el-col :span="14">
            <el-form-item class="fr">
              <el-button :size="'mini'" @click="() => tableData = []">取消</el-button>
              <el-button type="primary" :size="'mini'" :loading="loading" @click="onSubmit">提交</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div v-else>
      <upload-excel :on-success="onSuccess" :before-upload="beforeUpload" />
    </div>

    <ex-table :columns="columns" :table="table" :data="tableData" style="margin: 15px 0 0 0" />
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/netOrderEntry/netOrderEnter";
import { isMobile } from "@/utils/validate";
import companyHelper from "@/mixins/companyHelper";
import { replaceTextWrapAndSpace } from "../../../utils";
import { MessageBox } from "element-ui";

import {
  columns,
  PROPERTYS,
  getTableProperty,
  createFieldVerification,
  requsetFields,
  requiredFields,
  numberFields,
  getTableLabel,
  intNumberFields
} from "./template";

export default {
  mixins: [companyHelper],
  props: ["visible"],
  data() {
    return {
      columns,
      loading: false,
      tableData: [],
      ruleForm: {
        manager: "",
        managerid: []
      },
      rules: {
        managerid: [
          {
            type: 'array',
            required: true,
            message: '请选择业务经理'
          }
        ]
      },
      table: {
        stripe: true,
        border: true,
        "max-height": "800px"
      }
    };
  },
  computed: {
    innerVisible: {
      get() {
        return this.visible;
      },
      set(newVal) {
        this.$emit("update:visible", newVal);
      }
    }
  },
  methods: {
    managerChange(e) {
      const { id, label } = e;
      this.ruleForm.managerid = id ? [id] : [];
      this.ruleForm.manager = label
      this.$refs.ruleForm.validateFields("managerid")
    },
    validateTableHeader(header, importHeader) {
      let isHeaderOk = true;
      if (header.length !== importHeader.length) return false;
      for (const index in header) {
        const field = header[index];
        const importField = importHeader[index];
        if (field !== importField) {
          isHeaderOk = false;
          break;
        }
      }

      return isHeaderOk;
    },
    /* 校验导入的销售方列表编码(与选择的公司必须一致) **/
    validateCompanyNo(value, row) {
      const verification = createFieldVerification();
      const current = this.currentCompany;
      if (value !== current) {
        verification.isValid = false;
        verification.message = `第 ${row} 行,销售方公司必须与选择的公司一致`;
        return verification;
      }
      return verification;
    },
    /* 校验导入的购买方列表编码(开头必须为KH) **/
    validateKhNo(value, row) {
      const verification = createFieldVerification();
      const perfix = String(value || "").slice(0, 2);
      if (perfix !== "KH") {
        verification.isValid = false;
        verification.message = `第 ${row} 行,"购买方公司编码必须以'KH'开头`;
        return verification;
      }
      return verification;
    },
    formatDate2(serialNumber, format = "-", mao = ":") {
      var timestamp = (serialNumber - 25569 - 8 / 24) * 86400 * 1000; // 转换为时间戳
      var newDate = new Date(timestamp); // 转换为日期时间对象
      const year = newDate.getFullYear(); // 获取年份，例如 2023
      const month = newDate.getMonth() + 1; // 获取月份，注意需要加上 1，例如 4
      const day = newDate.getDate(); // 获取日期，例如 9
      let hours = newDate.getHours(); // 获取小时，例如 0
      let minutes = newDate.getMinutes(); // 获取分钟，例如 0
      let seconds = newDate.getSeconds(); // 获取秒数，例如 0

      // 判断小时、分钟和秒是否小于 10，如果是，则在前面补一个零
      if (hours < 10) {
        hours = "0" + hours;
      }
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
    /* 校验导入的联系电话是否合法 **/
    validateMobile(value, row) {
      const verification = createFieldVerification();
      if (!isMobile(value)) {
        verification.isValid = false;
        verification.message = `第${Number(row)}行,联系方式,手机号格式不正确`;
        return verification;
      }
      return verification;
    },
    /* 校验导入的购买方列表编码(开头必须为QS) **/
    validateSupplierNo(value, row) {
      const verification = createFieldVerification();
      const perfix = String(value || "").slice(0, 2);
      if (perfix !== "QS") {
        verification.isValid = false;
        verification.message = `第 ${row} 供应商公司编码必须以'QS'开头`;
        return verification;
      }
      return verification;
    },
    validateNumberField(field, value, row) {
      const verification = createFieldVerification();
      if (!/^\d*\.?\d+$/.test(value)) {
        verification.isValid = false;
        verification.message = `第${Number(row)}行,${getTableLabel(
          field
        )}必须为数字,且不能小于0`;
        return verification;
      }
      return verification;
    },
    validateIntNumberField(field, value, row) {
      const verification = createFieldVerification();
      if (!/^\d+$/.test(value)) {
        verification.isValid = false;
        verification.message = `第${Number(row)}行,${getTableLabel(
          field
        )}必须为正整数`;
        return verification;
      }
      return verification;
    },
    /* 校验导入的税率、数量、采购单价、销售单价是否为数字 **/
    validateDateField(value) {
      // const verification = createFieldVerification()
      // if (!(/^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$/.test(value))) {
      //   verification.isValid = false
      //   verification.message = `第${Number(index)}行,发货日期不能为空,且必须为日期格式`
      //   return verification
      // }
      return /^\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2}:\d{1,2}$/.test(value);
    },
    validateRequiredField(field, value, row) {
      const verification = createFieldVerification();
      if (replaceTextWrapAndSpace(value) === "") {
        verification.isValid = false;
        verification.message = `第${row}行,${getTableLabel(field)}不能为空`;
        return verification;
      }
      return verification;
    },
    /* 处理不合法的值,提示错误信息,并返回最终的验证状态 **/
    handleNotValidFields(...validFns) {
      let isFinalValid = true;
      for (const validFn of validFns) {
        const { message, isValid } = validFn();
        if (!isValid) {
          isFinalValid = false;
          MessageBox({ type: "warning", title: "数据填写错误", message });
          break;
        }
      }
      return isFinalValid;
    },
    /* 校验导入的数据 **/
    validateFields(tableData = []) {
      let verification = null;
      for (const row in tableData) {
        if (row === "remove") {
          continue;
        }

        const tableItem = tableData[row];
        const index = Number(row) + 1;

        for (const field in tableItem) {
          if (requiredFields.includes(field)) {
            verification = this.validateRequiredField(
              field,
              tableItem[field],
              index
            );
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }

          if (intNumberFields.includes(field)) {
            verification = this.validateIntNumberField(
              field,
              tableItem[field],
              index
            );
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }

          if (numberFields.includes(field)) {
            verification = this.validateNumberField(
              field,
              tableItem[field],
              index
            );
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }

          if (field === PROPERTYS.MOBILE) {
            verification = this.validateMobile(tableItem[field], index);
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }

          if (field === PROPERTYS.CUSTOMER_NO) {
            verification = this.validateKhNo(tableItem[field], index);
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }

          if (field === PROPERTYS.COMPANY_NO) {
            verification = this.validateCompanyNo(tableItem[field], index);
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }

          if (field === PROPERTYS.SUPPLIER_NO) {
            verification = this.validateSupplierNo(tableItem[field], index);
            if (!verification.isValid) {
              MessageBox({
                type: "warning",
                title: "数据填写错误",
                message: verification.message
              });
              return false;
            }
          }
        }
      }
      return true;
    },
    mapTemplateItemToTableItem(templateItem) {
      const tableItem = {};
      const templatePropertys = Object.keys(templateItem);
      templatePropertys.forEach(templateProperty => {
        const tableproperty = getTableProperty(templateProperty);
        tableItem[tableproperty] = templateItem[templateProperty];
      });
      return tableItem;
    },
    onSuccess({ results: templateItems, header: templateHeader }) {
      if (templateItems.length > 1000) {
        this.$message.error("导入数据不能超过 1000 条");
        return;
      }

      const isHeaderValid = this.validateTableHeader(
        this.columns.map(({ label }) => label).slice(1),
        templateHeader
      );
      if (!isHeaderValid) {
        this.$message.warning("表格与导入的表头不一致!");
        return;
      }
      if (templateItems.length === 0) {
        this.$message.warning("导入的表格没有数据!");
        return;
      }
      templateItems.forEach(templateItem => {
        const tableItem = this.mapTemplateItemToTableItem(templateItem);
        Object.keys(tableItem).forEach(field => {
          let target = "";
          if (field === PROPERTYS.SEND_TIME) {
            target = this.validateDateField(tableItem[PROPERTYS.SEND_TIME])
              ? tableItem[PROPERTYS.SEND_TIME]
              : this.formatDate2(tableItem[PROPERTYS.SEND_TIME]);
          } else {
            target = tableItem[field] ? String(tableItem[field]).trim() : "";
          }
          tableItem[field] = target;
        });
        this.tableData.push(tableItem);
      });

      this.validateFields(this.tableData);
    },
    async onSubmit() {
      try {
        await this.$refs.ruleForm.validate()
        if (!this.validateFields(this.tableData)) return;
        const list = this.tableData.map(tableItem =>
          requsetFields.reduce(
            (prev, currentKey) => ({
              ...prev,
              workCode: "",
              [currentKey]: tableItem[currentKey]
            }),
            {}
          )
        );

        this.loading = true;
        
        const result = await asyncRequest.importOrder({
          list:list.map((item) => ({
            ...item,
            ...this.ruleForm,
             managerid:Array.isArray(this.ruleForm.managerid) ? this.ruleForm.managerid[0] : this.ruleForm.managerid
          })),
          ...this.ruleForm,
          managerid:Array.isArray(this.ruleForm.managerid) ? this.ruleForm.managerid[0] : this.ruleForm.managerid
        });

        this.loading = false;

        switch (String(result.code)) {
          case "0":
            this.$message.success("导入成功");
            this.innerVisible = false;
            this.$emit("refresh");
            break;
          default:
            this.$message.warning(result.message);
            break;
        }

      } catch (e) {
        console.log(e)
      }
    }
  }
};
</script>

<style lang="scss">
.error-message__wrapper {
  width: 1024px;
}
</style>
