<!-- 用户编辑弹窗 -->
<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="https://file.wsdns.cn/download/20230523/8b20591126ab49448fdd69cfee8ab260.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 { read, utils } from 'xlsx';
  import { ref } from 'vue';
  import { Accessory } from '@/api/tower/accessory/model';
  import { addBatchAccessory } from '@/api/tower/accessory';

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

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

  // 导入的数据
  const importData = ref<Accessory[]>([]);
  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();
    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) => {
        importData.value.push({
          accessoryName: d[0],
          accessoryCategory: d[1],
          accessoryModel: d[2],
          accessorySpecs: d[3],
          accessoryUnit: d[4],
          accessoryWeight: d[5],
          accessoryPrice: Number(d[6]),
          accessoryNo: d[7],
          companyNo: d[8],
          companyName: d[9],
          manufactor: d[10],
          factoryDate: d[11],
          comments: d[12]
        });
      });
      addBatchAccessory(importData.value).then(() => {
        message.success('导入成功');
        updateVisible(false);
        emit('done');
      });
    };
    reader.readAsArrayBuffer(file);
    return false;
  };
</script>
