<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>
        <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="warning"> 自动检测</el-button>
          </div>
          <div>
            <el-button type="danger"> 驳回重提</el-button>
            <el-button type="primary"> 审核存档</el-button>
          </div>
        </div>
        <div id="luckysheet"></div>
      </div>
    </div>
   
  </div>
</template>

<script>

import LuckyExcel from 'luckyexcel';
import options from "@/utils/luckysheetConfig.js";
import { mapGetters } from 'vuex'
import { requestPost, requestGet } from "@/js/dai/request";

export default {
  data() {
    return {
      selectedCell: '',
      menuList: [
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        }
      ],
      menuActive: 0,
      socket: null,
    };
  },
  props: {
    workbookId: {
      type: String,
      default: ''
    }
  },
  computed: {
    tableHeight() {
      return (this.clientHeight - 140) + 'px'

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

  },
  watch: {},
  mounted() {
    this.initSocket()
    this.loadWorkBook()
  },
  methods: {
     async loadWorkBook() {
      const data = await this.$http.post(`/actual/base/luckySheet/workbook/load?workbookId=${this.workbookId}`)
        window.luckysheet.destroy();
        options.data = data.data
        window.luckysheet.create({
          ...options,
          hook: {
            cellEditBefore: this.handleCellEditBefore,
            // cellUpdateBefore: this.handleCellUpdateBefore,
            sheetCreateAfter: this.handleSheetCreateAfter,
            cellUpdated: this.handleCellUpdated,
          },
        });
    },
    handleSheetCreateAfter(e) {
      console.log('setsheet', e);
    },
    initSocket() {
      const {id} = this.$store.state.user;//${location.origin}
      const token = localStorage.getItem("token")
      this.socket = new WebSocket(`ws://192.168.1.144/api/actual/base/ws/luckysheet/${this.workbookId}/${id}`,token);
      this.socket.addEventListener('open', () => {
        console.log('WebSocket连接已打开');
      });
      this.socket.addEventListener('message', (event) => {
        console.log(event, '接收到消息了');
        const message = JSON.parse(event.data);

      });
    },
    sendMessage(message) {
      this.socket.send(JSON.stringify(message));
    },
    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];
      debugger
      if (suffix != 'xlsx') return alert('目前只支持导入xlsx文件');
      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')
    //   })
    // },


  

    handleCellUpdated(r, c, oldValue, newValue, isRefresh) {
      console.log(r, c, oldValue, newValue, isRefresh, '--11')
      let obj = {
        r,
        c,
        t:'v',
        ...newValue
      }
      this.sendMessage(obj)
    },
    handleCellEditBefore(e) {
      console.log(e, '--11')
      let column = parseInt(e[0].column[0]) + 1, row = parseInt(e[0].row[0]) + 1;
      this.selectedCell = "第" + row + "行" + "第" + column + "列";
      
    },
    handleCellUpdateBefore() {
      this.selectedCell = "";
    },
    handleTabClick(tab, event) {
      console.log(tab, event);
    },
    handelClickBack() {
      this.$emit('close')
    },
  },
  beforeDestroy() {
    this.$store.state.sidebarFold = false;
    if (this.socket) {
      this.socket.close();
    }
  },

};
</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>