type SalesForcastData = {
    year: string
    salesName: string,
    forcast: number[],
    turnover?: number[]
    completion?: number;
    accCompletion?: number;
}

export const analiseSalesForcast = async (context: Excel.RequestContext, rawData: Array<Array<string | number>>) => {
    const [yearRow, headerRow, ...dataRows] = rawData;
    const salesForcatDataList: SalesForcastData[] = [];
    headerRow.splice(0, 1);
    const monthData = {
        year: yearRow[1] as string,
        forcast: headerRow
    };

    for (const salesRow of dataRows) {
        const salesForcastData = {
            year: yearRow[1] as string,
            salesName: salesRow[0] as string,
            forcast: []
        }
        for (let i = 1; i < salesRow.length; i++) {
            salesForcastData.forcast.push(salesRow[i]);
        }
        salesForcatDataList.push(salesForcastData)
    }
    // 新增或取得「業務月達成率」sheet
    let sheet;
    let isNewSheet = true;
    try {
        sheet = context.workbook.worksheets.add("業務月達成率");
        await context.sync(); // Sync the changes with Excel
    } catch {
        sheet = context.workbook.worksheets.getItem("業務月達成率");
        try {
            const usedRange = sheet.getUsedRangeOrNullObject();
            usedRange.load("isNullObject");
            await context.sync();
            if (!usedRange.isNullObject) {
                usedRange.clear();
            }
        } catch (e) {
            // 若無 UsedRange 也忽略
        }
    }

    // 寫入轉置後的資料
    // 產生月份陣列
    const monthCount = monthData?.forcast.length || 0;
    // 合併 A1:A2 並填入年份
    try {
        const yearValue = monthData?.year || yearRow[1];
        // A1:A2 合併並填年份
        sheet.getRange("A1:A2").merge();
        sheet.getRange("A1").values = [[yearValue.toString()]];
        sheet.getRange("A1").numberFormat = [['@']];
        // A3~: 填入月份
        if (monthCount > 0) {
            sheet.getRange(`A3:A${monthCount + 2}`).values = monthData.forcast.map(m => [m]);
        }
        // B1~: 填入 salesName 並合併
        let col = 1; // B欄開始
        for (let i = 0; i < salesForcatDataList.length; i++) {
            const salesForcastData = salesForcatDataList[i];
            let rowIndex = 0;
            const startCol = col;
            const endCol = col + 4;
            sheet.getRangeByIndexes(rowIndex, startCol, 1, 2).merge();
            sheet.getRangeByIndexes(rowIndex, startCol, 1, 1).values = [[salesForcastData.salesName]];
            sheet.getRangeByIndexes(rowIndex, startCol + 2, 2, 1).merge();
            sheet.getRangeByIndexes(rowIndex, startCol + 2, 1, 1).values = [['完成%']];
            sheet.getRangeByIndexes(rowIndex, startCol + 3, 2, 1).merge();
            sheet.getRangeByIndexes(rowIndex, startCol + 3, 1, 1).values = [['累積達成率']];

            rowIndex++;
            sheet.getRangeByIndexes(rowIndex, startCol, 1, 1).values = [['Y-forecast']];
            sheet.getRangeByIndexes(rowIndex, startCol + 1, 1, 1).values = [['turnover']];

            rowIndex++;
            for (const forcastMonth of salesForcastData.forcast) {
                const cell = sheet.getRangeByIndexes(rowIndex, startCol, 1, 1);
                cell.values = [[forcastMonth]];
                cell.numberFormat = [["#,##0"]]; // 千分號格式
                rowIndex++;
            }

            col = endCol;
        }
        
        await context.sync(); // Sync the changes with Excel
        // 自適應所有已用欄位寬度
        const usedRange = sheet.getUsedRangeOrNullObject();
        usedRange.load("isNullObject");
        await context.sync();
        if (!usedRange.isNullObject) {
            usedRange.format.autofitColumns();
        }
        await context.sync();
    } catch (e) {
        console.error('catch err', e)
    }

}