<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { execlUpload } from "/@/components/execlUpload";
import { httpBatch } from "/@/api/InvoiceSaleSettings/commodityCost";

import { useResponseHandle } from "/@/hooks";

import {
  initheaders,
  columns,
  mapProp,
  requireHeaders
} from "./columns-config";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";

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

const mapTag = {
  免税: "1",
  不征税: "2",
  零税率: "3"
};

const mapDiscount = {
  是: "1",
  否: "0"
};

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) => {
        const key = "value" + sii;
        model[key] = si + "";
        const prop = mapProp[key];
      });
      tableData.value.push(model);
    }

    loading.value = false;
  } catch (err) {
    return err;
  }
};
//提交
const handleSubmit = async () => {
  if (loading.value) return;
  loading.value = true;
  const data = [];
  const errorZeroNotDiscous = [];
  tableData.value.forEach((item, index) => {
    const obj: Record<string, string> = {};
    Object.keys(item).forEach(key => {
      const prop = mapProp[key];
      const value = item[key];
      switch (prop) {
        case "tax":
          obj[prop] = value * 100 + "%";
          break;
        default:
          obj[prop] = value;
          break;
      }
    });
    data.push(obj);
  });


  const { code, message } = await httpBatch({
    list: data,
    status: "1"
  });

  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
    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>
          <p
            class="flex"
            v-if="
              mapProp[si.prop] === 'inv_tag' || mapProp[si.prop] === 'addTax'
            "
          >
            {{ si.label }}
            <el-popover
              placement="top-start"
              title="选项"
              :width="200"
              trigger="hover"
              content="免税、不征税、零税率"
            >
              <template #reference>
                <el-button
                  link
                  size="small"
                  :icon="useRenderIcon('question-filled')"
                />
              </template>
            </el-popover>
          </p>

          <span
            v-else-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>
