<template>
  <div>
    <div class='flex' :style="{ height: tableHeight }">
      <div class="left_menu flex flex-y">
        <el-button type="text" round @click="handelClickBack" icon="el-icon-back">返回</el-button>
        <!-- <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 :class="{ 'menu_item': true, 'active': menuActive === index }" v-for="(item, index) in menuList"
          :key="index" @click="handleClickMenu(index)">
          <span>{{ item.name }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="flex flex-y luckysheet-wrap">
        <div class="top_btn flex flex-end">
          <div>
            <el-button type="primary"> 自动检测</el-button>
          </div>
          <div>
            <el-button type="primary"> 驳回重提</el-button>
            <el-button type="primary"> 审核存档</el-button>
          </div>
        </div>
        <div id="luckysheet" ></div>
      </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";
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      drawer: false,
      direction: 'rtl',
      selectedCell: '',
      activeName: 'first',
      radio1: '1',
      radio2: '1',
      menuList: [
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        }
      ],
      menuActive: 0,
      socket: null,

    };
  },

  computed: {
    tableHeight() {
      return (this.clientHeight - 140) + 'px'

    },
    ...mapGetters(['clientHeight', 'resolution']),
  },
  async created() {

  },
  watch: {},
  mounted() {
    this.initSocket()
    window.luckysheet.destroy();
    options.data = [
      {
        "name": "Cell", //工作表名称
        "color": "", //工作表颜色
        "index": 0, //工作表索引
        "status": 1, //激活状态
        "order": 0, //工作表的下标
        "hide": 0,//是否隐藏
        "row": 36, //行数
        "column": 18, //列数
        "defaultRowHeight": 19, //自定义行高其
        "defaultColWidth": 73, //自定义列宽
        "celldata": [{ r: 0, c: 0, v: { m: "1", v: 'value', bg: "#00FF00", ct: { fa: 'General', t: 'g' } } }], //初始化使用的单元格数据
        "config": {
          "merge": {}, //合并单元格
          "rowlen": {}, //表格行高
          "columnlen": {}, //表格列宽
          "rowhidden": {}, //隐藏行
          "colhidden": {}, //隐藏列
          "borderInfo": {}, //边框
          "authority": {}, //工作表保护

        },
        "scrollLeft": 0, //左右滚动条位置
        "scrollTop": 315, //上下滚动条位置
        "luckysheet_select_save": [], //选中的区域
        "calcChain": [],//公式链
        "isPivotTable": false,//是否数据透视表
        "pivotTable": {},//数据透视表设置
        "filter_select": {},//筛选范围
        "filter": null,//筛选配置
        "luckysheet_alternateformat_save": [], //交替颜色
        "luckysheet_alternateformat_save_modelCustom": [], //自定义交替颜色	
        "luckysheet_conditionformat_save": {},//条件格式
        "frozen": {}, //冻结行列配置
        "chart": [], //图表配置
        "zoomRatio": 1, // 缩放比例
        "image": [], //图片
        "showGridLines": 1, //是否显示网格线
        "dataVerification": {} //数据验证配置
      },
      {
        "name": "Sheet2",
        "color": "",
        "index": 1,
        "status": 0,
        "order": 1,
        "celldata": [],
        "config": {}
      },
      {
        "name": "Sheet3",
        "color": "",
        "index": 2,
        "status": 0,
        "order": 2,
        "celldata": [],
        "config": {},
      }
    ]
    window.luckysheet.create({
      ...options,
      hook: {
        cellEditBefore: this.handleCellEditBefore,
        // cellUpdateBefore: this.handleCellUpdateBefore,
        sheetCreateAfter:this.handleSheetCreateAfter
      },
    });

  },

  methods: {
    handleSheetCreateAfter(e){
      console.log('setsheet',e);
    },
    initSocket() {
      this.socket = new WebSocket('');
      this.socket.addEventListener('open', () => {
        console.log('WebSocket连接已打开');
      });
      this.socket.addEventListener('message', (event) => {
        console.log(event,'接收到消息了');
      });
    },
    sendMessage() {
      const message = {
        sender: '客户端'
      };
      this.socket.send(JSON.stringify(message));
      this.newMessage = '';
    },
    handleClickMenu(i) {
      this.menuActive = i;
    },
    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: {

          },
        });
      });
    },
    // //保存
    // 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) {
      console.log(e, 'seeeeeee');
      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);
    },
    handelClickBack() {
      this.$emit('close')
    },
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  },
  props: {},
};
</script>
<style lang="scss" scoped>
.luckysheet-wrap {
  margin: 10px;
  padding: 0px;
  z-index: 2;
  width: calc(100% - 240px);
  height: calc(100% - 20px);
}
#luckysheet{
  width: 100%;
  padding: 0px;
  z-index: 2;
  height: calc(100% - 80px);
  margin: 10px;
}
.top_btn{
  height: 60px;
  width: 100%;
}
.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;
}

.left_menu {
  width: 240px;

  .menu_item {
    cursor: pointer;
    padding: 10px 16px;
    box-sizing: border-box;
    margin-bottom: 5px;
    background-color: #f2f8fd;
    border-radius: 5px;
    font-size: 14px;
  }

  .active {
    color: #3989eb;
  }
}
</style>