<script setup lang="ts">
import { ref } from "vue";
import { httpUpload } from "/@/api/InvoiceSales/invoiceApply";
import { initheaders, columns, mapProp } from "./columns-config";
import { ElMessage } from "element-plus";
import { responseHandle } from "/@/utils/responseHandle";
import { useNav } from "/@/layout/hooks/nav";
import { execlUpload } from "/@/components/execlUpload";
import { xs_inv_type_list } from "/@/utils/status";
const visible = ref(false);
const loading = ref(false);
const tableData = ref([]);
const columnsConfig = columns();
const { logout } = useNav();
const emit = defineEmits(["onSuccess"]);

const All_INV_TYPE = xs_inv_type_list.map(({ label }) => label);

const row = ref(1);

const createInvErrorMessage = (row: string) =>
  `导入数据第 ${row} 行 发票类型格式不正确,发票类型必须为${All_INV_TYPE.join(
    ","
  )}`;

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 = [];

  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;
};
//提交
const handleSubmit = async () => {
  if (loading.value) return;
  loading.value = true;

  const data = [];
  const invErrors: any[] = [];
  const checkedErrors: any[] = [];

  tableData.value.forEach(key => {
    const obj: Record<string, string> = {};
    for (let i in key) {
      const prop = mapProp[i];
      const value = key[i];
      obj[prop] = value;
    }
    data.push(obj);
  });

  let checked = true;

  data.forEach((item, index) => {
    const { inv_type } = item;

    const invType = xs_inv_type_list.find(
      ({ label }) => label === inv_type.trim()
    );

    if (invType) {
      item.inv_type = invType.value;
    } else {
      invErrors.push(index + 1);
    }

    if (
      (item.inv_type === "electronic" || item.inv_type === "normal") &&
      !item.check_code
    )
      checkedErrors.push(index + 1);
  });

  if (checkedErrors.length > 0) {
    ElMessage.error(`第 ${checkedErrors.join(",")} 行校验码不能为空`);
    loading.value = false;
    return;
  }

  if (invErrors.length > 0) {
    ElMessage.error(createInvErrorMessage(invErrors.join(",")));
    loading.value = false;
    return;
  }

  const { code, message } = await httpUpload({ data });
  loading.value = false;
  responseHandle({
    code,
    message,
    logout,
    handler: () => {
      ElMessage.success("数据导入成功！");
      emit("onSuccess");
      visible.value = false;
      row.value = 1;
    }
  });
};
const cancel = () => {
  tableData.value = [];
  row.value = 1;
};

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"
        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="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>
