<script setup lang="ts">
import { shallowReactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { tableColumns, tableHeader, mapProperties } from "./columns-config";
import { execlUpload } from "/@/components/execlUpload";
import { division } from "/@/utils/calc";
import apis from "./../config/apis";

const state = shallowReactive({ visible: false, loading: false });

const departId = ref("");
const emit = defineEmits(["refresh"]);
const tableData = ref<Record<string, string>[]>([]);

function isValidTableHeader(importTableHeader, tableHeader) {
  if (importTableHeader.length !== tableHeader.length) {
    ElMessage.warning("表头与导入模板不匹配！");
    return false;
  }

  for (const index in importTableHeader) {
    if (tableHeader[index] !== importTableHeader[index]) {
      ElMessage.warning("表头与导入模板不匹配！");
      return false;
    }
  }
  return true;
}

function isValidTableData(results) {
  const list: Record<string, string>[] = [];
  const messages: string[] = [];
  let isValid = true;

  for (const index in results) {
    const result = results[index];
    let isCurrentValid = true;
    let baseMessage = "";

    const reg1 = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]+$/;
    if (String(result[mapProperties.orderCode]).trim() === "") {
      isCurrentValid = false;
      baseMessage += ",销售主订单编号不能为空";
    } else if (
      reg1.test(String(result[mapProperties.orderCode]).trim()) === false
    ) {
      isCurrentValid = false;
      baseMessage += ",销售主订单编号必须由字母和数字组成";
    }

    // if (String(result[mapProperties.skuCode]).trim() === "") {
    //   isCurrentValid = false;
    //   baseMessage += ",商品成本编号不能为空";
    // } else if (
    //   reg1.test(String(result[mapProperties.orderCode]).trim()) === false
    // ) {
    //   isCurrentValid = false;
    //   baseMessage += ",商品成本编号必须由字母和数字组成";
    // }

    const reg = /^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$/;
    if (String(result[mapProperties.corr]).trim() === "") {
      isCurrentValid = false;
      baseMessage += ",修改后的提成系数不能为空";
    } else if (reg.test(String(result[mapProperties.corr]).trim()) === false) {
      isCurrentValid = false;
      baseMessage += ",修改后的提成系数必须为数字";
    }

    if (!isCurrentValid) {
      isValid = false;
    }

    messages.push(baseMessage);

    list.push({
      orderCode: result[mapProperties.orderCode],
      // skuCode: result[mapProperties.skuCode],
      corr: result[mapProperties.corr]
    });
  }

  return { list, isValid, messages };
}

function createErrorMessage(messages: string[]) {
  return messages.reduce((prev, current, index) => {
    const suffix = index === messages.length - 1 ? "</ul>" : "";
    const content =
      prev +
      (current
        ? `<li><strong style="font-weight:700"> 第${
            Number(index) + 1
          }行</strong>${current}</li>`
        : "");
    return content + suffix;
  }, "<ul>");
}
const Uploadsuccess = ({ results }) => {
  if (results.length === 0) {
    ElMessage.warning("上传数据不能为空!");
    return;
  }

  const importTableHeader = Object.keys(results[0]);
  // 校验表头是否合法
  if (!isValidTableHeader(importTableHeader, tableHeader)) return;
  const { isValid, list, messages } = isValidTableData(results);

  if (!isValid) {
    ElMessageBox({
      type: "warning",
      title: "数据填写错误",
      dangerouslyUseHTMLString: true,
      message: createErrorMessage(messages)
    });
    return;
  }
  tableData.value = list;
};

const handleSubmit = async () => {
  if (!departId.value) {
    ElMessage.warning("请选择修改部门");
    return;
  }

  try {
    const change_type = "3";
    const depart_type = departId.value;

    const list = tableData.value.map(({ orderCode, corr }) => ({
      orderCode,
      after: corr
    }));

    const response = await apis.create({ change_type, depart_type, list });

    if (Number(response.code) !== 1) {
      ElMessage.warning(response.message);
      return;
    }

    emit("refresh");
    state.visible = false;
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const handleClose = () => {
  state.visible = false;
  tableData.value = [];
  departId.value = "";
};

defineExpose({
  onDisplay: () => ((state.visible = true), (tableData.value = []))
});
</script>

<template>
  <el-dialog
    title="销售提成(订单商品成本修改）"
    :close-on-click-modal="false"
    v-model="state.visible"
    @close="handleClose"
    width="1040px"
    top="8vh"
    center
  >
    <div
      style="
        width: 300px;
        display: flex;
        margin-bottom: 10px;
        align-items: center;
      "
    >
      <p style="color: red; margin-right: 5px">*</p>
      <p style="white-space: nowrap; margin-right: 5px">修改部门:</p>
      <el-select v-model="departId">
        <el-option value="1" label="客服部@百辰荣达" />
        <!-- <el-option value="2" label="新媒体" /> -->
        <el-option value="3" label="项目部@普润心堂" />
        <el-option value="4" label="销售部" />
      </el-select>
    </div>

    <execlUpload @on-success="Uploadsuccess" v-if="tableData.length === 0" />

    <el-table
      :data="tableData"
      stripe
      border
      max-height="500px"
      size="small"
      style="width: 100%"
    >
      <el-table-column
        v-for="(si, sii) in tableColumns"
        v-bind="si"
        :key="sii"
        show-overflow-tooltip
      />
    </el-table>

    <div
      flex
      justify-end
      gap-2
      v-if="tableData.length !== 0"
      style="padding: 10px 0 0 0"
    >
      <el-button size="small" @click="tableData = []">取消</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="state.loading"
        @click="handleSubmit"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-upload-list__item) {
  display: none !important;
}
</style>
