import { Sheet } from "xlsx";

type SalesInvoiceData = {
    "业务": string;
    "发票日期": string;
    "发货日期": number;
    "合計金額": number;
    "含税单价": number;
    "备注": string;
    "客户名称": string;
    "数量(KG)": number;
    "未税金额": number;
    "申报所属月份": string;
    "發票號碼": string;
    "稅金13%": number;
    "英文品名": string;
    "订单号码": string;
}
type ClientInfo = {
    area: string,
    industry: string,
    capacityPerYear: string,
    name: string,
    purchaseManager: string,
    purchaseManagerPhone: string,
    purchaser: string,
    purchaserPhone: string,
    address: string,
}

export const readClientInfo = async (context: Excel.RequestContext) => {
    // 取得「客戶資料」工作表
    const sheet = context.workbook.worksheets.getItem("客戶資料");
    // 取得已用範圍
    const usedRange = sheet.getUsedRange();
    usedRange.load(["values"]);
    await context.sync();
    // 取得所有資料
    const rawClientInfo = usedRange.values;
    const [header, ...clientInfoDataSource] = rawClientInfo as string[][];
    const clientInfoMap: { [key: string]: ClientInfo } = {}
    for (const clientInfo of clientInfoDataSource) {
        clientInfoMap[clientInfo[3]] = {
            area: clientInfo[0],
            industry: clientInfo[1],
            capacityPerYear: clientInfo[2],
            name: clientInfo[3],
            purchaseManager: clientInfo[4],
            purchaseManagerPhone: clientInfo[5],
            purchaser: clientInfo[6],
            purchaserPhone: clientInfo[7],
            address: clientInfo[8]
        }
    }

    return clientInfoMap;
}

export const groupByUsers = (invoiceDataList: SalesInvoiceData[]) => {
    const groupedUsers: Record<string, SalesInvoiceData[]> = {};

    invoiceDataList.forEach((invoiceData) => {  // Iterate over each user in the input array
        const key = invoiceData["业务"]?.toLowerCase();  // Use the "客户名称" field as the grouping key

        if (!groupedUsers[key]) {  // If this key doesn't exist in the groupedUsers object, create it
            groupedUsers[key] = [];  // Initialize it with an empty array
        }

        groupedUsers[key].push(invoiceData);  // Push the current user into the appropriate group
    });

    return groupedUsers;  // Return the grouped data
}
const groupInvoiceDataByProduct = (userInvoiceList: SalesInvoiceData[]) => {
    return userInvoiceList.reduce((accGroupedInvoiceData, invoiceData) => {
        const clientName = invoiceData['客户名称']
        if (!accGroupedInvoiceData[clientName]) {
            accGroupedInvoiceData[clientName] = { total: {} }
        }
        const invoiceDataByClient = accGroupedInvoiceData[clientName];

        const productName = invoiceData['英文品名'];
        if (!invoiceDataByClient[productName]) {
            invoiceDataByClient[productName] = {}
        }
        const invoiceDataByProduct = invoiceDataByClient[productName];

        const monthName = invoiceData['申报所属月份'];
        if (!invoiceDataByProduct[monthName]) {
            invoiceDataByProduct[monthName] = {
                quantity: 0,
                price: 0,
                totalPrice: 0
            };
        }
        const invoiceDataByMonth = invoiceDataByProduct[monthName];
        invoiceDataByMonth.quantity += isFinite(invoiceData['数量(KG)']) ? invoiceData['数量(KG)'] : 0;
        invoiceDataByMonth.price += invoiceData['含税单价'];
        invoiceDataByMonth.totalPrice += invoiceData['合計金額'];

        if (!invoiceDataByClient.total[monthName]) {
            invoiceDataByClient.total[monthName] = {
                quantity: 0,
                price: 0,
                totalPrice: 0
            };
        }
        invoiceDataByClient.total[monthName].quantity += invoiceDataByMonth.quantity;
        invoiceDataByClient.total[monthName].price += invoiceDataByMonth.price;
        invoiceDataByClient.total[monthName].totalPrice += invoiceDataByMonth.totalPrice;

        return accGroupedInvoiceData;
    }, {});

}

