<template>
  <!-- <div>
    <input type="file" accept=".xlsx" @change="handleFileUpload" />
    <el-button type="primary" @click="importExcel">导入</el-button>
    <el-upload></el-upload>
  </div> -->
  <el-upload
    ref="upload"
    class="upload-demo"
    action="#"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="handleExcelChange"
    :accept="'.xlsx,.xls,application/vnd.ms-excel'"
    multiple
  >
    <el-button type="primary">导入</el-button>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      file: null,
      data: [],
      columns: [],
    };
  },
  methods: {
    // beforeUpload(file) {
    //   console.log(file);
    //   this.importExcel()
    // },
    // handleFileUpload(event) {
    //   this.file = event.target.files[0];
    // },
    handleExcelChange(file) {
      this.file = file.raw;
      const reader = new FileReader();

      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        var XLSX = require("xlsx");
        const workbook = XLSX.read(data, { type: "array" });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        console.log(worksheet);

        // 将表格数据转为json数组
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        console.log(jsonData);

        // 获取表头
        this.columns = jsonData[0];

        // 获取表格数据（不包括表头）
        this.data = jsonData.slice(1);
        console.log(this.data);
        this.$emit("listenToChildEvent", this.data);
        // 提交数据到接口
        // axios
        //   .post("/api/submit", this.data)
        //   .then((response) => {
        //     console.log("提交成功");
        //   })
        //   .catch((error) => {
        //     console.error("提交失败", error);
        //   });
      };

      reader.readAsArrayBuffer(this.file);
    },
  },
};
</script>

<style></style>
