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

export default class visitorHomeProfileStrategy extends abstractCustomerProfileStrategy {

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

    processData(type: string, data: any): any {
        const total = type === 'ticket' ? 1000 : 3429;

        const cityCounts: { [key: string]: number } = {};
        data.forEach((row: any) => {
            const city = row['城市'];
            if (!cityCounts[city]) {
                cityCounts[city] = 0;
            }
            cityCounts[city] += 1;
        });

        const totalVisitors = Object.values(cityCounts).reduce((a, b) => a + b, 0);
        const scaleFactor = total / totalVisitors;

        const result = Object.entries(cityCounts).map(([key, count]) => {
            const scaledCount = Math.floor(count * scaleFactor);
            return {
                key,
                value: scaledCount
            };
        });

        const currentTotal = result.reduce((sum, city) => sum + city.value, 0);
        if (currentTotal !== total) {
            const difference = total - currentTotal;
            result[0].value += difference;
        }

        return result;
    }
}
