<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { execlUpload } from "/@/components/execlUpload";
import { httpBatchimport } from "/@/api/purchase/ticketReturn";
import { useResponseHandle } from "/@/hooks";
import { useCompany } from "/@/hooks/core/useCompany";

import {
  initheaders,
  columns,
  mapProp,
  requireHeaders
} from "./columns-config";

const visible = ref(false);
const loading = ref(false);
const tableData = ref([]);
const columnsConfig = columns();
const emit = defineEmits(["onSuccess"]);

const { currentCompany } = useCompany();

const responseHandle = useResponseHandle();

const Uploadsuccess = ({ results, header }) => {
  loading.value = true;

  if (results.length === 0) {
    ElMessage.error("表格无有效数据！");
    loading.value = false;
    return;
  }

  let headok = true;
  if (header.length !== initheaders.length) {
    headok = false;
  } else {
    initheaders.forEach((si, sii) => {
      if (si !== header[sii]) {
        headok = false;
      }
    });
  }

  if (!headok) {
    ElMessage.error("表头与导入模板不匹配！");
    loading.value = false;
    return;
  }
  tableData.value = [];

  try {
    for (const v1 of results) {
      const b = Object.values(v1);
      let model = {};
      b.forEach((si, sii) => {
        model["value" + sii] = si + "";
      });
      tableData.value.push(model);
    }
    loading.value = false;
  } catch (err) {
    return err;
  }
};
//提交
const handleSubmit = async () => {
  if (loading.value) return;
  loading.value = true;

  const data = [];
  const errorStatus = [];
  const errorHp = [];
  const errorDz = [];

  tableData.value.forEach((key, index) => {
    const obj: Record<string, string> = {};

    for (let i in key) {
      const prop = mapProp[i];
      const value = key[i];
      if (prop === "status") {
        const trimValue = value.trim();
        if (trimValue !== "通过" && trimValue !== "驳回") {
          errorStatus.push(index + 1);
        } else {
          obj[prop] = trimValue === "通过" ? "4" : "7";
        }
      } else if (prop === "hpNo") {
        if (!value) errorHp.push(index + 1);
        obj[prop] = value;
      } else if (prop === "payNo") {
        if (!value) errorDz.push(index + 1);
        obj[prop] = value;
      } else {
        obj[prop] = value;
      }
    }
    data.push(obj);
  });

  const buyers = data.map(({ companyNo }) => companyNo);
  const setBuyers = [...new Set(buyers)];

  if (errorStatus.length > 0) {
    ElMessage.error(
      `第 ${errorStatus.join(",")} 行审核状态格式不正确,应该为'通过',或'驳回'`
    );
    loading.value = false;
    return;
  }

  if (errorHp.length > 0) {
    ElMessage.error(
      `第 ${errorHp.join(",")} 行格式不正确,回票申请编码为必填项`
    );
    loading.value = false;
    return;
  }

  if (errorDz.length > 0) {
    ElMessage.error(`第 ${errorDz.join(",")} 行格式不正确,对账编码为必填项`);
    loading.value = false;
    return;
  }

  if (setBuyers.length > 1) {
    ElMessage.error("买方公司编码不一致");
    loading.value = false;
    return;
  }

  if (setBuyers[0] !== currentCompany.value.companyNo) {
    ElMessage.error("买方公司编码与当前选择的公司不一致");
    loading.value = false;
    return;
  }

  data.forEach(item => {
    delete item["payNo"];
    delete item["companyNo"];
  });

  const { code, message } = await httpBatchimport({
    list: data
  });

  loading.value = false;

  responseHandle({
    code,
    message,
    handler: () => {
      ElMessage.success("数据导入成功！");
      emit("onSuccess");
      visible.value = false;
    }
  });
};
const cancel = () => {
  tableData.value = [];
};
defineExpose({
  onDisplay: () => ((visible.value = true), (tableData.value = []))
});
</script>

<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    title="批量导入认证结果"
    width="1040px"
    top="8vh"
    center
  >
    <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 columnsConfig"
        :type="si.type"
        :minWidth="si.minWidth"
        :fixed="si.fixed"
        :key="sii"
        :prop="si.prop"
        show-overflow-tooltip
      >
        <template #header>
          <span
            v-if="
              !requireHeaders.includes(mapProp[si.prop]) || si.label === '序号'
            "
            >{{ si.label }}</span
          >
          <p v-else>
            <span style="color: #f56c6c; font-size: 14px">* </span>
            {{ si.label }}
          </p>
        </template>
      </el-table-column>
    </el-table>
    <div
      flex
      justify-end
      gap-2
      v-if="tableData.length !== 0"
      style="padding: 10px 0 0 0"
    >
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button
        size="small"
        type="primary"
        :loading="loading"
        @click="handleSubmit"
        >保存</el-button
      >
    </div>
  </el-dialog>
</template>

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