<template>
  <!--  :style="{ height: tableHeight }" -->
  <div class='flex el-card'>
    <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,item)">
        <span>{{ item.name }}</span>
        <i class="el-icon-arrow-right"></i>
      </div>
    </div>
    <div class="flex flex-y flex1 luckysheet-wrap">
      <div class="top_btn flex flex-end">
        <div>
          <el-button type="warning" @click="getAllTables"> 自动检测</el-button>
          <el-button type="warning" @click="onClickUplond()"> 智能填表</el-button>
        </div>
        <div>
          <el-button type="danger"> 驳回重提</el-button>
          <el-button type="primary"> 审核存档</el-button>
        </div>
      </div>
      <div id="luckysheet"></div>
    </div>
    <el-dialog title="上传共享数据" :visible.sync="showUploadData" width="50%" :close-on-click-modal="false">
      <excelUploadData   @handelUploadData="handelUploadData">
      </excelUploadData>
    </el-dialog>
  </div>
</template>

<script>
import excelUploadData from './excel-upload-data.vue';
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 {
      showUploadData:false,
      menuList: [
        {
          name: '2024年11月第三周（已提交）',
          workbookId:'1876569275607785473'
        },
        {
          name: '2024年11月第三周（已提交）',
          workbookId:'1876571135966158850'
        },
        {
          name: '2024年11月第三周（已提交）',
          workbookId:'1879063358107648002'
        },
        {
          name: '2024年11月第三周（已提交）'
        },
        {
          name: '2024年11月第三周（已提交）'
        }
      ],
      menuActive: 0,
      socket: null,
      currentTable:null,
      currentId:'1876569275607785473'
    };
  },
  props: {
    workbookId: {
      type: String,
      default: ''
    }
  },
  computed: {
    tableHeight() {
      return (this.clientHeight - 140) + 'px'

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

  },
  watch: {},
  mounted() {
    this.$nextTick(() => {
      this.loadWorkBook()
    })
  },
  methods: {
    onClickUplond(){
      this.showUploadData=true
    },
    handelUploadData(){
      this.showUploadData=false
    },
    loadWorkBook() {
      window.luckysheet.destroy();
      const { id } = this.$store.state.user;
      options.gridKey = this.currentId;
      options.allowUpdate = true;
      options.container = 'luckysheet'
      options.loadUrl = `http://219.146.91.110:30801/api/actual/base/luckySheet/workbook/load?workbookId=${this.currentId}`
      options.updateUrl = `ws://219.146.91.110:30801/api/actual/base/ws/luckysheet/${this.currentId}/${id}`
      options.loadSheetUrl = `http://219.146.91.110:30801/api/actual/base/luckySheet/workbook/loadSheets?workbookId=${this.currentId}`
      window.luckysheet.create({
        ...options,
        hook: {
          cellEditBefore: this.handleCellEditBefore,
          sheetCreateAfter: this.handleSheetCreateAfter,
        },
      });
    },
    handleSheetCreateAfter(e) {
      console.log('setsheet', e);
    },
    handleClickMenu(i,val) {
      this.menuActive = i;
      this.currentId = val.workbookId;
      this.loadWorkBook()
    },
    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: {

          },
        });
      });
    },
    handleTabClick(tab, event) {
      console.log(tab, event);
    },
    handelClickBack() {
      this.$emit('close')
    },
    getAllTables() {
      let list = luckysheet.getAllSheets()
      this.currentTable = list.filter(item => item.status == '1')
      
      const findLastNonNullIndex = (arr) => {
        for (let i = arr.length - 1; i >= 0; i--) {
            const subArray = arr[i];
            // 判断：是数组，且至少有一个不为 null 的元素
            if (Array.isArray(subArray) && subArray.some(item => item !== null && item.v && item.v !== null&& item.v !== '')) {
                return i;  // 返回下标
            }
        }
        return -1;  // 如果没有符合条件的，返回 -1
    };
      this.sheetR =  findLastNonNullIndex(this.currentTable[0].data)
      console.log(this.sheetR);
      if(this.sheetR != -1){
        luckysheet.insertRow(this.currentTable[0].data.length,5)
        this.updataSheet()
      }
    },
    updataSheet() {
      let arr = [
        {
          1: '张三1',
          2: '证件类型1',
          3: '1234',
          4: '456',
          5: '国籍',
          6: '性别',
          7: '出生日期',
          8: '所属社区',
          9: '所属网格',
          10: '所属小区',
          11: '楼栋名称',
          12: '单元号',
          13: '门牌号',
          14: '人房关系',
          15: '人户状况',
          16: '与户主关系',
          17: '民族'
        },
        {
          1: '张三12',
          2: '证件类型12',
          3: '12342',
          4: '4562',
          5: '国籍2',
          6: '性别2',
          7: '出生日期2',
          8: '所属社区2',
          9: '所属网格2',
          10: '所属小区2',
          11: '楼栋名称2',
          12: '单元号2',
          13: '门牌号2',
          14: '人房关系2',
          15: '人户状况2',
          16: '与户主关系2',
          17: '民族'
        }
      ]
      arr.forEach((item, index) => {
        luckysheet.insertRow(this.currentTable[0].data.length,1)
        for (let k in item) {
          luckysheet.setCellValue(index+this.sheetR + 1, k - 1, item[k])
        }
      })
    },
  },
  components:{
    excelUploadData
  },
  components:{
    excelUploadData
  },
  beforeDestroy() {
    this.$store.state.sidebarFold = false;
    if (this.socket) {
      this.socket.close();
    }
  },

};
</script>
<style lang="scss" scoped>
.el-card {
  margin: 10px auto;
  padding: 0 16px;
  box-sizing: border-box;
  width: calc(100% - 40px);
  border: none;
}

.luckysheet-wrap {
  margin: 10px;
  padding: 0px;
  z-index: 2;
  width: calc(100vw - 400px);
  height: calc(100vh - 250px);
}

#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>