<template>
  <div>
    <div style="height: 10px;position: absolute">

      <el-upload ref="upload" class="upload-demo" action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
        :limit="1" :on-change="handleFileChange" :auto-upload="false" accept=".xlsx">
        <template #trigger>
          <el-button type="primary">上传报表模板</el-button>
        </template>
      </el-upload>
    </div>
    <div id="luckysheet" class="luckysheet-wrap"></div>
    <!-- <div v-show="displaySlider" class="right-slider">
        <div class="title">设置面板</div>
    </div> -->
    <el-drawer title="设置面板" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <el-container>
        <el-header>选中单元格：<b>{{ selectedCell }}</b></el-header>
        <el-main>
          <el-row>
            <el-col :span="24">
              设置统计条件：
            </el-col>
          </el-row>
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="常规统计项" name="first">
              <div>老年人：</div>
              <div>
                <el-radio v-model="radio1" label="1" border>60岁（含）以上老年人</el-radio>
                <el-radio v-model="radio1" label="2" border>80岁（含）以上老年人</el-radio>
              </div>
              <div>
                <el-radio v-model="radio1" label="3" border>独居老年人</el-radio>
                <el-radio v-model="radio1" label="4" border>空巢老年人</el-radio>
                <el-radio v-model="radio1" label="5" border>失能老年人</el-radio>
              </div>
              <div>政治面貌：</div>
              <div>
                <el-radio v-model="radio1" label="6" border>中共党员数</el-radio>
                <el-radio v-model="radio1" label="7" border>中共流动党员数</el-radio>
                <el-radio v-model="radio1" label="8" border>共青团员数</el-radio>
              </div>
              <div>
                <el-radio v-model="radio1" label="9" border>民主党派成员数</el-radio>
                <el-radio v-model="radio1" label="10" border>无党派民主人士数</el-radio>
                <el-radio v-model="radio1" label="11" border>群众</el-radio>
              </div>
              <div>健康状况：</div>
              <div>
                <el-radio v-model="radio1" label="6" border>残疾人数</el-radio>
                <el-radio v-model="radio1" label="7" border>大病人数</el-radio>
                <el-radio v-model="radio1" label="8" border>慢病人数</el-radio>
              </div>
              <div>关注人群：</div>
              <div>
                <el-radio v-model="radio1" label="6" border>流动人员数</el-radio>
                <el-radio v-model="radio1" label="7" border>退役军人数</el-radio>
                <el-radio v-model="radio1" label="8" border>低保人数</el-radio>
              </div>
            </el-tab-pane>
            <el-tab-pane label="自定义统计项" name="second"></el-tab-pane>
          </el-tabs>
        </el-main>
        <el-footer>
          <el-col :span="24" align="right">
            <el-button style="margin-left: 10px" type="default " >取消</el-button>
            <el-button style="margin-left: 20px"  type="primary ">确定</el-button>
          </el-col>
        </el-footer>
      </el-container>
    </el-drawer>
  </div>
</template>
    
<script>

import LuckyExcel from 'luckyexcel';
import options from "@/utils/luckysheetConfig.js";


