<template>
  <div class="lucky-sheet-container">
    <!-- 操作按钮栏 -->
    <!-- <el-card class="operate-bar" shadow="never">
      <el-button type="primary" icon="el-icon-download" @click="exportExcel">导出Excel</el-button>
      <el-button icon="el-icon-upload2" @click="importExcel">导入Excel</el-button>
      <el-button icon="el-icon-document" @click="getData">获取数据</el-button>
      <el-input
        v-model="sheetName"
        placeholder="请输入表格名称"
        style="width: 200px; margin-left: 10px;"
        @change="updateSheetName"
      ></el-input>
      <input
        type="file"
        ref="fileInput"
        accept=".xlsx"
        style="display: none"
        @change="handleFileImport"
      >
    </el-card> -->
    
    <!-- Luckysheet 容器 -->
    <div id="luckysheet" style="width: 99%; height: 100%; margin: 0px;"></div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import LuckyExcel from 'luckyexcel'

const ExcelJS = require('exceljs')

export default {
  name: 'LuckySheet',
  props: {
    initialData: {
      type: Array,
      default: () => []
    },
    options: {
      type: Object,
      default: () => ({})
    },
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      sheetName: '新建表格',
      luckyOptions: {
        container: 'luckysheet',
        title: '新建表格',
        lang: 'zh',
        showinfobar: false,
        showtoolbar: true,
        showstatisticBar: true,
        showconfigbar: true,
        showsheetbar: true,
        showsheetbarConfig: {
          add: true,
          menu: true,
        },
        allowEdit: true,
        enableAddRow: true,
        enableAddCol: true,
        sheetFormulaBar: true,
        pointEdit: true,
        pointEditUpdate: true,
        data: [],
        // loadUrl:"http://"+ location.host +"/blade-manager/exceltab/getExcelUrl",
      }
    }
  },
  watch: {
  initialData(newVal, oldVal) {
    // 避免初始值为空时的无效触发
    if (!newVal || newVal.length === 0) return;
    
    // 简单判断数据是否真的变化（根据实际数据结构调整）
    if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {

      this.initLuckysheet();
    }
  }
},
  
  mounted() {
    this.$nextTick(() => {
      this.initLuckysheet()
    })
  },
  beforeDestroy() {
    // 销毁Luckysheet实例
    if (window.luckysheet) {
      window.luckysheet.destroy()
    }
  },
  methods: {
    // 初始化Luckysheet
    initLuckysheet() {
       // 先销毁已有实例
      if (window.luckysheet) {
        window.luckysheet.destroy();
      }
      const options = { ...this.luckyOptions, ...this.options }
      options.title = this.sheetName
      
      // 如果有初始数据，使用初始数据
      if (this.initialData && this.initialData.length > 0) {
        options.data = this.initialData
      }
      
      // 创建Luckysheet实例
      window.luckysheet.create(options)
    },

    
    // 导出Excel
    async exportExcel() {
      try {
        // 获取所有工作表数据
        const luckysheet = window.luckysheet.getAllSheets()
        
        // 创建工作簿
        const workbook = new ExcelJS.Workbook()
        
        // 遍历所有工作表
        luckysheet.forEach((table) => {
          if (table.data.length === 0) return
          
          // 添加工作表
          const worksheet = workbook.addWorksheet(table.name)
          
          // 设置单元格样式和值
          this.setStyleAndValue(table.data, worksheet)
          
          // 设置合并单元格
          if (table.config && table.config.merge) {
            this.setMerge(table.config.merge, worksheet)
          }
          
          // 设置边框
          if (table.config && table.config.borderInfo) {
            this.setBorder(table.config.borderInfo, worksheet)
          }
        })
        
        // 写入buffer
        const buffer = await workbook.xlsx.writeBuffer()
        
        // 保存文件
        FileSaver.saveAs(
          new Blob([buffer], { type: 'application/octet-stream' }),
          `${this.sheetName}.xlsx`
        )
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    
    // 导入Excel
    importExcel() {
      this.$refs.fileInput.click()
    },
    
    // 处理文件导入
    handleFileImport(e) {
      const file = e.target.files[0]
      if (!file) return
      
      const that = this
      LuckyExcel.transformExcelToLucky(file, function(exportJson, luckysheetfile) {
        if (exportJson.sheets === null || exportJson.sheets.length === 0) {
          that.$message.error('无法读取excel文件的内容')
          return
        }
        
        // 销毁现有实例
        window.luckysheet.destroy()
        
        // 更新表格名称
        that.sheetName = exportJson.info.name || '导入的表格'
        
        // 创建新实例
        window.luckysheet.create({
          container: 'luckysheet',
          title: that.sheetName,
          lang: 'zh',
          data: exportJson.sheets,
          showinfobar: false
        })
        
        that.$message.success('导入成功')
      }, function(error) {
        console.error('导入错误:', error)
        that.$message.error('导入失败，请检查文件格式')
      })
      
      // 清空文件输入，允许再次选择相同文件
      e.target.value = ''
    },
    
    // 获取表格数据
    getData() {
      const data = window.luckysheet.getAllSheets()
      console.log(data,'data');
      
      this.$emit('data-change', data)
      // this.$message.success('已获取最新数据')
      return data
    },
    
    // 更新表格名称
    updateSheetName() {
      if (window.luckysheet) {
        window.luckysheet.setWorkbookName(this.sheetName)
      }
    },
    
    // 设置单元格样式和值
    setStyleAndValue(data, worksheet) {
      // 简化实现，实际应用可能需要更复杂的逻辑
      data.forEach((row, rowIndex) => {
        row.forEach((cell, colIndex) => {
          if (cell !== null) {
            const worksheetCell = worksheet.getCell(rowIndex + 1, colIndex + 1)
            worksheetCell.value = cell.v !== undefined ? cell.v : cell
            
            // 设置样式
            if (cell.ct) {
              if (cell.ct.fa) {
                worksheetCell.numFmt = cell.ct.fa
              }
              
              if (cell.ct.s) {
                const style = cell.ct.s
                if (style.fc) {
                  worksheetCell.font = { color: { argb: style.fc.replace('#', '') } }
                }
                if (style.bg) {
                  worksheetCell.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: { argb: style.bg.replace('#', '') }
                  }
                }
              }
            }
          }
        })
      })
    },
    
    // 设置合并单元格
    setMerge(mergeData, worksheet) {
      Object.values(mergeData).forEach((item) => {
        worksheet.mergeCells(
          item.r + 1,
          item.c + 1,
          item.r + item.rs,
          item.c + item.cs
        )
      })
    },
    
    // 设置边框
    setBorder(borderInfo, worksheet) {
      // 简化实现，实际应用可能需要更复杂的逻辑
      if (!Array.isArray(borderInfo)) return
      
      borderInfo.forEach((elem) => {
        if (elem.rangeType === 'range') {
          const range = elem.range[0]
          const row = range.row
          const col = range.column
          
          for (let i = row[0] + 1; i < row[1] + 2; i++) {
            for (let j = col[0] + 1; j < col[1] + 2; j++) {
              const cell = worksheet.getCell(i, j)
              cell.border = {
                top: { style: 'thin' },
                left: { style: 'thin' },
                bottom: { style: 'thin' },
                right: { style: 'thin' }
              }
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.lucky-sheet-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  /* border: 1px solid yellow; */
}

.operate-bar {
  margin-bottom: 10px;
}
</style>