/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

/* global console, document, Excel, Office */
import * as XLSX from "xlsx";
import { generateTotalSheet, groupByUsers } from "../process";
import { analiseSalesForcast } from '../processForcast'

Office.onReady((info) => {
  if (info.host === Office.HostType.Excel) {
    document.getElementById("app-body").style.display = "flex";
    document.getElementById("run").onclick = run;
    document.getElementById("forcast").onclick = genForcast;


    // Add event listener for file input
    const fileInput = document.getElementById("sales-invoce-data-source") as HTMLInputElement;
    fileInput.addEventListener("change", handleFileUpload);
  }
});
let salesInvoiceData: any[] = [];

function handleFileUpload(event: Event) {
  const fileInput = event.target as HTMLInputElement;
  if (fileInput.files && fileInput.files[0]) {
    const file = fileInput.files[0];

    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target?.result as ArrayBuffer);
      const workbook = XLSX.read(data, { type: "array" });

      // Get the first sheet name
      const sheetName = workbook.SheetNames[0];

      // Get the worksheet
      const worksheet = workbook.Sheets[sheetName];

      // Convert the worksheet to JSON
      const dataSource = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

      // Convert the rows to objects using the headers
      const [_, headers, ...rows] = dataSource;
      salesInvoiceData = tableAsObjects(headers, rows);

      // Log the data or display it
      // console.log("Excel Data:", salesInvoiceData);
    };

    reader.readAsArrayBuffer(file);
  }
}

const tableAsObjects = (headers, rows) => rows.map((row) => {
  const obj: Record<string, any> = {};
  headers.forEach((header, index) => {
    obj[header.replace(/\r\n/g, '')] = row[index];
  });
  return obj;
});

let isRuningTotal = false;
export async function run(e) {
  if (isRuningForcast) return;

  isRuningForcast = true;
  const buttonLabel: HTMLElement = e.target;
  buttonLabel.textContent = '正在生成...';

  try {
    await Excel.run(async (context) => {
      // Get the active worksheet
      const sheet = context.workbook.worksheets.getActiveWorksheet();
      if (!salesInvoiceData) {
        console.error("No sales invice data imported!");
        return;
      }

      const salesData = groupByUsers(salesInvoiceData);
      await generateTotalSheet(context, salesData);
      // Log the objects to the console
      console.log("Table as objects:", salesData);
    });
  } catch (error) {
    console.error(error);
  } finally {
    isRuningForcast = false;
  }

  buttonLabel.textContent = '導入銷售表';
}

let isRuningForcast = false;
export async function genForcast(e) {
  if (isRuningForcast) return;

  isRuningForcast = true;
  console.log('earo say the e.target', e.target);
  const buttonLabel: HTMLElement = e.target;
  buttonLabel.textContent = '正在生成...';

  try {
    await Excel.run(async (context) => {
      // 取得「銷售年度預估」工作表
      const salesForecastSheet = context.workbook.worksheets.getItem("銷售年度預估");
      const salesRange = salesForecastSheet.getUsedRange();
      salesRange.load(["values"]);

      // 取得「產品年度預估」工作表
      const productForecastSheet = context.workbook.worksheets.getItem("產品年度預估");
      const productRange = productForecastSheet.getUsedRange();
      productRange.load(["values"]);

      await context.sync();

      // 轉為陣列
      const salesForecastData = salesRange.values;
      const productForecastData = productRange.values;

      // 輸出到 console 以供檢查
      console.log("銷售年度預估:", salesForecastData);
      console.log("產品年度預估:", productForecastData);

      await analiseSalesForcast(context, salesForecastData);
    });
  } catch (error) {
    console.error(error);
  } finally {
    isRuningForcast = false;
  }

  buttonLabel.textContent = '制定年度預估';
}