<template>
  <div class='flex'>
    <div :class="['flex', 'flex-y', 'flex1', 'luckysheet-wrap-all']">
      <div class="top_btn flex flex-end">
        <div>
          <el-button type="text" round @click="handelClickBack" icon="el-icon-back">返回</el-button>
          <el-button type="warning" @click="handleClickInspect">上传统计模板
          </el-button>
          <el-button type="success" @click="onClickUplond()"> 数据列表导出</el-button>
        </div>
        <div>
          <el-button type="primary" @click="handleClickCurrencyEvent('submit')"> 导出</el-button>
        </div>
      </div>
      <div id="luckysheet"></div>
    </div>
    <el-dialog title="数据列表导出" v-if="showUploadData" :visible.sync="showUploadData" width="60%"
      :close-on-click-modal="false">
      <excelUploadData @handleUploadDataHide="handleUploadDataHide" :currentTable="currentTable"
        :btnLoading="btnLoading" :pageType='`report`' :workBookId="workBookId" @saveLuckysheetHead="saveLuckysheet">
      </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";
import nextTick from "dai-js/tools/nextTick";
import { exportSheetExcel } from "@/utils/export";

export default {
  data() {
    return {
      showUploadData: false,
      menuList: [],
      menuActive: 0,
      socket: null,
      currentTable: null,
      currentId: '',
      btnLoading: false,
      workBookId: ''
    };
  },
  props: {
    pageType: {
      type: String,
      default: ''
    },
    infoIds: {
      type: Object,
      default: () => { }
    }
  },
  computed: {
    tableHeight() {
      return (this.clientHeight - 140) + 'px'
    },
    ...mapGetters(['clientHeight', 'resolution']),
  },
  created() {

  },
  watch: {},
  async mounted() {
    await this.loadWorkBook()
    if (this.pageType === 'info') {
      await this.getSheetList()
    }
  },
  methods: {
    async getSheetList() {
      const { data, code } = await requestGet('/actual/base/intellgentizeReport/detail', { id: this.infoIds.id })
      if (code === 0) {
        console.log(data);
      }
    },
    handleClickCurrencyEvent() {
      exportSheetExcel(luckysheet.getAllSheets(), '导出文件')
    },
    // 上传模板
    async handleClickInspect() {

    },
    
    onClickUplond() {
      this.showUploadData = true;
      let list = luckysheet.getAllSheets()
      this.currentTable = list.filter(item => item.status == '1')

    },
    async handleUploadDataHide(val) {
      let listData = await this.getListData(val.id)
      luckysheet.insertRow(this.currentTable[0].data.length, 1)
      luckysheet.insertRow(this.currentTable[0].data.length, { number: listData.length });
      this.showUploadData = false;
      await nextTick(500)
      let newArray = listData.map(obj => {
        return Object.keys(obj).map(key => {
          return { m: obj[key], "ct": { "fa": "General", "t": "g" }, v: obj[key] };
        });
      });
      let bottomRightCorner = this.numberToLetter(Object.keys(listData[0]).length)//选区右下角数字
      luckysheet.setRangeValue(newArray, {
        range: `A2:${bottomRightCorner}${2 + listData.length}`,
      })
     
    },
    async saveLuckysheet(head) {
      if (this.currentTable[0].data[0].every(item => !item) && head) {
        let temp = head.map(item => item.children).flat();
        for (let i in temp) {
          luckysheet.setCellValue(0, i, temp[i].label)
        }
      }
      let luckysheetJson = luckysheet.getAllSheets()
      const { data, code, msg } = await requestPost(`/actual/base/luckySheet/workbook/createByJson?fileName=`, luckysheetJson)
      if (code === 0) {
        this.workBookId = data.workbookId;
      } else {
        console.log(msg);
      }
    },
    async getListData(id) {
      const { data, code } = await requestGet('/actual/base/intellgentizeReport/listDatasById', { id })
      if (code === 0) {
        console.log(data);
        return data
      }
    },
    // 数字转换对应顺序英文
    numberToLetter(num) {
      let letter = '';
      while (num > 0) {
        num -= 1; // 调整为从 0 开始（即 1 -> 'A'，2 -> 'B'，...）
        letter = String.fromCharCode(num % 26 + 65) + letter; // 65 是 'A' 的 Unicode 编码
        num = Math.floor(num / 26);
      }
      return letter;
    },
    loadWorkBook() {
      window.luckysheet.destroy();
      options.allowUpdate = true;
      options.container = 'luckysheet'
      options.gridKey = this.pageType === 'info' ? this.infoIds.workbookId : null;
      if (this.pageType === 'info') {
        options.loadUrl = `${process.env.VUE_APP_API_SERVER}/actual/base/luckySheet/workbook/load?workbookId=${this.infoIds.workbookId}`
      }else{
        options.loadUrl = null
      }
      // options.updateUrl = `${process.env.VUE_APP_SOCKET_SERVER}/actual/base/ws/luckysheet/${this.currentId}/${id}`
      window.luckysheet.create({
        ...options,
      });
    },
    handelClickBack() {
      this.$emit('close')
    },
  },
  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-wrap-all {
  margin: 10px;
  padding: 0px;
  z-index: 2;
  width: calc(100vw - 100px);
  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>