"use strict";
// @ts-nocheck
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var dayjs_1 = __importDefault(require("dayjs"));
var timezone_1 = __importDefault(require("dayjs/plugin/timezone"));
var utc_1 = __importDefault(require("dayjs/plugin/utc"));
dayjs_1.default.extend(utc_1.default);
dayjs_1.default.extend(timezone_1.default);
dayjs_1.default.tz.setDefault("Asia/Seoul");
var CommonChartOption = {
    cutoutPercentage: 75,
    responsive: true,
    responsiveAnimationDuration: 1200,
    animation: {
        duration: 1200,
    },
    maintainAspectRatio: false,
};
var useTrainingLevelScoreChartDatas = function (props) {
    var data = props.data, selOption = props.selOption, startDate = props.startDate, endDate = props.endDate, language = props.language;
    var _a = (0, react_1.useState)({ startDate: startDate || "0000-00-00", endDate: endDate || "0000-00-00" }), dueDate = _a[0], setDueDate = _a[1];
    var trainingTypesColor = (0, react_1.useMemo)(function () { return ({
        SentenceMask: "#FA8128",
        VisualSpan: "#28a745",
        KeywordFinding: "#344f66",
        CategoryFinding: "#800080",
        VisualCounting: "#f00",
        TMT: "#46bbbb",
        Stroop: "#a6a55d",
        WordOrdering: "#00f",
    }); }, []);
    var CommonDataOptions = (0, react_1.useMemo)(function () { return ({
        steepedLine: false,
        lineTension: 0,
        fill: false,
        yAxisID: "y1",
        xAxisID: "x1",
        borderWidth: 1.5,
        pointRadius: 3,
        pointHoverRadius: 3, //hover 데이터포인터크기
    }); }, []);
    var displayFormats = (0, react_1.useMemo)(function () {
        if (selOption === 1) {
            return {
                time: {
                    unit: "day",
                    displayFormats: { day: "MM월 DD일" },
                },
            };
        }
        else if (selOption === 2) {
            return {
                time: {
                    unit: "week",
                    displayFormats: { week: "MM월 DD일" },
                },
            };
        }
        else if (selOption === 3) {
            return {
                time: {
                    unit: "month",
                    displayFormats: { month: "YYYY년 MM월" },
                },
            };
        }
    }, [selOption]);
    var chartData = (0, react_1.useMemo)(function () {
        if (!data || data.length === 0) {
            return;
        }
        var selType = { 1: "d", 2: "w", 3: "M" }; // 일별, 주별, 월별
        var midnight = (0, dayjs_1.default)(endDate).format("YYYY-MM-DD 00:00:00");
        var now = (0, dayjs_1.default)(endDate);
        var startDate = (0, dayjs_1.default)(midnight).add(-9, selType[selOption]); // 오늘 포함해야하니까 -9로 이동
        var ptr = (0, dayjs_1.default)(midnight).add(-9, selType[selOption]);
        // 주별이 선택되어있을때는 월요일로 옮겨야함
        if (selOption === 2) {
            ptr = ptr.day(1);
        }
        // 월별이 선택되어있을때는 1일로 옮겨야함
        if (selOption === 3) {
            ptr.set("date", 1);
        }
        var betweenDateList = [];
        while (ptr <= now) {
            var dayFormat = ptr.format("YYYY-MM-DD");
            var monthFormat = ptr.format("YYYY-MM");
            betweenDateList.push({ dayFormat: dayFormat, dayjs: (0, dayjs_1.default)(dayFormat), monthFormat: monthFormat });
            ptr = ptr.add(1, selType[selOption]);
        }
        // [레벨스코어 = 점수 + 레벨 * 20]
        // 트레이닝 레벨 가중 점수 = 현재 점수 + 레벨 * 20
        var ds = [];
        for (var i = 0; i < data.length; i++) {
            var task = data[i];
            var trList = [];
            var trDateList = Object.keys(task.trainingResult).sort(function (a, b) { return new Date(a) - new Date(b); });
            for (var j = 0; j < trDateList.length; j++) {
                var _loop_1 = function (k) {
                    var trMoment = (0, dayjs_1.default)("".concat(trDateList[j], " 00:00:00"));
                    if (trMoment < betweenDateList[k].dayjs) {
                        return "continue";
                    }
                    if (k !== betweenDateList.length - 1 && trMoment >= betweenDateList[k + 1].dayjs) {
                        return "continue";
                    }
                    // betweenDateList[k]
                    var tr = task.task_type === "Reading" ? task.trainingResult[trDateList[j]].filter(function (f) { return f.tr_language === language; }) : task.trainingResult[trDateList[j]];
                    var score = +(tr.reduce(function (prev, curr) { return prev + (curr.tr_score + curr.tr_level * 20); }, 0) / tr.length).toFixed(1);
                    var f = void 0;
                    // 3이면 월별
                    var x = selOption === 3 ? betweenDateList[k].monthFormat : betweenDateList[k].dayFormat;
                    f = trList.find(function (f) { return f.x === x; });
                    if (!f) {
                        trList.push({
                            x: x,
                            y: score,
                            count: tr.length,
                            dayCount: 1,
                        });
                    }
                    else {
                        f.y = +(f.y + score).toFixed(1);
                        f.count += tr.length;
                        f.dayCount++;
                    }
                };
                for (var k = 0; k < betweenDateList.length; k++) {
                    _loop_1(k);
                }
            }
            if (selOption !== 1) {
                trList = trList.map(function (tr) {
                    return __assign(__assign({}, tr), { y: +(tr.y / tr.dayCount).toFixed(1) });
                });
            }
            ds.push(__assign({ data: trList, borderColor: trainingTypesColor[task.task_name], backgroundColor: trainingTypesColor[task.task_name], label: task.task_name }, CommonDataOptions));
        }
        // 월별일때 체크
        var labels;
        if (selOption === 3) {
            startDate = startDate.format("YYYY-MM");
            now = now.format("YYYY-MM");
            labels = betweenDateList.map(function (b) { return b.monthFormat; });
        }
        else {
            startDate = startDate.format("YYYY-MM-DD");
            now = now.format("YYYY-MM-DD");
            labels = betweenDateList.map(function (b) { return b.dayFormat; });
        }
        setDueDate({ startDate: startDate, endDate: now });
        return {
            labels: labels,
            datasets: ds,
        };
    }, [selOption, data, trainingTypesColor, CommonDataOptions, endDate, language]);
    var chartOption = (0, react_1.useMemo)(function () {
        if (!chartData) {
            return;
        }
        return __assign(__assign({}, CommonChartOption), { tooltips: {
                usePointStyle: true,
                callbacks: {
                    labelPointStyle: function () {
                        return {
                            pointStyle: "triangle",
                            rotation: 0,
                        };
                    },
                    label: function (tooltipItem, d) {
                        var index = tooltipItem.index;
                        var datasetIndex = tooltipItem.datasetIndex;
                        var tr_type = d.datasets[datasetIndex].label;
                        var count = d.datasets[datasetIndex].data[index].count;
                        return [tr_type, "\uD6C8\uB828\uC77C : ".concat(tooltipItem.xLabel), "\uD6C8\uB828\uD69F\uC218 : ".concat(count, "\uD68C"), "\uB808\uBCA8\uC2A4\uCF54\uC5B4 : ".concat(tooltipItem.yLabel, "\uC810")];
                    },
                    labelColor: function (tooltipItem, chart) {
                        var dataset = chart.config.data.datasets[tooltipItem.datasetIndex];
                        return {
                            borderColor: dataset.backgroundColor,
                            backgroundColor: dataset.backgroundColor,
                            borderWidth: 0,
                        };
                    },
                    labelTextColor: function (tooltipItem, chart) {
                        return "#666";
                    },
                    title: function (tooltipItem, data) {
                        return "";
                    },
                },
                backgroundColor: "#FFF",
                titleFontSize: 14,
                titleFontColor: "#0066ff",
                bodyFontColor: "#000",
                bodyFontSize: 14,
                displayColors: true,
                borderColor: "#145894",
                borderWidth: 1,
            }, plugins: {
                datalabels: {
                    formatter: function (value, ctx) {
                        return null;
                    },
                    anchor: "center",
                    align: "center",
                    color: "#000000",
                },
            }, scales: {
                xAxes: [
                    __assign(__assign({ id: "x1", display: true, type: "time" }, displayFormats), { ticks: {
                            source: "labels", // data 속성의 labels 배열을 따라가겠다는 의미
                            // min: dueDate.startDate,
                            // max: dueDate.endDate,
                        }, gridLines: {
                            display: true,
                            color: "rgb(50,50,50,0.5)",
                        } }),
                ],
                yAxes: [
                    {
                        id: "y1",
                        position: "left",
                        gridLines: {
                            display: true,
                            color: "rgba(0, 0, 0, 0)",
                        },
                        scaleLabel: {
                            /////////////////x축아래 라벨
                            display: true,
                            labelString: "레벨 스코어",
                            //fontStyle: 'bold',
                            fontSize: 15,
                        },
                        ticks: {
                            source: "data",
                            suggestedMin: -50,
                            suggestedMax: 250,
                        },
                    },
                ],
            } });
    }, [chartData, displayFormats]);
    return { chartData: chartData, chartOption: chartOption, dueDate: dueDate };
};
exports.default = useTrainingLevelScoreChartDatas;
