<template>
  <div style="height: 100%">
    <div
      :id="containerId"
      :key="containerId"
      style="
        margin: 0px;
        padding: 0px;
        height: 100%;
        width: 100%;
        left: 0px;
        top: 30px;
        bottom: 0px;
      "
    ></div>
    <div
      v-show="isMaskShow"
      style="
        position: absolute;
        z-index: 1000000;
        left: 0px;
        top: 0px;
        bottom: 0px;
        right: 0px;
        background: rgba(255, 255, 255, 0.8);
        text-align: center;
        font-size: 40px;
        align-items: center;
        justify-content: center;
        display: flex;
      "
    >
      Downloading
    </div>
  </div>
</template>

<script>
import LuckyExcel from "luckyexcel";
//导入库export.js 这个文件是es6的，不能在普通的HTML文件直接引入js文件（虽然都是js文件，但是有区别，具体请百度es6与es5）！需要把es6转es5才可以直接引入使用！
import { exportExcel, generateExcelFile } from "./export";
import { saveAs } from "file-saver";

export default {
  name: "luckysheet",
  props: {
    options: {
      type: Object,
      default: () => {},
    },
    data: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      selected: "",
      isMaskShow: false,
      // 生成随机ID，避免多个组件实例之间的ID冲突
      containerId: "luckysheet-" + Math.random().toString(36).substr(2, 9),
    };
  },
  beforeDestroy() {
    if (luckysheet) {
      this.exitEditMode();
      luckysheet.destroy();
    }
  },
  mounted() {
    // In some cases, you need to use $nextTick
    // this.$nextTick(() => {
    let config = this.options.config || {};
    let data = this.data.length > 0 ? this.data : null;
    if (!data) {
      data = [
        {
          name: "Sheet1",
          color: "",
          status: "1",
          order: "0",
          data: [],
          config: {},
          index: 0,
        },
      ];
    }
    luckysheet.create({
      container: this.containerId,
      lang: "zh",
      showinfobar: false,
      data: data,
      ...config,
    });

    // });
  },
  methods: {
    generateExcelFile(callback) {
      // 检查luckysheet是否存在
      if (!luckysheet) {
        console.error("luckysheet未初始化");
        return;
      }

      try {
        // 获取luckysheet数据
        if (luckysheet.getLuckysheetfile) {
          const excelData = luckysheet.getLuckysheetfile();
          console.log("获取Excel数据成功", excelData);

          // 生成Excel文件对象
          generateExcelFile(excelData, "测试文件")
            .then((file) => {
              callback && callback(file);
              // console.log("生成Excel文件对象成功", file);
              // console.log("文件名:", file.name);
              // console.log("文件大小:", file.size);
              // console.log("文件类型:", file.type);

              // 这里可以使用file对象进行上传等操作
              // 例如：uploadFile(file);
              // const fileName = `电子表格_${new Date().getTime()}.xlsx`;
              // saveAs(file, fileName);
            })
            .catch((error) => {
              console.error("生成Excel文件对象失败:", error);
            });
        } else {
          console.error("luckysheet不支持getLuckysheetfile方法");
        }
      } catch (error) {
        console.error("生成Excel文件对象失败:", error);
      }
    },
    uploadExcel(evt) {
      const files = evt.target.files;
      if (files == null || files.length == 0) {
        alert("No files wait for import");
        return;
      }

      let name = files[0].name;
      let suffixArr = name.split("."),
        suffix = suffixArr[suffixArr.length - 1];
      if (suffix != "xlsx") {
        alert("Currently only supports the import of xlsx files");
        return;
      }
      const self = this;
      LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
          alert(
            "Failed to read the content of the excel file, currently does not support xls files!"
          );
          return;
        }
        luckysheet.destroy();

        luckysheet.create({
          container: self.containerId, //使用当前组件的容器ID
          showinfobar: false,
          data: exportJson.sheets,
          title: exportJson.info.name,
          userInfo: exportJson.info.name.creator,
        });
      });
    },
    exitEditMode() {
      luckysheet.exitEditMode();
    },
    getValue() {
      luckysheet.exitEditMode();
      let sheetData = luckysheet.getluckysheetfile();
      return sheetData;
    },
    downloadExcel() {
      exportExcel(luckysheet.getAllSheets(), "下载");
    },
    getJson() {
      luckysheet.exitEditMode();
      let json = luckysheet.toJson();
      return json;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
<style>
#luckysheet-icon-morebtn-div {
  z-index: 10030 !important;
}
</style>
