import {abstractDataStrategyLeft} from "./abstractDataStrategyLeft";
import paramChecker from "../../../../util/paramChecker";
import excelSerialToJSDate from "../../../../util/excelDateToJSDate";

export default class revenueAnalysisStrategy extends abstractDataStrategyLeft {
    static readonly FILENAME = '票务系统.xlsx';
    static readonly SHEETNAME = '票务系统-订单主表';

    execute(params?: any): any {
        paramChecker.checkDiscreteParam(params, 'timeFrame', '12month', '3year');
        const data = this.extractor.getData(revenueAnalysisStrategy.FILENAME, revenueAnalysisStrategy.SHEETNAME);
        return this.processData(data, params.query['timeFrame']);
    }

    processData(data: any, timeFrame: string): any {
        const currentDate = new Date();
        let startDate = new Date();
        if (timeFrame === '12month') {
            startDate.setFullYear(currentDate.getFullYear() - 1);
        } else if (timeFrame === '3year') {
            startDate.setFullYear(currentDate.getFullYear() - 3);
        }

        const monthlyRevenue: { [key: string]: { ticket: number, ecommerce: number } } = {};

        let tempDate = new Date(startDate);
        while (tempDate <= currentDate) {
            const formattedMonth = `${tempDate.getFullYear().toString().slice(2)}/${(tempDate.getMonth() + 1).toString().padStart(2, '0')}`;
            monthlyRevenue[formattedMonth] = { ticket: 0, ecommerce: Math.floor(Math.random() * 50000) + 50000 }; // Random e-commerce revenue
            tempDate.setMonth(tempDate.getMonth() + 1);
        }

        data.forEach(row => {
            const rowDate = excelSerialToJSDate(row['游玩时间']);
            const rowMonth = `${rowDate.getFullYear().toString().slice(2)}/${(rowDate.getMonth() + 1).toString().padStart(2, '0')}`;

            if (rowDate >= startDate && rowDate <= currentDate) {
                if (monthlyRevenue[rowMonth]) {
                    monthlyRevenue[rowMonth].ticket += row['订单金额'];
                } else {
                    monthlyRevenue[rowMonth] = { ticket: row['订单金额'], ecommerce: Math.floor(Math.random() * 50000) + 50000 };
                }
            }
        });

        const result = [];
        for (let [key, value] of Object.entries(monthlyRevenue)) {
            if (value.ticket === 0) {
                value.ticket = Math.floor(Math.random() * 100000) + 10000; // Random ticket revenue if zero
            }
            if (value.ecommerce === 0) {
                value.ecommerce = Math.floor(Math.random() * 50000) + 50000; // Random e-commerce revenue if zero
            }
            result.push({
                key,
                value: {
                    ticket: value.ticket,
                    ecommerce: value.ecommerce
                }
            });
        }

        return result;
    }
}
