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

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

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

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

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

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

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

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

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



let dailyPushChart;
let dailyTotalAmountChart;
let treatmentPercentChart;
let pushStateChart;

let kakaoTemplateAgGridData = [];
let pushAgGridData = [];

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

    $.ajax({
        url: encodeURI('/webstatistics/selectStatisticsPush.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async:true,
        success: function(data){
            if(data.msgCode=='0'){
                // 앱푸시, SMS, 알림톡 건수 / 비용
                if(0<data.totalCountAmount.length){
                    let totalCount = 0;
                    let totalAmount = 0;

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

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

                    // 전체 건수, 금액
                    $("#pushAll p").eq(0).text(fn_numberFormat(totalCount)+"건");
                    $("#pushAll p").eq(1).text(fn_numberFormat(totalAmount)+"원");
                }

                // 푸시 트렌드
                // 앱푸시
                // 초기화
                dailyAppPushData.data = [];
                dailyAppPushData.labels = [];
                if(0<data.thisDailyAppPush.length){
                    for(let i=0; i<data.thisDailyAppPush.length; i++){
                        dailyAppPushData.data.push(data.thisDailyAppPush[i].totalCount);
                        dailyAppPushData.labels.push(data.thisDailyAppPush[i].date);
                    }
                }

                // SMS
                // 초기화
                dailySmsData.data = [];
                dailySmsData.labels = [];
                if(0<data.thisDailySms.length){
                    for(let i=0; i<data.thisDailySms.length; i++){
                        dailySmsData.data.push(data.thisDailySms[i].totalCount);
                        dailySmsData.labels.push(data.thisDailySms[i].date);
                    }
                }

                // 알림톡
                // 초기화
                dailyKakaoData.data = [];
                dailyKakaoData.labels = [];
                if(0<data.thisDailyKakao.length){
                    for(let i=0; i<data.thisDailyKakao.length; i++){
                        dailyKakaoData.data.push(data.thisDailyKakao[i].totalCount);
                        dailyKakaoData.labels.push(data.thisDailyKakao[i].date);
                    }
                }

                dailyPushChart.data.labels = dailyAppPushData.labels;
                dailyPushChart.data.datasets[0].data = dailyAppPushData.data;
                dailyPushChart.data.datasets[1].labels = dailySmsData.labels;
                dailyPushChart.data.datasets[1].data = dailySmsData.data;
                dailyPushChart.data.datasets[2].labels = dailyKakaoData.labels;
                dailyPushChart.data.datasets[2].data = dailyKakaoData.data;
                dailyPushChart.update();

                // 푸시 비용
                dailyTotalAmountData.labels = data.thisDailyTotalAmount.map(item => item.date);
                dailyTotalAmountData.data = data.thisDailyTotalAmount.map(item => item.totalAmount);
                dailyTotalAmountChart.data.labels = dailyTotalAmountData.labels;
                dailyTotalAmountChart.data.datasets[0].data = dailyTotalAmountData.data;
                dailyTotalAmountChart.update();


                // 전송상태 비율
                // 초기화
                pushStateData.data = [];
                pushStateData.labels = [];
                if(0<data.pushState.length){
                    for(let i=0; i<data.pushState.length; i++){
                        pushStateData.data.push(data.pushState[i].totalCount);
                        pushStateData.labels.push(data.pushState[i].state);
                    }
                }
                pushStateChart.data.labels = pushStateData.labels;
                pushStateChart.data.datasets[0].data = pushStateData.data;
                pushStateChart.update();


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

                    for(let i=0; i<data.kakaoTemplateCountYn.length; i++){
                        if(10 == i){
                            break;
                        }else{
                            let percent = Math.round(data.kakaoTemplateCountYn[i].totalCount / tempTotalCount * 100);
                            if(isNaN(percent)){ // NaN => 0 으로 처리
                                percent = 0;
                            }
                            data.kakaoTemplateCountYn[i].percent = percent;
                            tempData.push(data.kakaoTemplateCountYn[i]);
                        }
                    }
                }
                kakaoTemplateAgGridData = tempData;
                kakaoTemplateGridOptions.api.setRowData(kakaoTemplateAgGridData);


                // 상세 내역 그리드
                pushAgGridData = data.pushListMap;
                pushGridOptions.api.setRowData(pushAgGridData);

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

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

        let url = encodeURI("/webstatistics/downloadStatisticsPushExcel.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 dailyPushCountStatistics = document.getElementById('dailyPushCountStatistics');
    dailyPushChart = new Chart(dailyPushCountStatistics, {
        type: 'line',
        data: {
            labels: dailyAppPushData.labels,
            datasets: [
                {
                    label: '앱 푸시',
                    data: dailyAppPushData.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: 'SMS',
                    data: dailySmsData.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: dailyKakaoData.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
                }
            ]
        },
        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 : 10000, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 2000 /* 표시되는 축의 값 */
                    }
                }
            },
            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 += context.parsed.y;
                            }
                            return label;
                        },
                        title: function(tooltipItems) {
                            const dataIndex = tooltipItems[0].dataIndex;
                            const label = tooltipItems[0].datasetIndex === 0 ? dailyAppPushData.labels[dataIndex] : dailySmsData.labels[dataIndex];
                            return label;
                        }
                    }
                }
            }
        }
    });

    const dailyTotalAmountStatistics = document.getElementById('dailyTotalAmountStatistics');
    dailyTotalAmountChart = new Chart(dailyTotalAmountStatistics, {
        type: 'bar',
        data: {
            labels: dailyTotalAmountData.labels,
            datasets: [{
                label: '비용(원)',
                data: dailyTotalAmountData.data,
                borderWidth: 1,
                backgroundColor: 'rgba(38, 153, 251, 1)',
                barThickness: 20
            }]
        },
        options: {
            responsive: false,
            scales: {
                x: {
                    ticks: {
                        display: true,
                        align: 'center',
                        maxRotation: 0,
                        minRotation: 0
                    }
                },
                y: {
                    beginAtZero: true,
                    suggestedMax : 10000, /* 자동 맞춤 동작을 유지하면서 축 범위를 확장 */
                    ticks : {
                        stepSize : 2000 /* 표시되는 축의 값 */
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    align: 'center',
                }
            },
            layout: {
            }
        }
    });

    const pushStateStatistics = document.getElementById('pushStateStatistics');
    pushStateChart = new Chart(pushStateStatistics, {
        type: 'pie',
        data: {
            labels: pushStateData.labels,
            datasets: [{
                label: '건',
                data: pushStateData.data,
                backgroundColor: [
                    'rgba(255, 129, 149, 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_formatAmount(amount){
    let data = typeof amount === 'number'?amount:amount.value;
    return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// 상세 내역
let pushColumnDefs = [
        {field: "writeDate", headerName: "날짜", minWidth: 100, maxWidth: 100},
        {field: "sendType", headerName: "푸시 구분", minWidth: 100, maxWidth: 100},
        {field: "type", headerName: "푸시 유형", minWidth: 150, maxWidth: 200},
        {field: "content", headerName: "내용", minWidth: 150},
        {field: "successCount", headerName: "성공", minWidth: 100,maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "failCount", headerName: "실패", minWidth: 100,maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "totalCount", headerName: "총 전송 수", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "totalAmount", headerName:"비용", minWidth:90, maxWidth:90, cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount}
];

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

let pushGridOptionsGridDiv = document.querySelector('#pushGrid');

new agGrid.Grid(pushGridOptionsGridDiv, pushGridOptions);

// 매출 TOP 10 시술
let kakaoTemplateColumnDefs = [
        {field: "rowNumber", headerName: "순위", minWidth: 70, maxWidth: 70
            ,valueGetter : params => {
                return (params.node.rowIndex + 1) * 1;
            }
        },
        {field: "templateTitle", headerName: "푸시 유형", minWidth: 100},
        {field: "totalCount", headerName: "총 전송 수", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "successCount", headerName: "성공", minWidth: 100, maxWidth: 100, valueFormatter: fn_numberFormatter, cellStyle:{textAlign: 'right'}},
        {field: "failCount", 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/*, cellStyle:{textAlign: 'right'}*/}
];

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

let kakaoTemplateGridDiv = document.querySelector('#kakaoTemplateGrid');

new agGrid.Grid(kakaoTemplateGridDiv, kakaoTemplateGridOptions);

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