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

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

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

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

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

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

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

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

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



let dailyPaymentChart;
let treatmentPaymentChart;
let treatmentPercentChart;
let memberPaymentChart;

let topPaymentAgGridData = [];
let paymentAgGridData = [];

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

    $.ajax({
        url: encodeURI('/webstatistics/selectStatisticsClinic.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async:true,
        success: function(data){
            if(data.msgCode=='0'){
                // 진료별 건수, 금액
                if(0<data.totalPayment.length){
                    let totalCount = 0;
                    let totalAmount = 0;

                    for(let i=0; i<data.totalPayment.length; i++){
                        totalCount  += data.totalPayment[i].totalCount;
                        totalAmount += data.totalPayment[i].totalAmount;

                        $("#treatment"+i+" p").eq(0).text(fn_numberFormat(data.totalPayment[i].totalCount)+"건");
                        $("#treatment"+i+" p").eq(1).text(fn_numberFormat(data.totalPayment[i].totalAmount)+"원");
                    }

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

                    // 전체 건수, 금액
                    $("#treatmentAll p").eq(0).text(fn_numberFormat(totalCount)+"건");
                    $("#treatmentAll p").eq(1).text(fn_numberFormat(totalAmount)+"원");
                    
                    
                    // 진료 매출 그래프
                    treatmentPaymentData.labels = data.totalPayment.map(item => item.treatmentName);
                    treatmentPaymentData.data = data.totalPayment.map(item => item.totalAmount);
                    treatmentPaymentChart.data.labels = treatmentPaymentData.labels;
                    treatmentPaymentChart.data.datasets[0].data = treatmentPaymentData.data;
                    treatmentPaymentChart.update();

                    // 진료 매출 비중 그래프
                    treatmentPercentData.labels = data.totalPayment.map(item => item.treatmentName);
                    treatmentPercentData.data = data.totalPayment.map(item => item.percent);
                    treatmentPercentChart.data.labels = treatmentPercentData.labels;
                    treatmentPercentChart.data.datasets[0].data = treatmentPercentData.data;
                    treatmentPercentChart.update();
                }

                // 진료 매출 트렌드
                // 피부
                // 초기화
                dailyPaymentData0.data = [];
                dailyPaymentData0.labels = [];
                if(0<data.thisDailyPayment0.length){
                    for(let i=0; i<data.thisDailyPayment0.length; i++){
                        dailyPaymentData0.data.push(data.thisDailyPayment0[i].totalAmount);
                        dailyPaymentData0.labels.push(data.thisDailyPayment0[i].date);
                    }
                }

                // 쁘띠
                // 초기화
                dailyPaymentData1.data = [];
                dailyPaymentData1.labels = [];
                if(0<data.thisDailyPayment1.length){
                    for(let i=0; i<data.thisDailyPayment1.length; i++){
                        dailyPaymentData1.data.push(data.thisDailyPayment1[i].totalAmount);
                        dailyPaymentData1.labels.push(data.thisDailyPayment1[i].date);
                    }
                }

                // 비만
                // 초기화
                dailyPaymentData2.data = [];
                dailyPaymentData2.labels = [];
                if(0<data.thisDailyPayment2.length){
                    for(let i=0; i<data.thisDailyPayment2.length; i++){
                        dailyPaymentData2.data.push(data.thisDailyPayment2[i].totalAmount);
                        dailyPaymentData2.labels.push(data.thisDailyPayment2[i].date);
                    }
                }

                // 제모
                // 초기화
                dailyPaymentData3.data = [];
                dailyPaymentData3.labels = [];
                if(0<data.thisDailyPayment3.length){
                    for(let i=0; i<data.thisDailyPayment3.length; i++){
                        dailyPaymentData3.data.push(data.thisDailyPayment3[i].totalAmount);
                        dailyPaymentData3.labels.push(data.thisDailyPayment3[i].date);
                    }
                }

                // 기타
                // 초기화
                dailyPaymentData4.data = [];
                dailyPaymentData4.labels = [];
                if(0<data.thisDailyPayment4.length){
                    for(let i=0; i<data.thisDailyPayment4.length; i++){
                        dailyPaymentData4.data.push(data.thisDailyPayment4[i].totalAmount);
                        dailyPaymentData4.labels.push(data.thisDailyPayment4[i].date);
                    }
                }

                dailyPaymentChart.data.labels = dailyPaymentData0.labels;
                dailyPaymentChart.data.datasets[0].data = dailyPaymentData0.data;
                dailyPaymentChart.data.datasets[1].labels = dailyPaymentData1.labels;
                dailyPaymentChart.data.datasets[1].data = dailyPaymentData1.data;
                dailyPaymentChart.data.datasets[2].labels = dailyPaymentData2.labels;
                dailyPaymentChart.data.datasets[2].data = dailyPaymentData2.data;
                dailyPaymentChart.data.datasets[3].labels = dailyPaymentData3.labels;
                dailyPaymentChart.data.datasets[3].data = dailyPaymentData3.data;
                dailyPaymentChart.data.datasets[4].labels = dailyPaymentData4.labels;
                dailyPaymentChart.data.datasets[4].data = dailyPaymentData4.data;
                dailyPaymentChart.update();


                // 닥터/상담 매출 비중
                // 초기화
                memberPaymentData.data = [];
                memberPaymentData.labels = [];
                if(0<data.clinicMemberList.length){
                    for(let i=0; i<data.clinicMemberList.length; i++){
                        memberPaymentData.data.push(data.clinicMemberList[i].totalCount);
                        memberPaymentData.labels.push(data.clinicMemberList[i].memberName);
                    }
                }
                memberPaymentChart.data.labels = memberPaymentData.labels;
                memberPaymentChart.data.datasets[0].data = memberPaymentData.data;
                memberPaymentChart.update();


                // 매출 TOP 10 시술
                let tempData = [];
                let tempTopTotalAmount = 0;
                if(0<data.topPaymentList.length){
                    for(let i=0; i<data.topPaymentList.length; i++){
                        tempTopTotalAmount += data.topPaymentList[i].totalAmount;
                    }

                    for(let i=0; i<data.topPaymentList.length; i++){
                        if(10 == i){
                            break;
                        }else{
                            let percent = Math.round(data.topPaymentList[i].totalAmount / tempTopTotalAmount * 100);
                            if(isNaN(percent)){ // NaN => 0 으로 처리
                                percent = 0;
                            }
                            data.topPaymentList[i].percent = percent;
                            tempData.push(data.topPaymentList[i]);
                        }
                    }
                }
                topPaymentAgGridData = tempData;
                topPaymentGridOptions.api.setRowData(topPaymentAgGridData);


                // 상세 내역 그리드
                paymentAgGridData = data.paymentListMap;
                paymentGridOptions.api.setRowData(paymentAgGridData);

            }else{
                modalEvent.danger("오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "대시보드 조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend: function () {
        },
        complete: function () {
        }
    });
}

/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadStatisticsClinicExcel() {
    if ("Y" == downloadUseYn) {
        // 수정가능
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += '&statisticsSearchDate=' + statisticsSearchDate

        let url = encodeURI("/webstatistics/downloadStatisticsClinicExcel.do" + pagingParam);
        $("#excelForm").prop("action", url);
        $("#excelForm").submit();
    } else {
        modalEvent.warning("", "내려받기 권한이 없습니다.");
        return false;
    }
}

/****************************************************************************
 * 페이지 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('dailyClinicStatistics');
    dailyPaymentChart = new Chart(dailyPaymentStatistics, {
        type: 'line',
        data: {
            labels: dailyPaymentData0.labels,
            datasets: [
                {
                    label: '피부',
                    data: dailyPaymentData0.data,
                    borderColor: 'rgba(255, 129, 149, 1)',
                    backgroundColor: 'rgba(255, 129, 149, 1)',
                    lineJoin: 'miter',
                    pointRadius: 7,
                    pointHoverRadius:9 ,
                    pointBackgroundColor: 'rgba(255, 129, 149, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(255, 129, 149, 1)',
                    fill: false,
                    tension: 0.1,
                    // spanGaps: true
                },
                {
                    label: '쁘띠',
                    data: dailyPaymentData1.data,
                    borderColor: 'rgba(35, 209, 109, 1)',
                    backgroundColor: 'rgba(35, 209, 109, 1)',
                    lineJoin: 'miter',
                    pointRadius: 7,
                    pointHoverRadius:9 ,
                    pointBackgroundColor: 'rgba(35, 209, 109, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(35, 209, 109, 1)',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true
                },
                {
                    label: '비만',
                    data: dailyPaymentData2.data,
                    borderColor: 'rgba(38, 153, 251, 1)',
                    backgroundColor: 'rgba(38, 153, 251, 1)',
                    lineJoin: 'miter',
                    pointRadius: 7,
                    pointHoverRadius:9 ,
                    pointBackgroundColor: 'rgba(38, 153, 251, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(38, 153, 251, 1)',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true
                },
                {
                    label: '제모',
                    data: dailyPaymentData3.data,
                    borderColor: 'rgba(255, 186, 0, 1)',
                    backgroundColor: 'rgba(255, 186, 0, 1)',
                    lineJoin: 'miter',
                    pointRadius: 7,
                    pointHoverRadius:9 ,
                    pointBackgroundColor: 'rgba(255, 186, 0, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(255, 186, 0, 1)',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true
                },
                {
                    label: '기타',
                    data: dailyPaymentData4.data,
                    borderColor: 'rgba(216, 221, 227, 1)',
                    backgroundColor: 'rgba(216, 221, 227, 1)',
                    lineJoin: 'miter',
                    pointRadius: 7,
                    pointHoverRadius:9 ,
                    pointBackgroundColor: 'rgba(216, 221, 227, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(216, 221, 227, 1)',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true
                }
            ]
        },
        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,
                    suggestedMax : 50000000, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 10000000 /* 표시되는 축의 값 */
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    align: 'end',
                },
                tooltip: {
                    enabled: true,
                    callbacks: {
                        label: function(context) {
                            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 ? dailyPaymentData0.labels[dataIndex] : dailyPaymentData1.labels[dataIndex];
                            return label;
                        }
                    }
                }
            }
        }
    });

    const treatmentPaymentStatistics = document.getElementById('treatmentPaymentStatistics');
    treatmentPaymentChart = new Chart(treatmentPaymentStatistics, {
        type: 'bar',
        data: {
            labels: treatmentPaymentData.labels,
            datasets: [{
                label: '결제금액(원)',
                data: treatmentPaymentData.data,
                borderWidth: 1,
                backgroundColor: [
                    'rgba(255, 129, 149, 1)',
                    'rgba(35, 209, 109, 1)',
                    'rgba(38, 153, 251, 1)',
                    'rgba(255, 186, 0, 1)',
                    'rgba(216, 221, 227, 1)'
                ],
                barThickness: 50
            }]
        },
        options: {
            responsive: false,
            scales: {
                x: {
                    ticks: {
                        display: true,
                        align: 'center',
                        maxRotation: 0,
                        minRotation: 0
                    }
                },
                y: {
                    beginAtZero: true,
                    suggestedMax : 50000000, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 10000000 /* 표시되는 축의 값 */
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

    const treatmentPercentStatistics = document.getElementById('treatmentPercentStatistics');
    treatmentPercentChart = new Chart(treatmentPercentStatistics, {
        type: 'pie',
        data: {
            labels: treatmentPaymentData.labels,
            datasets: [{
                label: '비율 (%)',
                data: treatmentPaymentData.data,
                backgroundColor: [
                    'rgba(255, 129, 149, 1)',
                    'rgba(35, 209, 109, 1)',
                    'rgba(38, 153, 251, 1)',
                    'rgba(255, 186, 0, 1)',
                    'rgba(216, 221, 227, 1)',
                ]
            }]
        },
        options: {
            responsive: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

    const memberPaymentStatistics = document.getElementById('memberPaymentStatistics');
    memberPaymentChart = new Chart(memberPaymentStatistics, {
        type: 'pie',
        data: {
            labels: memberPaymentData.labels,
            datasets: [{
                label: '건',
                data: memberPaymentData.data,
                backgroundColor: [
                    'rgba(255, 129, 149, 1)',
                    'rgba(35, 209, 109, 1)',
                    'rgba(38, 153, 251, 1)',
                    'rgba(255, 186, 0, 1)',
                    'rgba(216, 221, 227, 1)',
                ]
            }]
        },
        options: {
            responsive: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

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

function fn_numberFormatter(params){
    return fn_numberFormat(params.value);
}

function fn_percentFormatter(params){
    return params.value+"%";
}

function fn_formatAmount(amount){
    let data = typeof amount === 'number'?amount:amount.value;
    return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 상세 내역
let paymentColumnDefs = [
        {field: "paymentDate", headerName: "날짜", minWidth: 100, maxWidth: 140},
        {field: "treatmentName", headerName: "진료유형", minWidth: 100, maxWidth: 100},
        {field: "treatmentProcedureNm", headerName: "시술(상품)명", minWidth: 150},
        {field: "userName", headerName: "고객명", minWidth: 150, maxWidth: 150},
        {field: "reserveMemberName", headerName: "닥터/상담", minWidth: 100,maxWidth: 100},
        {field: "muMemberName", headerName: "담당자", minWidth: 100,maxWidth: 100},
        {field: "reserveStatus", headerName: "진료상태", minWidth: 130, maxWidth: 130},
        {field: "status1", headerName: "결제상태", minWidth: 130, maxWidth: 130},
        {field: "paymentAmount", headerName:"결제금액", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount}
];

// let the grid know which columns and what data to use
let paymentGridOptions = {
    suppressRowTransform: true,
    columnDefs: paymentColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: true,		// 그리드에서 데이터 수정
        cellStyle: {textAlign: 'left', fontSize: '14px', padding: '0'},
        //suppressSizeToFit:true,		//자동 맞춤
        //enableRowGroup: true,		// 그룹 묶음
        enablePivot: true,
        enableValue: true
    },
    //suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
    headerHeight: 41, // header 높이
    rowHeight: 41, // row 높이
    rowData: paymentAgGridData,
    suppressRowClickSelection: true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText: {
        noRowsToShow: '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection: 'multiple', // row 다중 선택
    debug: false,
    onCellClicked: function (event) { //셀 클릭 이벤트
    },
    onSelectionChanged: function (event) { //체크박스 선택
    },
    onSortChanged: function (event) {
    }
};

let paymentGridDiv = document.querySelector('#paymentGrid');

new agGrid.Grid(paymentGridDiv, paymentGridOptions);

// 매출 TOP 10 시술
let topPaymentColumnDefs = [
        {field: "rowNumber", headerName: "순위", minWidth: 100, maxWidth: 140
            ,valueGetter : params => {
                return (params.node.rowIndex + 1) * 1;
            }
        },
        {field: "treatmentName", headerName: "진료유형", minWidth: 100, maxWidth: 100},
        {field: "treatmentProcedureName", headerName: "시술(상품)명", minWidth: 150},
        {field: "totalCount", headerName: "진료수", minWidth: 150, maxWidth: 150, valueFormatter: fn_numberFormatter},
        {field: "totalAmount", headerName: "금액", minWidth: 150, maxWidth: 150, valueFormatter: fn_numberFormatter},
        {field: "percent", headerName: "비중", minWidth: 150, maxWidth: 250, valueFormatter: fn_percentFormatter/*, cellStyle:{textAlign: 'right'}*/}
];

// let the grid know which columns and what data to use
let topPaymentGridOptions = {
    suppressRowTransform: true,
    columnDefs: topPaymentColumnDefs,
    defaultColDef: {		// 리스트 기본 설정
        flex: 1,
        sortable: true,		//정렬 여부
        resizable: true,	//리사이즈
        editable: true,		// 그리드에서 데이터 수정
        cellStyle: {textAlign: 'left', fontSize: '14px', padding: '0'},
        //suppressSizeToFit:true,		//자동 맞춤
        //enableRowGroup: true,		// 그룹 묶음
        enablePivot: true,
        enableValue: true
    },
    //suppressMultiSort:true,  //단일솔트 true가 단일, false가 다중 shift + sort 시
    headerHeight: 41, // header 높이
    rowHeight: 41, // row 높이
    rowData: topPaymentAgGridData,
    suppressRowClickSelection: true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText: {
        noRowsToShow: '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection: 'multiple', // row 다중 선택
    debug: false,
    onCellClicked: function (event) { //셀 클릭 이벤트
    },
    onSelectionChanged: function (event) { //체크박스 선택
    },
    onSortChanged: function (event) {
    }
};

let topPaymentGridDiv = document.querySelector('#topPaymentGrid');

new agGrid.Grid(topPaymentGridDiv, topPaymentGridOptions);

document.getElementById("downLoadBtn").addEventListener('click',()=>{
    fn_downloadStatisticsClinicExcel();
});