<template>
  <el-dialog :model-value="visible" title="批量导入" @close="close" :width="width">
    <el-upload drag action="#" class="mx-30px mt-20px" ref="uploadRef" :show-file-list="false" :auto-upload="false"
      @change="handleChange">
      <el-icon class="text-60px text-blue-500"><upload-filled /></el-icon>
      <div class="el-upload__text"> 点击上传或者拖拽xlsx文件到此处</div>
    </el-upload>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" @click="close()">取消</el-button>
        <el-button plain class="w-100px" type="success" @click="download()">下载模板</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import * as XLSX from 'xlsx';
import { templateList, getDrugList } from './drug-dict.js';

const emits = defineEmits(["close", "change"]);
const props = defineProps({
  visible: { type: Boolean, default: false },
  width: { type: Number, default: 300 },
  // 库类型：hlw = 互联网医院药品库(drug-info)，online = 配送/线上药品库(online-drug-info)
  libType: { type: String, default: 'hlw' },
});
const uploadRef = ref(null);

function close() {
  emits("close");
};


function download() {
  // 生成 worksheet
  const worksheet = XLSX.utils.json_to_sheet(templateList);
  // 转为 CSV 字符串
  // const csv = XLSX.utils.sheet_to_csv(worksheet);
  // // 创建 Blob 并下载
  // const bom = '\uFEFF';
  // const blob = new Blob([bom + csv], { type: 'text/csv;charset=utf-8;' });
  // const link = document.createElement('a');
  // link.href = URL.createObjectURL(blob);
  // link.download = '药品导入模板.csv';
  // document.body.appendChild(link);
  // link.click();
  // document.body.removeChild(link);
  // 设置列宽
  const colWidths = [];
  if (templateList.length > 0) {
    // 根据数据字段数量设置列宽
    Object.keys(templateList[0]).forEach((i) => {
      colWidths.push({ wch: typeof i === 'string' ? i.length + 10 : 15 }); // 每列宽度设置为20个字符
    });
  }
  worksheet['!cols'] = colWidths;
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  // 生成 XLSX 二进制数据
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  // 创建 Blob 并下载
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '药品导入模板.xlsx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

async function handleChange(file) {
  const isXlsx = file.raw && (
    file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.raw.name.toLowerCase().endsWith('.xlsx')
  );
  if (!isXlsx) {
    ElMessage.error('只能上传XLSX文件');
    uploadRef.value && uploadRef.value.clearFiles();
    return;
  }
  const maxSize = 5 * 1024 * 1024;
  if (file.raw.size > maxSize) {
    ElMessage.error('文件大小不能超过5MB');
    uploadRef.value && uploadRef.value.clearFiles();
    return;
  }
  if (file && file.raw) {
    const data = await parseExcel(file.raw);
    const res = getDrugList(data, 'name', true, props.libType);
    if (res.length) {
      emits('change', { list: res });
      close()
    } else {
      ElMessage.error('导入失败，请检查数据格式')
    }
  }
  uploadRef.value && uploadRef.value.clearFiles()
}

function parseExcel(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const csv = e.target.result;
        // 解析为 workbook
        const workbook = XLSX.read(csv, { type: 'string' });
        // 获取第一个 Sheet
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        // 4. 转为 JSON 数据
        const jsonData = XLSX.utils.sheet_to_json(worksheet);
        resolve(jsonData);
      } catch (error) {
        reject(error);
      }
    };

    reader.onerror = (error) => reject(error);
    reader.readAsArrayBuffer(file); // 读取文件为 ArrayBuffer
  });
}
</script>
