<template>
  <SysDialog
    class="import-partition"
    :visible="dialog.visible"
    v-bind="getBindValue"
    @onClose="onClose"
  >
    <template #content>
      <div class="import-partition-warp">
        <el-alert type="info" show-icon>
          表头顺序必须以国家/地区名称、二字简码、分区名称为准
          <br />
          快速导入会直接覆盖当前分区更新
          <br />
          可直接复制excel文件导入分区
          <el-button
            class="import-model"
            type="primary"
            link
            @click="exportTemplate"
            :disabled="importPartition.exportLoad"
            :loading="importPartition.exportLoad"
            >下载模版</el-button
          >
        </el-alert>
        <div class="title">国家/地区分区设置</div>
        <el-input
          v-model="importPartition.content"
          :autosize="{ minRows: 22, maxRows: 22 }"
          type="textarea"
        />
      </div>
      <div class="flex justify-end footer">
        <el-button type="danger" @click="onClose"> 取消 </el-button>
        <el-button type="primary" @click="hanleSetZones"> 确定 </el-button>
      </div>
    </template>
  </SysDialog>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import { useMessage } from "@/hooks/useMessage";
import { BasePartitionTypeEnum } from "@/type/BasePartitionTypeEnum";
import { v4 as uuidv4 } from "uuid";
import { zoningStore } from "@/store/zoning";
import { useErrorConfirm } from "@/utils/useErrorConfirm";
import { api_DownloadCountryPartition } from "@/api/partition/partition";
import { downloadByData } from "@/utils/download";

const emit = defineEmits(["savePartition"]);
const { ElMessageBox, createMessage } = useMessage();
const { report } = useErrorConfirm();
//弹框属性
const { dialog, onClose, onShow } = useDialog();
// 弹框一些配置
const getBindValue = reactive({
  title: "导入分区",
  top: "6vh",
  width: 420,
  height: 0,
  isFooter: true,
  closeOnClickModal: false,
});
// 分区 store
const zoningstore = zoningStore();
// 基础数据
const importPartition = reactive({
  content: "", //国家/地区分区设置
  partitionList: [] as Recordable[],
  exportLoad: false,
});

const show = () => {
  onShow();
};

// 导出模版
const exportTemplate = async () => {
  importPartition.exportLoad = true;
  try {
    const res = await api_DownloadCountryPartition({});
    // debugger
    if (res) {
      // 获取接口表格响应的头
      const header = res.headers["content-disposition"].split("''");
      // 转中文
      const fileName = decodeURIComponent(header[1]);
      // 通过blod导出模板
      downloadByData(res.data, fileName);
      importPartition.exportLoad = false;
    }
  } catch (error) {
    importPartition.exportLoad = false;
  }
};

// 判断表头顺序必须以国家/地区名称、二字简码、分区名称为准
function checkArrayHead(arr) {
  const xlsxHead = ["国家/地区名称", "二字简码", "分区名称"];
  if (
    Array.isArray(arr) &&
    arr.length === 3 &&
    arr.every((item, index) => item === xlsxHead[index])
  ) {
    return true;
  } else {
    return false;
  }
}

// 获取二字简码相同的国家/地区
function getCountriesWithSameCode(arr) {
  const sameCodeCountries: string[] = [];
  const countryCodeMap = {};

  for (let i = 1; i < arr.length; i++) {
    const countryInfo = arr[i].split(/\s{2,}|\t/g);
    const countryCode = countryInfo[1].trim();
    if (countryCodeMap[countryCode]) {
      // 如果已经存在该二字简码，将对应的国家/地区名称保存下来
      sameCodeCountries.push(countryCodeMap[countryCode]);
      sameCodeCountries.push(countryInfo[0].trim());
    } else {
      // 否则将该二字简码和国家/地区名称存入对象
      countryCodeMap[countryCode] = countryInfo[0].trim();
    }
  }
  const uniqueArr = Array.from(new Set(sameCodeCountries));
  return uniqueArr;
}

const hanleSetZones = async () => {
  const content = importPartition.content;
  try {
    if (content) {
      // 拆行数据并且过滤空格
      const itemList = content.split(/[\r\n]+/).filter((item) => item);
      // 表头
      const headers = itemList[0].split(/\s{2,}|\t/g);
      // 规定这个表头
      const isHead = checkArrayHead(headers);
      if (!isHead) {
        ElMessageBox.alert(
          "Excel表头顺序必须是（国家/地区名称、二字简码、分区名称）"
        );
        return false;
      }
      // 判断表格是否对齐
      const notAligned = itemList.filter((x) => {
        return (
          x.split(/\s{2,}|\t/g).filter((str) => str).length != headers.length
        );
      });
      if (notAligned.length > 0) {
        // 表格未对齐
        ElMessageBox.alert(
          "当前分区内容表格未对齐<br/>" + notAligned.join("<br/>"),
          { dangerouslyUseHTMLString: true }
        );
        return false;
      }

      const sameCodes = getCountriesWithSameCode(itemList);
      if (sameCodes.length > 0) {
        // 相同二字简码
        ElMessageBox.alert(
          "当前内容有相同二字简码<br/>" + sameCodes.join("<br/>"),
          { dangerouslyUseHTMLString: true }
        );
        return false;
      }

      for (let i = 1; i < itemList.length; i++) {
        // xlsx行数据
        const fields = itemList[i].split(/\s{2,}|\t/g);
        // 国家/地区信息
        const country = {
          countryId: fields[1],
          haveZipCodeArea: false,
        };

        // 判断分区名称是否存在，存在以分区名称添加国家/地区信息
        let found = false;
        const fieldsText = fields[2] && fields[2].replace(/\s/g, "")
        for (let j = 0; j < importPartition.partitionList.length; j++) {
          const partitionName = importPartition.partitionList[j].partitionName
          const partitionNameText = partitionName && partitionName.replace(/\s/g, "")
          if (
            partitionNameText === fieldsText
          ) {
            const countryInfoList =
              importPartition.partitionList[j].countryInfoList;
            const isPush = countryInfoList.some(
              (info) => info.countryId === country.countryId
            );
            // 去重
            if (!isPush)
              importPartition.partitionList[j].countryInfoList.push(country);
            found = true;
            break;
          }
        }
        // 分区不存在添加到数组中
        if (!found) {
          importPartition.partitionList.push({
            id: uuidv4(), // 以uuid生成的分区编号
            feeId: zoningstore.feeId, // 费用编号
            partitionName: fieldsText, //分区名称
            orderNumber: importPartition.partitionList.length + 1, //序号
            partitionType: BasePartitionTypeEnum.COUNTRY, //分区类型
            countryInfoList: [country], //国家/地区分区
          });
        }
      }
      ElMessageBox.confirm("是否确定快速导入").then(() => {
        // console.log(importPartition.partitionList, "<==国家/地区分区数据");
        emit("savePartition", importPartition.partitionList);
        clear();
      });
    } else {
      ElMessageBox.alert("请输入详细报价");
    }
  } catch (error) {
    report(error);
  }
};

// 清空数据
const clear = () => {
  importPartition.content = "";
  importPartition.partitionList = [];
  onClose();
};

//父组件调用子组件显示弹框
//暴露出去给外部使用
defineExpose({
  show,
});
</script>
<style lang="scss" scoped>
.import-partition {
  .import-partition-warp {
    .title {
      padding: 10px 0;
    }
  }

  .footer {
    padding-top: 16px;
  }
  .import-model {
    font-size: 12px;
    text-decoration: underline;
    margin-bottom: 3px;
  }
}
</style>