export default {
  data() {
    return {
      drawer: false,
      direction: 'rtl',
      selectedCell: '',
      activeName: 'first',
      radio1: '1',
      radio2: '1',
    };
  },

  computed: {

  },
  async created() {

  },
  watch: {},
  mounted() {

    window.luckysheet.destroy();
    window.luckysheet.create({
      ...options,
      hook: {
        cellEditBefore: this.handleCellEditBefore,
        cellUpdateBefore: this.handleCellUpdateBefore,
      },
    });

  },

  methods: {
    loadExcel() {
      var url = 'http://localhost:9001/epmet-work-pc/test.xlsx'

      var that = this
      fetch(url).then(response => response.blob()) // 将响应转换为Blob
        .then(blob => {
          const fileName = 'test.xlsx';
          const file = new File([blob], fileName, { type: 'excel/xlsx' });
          var files = [];
          files.push(file);
          that.uploadExcel(files);
        }).catch(error => console.error('Error fetching file:', error));
    },


    uploadExcel(files) {
      if (files == null || files.length == 0) return alert('没有文件等待导入');
      let name = files[0].name;
      let suffixArr = name.split('.'),
        suffix = suffixArr[suffixArr.length - 1];
      if (suffix != 'xlsx') return alert('目前只支持导入xlsx文件');
      let that = this
      LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) return alert('读取excel文件内容失败, 目前不支持XLS文件!');
        window.luckysheet.destroy();
        window.luckysheet.create({
          ...options,
          data: exportJson.sheets,
          title: exportJson.info.name,
          hook: {
            cellEditBefore: that.handleCellEditBefore,
            cellUpdateBefore: that.handleCellUpdateBefore,
          },
        });
      });
    },
    // //保存
    // tableSave() {
    //   var json = window.luckysheet.getAllSheets();  //获取表格的全部数据
    //   exportExcel(json, "名字").then(res => {
    //     //拿到表格的blob方便下一步操作
    //     console.log(res, '--11')
    //   })
    // },


    handleFileChange(file, newFileList) {
      const selectedFile = file.raw;
      if (!(selectedFile instanceof File)) {
        console.error('传入了非文件对象');
        return;
      }

      if (selectedFile.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        console.log('文件是xlsx类型');
      } else {
        console.error('不是xlsx文件');
        return;
      }
      this.loadExcel();

      // let filename = selectedFile.name.replace(/\.[^/.]+$/, ""); // 去除文件扩展名
      // let reader = new FileReader();

      // reader.onload = async (e) => {
      //   let fileData = e.target.result;
      //   try {

      //     LuckyExcel.transformExcelToLucky(fileData, async (exportJson, luckysheetfile) => {
      //       console.log(exportJson.sheets)
      //       creatExcel(filename, JSON.stringify(exportJson.sheets))
      //     });
      //   } catch (e) {
      //     console.error(e);
      //   }
      // };

      // reader.onerror = function() {
      //   console.error("File could not be read! Code " + reader.error.code);
      // };

      // reader.readAsArrayBuffer(selectedFile);
    },

    // creatExcel(title, content){
    //   const options = {
    //     container: 'luckysheet', // 设定DOM容器的id
    //     title: 'excel 表格', // 设定表格名称
    //     lang: 'zh', // 设定表格语言
    //     hook: {
    //       updated: (e) => {
    //         //监听更新,并在1s后自动保存
    //         $('#luckysheet_info_detail_save').text("已修改")
    //         let title = $('#luckysheet_info_detail_input').val();
    //         let content = luckysheet.getAllSheets();
    //         //去除临时数据,减小体积
    //         for (let i in content)
    //           content[i].data = undefined
    //         console.log(title)
    //         console.log(content)
    //       }
    //     },

    //   }
    //   options.data = JSON.parse(content)
    //   options.title = title;

    //   window.luckysheet.create(options)
    // }
    handleClose(done) {
      done();
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => { });
    },
    handleCellEditBefore(e) {
      this.drawer = true;
      let column = parseInt(e[0].column[0]) + 1, row = parseInt(e[0].row[0]) + 1;
      this.selectedCell = "第" + row + "行" + "第" + column + "列";

    },
    handleCellUpdateBefore() {
      this.drawer = false;
      this.selectedCell = "";
    },
    handleTabClick(tab, event) {
      console.log(tab, event);
    }
  },

  props: {},
};
</script>
<style lang="scss" scoped>
.luckysheet-wrap {

  margin: 10px;
  padding: 0px;
  position: absolute;
  z-index: 2;
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  left: 0px;
  top: 0px;
}

.upload-demo {
  position: absolute;
  z-index: 999999;
  margin: 20px 0 0 22px;
}

.right-slider {
  position: absolute;
  z-index: 999999;
  border: 1px solid #eeeeee;
  box-shadow: -5px 0px 5px 0px rgba(0, 0, 0, 0.2);
  background: #ffffff;
  margin: 10px 0 0 22px;
  right: 10px;
  width: 36%;
  height: calc(100% - 20px);
}

.el-header,
.el-footer {
  text-align: left;
  line-height: 40px;
  padding-top: 0;
  padding-bottom: 0;
}

.el-main {
  text-align: left;
  line-height: 40px;
  padding-top: 0;
  padding-bottom: 0;
}

.el-container {
  display: flex;
  height: 100%;
  flex-direction: column;
}
</style>
    