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

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

let dailyPaymentChart;

let paymentAgGridData = [];

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

    $.ajax({
        url: encodeURI('/webstatistics/selectStatisticsPayment.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){
                    // 결제완료
                    $("#totalPaymentStatus0").text(fn_numberFormat(data.totalPayment[0].paymentAmount)+"원");
                    // 결제취소
                    $("#totalPaymentStatus1").text(fn_numberFormat(data.totalPayment[0].cancelPaymentAmount)+"원");
                    // 할인
                    $("#totalPaymentStatus2").text(fn_numberFormat(data.totalPayment[0].discountAmount)+"원");
                    // 환불
                    $("#totalPaymentStatus3").text(fn_numberFormat(data.totalPayment[0].refundPaymentAmount)+"원");
                    // 미수
                    $("#totalPaymentStatus4").text(fn_numberFormat(data.totalPayment[0].nonPaymentAmount)+"원");
                }

                // 당월 결제 금액
                // 초기화
                dailyPaymentData.data = [];
                dailyPaymentData.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);
                    }
                }
                dailyPaymentChart.data.labels = dailyPaymentData.labels;
                dailyPaymentChart.data.datasets[0].data = dailyPaymentData.data;
                dailyPaymentChart.update();

                // 결제 수단별 금액
                if(0<data.totalPaymentCategory.length){
                    // 총 금액 구하기
                    let totalAmount = 0;
                    for(let i=0; i<data.totalPaymentCategory.length; i++){
                        if("MM" != data.totalPaymentCategory[i].paymentCategoryItemId){
                            // 멤버십은 제외
                            totalAmount += data.totalPaymentCategory[i].totalAmount;
                        }
                    }

                    for(let i=0; i<data.totalPaymentCategory.length; i++){
                        let percent = 0;
                        if("MM" != data.totalPaymentCategory[i].paymentCategoryItemId){
                            // 멤버십은 제외
                            percent = Math.round(data.totalPaymentCategory[i].totalAmount / totalAmount * 100);

                            if(isNaN(percent)){ // NaN => 0 으로 처리
                                percent = 0;
                            }
                        }

                        $("#paymentCategoryName"+i).text(fn_numberFormat(data.totalPaymentCategory[i].totalAmount)+" ("+percent+"%)");
                    }
                }

                // 상세 내역 그리드
                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_removeDuplicateWord(param){
    let originalString = param.value;

    let array = originalString.split(',');
    let uniqueArray = [...new Set(array)];

    return uniqueArray.join(', ');

}
function formatTreatmentProcedure(treatmentProcedureNm) {
    let procedures = treatmentProcedureNm.value.split(',');
    let mainProcedure = procedures[0];
    let additionalCount = procedures.length - 1;
    let result = mainProcedure;
    if (additionalCount > 0) {
        result += ` 외 ${additionalCount}건`;
    }
    return result;
}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadStatisticsPaymentExcel() {
    if ("Y" == downloadUseYn) {
        // 수정가능
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += '&statisticsSearchDate=' + statisticsSearchDate

        let url = encodeURI("/webstatistics/downloadStatisticsPaymentExcel.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('dailyPaymentStatistics');

    dailyPaymentChart = new Chart(dailyPaymentStatistics, {
        type: 'bar',
        data: {
            labels: dailyPaymentData.labels,
            datasets: [{
                label: '단위(원)',
                data: dailyPaymentData.data,
                borderColor: 'rgba(57, 133, 234, 1)',
                borderWidth: 1,
                backgroundColor: '#3985EA',
                barThickness: 20
            }]
        },
        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: {
            }
        }
    });

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

function fn_numberFormatter(params){
    return fn_numberFormat(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,cellRenderer:formatTreatmentProcedure},
        {field: "treatmentProcedureNm", headerName: "시술(상품)명", minWidth: 150,cellRenderer:formatTreatmentProcedure},
        {field: "userName", headerName: "고객명", minWidth: 150, maxWidth: 150},
        {field: "paymentCategoryItemName", headerName: "결제구분", minWidth: 100,maxWidth: 100/*,valueFormatter:fn_removeDuplicateWord*/},
        {field: "totalAmount", headerName:"결제총액", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "discountAmount", headerName:"할인", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "membershipPrice", headerName:"멤버십", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "nonpaymentAmount", headerName:"미수", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "paymentAmount", headerName:"결제금액", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "amount", headerName:"공급가", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "vat", headerName:"VAT", minWidth:90, maxWidth:90,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "refundAmount", headerName:"취소/환불", minWidth:130, maxWidth:130,cellStyle:{textAlign: 'right'}, cellRenderer:fn_formatAmount},
        {field: "status1", headerName:"결제상태", minWidth:100, maxWidth:100}
];

// 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) {
        /*//정렬
        paymentSort = ''; //기존 정렬 초기화
        let columnArr = event.columnApi.getColumnState();
        if (0 < columnArr.length) {

            //sort index 순으로 재정렬
            columnArr.sort(function (a, b) {
                return a.sortIndex - b.sortIndex;
            });

            let nullCnt = 0;
            for (let i = 0; i < columnArr.length; i++) {
                let gridSortModel = columnArr[i].colId;
                let gridSort = columnArr[i].sort;

                if (gridSort != null) {
                    paymentStart = 0;

                    paymentSort += gridSortModel + ' ' + gridSort + ',';

                } else {
                    nullCnt++;

                    if (nullCnt == columnArr.length) {
                        paymentSort = '';
                        paymentDir = '';

                        paymentStart = 0;
                    }
                }
            }
        }

        paymentSort = paymentSort.substring(0, paymentSort.lastIndexOf(",")); //맨끝 콤마 지우기

        fn_userSearch();*/
    }
};

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

new agGrid.Grid(paymentGridDiv, paymentGridOptions);

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