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

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

    execute(params?: any): any {
        paramChecker.checkDiscreteParam(params, 'metric', 'amount', 'ticketCount');
        const data = this.extractor.getData(ticketSalesAnalysisStrategy.FILENAME, ticketSalesAnalysisStrategy.SHEETNAME);
        return this.processData(data, params.query['metric']);
    }

    processData(data: any, metric: string): any {
        let totalSales = 0;
        let totalCancellations = 0;
        let conversionRate = 0;
        let totalCheckedIn = 0;
        let totalTickets = 0;
        let cancellationCount = 0;

        data.forEach(row => {
            const amount = row['订单金额'];
            const isCancelled = row['是否退票'] === '是';
            const isCheckedIn = row['是否检票'] === '是';

            totalSales += amount;
            if (isCancelled) {
                totalCancellations += amount;
                cancellationCount += 1;
            }
            if (isCheckedIn) {
                totalCheckedIn += amount;
            }
            totalTickets += 1;
        });

        if (totalSales > 0) {
            conversionRate = (totalCheckedIn / totalSales) * 100;
        }

        const result = metric === 'amount'
            ? {
                totalSales: parseFloat(totalSales.toFixed(2)),
                totalCheckedIn: parseFloat(totalCheckedIn.toFixed(2)),
                totalCancellations: parseFloat(totalCancellations.toFixed(2)),
                conversionRate: parseFloat(conversionRate.toFixed(2))
            }
            : {
                totalSales: totalTickets,
                totalCheckedIn: totalTickets,
                totalCancellations: cancellationCount,
                conversionRate: parseFloat(conversionRate.toFixed(2))
            };

        return Object.entries(result).map(([key, value]) => ({ key, value }));
    }
}
