<template>
  <div>
    <button @click="loadExcel">从MinIO加载Excel文件</button>
    <button @click="saveExcel">将Excel文件保存至MinIO</button>
    <div id="x-spreadsheet"></div>
  </div>
</template>

<script>
import axios from 'axios';
import 'x-data-spreadsheet/dist/xspreadsheet.css';
import zhCN from 'x-data-spreadsheet/src/locale/zh-cn';
import x_spreadsheet from 'x-data-spreadsheet';
import XLSX from 'xlsx';
import { stox, xtos } from '@/utils/xlsxspread';

export default {
  name: 'ExcelComponent',
  data() {
    return {
      spreadsheet: null,
    };
  },
  mounted() {
    x_spreadsheet.locale('zh-cn', zhCN);
    this.spreadsheet = new x_spreadsheet('#x-spreadsheet', {
      mode: 'edit',
      showToolbar: true,
      showGrid: true,
      showContextmenu: true,
      showBottomBar: true,
      view: {
        height: () => document.documentElement.clientHeight * 0.9,
        width: () => document.documentElement.clientWidth,
      },
      row: {
        len: 100,
        height: 25,
      },
      col: {
        len: 26,
        width: 100,
        indexWidth: 60,
        minWidth: 60,
      },
      style: {
        bgcolor: '#ffffff',
        align: 'left',
        valign: 'middle',
        textwrap: false,
        strike: false,
        underline: false,
        color: '#0a0a0a',
        font: {
          name: 'Helvetica',
          size: 10,
          bold: false,
          italic: false,
        },
      },
    });
  },
  methods: {
    // 从MinIO加载Excel文件
    loadExcel() {
      const minioUrl = 'http://47.95.198.7:30000/tmp/123.xlsx';

      axios.get(minioUrl, { responseType: 'arraybuffer' })
        .then(response => {
          // 将Excel文件转换为数组缓冲区
          const data = new Uint8Array(response.data);
          // 将数组缓冲区转换为工作簿对象
          const workbook = XLSX.read(data, { type: 'array' });
          // 将工作簿对象转换为Spreadsheet数据格式
          const spreadsheetData = stox(workbook);
          // 添加自定义公式，123.xlsx表格中B列已有的公式为A+C+D。下面在F列添加A+D的计算公式.
          const firstSheetRows = spreadsheetData[0].rows;
          const keys = Object.keys(firstSheetRows);
          for (let i = 1; i < keys.length - 1; i++) {
            console.log(i, keys[i]);
            // 在F列添加A+D的计算公式，F列的序号为5.
            firstSheetRows[keys[i]].cells['5'] = { 
              text: `=SUM(A${i + 1},D${i + 1})`
            }
          }
          // 将数据加载到Spreadsheet
          this.spreadsheet.loadData(spreadsheetData);
        })
        .catch(error => console.error('加载文件失败:', error));
    },
    saveExcel() {
      // 获取Spreadsheet的数据
      const data = this.spreadsheet.getData();
      // 将数据转换为XLSX格式
      const workbook = xtos(data);

      // 将XLSX数据保存为文件
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });

      // 将blob对象上传至minio
      const minioUploadUrl = 'http://47.95.198.7:30000/tmp/123.xlsx';
      axios.put(minioUploadUrl, blob, {
        headers: {
          'Content-Type': 'application/octet-stream',
        }
      })
      .then(response => {
        console.log('文件上传成功', response);
      })
      .catch(error => console.error('文件上传失败:', error));
    }
  }
};
</script>

<style scoped>
#x-spreadsheet {
  width: 100%;
  height: 500px;
  margin-bottom: 20px;
}
</style>