<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="600"
    :visible="visible"
    :maskClosable="false"
    :title="`导入客户`"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    :footer="null"
  >
    <a-upload-dragger
      name="file"
      :show-upload-list="false"
      accept=".xls,.xlsx"
      :before-upload="handleImport"
    >
      <p class="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
      <p class="ant-upload-hint" style="max-width: 550px">
        提示：附件上传中，请不要做任何操作！ 支持的文件类型为*.xls, *.xlsx!
      </p>
    </a-upload-dragger>
    <div style="margin: 20px auto; display: flex; justify-content: center">
      <a
        href="http://1.14.159.185:10042/template/customer_template.xlsx"
        target="_blank"
      >下载客户导入模板</a
      >
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
import { InboxOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { addBatchTowerEquipment } from "@/api/tower/equipment";
import { read, utils } from "xlsx";
import { ref } from "vue";
import type { Customer } from '@/api/oa/customer/model';
import { addBatchCustomer } from "@/api/oa/customer";
const emit = defineEmits<{
  (e: "done"): void;
  (e: "update:visible", visible: boolean): void;
}>();

/* 更新visible */
const updateVisible = (value: boolean) => {
  emit("update:visible", value);
};

// 导入的数据
const importData = ref<Customer[]>([]);
const handleImport = (file: File) => {
  if (
    ![
      "application/vnd.ms-excel",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    ].includes(file.type)
  ) {
    message.error("只能选择 excel 文件");
    return false;
  }
  if (file.size / 1024 / 1024 > 20) {
    message.error("大小不能超过 20MB");
    return false;
  }
  const reader = new FileReader();
  importData.value = []
  reader.onload = (e) => {
    const data = new Uint8Array(e.target?.result as any);
    const workbook = read(data, { type: "array" });
    const sheetNames = workbook.SheetNames;
    const worksheet = workbook.Sheets[sheetNames[0]];
    // 解析成二维数组
    const aoa = utils.sheet_to_json<string[]>(worksheet, { header: 1 });
    console.log(aoa);
    aoa.slice(1).map((d) => {
      if (d[1] && d[0]) {
        importData.value.push({
          name: d[0],
          creditCode: d[1],
          fullName: d[2],
          address: d[3],
          contact: d[4],
          telPhone: d[5],
          phone: d[6],
        });
      }
    });
    addBatchCustomer(importData.value).then(() => {
      message.success("导入成功");
      updateVisible(false);
      emit("done");
    });
  };
  reader.readAsArrayBuffer(file);
  return false;
};
</script>