const genSalesMonthData = ({
    userSheet,
    rowNumber,
    user,
    clientInfo,
    clientName,
    invoiceData,
    productName
}) => {

    const salesNameCell = userSheet.getRange(`A${rowNumber}`);
    salesNameCell.values = [[user]];

    const clientNameCell = userSheet.getRange(`E${rowNumber}`);
    const targetClientInfo = clientInfo[clientName];
    if (targetClientInfo) {
        userSheet.getRange(`B${rowNumber}:J${rowNumber}`).values = [[
            targetClientInfo.area,
            targetClientInfo.industry,
            targetClientInfo.capacityPerYear,
            targetClientInfo.name,
            targetClientInfo.purchaseManager,
            targetClientInfo.purchaseManagerPhone,
            targetClientInfo.purchaser,
            targetClientInfo.purchaserPhone,
            targetClientInfo.address
        ]]
    } else {
        clientNameCell.values = [[clientName]];
    }

    userSheet.getRange(`K${rowNumber}`).values = [[productName]];
    const monthColStartIndex = 12;
    const monthColEndIndex = 47;
    const productYearTotal = { price: 0, quantity: 0, totalPrice: 0 }
    for (let i = monthColStartIndex; i <= monthColEndIndex; i += 3) {
        const monthIndex = Math.floor((i - monthColStartIndex) / 3) + 1; // 1~12月
        const monthName = `${monthIndex}月`;
        //@ts-ignore
        const monthData = invoiceData[monthName];
        if (!monthData) continue;

        userSheet.getRangeByIndexes(rowNumber - 1, i, 1, 1).values = [[monthData.price]];
        userSheet.getRangeByIndexes(rowNumber - 1, i + 1, 1, 1).values = [[monthData.quantity]];
        userSheet.getRangeByIndexes(rowNumber - 1, i + 2, 1, 1).values = [[monthData.totalPrice]];

        productYearTotal.price += monthData.price;
        productYearTotal.quantity += monthData.quantity;
        productYearTotal.totalPrice += monthData.totalPrice;
    }
    userSheet.getRangeByIndexes(rowNumber - 1, 48, 1, 1).values = [[productYearTotal.quantity]];
    userSheet.getRangeByIndexes(rowNumber - 1, 49, 1, 1).values = [[productYearTotal.totalPrice]];
}

export const generateTotalSheet = async (context: Excel.RequestContext, invoiceDataByUser: Record<string, SalesInvoiceData[]>) => {
    const clientInfo = await readClientInfo(context);

    for (const user of Object.keys(invoiceDataByUser)) {
        let userSheet;
        try {
            userSheet = context.workbook.worksheets.add(`JQ Total(${user})`); // Create a new worksheet for each user
            await context.sync();
        } catch (e) {
            userSheet = context.workbook.worksheets.getItem(`JQ Total(${user})`);

            try {
                const usedRange = userSheet.getUsedRangeOrNullObject();
                usedRange.load("isNullObject");
                await context.sync();
                if (!usedRange.isNullObject) {
                    usedRange.clear();
                }
            } catch (e) {
                // 若無 UsedRange 也忽略
            }
        }
        context.trackedObjects.add(userSheet); // Track the worksheet object

        await preparedTotalHeader(userSheet, context); // Sync to ensure the used range is loaded
        // insert data into the worksheet
        const userInvoiceList = invoiceDataByUser[user]; // Get the data for the current user
        let rowNumber = 4; // Start from the 4th row (index 3) to avoid overwriting headers
        const groupedInvoiceList = groupInvoiceDataByProduct(userInvoiceList);
        for (const [clientName, productInvoiceData] of Object.entries(groupedInvoiceList)) {
            for (const [productName, montlyInvoiceData] of Object.entries(productInvoiceData)) {
                if (!productName || productName === 'total') {
                    continue;
                }

                genSalesMonthData({ userSheet, rowNumber, user, clientName, clientInfo, productName, invoiceData: montlyInvoiceData });
                rowNumber++; // Move to the next row for the next invoice data
            }

            genSalesMonthData({ userSheet, rowNumber, user, clientName, clientInfo, productName: '總銷售額', invoiceData: productInvoiceData.total });
            rowNumber++;
        }

        context.trackedObjects.remove(userSheet); // Remove the worksheet object from tracking
    }

    let totalSheet;
    try {
        totalSheet = context.workbook.worksheets.add(`JQ Total(Total)`); // Create a new worksheet for each user
        await context.sync();
    } catch (e) {
        totalSheet = context.workbook.worksheets.getItem(`JQ Total(Total)`);

        try {
            const usedRange = totalSheet.getUsedRangeOrNullObject();
            usedRange.load("isNullObject");
            await context.sync();
            if (!usedRange.isNullObject) {
                usedRange.clear();
            }
        } catch (e) {
            // 若無 UsedRange 也忽略
        }
    }

    await context.sync(); // Sync the changes with Excel
    await mergeUserSheetsToTotalSheet(context);
};

