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

export default class monthlyVisitorCountStrategy extends abstractDataStrategyLeft {
    execute(params?: any): any {
        paramChecker.checkDiscreteParam(params, 'timeFrame', '12month', '3year');
        let data = this.extractor.getData(monthlyVisitorCountStrategy.FILENAME, monthlyVisitorCountStrategy.SHEETNAME);
        return this.processData(data, params.query['timeFrame']);
    }

     processData(data: any, timeFrame: string) {
        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 eventCount: Map<string, number> = new Map();
        let tempDate = new Date(startDate);
        while (tempDate <= currentDate) {
            const formattedMonth = `${tempDate.getFullYear().toString().slice(2)}/${(tempDate.getMonth() + 1).toString().padStart(2, '0')}`;
            eventCount.set(formattedMonth, 0);
            tempDate.setMonth(tempDate.getMonth() + 1);
        }

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

            if (rowDate >= startDate && rowDate <= currentDate) {
                eventCount.set(formattedMonth, (eventCount.get(formattedMonth) || 0) + 1);
            }
        });

        const result = [];
        for (let [key, value] of eventCount.entries()) {
            if (value === 0) {
                value = Math.floor(Math.random() * 3000) + 1;
            }
            result.push({
                key: key,
                value: value
            });
        }

        return result;
    }
}
