<template>
  <div>
    <div style="margin-bottom: 10px;">
      <input 
        type="file" 
        accept=".csv" 
        ref="fileInput" 
        style="display: none;" 
        @change="handleFileImport"
      />
      <button @click="triggerImport">Import CSV</button>
      <button @click="exportCsv">Export CSV</button>
    </div>

    <gc-spread-sheets
      :hostClass="hostClass"
      @workbookInitialized="initWorkbook"
    ></gc-spread-sheets>
  </div>
</template>

<script>
import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2016colorful.css";
import * as GC from "@mescius/spread-sheets";
import "@mescius/spread-sheets-vue";

export default {
  name: "App",
  setup() {
    const hostClass = "spread-host";
    let spread = null;

    function initWorkbook(spreadInstance) {
      spread = spreadInstance;
      const sheet = spread.getActiveSheet();
      sheet.setValue(0, 0, "Hello SpreadJS + Vue!");
      sheet.setValue(1, 0, "Click 'Export CSV' to download this data.");
    }

    // Trigger file input dialog
    function triggerImport() {
      document.querySelector('input[type="file"]').click();
    }

    // Handle the imported CSV file
    function handleFileImport(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = function(e) {
        const csvData = e.target.result;
        const sheet = spread.getActiveSheet();

        // Clear old data
        sheet.clear(0, 0, sheet.getRowCount(), sheet.getColumnCount());

        // Import CSV data
        sheet.setCsv(0, 0, csvData, "\r\n", ",");
      };
      reader.readAsText(file);

      // Reset input value so the same file can be reselected later
      event.target.value = "";
    }

    // Export CSV and trigger download
    function exportCsv() {
      const sheet = spread.getActiveSheet();
      const csv = sheet.getCsv(0, 0, sheet.getRowCount(), sheet.getColumnCount(), "\r\n", ",");

      const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
      const link = document.createElement("a");
      link.href = URL.createObjectURL(blob);
      link.download = "spreadsheet-export.csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    return {
      hostClass,
      initWorkbook,
      triggerImport,
      handleFileImport,
      exportCsv,
    };
  },
};
</script>

<style>
.spread-host {
  width: 100%;
  height: 550px;
  border: 1px solid #ccc;
}
button {
  background-color: #007bff; 
  color: white;              
  border: none;              
  border-radius: 4px;        
  padding: 8px 14px;         
  margin-right: 8px;         
  cursor: pointer;           
  font-size: 14px;
  transition: background-color 0.2s ease;
}


button:hover {
  background-color: #0056b3;
}


button:active {
  background-color: #004085;
}
</style>
