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

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

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

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

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

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

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

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



let dailyFirstChart;
let firstYnChart;
let reserveCategoryChart;
let genderAgeChart;
let membershipChart;

let nationalityAgGridData = [];
let userTypeAgGridData = [];
let userAgGridData = [];

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

    $.ajax({
        url: encodeURI('/webstatistics/selectStatisticsUser.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async:true,
        success: function(data){
            if(data.msgCode=='0'){

                // 방문고객(전체)
                if(0<data.totalVisitor.length){
                    let html = '<span>'+fn_numberFormat(data.totalVisitor[0].thisTotalVisitorCount)+'</span> 명';
                    $("#totalVisitorCount").html(html).trigger("create");
                }
                // 고객유형
                if(0<data.firstYnVisitor.length){
                    let html = '초진 <span>'+fn_numberFormat(data.firstYnVisitor[0].totalCountY)+'</span> 재진 <span>'+fn_numberFormat(data.firstYnVisitor[0].totalCountN)+'</span> 명';
                    $("#firstYnVisitorCount").html(html).trigger("create");
                }
                // 성별
                if(0<data.genderVisitor.length){
                    let html = '여성 <span>'+fn_numberFormat(data.genderVisitor[0].totalCountF)+'</span> 남성 <span>'+fn_numberFormat(data.genderVisitor[0].totalCountM)+'</span> 명';
                    $("#genderVisitorCount").html(html).trigger("create");
                }
                // 멤버십회원
                if(0<data.membershipVisitor.length){
                    let html = '<span>'+fn_numberFormat(data.membershipVisitor[0].totalCountY)+'</span> 명';
                    $("#membershipVisitorCount").html(html).trigger("create");
                }

                // 진료 매출 트렌드
                // 초기화
                dailyFirstYData.data = [];
                dailyFirstYData.labels = [];
                dailyFirstNData.data = [];
                dailyFirstNData.labels = [];
                if(0<data.thisDailyVisitorFirstY.length){
                    for(let i=0; i<data.thisDailyVisitorFirstY.length; i++){
                        dailyFirstYData.data.push(data.thisDailyVisitorFirstY[i].totalCount);
                        dailyFirstYData.labels.push(data.thisDailyVisitorFirstY[i].date);
                    }
                }
                if(0<data.thisDailyVisitorFirstN.length){
                    for(let i=0; i<data.thisDailyVisitorFirstN.length; i++){
                        dailyFirstNData.data.push(data.thisDailyVisitorFirstN[i].totalCount);
                        dailyFirstNData.labels.push(data.thisDailyVisitorFirstN[i].date);
                    }
                }
                dailyFirstChart.data.labels = dailyFirstYData.labels;
                dailyFirstChart.data.datasets[0].data = dailyFirstYData.data;
                dailyFirstChart.data.datasets[1].labels = dailyFirstNData.labels;
                dailyFirstChart.data.datasets[1].data = dailyFirstNData.data;
                dailyFirstChart.update();

                // 초진/재진 비율
                // 초기화
                firstYnData.data = [];
                firstYnData.labels = ['초진', '재진'];
                let firstYnTotalCount = 0;
                let firstYCount = 0;
                let firstNCount = 0;
                if(0<data.thisDailyVisitorFirstY.length) {
                    for (let i = 0; i < data.thisDailyVisitorFirstY.length; i++) {
                        firstYCount += data.thisDailyVisitorFirstY[i].totalCount;
                        firstYnTotalCount += data.thisDailyVisitorFirstY[i].totalCount;
                    }
                }
                if(0<data.thisDailyVisitorFirstN.length){
                    for(let i=0; i<data.thisDailyVisitorFirstN.length; i++){
                        firstNCount += data.thisDailyVisitorFirstN[i].totalCount;
                        firstYnTotalCount += data.thisDailyVisitorFirstN[i].totalCount;
                    }
                }

                let firstYPercent = Math.round(firstYCount / firstYnTotalCount * 100);
                let firstNPercent = Math.round(firstNCount / firstYnTotalCount * 100);
                if(isNaN(firstYPercent)){ // NaN => 0 으로 처리
                    firstYPercent = 0;
                }
                if(isNaN(firstNPercent)){ // NaN => 0 으로 처리
                    firstNPercent = 0;
                }

                firstYnData.data.push(firstYPercent);
                firstYnData.data.push(firstNPercent);
                firstYnChart.data.labels = firstYnData.labels;
                firstYnChart.data.datasets[0].data = firstYnData.data;
                firstYnChart.update();


                // 예약 유형
                reserveCategoryData.labels = data.categoryVisitor.map(item => item.categoryItem);
                reserveCategoryData.data = data.categoryVisitor.map(item => item.totalCount);
                reserveCategoryChart.data.labels = reserveCategoryData.labels;
                reserveCategoryChart.data.datasets[0].data = reserveCategoryData.data;
                reserveCategoryChart.update();


                // 성별/연령
                // 초기화
                genderAgeFData.labels = ['1~19세', '20~29세', '30~39세', '40~49세', '50~59세', '60세+'];
                genderAgeFData.data = [];
                genderAgeMData.data = [];
                let age1_19  = 0
                let age20_29 = 0
                let age30_39 = 0
                let age40_49 = 0
                let age50_59 = 0
                let age60    = 0
                // 여성
                if(0<data.genderAgeVisitorF.length) {
                    for (let i = 0; i < data.genderAgeVisitorF.length; i++) {
                        if(1 <= data.genderAgeVisitorF[i].age && 19 >= data.genderAgeVisitorF[i].age){
                            console.log(data.genderAgeVisitorF[i].age);
                            age1_19 += data.genderAgeVisitorF[i].count;

                        }else if(20 <= data.genderAgeVisitorF[i].age && 29 >= data.genderAgeVisitorF[i].age){
                            age20_29 += data.genderAgeVisitorF[i].count;

                        }else if(30 <= data.genderAgeVisitorF[i].age && 39 >= data.genderAgeVisitorF[i].age){
                            age30_39 += data.genderAgeVisitorF[i].count;

                        }else if(40 <= data.genderAgeVisitorF[i].age && 49 >= data.genderAgeVisitorF[i].age){
                            age40_49 += data.genderAgeVisitorF[i].count;

                        }else if(50 <= data.genderAgeVisitorF[i].age && 59 >= data.genderAgeVisitorF[i].age){
                            age50_59 += data.genderAgeVisitorF[i].count;

                        }else if(60 <= data.genderAgeVisitorF[i].age){
                            age60 += data.genderAgeVisitorF[i].count;
                        }
                    }
                }
                genderAgeFData.data.push(age1_19, age20_29, age30_39, age40_49, age50_59, age60);

                age1_19  = 0
                age20_29 = 0
                age30_39 = 0
                age40_49 = 0
                age50_59 = 0
                age60    = 0
                // 남성
                if(0<data.genderAgeVisitorM.length) {
                    for (let i = 0; i < data.genderAgeVisitorM.length; i++) {
                        if(1 <= data.genderAgeVisitorM[i].age && 19 >= data.genderAgeVisitorM[i].age){
                            age1_19 += data.genderAgeVisitorM[i].count;

                        }else if(20 <= data.genderAgeVisitorM[i].age && 29 >= data.genderAgeVisitorM[i].age){
                            age20_29 += data.genderAgeVisitorM[i].count;

                        }else if(30 <= data.genderAgeVisitorM[i].age && 39 >= data.genderAgeVisitorM[i].age){
                            age30_39 += data.genderAgeVisitorM[i].count;

                        }else if(40 <= data.genderAgeVisitorM[i].age && 49 >= data.genderAgeVisitorM[i].age){
                            age40_49 += data.genderAgeVisitorM[i].count;

                        }else if(50 <= data.genderAgeVisitorM[i].age && 59 >= data.genderAgeVisitorM[i].age){
                            age50_59 += data.genderAgeVisitorM[i].count;

                        }else if(60 <= data.genderAgeVisitorM[i].age){
                            age60 += data.genderAgeVisitorM[i].count;
                        }
                    }
                }

                genderAgeMData.data.push(age1_19, age20_29, age30_39, age40_49, age50_59, age60);

                genderAgeChart.data.labels = genderAgeFData.labels;
                genderAgeChart.data.datasets[0].data = genderAgeFData.data;
                genderAgeChart.data.datasets[1].labels = genderAgeMData.labels;
                genderAgeChart.data.datasets[1].data = genderAgeMData.data;
                genderAgeChart.update();


                // 멤버십
                // 초기화
                membershipData.labels = ['일반', '멤버십'];
                membershipData.data = [];
                let membershipTotalCount = 0;
                let membershipYPercent = 0;
                let membershipNPercent = 0;
                if(0<data.membershipVisitor.length){
                    membershipTotalCount = data.membershipVisitor[0].totalCountY + data.membershipVisitor[0].totalCountN;

                    membershipYPercent  = Math.round(data.membershipVisitor[0].totalCountY / membershipTotalCount * 100);
                    membershipNPercent  = Math.round(data.membershipVisitor[0].totalCountN / membershipTotalCount * 100);
                }
                if(isNaN(membershipYPercent)){
                    membershipYPercent = 0;
                }
                if(isNaN(membershipNPercent)){
                    membershipNPercent = 0;
                }
                membershipData.data.push(membershipNPercent, membershipYPercent);

                membershipChart.data.labels = membershipData.labels;
                membershipChart.data.datasets[0].data = membershipData.data;
                membershipChart.update();


                // 국적
                let tempData = [];
                let tempTopTotalAmount = 0;
                if(0<data.nationalityVisitor.length){
                    for(let i=0; i<data.nationalityVisitor.length; i++){
                        tempTopTotalAmount += data.nationalityVisitor[i].totalAmount;
                    }

                    for(let i=0; i<data.nationalityVisitor.length; i++){
                        data.nationalityVisitor[i].percent = Math.round(data.nationalityVisitor[i].totalAmount / tempTopTotalAmount * 100);
                        tempData.push(data.nationalityVisitor[i]);
                    }
                }
                nationalityAgGridData = tempData;
                nationalityGridOptions.api.setRowData(nationalityAgGridData);


                // 고객구분
                tempData = [];
                tempTopTotalAmount = 0;
                if(0<data.userTypeVisitor.length){
                    for(let i=0; i<data.userTypeVisitor.length; i++){
                        tempTopTotalAmount += data.userTypeVisitor[i].totalAmount;
                    }

                    for(let i=0; i<data.userTypeVisitor.length; i++){
                        data.userTypeVisitor[i].percent = Math.round(data.userTypeVisitor[i].totalAmount / tempTopTotalAmount * 100);
                        tempData.push(data.userTypeVisitor[i]);
                    }
                }
                userTypeAgGridData = tempData;
                userTypeGridOptions.api.setRowData(userTypeAgGridData);


                // 상세 내역 그리드
                userAgGridData = data.userListMap;
                userGridOptions.api.setRowData(userAgGridData);




                // 진료별 건수, 금액
                /*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++){
                        data.totalPayment[i].percent = Math.round(data.totalPayment[i].totalAmount / totalAmount * 100);
                    }

                    // 전체 건수, 금액
                    $("#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{
                            data.topPaymentList[i].percent = Math.round(data.topPaymentList[i].totalAmount / tempTopTotalAmount * 100);
                            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_downloadStatisticsUserExcel() {
    if ("Y" == downloadUseYn) {
        // 수정가능
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += '&statisticsSearchDate=' + statisticsSearchDate

        let url = encodeURI("/webstatistics/downloadStatisticsUserExcel.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 dailyFirstYnGraph = document.getElementById('dailyFirstYnGraph');
    dailyFirstChart = new Chart(dailyFirstYnGraph, {
        type: 'line',
        data: {
            labels: dailyFirstYData.labels,
            datasets: [
                {
                    label: '초진',
                    data: dailyFirstYData.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: dailyFirstNData.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
                }
            ]
        },
        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 : 300, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 50 /* 표시되는 축의 값 */
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    align: 'end',
                },
                tooltip: {
                    enabled: true,
                    callbacks: {
                        label: function(context) {
                            let label = '명';

                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += context.parsed.y;
                            }else{
                                label += 0;
                            }
                            return label;
                        },
                        title: function(tooltipItems) {
                            const dataIndex = tooltipItems[0].dataIndex;
                            const label = tooltipItems[0].datasetIndex === 0 ? dailyFirstYData.labels[dataIndex] : dailyFirstYData.labels[dataIndex];
                            return label;
                        }
                    }
                }
            }
        }
    });

    const firstYnPercentGraph = document.getElementById('firstYnPercentGraph');
    firstYnChart = new Chart(firstYnPercentGraph, {
        type: 'pie',
        data: {
            labels: firstYnData.labels,
            datasets: [{
                label: '비율 (%)',
                data: firstYnData.data,
                borderWidth: 1,
                backgroundColor: [
                    'rgba(255, 129, 149, 1)',
                    'rgba(35, 209, 109, 1)'
                ]
            }]
        },
        options: {
            responsive: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

    const reserveCategoryGraph = document.getElementById('reserveCategoryGraph');
    reserveCategoryChart = new Chart(reserveCategoryGraph, {
        type: 'bar',
        data: {
            labels: reserveCategoryData.labels,
            datasets: [{
                label: '건',
                data: reserveCategoryData.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,
            scales: {
                y: {
                    beginAtZero: true,
                    suggestedMax : 300, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 50 /* 표시되는 축의 값 */
                    }
                }
            },
            plugins: {
                legend: {
                    display: false,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

    const genderAgeGraph = document.getElementById('genderAgeGraph');
    genderAgeChart = new Chart(genderAgeGraph, {
        type: 'bar',
        data: {
            labels: genderAgeFData.labels,
            datasets: [
                {
                    label: '여성',
                    data: genderAgeFData.data,
                    backgroundColor: 'rgba(255, 129, 149, 1)',
                    barThickness: 25
                },
                {
                    label: '남성',
                    data: genderAgeMData.data,
                    backgroundColor: 'rgba(38, 153, 251, 1)',
                    barThickness: 25
                },
            ]
        },
        options: {
            responsive: false,
            scales: {
                y: {
                    beginAtZero: true,
                    suggestedMax : 300, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 50 /* 표시되는 축의 값 */
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

    const membershipGraph = document.getElementById('membershipGraph');
    membershipChart = new Chart(membershipGraph, {
        type: 'pie',
        data: {
            labels: membershipData.labels,
            datasets: [{
                label: '비율 (%)',
                data: membershipData.data,
                backgroundColor: [
                    'rgba(216, 221, 227, 1)',
                    'rgba(38, 153, 251, 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_firstYnFormatter(params){
    if("Y" == params.value){
        return "초진";
    }else if("N" == params.value){
        return "재진";
    }else{
        return "";
    }
}

function fn_genderFormatter(params){
    if("F" == params.value){
        return "여성";
    }else if("M" == params.value){
        return "남성";
    }else{
        return "";
    }
}


// 국적
let nationalityColumnDefs = [
        {field: "rowNumber", headerName: "순위", minWidth: 80, maxWidth: 80
            ,valueGetter : params => {
                return (params.node.rowIndex + 1) * 1;
            }
        },
        {field: "categoryItemName", headerName: "국적"},
        {field: "totalCount", headerName: "진료수", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "totalAmount", headerName: "금액", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "percent", headerName: "비중", minWidth: 100, maxWidth: 100, valueFormatter: fn_percentFormatter}
];

// let the grid know which columns and what data to use
let nationalityGridOptions = {
    suppressRowTransform: true,
    columnDefs: nationalityColumnDefs,
    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: nationalityAgGridData,
    suppressRowClickSelection: true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText: {
        noRowsToShow: '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection: 'multiple', // row 다중 선택
    debug: false,
    onCellClicked: function (event) { //셀 클릭 이벤트
    },
    onSelectionChanged: function (event) { //체크박스 선택
    },
    onSortChanged: function (event) {
    }
};

let nationalityGridDiv = document.querySelector('#nationalityGrid');

new agGrid.Grid(nationalityGridDiv, nationalityGridOptions);

// 고객구분
let userTypeColumnDefs = [
        {field: "rowNumber", headerName: "순위", minWidth: 80, maxWidth: 80
            ,valueGetter : params => {
                return (params.node.rowIndex + 1) * 1;
            }
        },
        {field: "categoryItemName", headerName: "고객구분"},
        {field: "totalCount", headerName: "진료수", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "totalAmount", headerName: "금액", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "percent", headerName: "비중", minWidth: 100, maxWidth: 100, valueFormatter: fn_percentFormatter}
];

// let the grid know which columns and what data to use
let userTypeGridOptions = {
    suppressRowTransform: true,
    columnDefs: userTypeColumnDefs,
    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: userTypeAgGridData,
    suppressRowClickSelection: true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText: {
        noRowsToShow: '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection: 'multiple', // row 다중 선택
    debug: false,
    onCellClicked: function (event) { //셀 클릭 이벤트
    },
    onSelectionChanged: function (event) { //체크박스 선택
    },
    onSortChanged: function (event) {
    }
};

let userTypeGridDiv = document.querySelector('#userTypeGrid');

new agGrid.Grid(userTypeGridDiv, userTypeGridOptions);

// 상세 내역
let userColumnDefs = [
        {field: "writeDate", headerName: "날짜", minWidth: 100, maxWidth: 140},
        {field: "firstYn", headerName: "방문유형", minWidth: 100, maxWidth: 100},
        {field: "reserveCategoryItemName", headerName: "예약유형", minWidth: 100, maxWidth: 100},
        {field: "treatmentName", headerName: "진료구분", minWidth: 100, maxWidth: 100},
        {field: "treatmentProcedureName", headerName: "시술(상품)명", minWidth: 150},
        {field: "userName", headerName: "고객명", minWidth: 150, maxWidth: 150},
        {field: "nationalityName", headerName: "국적", minWidth: 150, maxWidth: 150},
        {field: "birthDay", headerName: "생년월일", minWidth: 130, maxWidth: 130},
        {field: "gender", headerName: "성별", minWidth: 130, maxWidth: 130}
];

// let the grid know which columns and what data to use
let userGridOptions = {
    suppressRowTransform: true,
    columnDefs: userColumnDefs,
    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: userAgGridData,
    suppressRowClickSelection: true, // 로우 클릭시 체크박스 선택 true no, false yes
    localeText: {
        noRowsToShow: '조회 결과가 없습니다.'
    }, //데이터 없을 시 나오는 문구
    rowSelection: 'multiple', // row 다중 선택
    debug: false,
    onCellClicked: function (event) { //셀 클릭 이벤트
    },
    onSelectionChanged: function (event) { //체크박스 선택
    },
    onSortChanged: function (event) {
    }
};

let userGridDiv = document.querySelector('#userGrid');

new agGrid.Grid(userGridDiv, userGridOptions);

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