/****************************************************************************
 * 그래프관련 변수
 ****************************************************************************/

let monthPaymentData = {
    labels: [],
    data: []
};

let dailyPaymentData = {
    labels: [],
    data: []
};
let comparisonDailyPaymentData = {
    labels: [],
    data: []
};

let monthPaymentChart;
let dailyPaymentChart;

/****************************************************************************
 * 대시보드 데이터 조회
 ****************************************************************************/
function fn_searchData(){
    statisticsSearchDate = $('#statisticsSearchDate').val();
    let formData = new FormData();
    formData.append('menuClass',menuClass);
    formData.append('statisticsSearchDate',statisticsSearchDate);

    $.ajax({
        url: encodeURI('/webstatistics/selectStatistics.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async:true,
        success: function(data){
            if(data.msgCode=='0'){
                $("#paymentUpDown").removeClass("up down");
                $("#treatmentUpDown").removeClass("up down");
                $("#visitorUpDown").removeClass("up down");

                // 매출 금액
                if(0<data.totalPayment.length){
                    // 당월 매출 금액
                    let thisTotalPaymentAmount = data.totalPayment[0].thisTotalPaymentAmount;
                    // 전월 매출 금액
                    let prevTotalPaymentAmount = data.totalPayment[0].prevTotalPaymentAmount;

                    $("#totalPaymentAmount").text(fn_numberFormat(thisTotalPaymentAmount));

                    // 매출 증감액
                    let totalPaymentDiff = Math.abs(thisTotalPaymentAmount - prevTotalPaymentAmount);
                    // 매출 증감률
                    let totalPaymentPercent = Math.abs(Math.round((thisTotalPaymentAmount - prevTotalPaymentAmount) / prevTotalPaymentAmount * 100));
                    if(isNaN(totalPaymentPercent)){ // NaN => 0 으로 처리
                        totalPaymentPercent = 0;
                    }else if(totalPaymentPercent === Infinity){
                        totalPaymentPercent = 100;
                    }
                    if(thisTotalPaymentAmount >= prevTotalPaymentAmount){
                        // 증가
                        $("#paymentUpDown").addClass("up");
                    }else{
                        // 감소
                        $("#paymentUpDown").addClass("down");
                    }
                    $("#paymentUpDown span").eq(0).text(fn_numberFormat(totalPaymentDiff));
                    $("#paymentUpDown span").eq(1).text("("+totalPaymentPercent+"%)");
                }

                // 진료
                if(0<data.totalTreatment.length){
                    // 당월 진료수
                    let thisTotalTreatmentCount = data.totalTreatment[0].thisTotalTreatmentCount;
                    // 전월 진료수
                    let prevTotalTreatmentCount = data.totalTreatment[0].prevTotalTreatmentCount;

                    $("#totalTreatmentCount").text(fn_numberFormat(thisTotalTreatmentCount));

                    // 진료 증감액
                    let totalTreatmentDiff = Math.abs(thisTotalTreatmentCount - prevTotalTreatmentCount);
                    // 진료 증감률
                    let totalTreatmentPercent = Math.abs(Math.round((thisTotalTreatmentCount - prevTotalTreatmentCount) / prevTotalTreatmentCount * 100));
                    if(isNaN(totalTreatmentPercent)){ // NaN => 0 으로 처리
                        totalTreatmentPercent = 0;
                    }else if(totalTreatmentPercent === Infinity){
                        totalTreatmentPercent = 100;
                    }
                    if(thisTotalTreatmentCount >= prevTotalTreatmentCount){
                        // 증가
                        $("#treatmentUpDown").addClass("up");
                    }else{
                        // 감소
                        $("#treatmentUpDown").addClass("down");
                    }
                    $("#treatmentUpDown span").eq(0).text(fn_numberFormat(totalTreatmentDiff));
                    $("#treatmentUpDown span").eq(1).text("("+totalTreatmentPercent+"%)");
                }

                // 진료 카테고리별 건수 %, 결제금액
                if(0<data.totalTreatmentCategory.length){
                    let listHTML = '';

                    // 퍼센트 계산
                    let totalCount = 0;
                    for(let i=0; i<data.totalTreatmentCategory.length; i++){
                        totalCount += data.totalTreatmentCategory[i].totalCount;
                    }

                    for(let i=0; i<data.totalTreatmentCategory.length; i++){
                        let percent = Math.round(data.totalTreatmentCategory[i].totalCount / totalCount * 100);
                        if(isNaN(percent)){ // NaN => 0 으로 처리
                            percent = 0;
                        }

                        listHTML += data.totalTreatmentCategory[i].treatmentName+'<span>'+percent+'%</span>';
                    }

                    $("#treatmentCategoryList").empty().html(listHTML).trigger("create");


                    // 결제금액 그래프
                    monthPaymentData.labels = data.totalTreatmentCategory.map(item => item.treatmentName);
                    monthPaymentData.data = data.totalTreatmentCategory.map(item => item.totalAmount);

                    // Update the month payment chart
                    if (monthPaymentChart) {
                        monthPaymentChart.data.labels = monthPaymentData.labels;
                        monthPaymentChart.data.datasets[0].data = monthPaymentData.data;
                        monthPaymentChart.update();
                    }
                }


                // 방문고객
                if(0<data.totalVisitor.length){
                    // 당월 진료수
                    let thisTotalVisitorCount = data.totalVisitor[0].thisTotalVisitorCount;
                    // 전월 진료수
                    let prevTotalVisitorCount = data.totalVisitor[0].prevTotalVisitorCount;

                    $("#totalVisitorCount").text(fn_numberFormat(thisTotalVisitorCount));

                    // 진료 증감액
                    let totalVisitorDiff = Math.abs(thisTotalVisitorCount - prevTotalVisitorCount);
                    // 진료 증감률
                    let totalVisitorPercent = Math.abs(Math.round((thisTotalVisitorCount - prevTotalVisitorCount) / prevTotalVisitorCount * 100));
                    if(isNaN(totalVisitorPercent)){ // NaN => 0 으로 처리
                        totalVisitorPercent = 0;
                    }else if(totalVisitorPercent === Infinity){
                        totalVisitorPercent = 100;
                    }
                    if(thisTotalVisitorCount >= prevTotalVisitorCount){
                        // 증가
                        $("#visitorUpDown").addClass("up");
                    }else{
                        // 감소
                        $("#visitorUpDown").addClass("down");
                    }
                    $("#visitorUpDown span").eq(0).text(fn_numberFormat(totalVisitorDiff));
                    $("#visitorUpDown span").eq(1).text("("+totalVisitorPercent+"%)");
                }

                // 방문고객 성별 비율
                if(0<data.totalVisitorGender.length){
                    let listHTML = '';

                    // 퍼센트 계산
                    let totalCountF = data.totalVisitorGender[0].totalCountF;
                    let totalCountM = data.totalVisitorGender[0].totalCountM;
                    let totalCount = (totalCountF + totalCountM);

                    let percentF = Math.round(totalCountF / totalCount * 100);
                    if(isNaN(percentF)){ // NaN => 0 으로 처리
                        percentF = 0;
                    }
                    let percentM = Math.round(totalCountM / totalCount * 100);
                    if(isNaN(percentM)){ // NaN => 0 으로 처리
                        percentM = 0;
                    }

                    listHTML += '여성<span>'+percentF+'%</span>';
                    listHTML += '남성<span>'+percentM+'%</span>';

                    $("#visitorGenderList").empty().html(listHTML).trigger("create");
                }

                // 당월 일별 매출 금액
                // 초기화
                dailyPaymentData.data = [];
                dailyPaymentData.labels = [];
                comparisonDailyPaymentData.data = [];
                comparisonDailyPaymentData.labels = [];
                if(0<data.thisDailyPayment.length){
                    for(let i=0; i<data.thisDailyPayment.length; i++){
                        dailyPaymentData.data.push(data.thisDailyPayment[i].totalAmount);
                        dailyPaymentData.labels.push(data.thisDailyPayment[i].date);
                    }
                }
                if(0<data.prevDailyPayment.length){
                    for(let i=0; i<data.prevDailyPayment.length; i++){
                        comparisonDailyPaymentData.data.push(data.prevDailyPayment[i].totalAmount);
                        comparisonDailyPaymentData.labels.push(data.prevDailyPayment[i].date);
                    }
                }

                // 최대 일자 구하기
                // 빈 일자는 빈 값(null) 입력
                let maxLength = Math.max(dailyPaymentData.labels.length, comparisonDailyPaymentData.labels.length);
                while(dailyPaymentData.labels.length < maxLength) {
                    dailyPaymentData.labels.push('');
                    dailyPaymentData.data.push(null);
                }
                while(comparisonDailyPaymentData.labels.length < maxLength) {
                    comparisonDailyPaymentData.labels.push('');
                    comparisonDailyPaymentData.data.push(null);
                }

                dailyPaymentChart.data.labels = dailyPaymentData.labels;
                dailyPaymentChart.data.datasets[0].data = dailyPaymentData.data;
                dailyPaymentChart.data.datasets[1].labels = comparisonDailyPaymentData.labels;
                dailyPaymentChart.data.datasets[1].data = comparisonDailyPaymentData.data;
                dailyPaymentChart.update();
            }else{
                modalEvent.danger("오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "대시보드 조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend: function () {
        },
        complete: function () {
        }
    });
}
function parseCustomDate(dateStr) {
    const [monthDay, dayOfWeek] = dateStr.split('(');
    const [month, day] = monthDay.split('.').map(Number);

    const year = new Date().getFullYear();

    return new Date(year, month - 1, day);
}
/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit() {
    $('#statisticsSearchDate').datetimepicker({
        allowInputToggle: true,
        viewMode: 'months',
        format: 'YYYY-MM',
        defaultDate: moment().format('YYYY-MM')
    });
    fn_searchData();
    $('#statisticsSearchDate').on('dp.change',()=>{
        fn_searchData();
    })
}
$(function(){

    const dailyPaymentStatistics = document.getElementById('dailyPaymentStatistics');
    const monthPaymentStatistics = document.getElementById('monthPaymentStatistics');

    monthPaymentChart = new Chart(monthPaymentStatistics, {
        type: 'bar',
        data: {
            labels: monthPaymentData.labels,
            datasets: [{
                label: '결제금액(원)',
                data: monthPaymentData.data,
                borderWidth: 1,
                backgroundColor: '#3985EA',
                barThickness: 50
            }]
        },
        options: {
            responsive: false,
            scales: {
                x: {
                    ticks: {
                        display: true,
                        align: 'center',
                        maxRotation: 0,
                        minRotation: 0
                    }
                },
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });


    dailyPaymentChart = new Chart(dailyPaymentStatistics, {
        type: 'line',
        data: {
            labels: dailyPaymentData.labels,
            datasets: [
                {
                    label: '당월',
                    data: dailyPaymentData.data,
                    borderColor: 'rgba(57, 133, 234, 1)',
                    backgroundColor: 'rgba(57, 133, 234, 1)',
                    lineJoin: 'miter',
                    pointRadius: 7,
                    pointHoverRadius:9 ,
                    pointBackgroundColor: 'rgba(57, 133, 234, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(57, 133, 234, 1)',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true
                },
                {
                    label: '전월',
                    data: comparisonDailyPaymentData.data,
                    borderColor: 'rgba(57, 133, 234, 1)',
                    backgroundColor: 'rgba(57, 133, 234, 1)',
                    lineJoin: 'miter',
                    pointRadius: 1,
                    pointHoverRadius: 9,
                    pointBackgroundColor: 'rgba(57, 133, 234, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(57, 133, 234, 1)',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true,
                    borderDash: [3, 4]
                }
            ]
        },
        options: {
            responsive: false,
            scales: {
                x: {
                    grid: {
                        drawBorder: true,
                        drawOnChartArea: true,
                        drawTicks: true,
                        color: function(context) {
                            if (context.tick.label === '') {
                                return 'rgba(0, 0, 0, 0)';
                            }
                            return 'rgba(204, 204, 204, 1)';
                        }
                    }
                },
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    align: 'end',
                },
                tooltip: {
                    enabled: true,
                    callbacks: {
                        label: function(context) {
                            console.log(context.dataset);
                            let label = context.dataset.label;

                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'KRW' }).format(context.parsed.y);
                            }
                            return label;
                        },
                        title: function(tooltipItems) {
                            const dataIndex = tooltipItems[0].dataIndex;
                            const label = tooltipItems[0].datasetIndex === 0 ? dailyPaymentData.labels[dataIndex] : comparisonDailyPaymentData.labels[dataIndex];
                            return label;
                        }
                    }
                }
            }
        }
    });

    // 페이지 init
    fn_pageInit();
});