// 合併所有 JQ Total(user) sheet 到 JQ Total(Total)
async function mergeUserSheetsToTotalSheet(context: Excel.RequestContext) {
    // 取得所有 worksheet 名稱
    const sheets = context.workbook.worksheets;
    sheets.load("items/name");
    await context.sync();
    // 篩選出 JQ Total( 開頭且不是 JQ Total(Total) 的 sheet
    const userSheetNames = sheets.items
        .map(s => s.name)
        .filter(name => name.startsWith("JQ Total(") && name !== "JQ Total(Total)");
    // 取得總表
    let totalSheet;
    try {
        totalSheet = context.workbook.worksheets.add("JQ Total(Total)");
        await context.sync();
    } catch {
        totalSheet = context.workbook.worksheets.getItem("JQ Total(Total)");
        try {
            const usedRange = totalSheet.getUsedRangeOrNullObject();
            usedRange.load("isNullObject");
            await context.sync();
            if (!usedRange.isNullObject) {
                usedRange.clear();
            }
        } catch { }
    }
    await preparedTotalHeader(totalSheet, context);
    let allRows = [];
    for (const sheetName of userSheetNames) {
        const sheet = context.workbook.worksheets.getItem(sheetName);
        const usedRange = sheet.getUsedRange();
        usedRange.load(["values", "rowCount", "columnCount"]);
        await context.sync();
        // 跳過前3行header
        const dataRows = usedRange.values.slice(3);
        if (dataRows.length > 0) {
            allRows = allRows.concat(dataRows);
        }
    }
    if (allRows.length > 0) {
        totalSheet.getRangeByIndexes(3, 0, allRows.length, allRows[0].length).values = allRows;
    }
    const totalRowIndex = allRows.length + 4;
    totalSheet.getRange(`A${totalRowIndex}:E${totalRowIndex + 3}`).merge();
    totalSheet.getRange(`A${totalRowIndex}`).values = [['總結']];

    totalSheet.getRange(`K${totalRowIndex}`).values = [['總銷量及金額(未稅)']];
    totalSheet.getRange(`K${totalRowIndex + 1}`).values = [['總銷量及金額(含稅)']];
    totalSheet.getRange(`K${totalRowIndex + 2}`).values = [['總銷量及金額(外銷)']];
    totalSheet.getRange(`K${totalRowIndex + 3}`).values = [['總銷量及金額(內外銷)']];

    totalSheet.getRange(`N${totalRowIndex}`).values = [[`=(SUM(N4:N${totalRowIndex - 1})/2)+N354`]];
    totalSheet.getRange(`Q${totalRowIndex}`).values = [[`=(SUM(Q4:Q${totalRowIndex - 1})/2)+Q354`]];
    totalSheet.getRange(`T${totalRowIndex}`).values = [[`=(SUM(T4:T${totalRowIndex - 1})/2)+T354`]];
    totalSheet.getRange(`W${totalRowIndex}`).values = [[`=(SUM(W4:W${totalRowIndex - 1})/2)+W354`]];
    totalSheet.getRange(`Z${totalRowIndex}`).values = [[`=(SUM(Z4:Z${totalRowIndex - 1})/2)+Z354`]];
    totalSheet.getRange(`AC${totalRowIndex}`).values = [[`=(SUM(AC4:AC${totalRowIndex - 1})/2)+AC354`]];
    totalSheet.getRange(`AF${totalRowIndex}`).values = [[`=(SUM(AF4:AF${totalRowIndex - 1})/2)+AF354`]];
    totalSheet.getRange(`AI${totalRowIndex}`).values = [[`=(SUM(AI4:AI${totalRowIndex - 1})/2)+AI354`]];
    totalSheet.getRange(`AL${totalRowIndex}`).values = [[`=(SUM(AL4:AL${totalRowIndex - 1})/2)+AL354`]];
    totalSheet.getRange(`AO${totalRowIndex}`).values = [[`=(SUM(AO4:AO${totalRowIndex - 1})/2)+AO354`]];
    totalSheet.getRange(`AR${totalRowIndex}`).values = [[`=(SUM(AR4:AR${totalRowIndex - 1})/2)+AR354`]];
    totalSheet.getRange(`AU${totalRowIndex}`).values = [[`=(SUM(AU4:AU${totalRowIndex - 1})/2)+AU354`]];
    totalSheet.getRange(`AW${totalRowIndex}`).values = [[`=(SUM(AW4:AW${totalRowIndex - 1})/2)+AW354`]];

    totalSheet.getRange(`O${totalRowIndex}`).values = [[`=((SUM(O4:O${totalRowIndex - 1})/2) - O${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`R${totalRowIndex}`).values = [[`=((SUM(R4:R${totalRowIndex - 1})/2) - R${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`U${totalRowIndex}`).values = [[`=((SUM(U4:U${totalRowIndex - 1})/2) - U${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`X${totalRowIndex}`).values = [[`=((SUM(X4:X${totalRowIndex - 1})/2) - X${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AA${totalRowIndex}`).values = [[`=((SUM(AA4:AA${totalRowIndex - 1})/2) - AA${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AD${totalRowIndex}`).values = [[`=((SUM(AD4:AD${totalRowIndex - 1})/2) - AD${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AG${totalRowIndex}`).values = [[`=((SUM(AG4:AG${totalRowIndex - 1})/2) - AG${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AJ${totalRowIndex}`).values = [[`=((SUM(AJ4:AJ${totalRowIndex - 1})/2) - AJ${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AM${totalRowIndex}`).values = [[`=((SUM(AM4:AM${totalRowIndex - 1})/2) - AM${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AP${totalRowIndex}`).values = [[`=((SUM(AP4:AP${totalRowIndex - 1})/2) - AP${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AS${totalRowIndex}`).values = [[`=((SUM(AS4:AS${totalRowIndex - 1})/2) - AS${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AV${totalRowIndex}`).values = [[`=((SUM(AV4:AV${totalRowIndex - 1})/2) - AV${totalRowIndex + 2})/1.13`]];
    totalSheet.getRange(`AX${totalRowIndex}`).values = [[`=((SUM(AX4:AX${totalRowIndex - 1})/2) - AX${totalRowIndex + 2})/1.13`]];

    totalSheet.getRange(`N${totalRowIndex + 1}`).values = [[`=(SUM(N4:N${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`Q${totalRowIndex + 1}`).values = [[`=(SUM(Q4:Q${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`T${totalRowIndex + 1}`).values = [[`=(SUM(T4:T${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`W${totalRowIndex + 1}`).values = [[`=(SUM(W4:W${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`Z${totalRowIndex + 1}`).values = [[`=(SUM(Z4:Z${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AC${totalRowIndex + 1}`).values = [[`=(SUM(AC4:AC${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AF${totalRowIndex + 1}`).values = [[`=(SUM(AF4:AF${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AI${totalRowIndex + 1}`).values = [[`=(SUM(AI4:AI${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AL${totalRowIndex + 1}`).values = [[`=(SUM(AL4:AL${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AO${totalRowIndex + 1}`).values = [[`=(SUM(AO4:AO${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AR${totalRowIndex + 1}`).values = [[`=(SUM(AR4:AR${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AU${totalRowIndex + 1}`).values = [[`=(SUM(AU4:AU${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AW${totalRowIndex + 1}`).values = [[`=(SUM(AW4:AW${totalRowIndex - 1})/2)`]];

    totalSheet.getRange(`O${totalRowIndex + 1}`).values = [[`=(SUM(O4:O${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`R${totalRowIndex + 1}`).values = [[`=(SUM(R4:R${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`U${totalRowIndex + 1}`).values = [[`=(SUM(U4:U${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`X${totalRowIndex + 1}`).values = [[`=(SUM(X4:X${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AA${totalRowIndex + 1}`).values = [[`=(SUM(AA4:AA${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AD${totalRowIndex + 1}`).values = [[`=(SUM(AD4:AD${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AG${totalRowIndex + 1}`).values = [[`=(SUM(AG4:AG${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AJ${totalRowIndex + 1}`).values = [[`=(SUM(AJ4:AJ${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AM${totalRowIndex + 1}`).values = [[`=(SUM(AM4:AM${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AP${totalRowIndex + 1}`).values = [[`=(SUM(AP4:AP${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AS${totalRowIndex + 1}`).values = [[`=(SUM(AS4:AS${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AV${totalRowIndex + 1}`).values = [[`=(SUM(AV4:AV${totalRowIndex - 1})/2)`]];
    totalSheet.getRange(`AX${totalRowIndex + 1}`).values = [[`=(SUM(AX4:AX${totalRowIndex - 1})/2)`]];

    //TODO: totalRowIndex + 2

    totalSheet.getRange(`N${totalRowIndex + 3}`).values = [[`=N${totalRowIndex}+N${totalRowIndex + 2}`]];
    totalSheet.getRange(`Q${totalRowIndex + 3}`).values = [[`=Q${totalRowIndex}+Q${totalRowIndex + 2}`]];
    totalSheet.getRange(`T${totalRowIndex + 3}`).values = [[`=T${totalRowIndex}+T${totalRowIndex + 2}`]];
    totalSheet.getRange(`W${totalRowIndex + 3}`).values = [[`=W${totalRowIndex}+W${totalRowIndex + 2}`]];
    totalSheet.getRange(`Z${totalRowIndex + 3}`).values = [[`=Z${totalRowIndex}+Z${totalRowIndex + 2}`]];
    totalSheet.getRange(`AC${totalRowIndex + 3}`).values = [[`=AC${totalRowIndex}+AC${totalRowIndex + 2}`]];
    totalSheet.getRange(`AF${totalRowIndex + 3}`).values = [[`=AF${totalRowIndex}+AF${totalRowIndex + 2}`]];
    totalSheet.getRange(`AI${totalRowIndex + 3}`).values = [[`=AI${totalRowIndex}+AI${totalRowIndex + 2}`]];
    totalSheet.getRange(`AL${totalRowIndex + 3}`).values = [[`=AL${totalRowIndex}+AL${totalRowIndex + 2}`]];
    totalSheet.getRange(`AO${totalRowIndex + 3}`).values = [[`=AO${totalRowIndex}+AO${totalRowIndex + 2}`]];
    totalSheet.getRange(`AR${totalRowIndex + 3}`).values = [[`=AR${totalRowIndex}+AR${totalRowIndex + 2}`]];
    totalSheet.getRange(`AU${totalRowIndex + 3}`).values = [[`=AU${totalRowIndex}+AU${totalRowIndex + 2}`]];
    totalSheet.getRange(`AW${totalRowIndex + 3}`).values = [[`=AW${totalRowIndex}+AW${totalRowIndex + 2}`]];

    totalSheet.getRange(`O${totalRowIndex + 3}`).values = [[`=O${totalRowIndex}+O${totalRowIndex + 2}`]];
    totalSheet.getRange(`R${totalRowIndex + 3}`).values = [[`=R${totalRowIndex}+R${totalRowIndex + 2}`]];
    totalSheet.getRange(`U${totalRowIndex + 3}`).values = [[`=U${totalRowIndex}+U${totalRowIndex + 2}`]];
    totalSheet.getRange(`X${totalRowIndex + 3}`).values = [[`=X${totalRowIndex}+X${totalRowIndex + 2}`]];
    totalSheet.getRange(`AA${totalRowIndex + 3}`).values = [[`=AA${totalRowIndex}+AA${totalRowIndex + 2}`]];
    totalSheet.getRange(`AD${totalRowIndex + 3}`).values = [[`=AD${totalRowIndex}+AD${totalRowIndex + 2}`]];
    totalSheet.getRange(`AG${totalRowIndex + 3}`).values = [[`=AG${totalRowIndex}+AG${totalRowIndex + 2}`]];
    totalSheet.getRange(`AJ${totalRowIndex + 3}`).values = [[`=AJ${totalRowIndex}+AJ${totalRowIndex + 2}`]];
    totalSheet.getRange(`AM${totalRowIndex + 3}`).values = [[`=AM${totalRowIndex}+AM${totalRowIndex + 2}`]];
    totalSheet.getRange(`AP${totalRowIndex + 3}`).values = [[`=AP${totalRowIndex}+AP${totalRowIndex + 2}`]];
    totalSheet.getRange(`AS${totalRowIndex + 3}`).values = [[`=AS${totalRowIndex}+AS${totalRowIndex + 2}`]];
    totalSheet.getRange(`AV${totalRowIndex + 3}`).values = [[`=AV${totalRowIndex}+AV${totalRowIndex + 2}`]];
    totalSheet.getRange(`AX${totalRowIndex + 3}`).values = [[`=AX${totalRowIndex}+AX${totalRowIndex + 2}`]];

    await context.sync();
}

async function preparedTotalHeader(userSheet: Excel.Worksheet, context: Excel.RequestContext) {
    userSheet.getRange("A1:L1").merge();
    userSheet.getRange("A1").values = [['客戶資料']];

    userSheet.getRange("A2:A3").merge();
    userSheet.getRange("A2").values = [['業務']];
    userSheet.getRange("B2:B3").merge();
    userSheet.getRange("B2").values = [['地區']];
    userSheet.getRange("C2:C3").merge();
    userSheet.getRange("C2").values = [['行業']];
    userSheet.getRange("D2:D3").merge();
    userSheet.getRange("D2").values = [['產能/年']];
    userSheet.getRange("E2:E3").merge();
    userSheet.getRange("E2").values = [['名稱']];
    userSheet.getRange("F2:F3").merge();
    userSheet.getRange("F2").values = [['採購主管']];
    userSheet.getRange("G2:G3").merge();
    userSheet.getRange("G2").values = [['電話']];
    userSheet.getRange("H2:H3").merge();
    userSheet.getRange("H2").values = [['採購']];
    userSheet.getRange("I2:I3").merge();
    userSheet.getRange("I2").values = [['電話']];
    userSheet.getRange("J2:J3").merge();
    userSheet.getRange("J2").values = [['地址']];
    userSheet.getRange("K2:K3").merge();
    userSheet.getRange("K2").values = [['產品']];
    userSheet.getRange("L2:L3").merge();
    userSheet.getRange("L2").values = [['需求/月']];

    await context.sync(); // Sync to ensure the worksheet is fully initialized

    let usedRange = userSheet.getUsedRange(); // Get the used range of the worksheet
    usedRange.load(); // Load the used range
    await context.sync(); // Sync to ensure the used range is loaded

    const lastColumn = usedRange.getLastColumn(); // Get the last column of the used range
    lastColumn.load("columnIndex"); // Load the columnIndex property of the last column
    await context.sync(); // Sync to ensure the columnIndex is loaded

    const startColumn = lastColumn.columnIndex + 1; // Start from the next column
    userSheet.getRangeByIndexes(0, startColumn, 1, 38).merge();
    userSheet.getRangeByIndexes(0, startColumn, 1, 1).values = [['年度销售表']];

    // Set month headers
    for (let i = 0; i < 12; i++) {
        const startColumnIndex = startColumn + i * 3; // Each month takes 3 columns
        userSheet.getRangeByIndexes(1, startColumnIndex, 1, 3).merge();
        userSheet.getRangeByIndexes(1, startColumnIndex, 1, 1).values = [[`${i + 1}月`]];
        userSheet.getRangeByIndexes(2, startColumnIndex, 1, 1).values = [['單價']];
        userSheet.getRangeByIndexes(2, startColumnIndex + 1, 1, 1).values = [['數量']];
        userSheet.getRangeByIndexes(2, startColumnIndex + 2, 1, 1).values = [['金額']];
    }
    userSheet.getRangeByIndexes(1, startColumn + 36, 1, 2).merge();
    userSheet.getRangeByIndexes(1, startColumn + 36, 1, 1).values = [[`Total`]];
    userSheet.getRangeByIndexes(2, startColumn + 36, 1, 1).values = [[`總數量`]];
    userSheet.getRangeByIndexes(2, startColumn + 37, 1, 1).values = [[`總金額`]];
    // here I want to set all cell text to center
    usedRange = userSheet.getUsedRange(); // Get the used range of the worksheet
    usedRange.load(); // Load the used range
    await context.sync(); // Sync to ensure the used range is loaded
    usedRange.format.horizontalAlignment = "Center"; // Center align the header row
    await context.sync();
}
