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: { name: '售票', value: parseFloat(totalSales.toFixed(2)), unit: '元' },
                totalCheckedIn: { name: '核销', value: parseFloat(totalCheckedIn.toFixed(2)), unit: '元' },
                totalCancellations: { name: '退票', value: parseFloat(totalCancellations.toFixed(2)), unit: '元' },
                conversionRate: { name: '转化率', value: parseFloat(conversionRate.toFixed(2)), unit: '%' }
            }
            : {
                totalSales: { name: '售票', value: totalTickets, unit: '张' },
                totalCheckedIn: { name: '核销', value: totalTickets, unit: '张' },
                totalCancellations: { name: '退票', value: cancellationCount, unit: '张' },
                conversionRate: { name: '转化率', value: parseFloat(conversionRate.toFixed(2)), unit: '%' }
            };

        return Object.values(result);
    }
}
