/* 페이징 관련 변수 */
let paymentTotalCount   = 0;
let paymentTotalPages   = 0;

/*aggird*/
let paymentAgGridData = [];

let paymentSelectId = "";
/****************************************************************************
 * 수납 내역 리스트 조회
 ****************************************************************************/
function fn_selectListPaymentJson(){
    let formData = new FormData();
    formData.append("menuClass", menuClass);
    formData.append("paymentSearchKeywordParam", paymentSearchKeywordParam);
    formData.append("paymentSort", paymentSort);
    formData.append("paymentDir", paymentDir);
    formData.append("paymentStart", paymentStart);
    formData.append("paymentLimit", paymentLimit);
    formData.append("paymentSearchStartDate", paymentSearchStartDate);
    formData.append("paymentSearchEndDate", paymentSearchEndDate);
    formData.append("paymentSearchDateType", paymentSearchDateType);
    formData.append("muTreatmentId", muTreatmentId);
    formData.append("treatmentName", treatmentName);
    formData.append("paymentStatus", paymentStatus);
    formData.append("paymentStatusKeyword", paymentStatusKeyword);
    formData.append("paymentCategoryItemNm", paymentCategoryItemNm);

    $.ajax({
        url: encodeURI('/webpayment/selectListPayment.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                // 페이징 처리
                paymentTotalCount  = data.totalCount;
                Array.from(document.querySelectorAll('.total_list .title')).forEach(liElement => {
                    if (liElement.classList.contains('total')) return;

                    let itemName = liElement.textContent.split('(')[0]; // Extract the item name
                    liElement.textContent = `${itemName}(0)`;

                    let spanElement = liElement.nextElementSibling.querySelector('span');
                    spanElement.textContent = '0';
                });
                if(data.selectTotalAmount) {
                    let {amount, vat, totalAmount} = data.selectTotalAmount
                    $('#detail_total').text(totalAmount.toLocaleString());
                    $('#detail_total_amount').text(amount.toLocaleString());
                    $('#detail_total_vat').text(vat.toLocaleString());
                }else{
                    $('#detail_total').text(0);
                    $('#detail_total_amount').text(0);
                    $('#detail_total_vat').text(0);
                }
                if(data.groupByTreatment) {
                    data.groupByTreatment.forEach(row => {
                        let {count, paymentAmount, paymentCategoryItemName} = row;

                        let liElement = Array.from(document.querySelectorAll('.title.treatment')).find(p =>
                            p.textContent.includes(paymentCategoryItemName)
                        );

                        if (liElement) {
                            // Update the count
                            liElement.textContent = `${paymentCategoryItemName}(${count})`;

                            // Update the payment amountMU_MENU_SEQ
                            let spanElement = liElement.nextElementSibling.querySelector('span');
                            spanElement.textContent = paymentAmount.toLocaleString();
                        }
                    })
                }
                if(data.groupByPayment){
                    data.groupByPayment.forEach(row=>{
                        let {count, paymentAmount, paymentCategoryItemName} = row;

                        let liElement = Array.from(document.querySelectorAll('.title.method')).find(p =>
                            paymentCategoryItemName&&p.textContent.includes(paymentCategoryItemName)
                        );

                        if (liElement) {
                            // Update the count
                            liElement.textContent = `${paymentCategoryItemName}(${count})`;

                            // Update the payment amountMU_MENU_SEQ
                            let spanElement = liElement.nextElementSibling.querySelector('span');
                            spanElement.textContent = paymentAmount.toLocaleString();
                        }

                    })
                }
                if(data.groupByMembership){
                    data.groupByMembership.forEach(row=>{
                        let {count, paymentAmount, paymentCategoryItemName} = row;

                        let liElement = Array.from(document.querySelectorAll('.title.method')).find(p =>
                            paymentCategoryItemName&&p.textContent.includes(paymentCategoryItemName)
                        );

                        if (liElement) {
                            // Update the count
                            liElement.textContent = `${paymentCategoryItemName}(${count})`;

                            // Update the payment amountMU_MENU_SEQ
                            let spanElement = liElement.nextElementSibling.querySelector('span');
                            spanElement.textContent = paymentAmount.toLocaleString();
                        }

                    })
                }
                if(data.groupByCancel) {
                    data.groupByCancel.forEach(row => {
                        let {count, paymentAmount, paymentCategoryItemName} = row;

                        let liElement = Array.from(document.querySelectorAll('.title.cancel')).find(p =>
                            p.textContent.includes(paymentCategoryItemName)
                        );

                        if (liElement) {
                            // Update the count
                            liElement.textContent = `${paymentCategoryItemName}(${count})`;

                            // Update the payment amountMU_MENU_SEQ
                            let spanElement = liElement.nextElementSibling.querySelector('span');
                            spanElement.textContent = paymentAmount.toLocaleString();
                        }

                    })
                }

                paymentAgGridData = data.rows.map((item, index)=> {
                    item.rowNum= paymentStart + index + 1
                    return item;
                });
                paymentGridOptions.api.setRowData(paymentAgGridData);

                paymentTotalPages = Math.ceil(paymentTotalCount / paymentLimit);
                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#paymentPagination').twbsPagination({
                        startPage    : ((paymentStart/paymentLimit)+1),
                        totalPages   : (paymentTotalPages===0)?1:paymentTotalPages,
                        visiblePages : 10,
                        initiateStartPageClick: false,
                        prev         : '<img src="/image/web/page_navigation_arrow.svg" alt="prev"/>',
                        next         : '<img src="/image/web/page_navigation_arrow.svg" alt="next"/>',
                        first        : '',
                        last         : '',
                        onPageClick: function (event, page) {
                            fn_paymentPagination(page);
                        }
                    }).on('page', function (event, page) {
                        //console.info(page + ' (from event listening)');
                    });
                }
                else{

                }
            }
            else{
                modalEvent.danger("조회 오류", data.msgDesc);
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){
            // 로딩열기
            paymentGridOptions.api.showLoadingOverlay();
        },
        complete:function(){

        }
    });
}
function setGroupSumData(data){
    let groupedData = {};
    data.forEach(function(item) {
        if (!groupedData[item.paymentCategoryItemNm]) {
            groupedData[item.paymentCategoryItemNm] = { amount: 0, vat: 0 };
        }
        groupedData[item.paymentCategoryItemNm].amount += item.amount;
        groupedData[item.paymentCategoryItemNm].vat += item.vat;
    });

    let result;
    let treatmentData='';
    for (let key in groupedData) {
        result = fn_formatAmount(groupedData[key].amount+groupedData[key].vat)
        treatmentData+=`${key}(${result}),`
    }
    treatmentData = treatmentData.replace(/,$/, '');
    return treatmentData;
}
/****************************************************************************
 * 검색하기
 ****************************************************************************/
function fn_paymentSearch(param){
    if("A"!=param && "Y"!=selectUseYn){
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }

    fn_paymentPaginReset();

    paymentSearchKeywordParam = $("#paymentSearchKeywordParam").val()??'';

    paymentSearchDateType  = $("#paymentSearchDateType").val();
    paymentSearchStartDate = $("#paymentSearchStartDate").val();
    paymentSearchEndDate   = $("#paymentSearchEndDate").val();

    paymentCategoryItemNm  = $("#paymentCategoryItemNm").val();
    muTreatmentId          = $("#muTreatmentId").val();
    treatmentName          = $("#muTreatmentId").siblings('button').text()=='진료구분'?'':$("#muTreatmentId").siblings('button').text();
    paymentStatus          = $("#paymentStatus").val();
    let status = $("#paymentStatus").siblings('button').text();

    paymentStatusKeyword   = status==='전체'|| status==='결제상태'?'':status;

    fn_selectListPaymentJson();
}
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_paymentEnter(e){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            fn_paymentSearch();
        }
    }
    else{
        // 윈도우, 사파리, 크롬
        if(13 == event.keyCode) {
            //로그인 액션 스크립트
            fn_paymentSearch();
        }
    }
}
/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
function fn_downloadExcel(){
    if("Y"==downloadUseYn){
        // 수정가능
        let pagingParam = "?menuClass="+menuClass;
        pagingParam    += "&paymentSearchKeywordParam="+paymentSearchKeywordParam;
        pagingParam    += "&paymentSort="+paymentSort;
        pagingParam    += "&paymentDir="+paymentDir;
        pagingParam    += "&paymentStart="+paymentStart;
        pagingParam    += "&paymentLimit="+paymentLimit;
        pagingParam    += "&paymentSearchStartDate="+paymentSearchStartDate;
        pagingParam    += "&paymentSearchEndDate="+paymentSearchEndDate;
        pagingParam    += "&paymentSearchDateType="+paymentSearchDateType;
        pagingParam    += "&muTreatmentId="+muTreatmentId;
        pagingParam    += "&treatmentName="+treatmentName;
        pagingParam    += "&paymentStatus="+paymentStatus;
        pagingParam    += "&paymentStatusKeyword="+paymentStatusKeyword;
        pagingParam    += "&paymentCategoryItemNm="+paymentCategoryItemNm;
        var url = encodeURI("/webpayment/downloadPaymentExcel.do"+pagingParam);
        $("#excelForm").prop("action",url);
        $("#excelForm").submit();
    }
    else{
        modalEvent.warning("", "내려받기 권한이 없습니다.");
        return false;
    }
}
/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_paymentPagination(param){
    paymentStart = (parseInt(param)-1)*paymentLimit;

    fn_selectListPaymentJson();
}
/****************************************************************************
 * 페이징 리셋
 ****************************************************************************/
function fn_paymentPaginReset(){
    paymentSearchKeywordParam = '';

    paymentStart        = 0;
    paymentLimit        = 100;
    paymentTotalCount   = 0;
    paymentTotalPages   = 0;

    //페이징 초기화
    if($("#paymentPagination").data("twbs-pagination")){
        $("#paymentPagination").twbsPagination("destroy");
    }
}
/****************************************************************************
 * 진료구분 검색필터 세팅
 ****************************************************************************/
function setTreatmentOption(data){
    const ulElement = document.getElementById('treatmentList');

    data.forEach(treatment => {
        const liElement = document.createElement('li');
        liElement.className = 'option_list_item';
        liElement.textContent = treatment.treatmentName;
        liElement.id = treatment.muTreatmentId;

        ulElement.appendChild(liElement);
    });
}
/****************************************************************************
 * 검색 날짜 설정
 //(A:오늘, B:3일, C:7일, D:최근30일, E:최근90일, F:이번달, G:올해, H:지난주, I:지난달)
 ****************************************************************************/
function fn_paymentSetDate(param){
    if("A"==param){
        // 오늘
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchStartDate = year+'-'+month+'-'+day;
        paymentSearchEndDate   = year+'-'+month+'-'+day;
    }
    else if("B"==param){
        // 3일
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        toDate.setDate(toDate.getDate() - 3);
        year  = toDate.getFullYear();
        month = toDate.getMonth() + 1;
        day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchStartDate = year+'-'+month+'-'+day;
    }
    else if("C"==param){
        // 이번주
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        toDate.setDate(toDate.getDate() - 7);
        year  = toDate.getFullYear();
        month = toDate.getMonth() + 1;
        day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchStartDate = year+'-'+month+'-'+day;
    }
    else if("D"==param){
        // 최근30일
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        //최근30일
        toDate.setDate(toDate.getDate() - 30);
        startYear  = toDate.getFullYear();
        startMonth = toDate.getMonth() + 1;
        startDay   = toDate.getDate();

        if(startMonth < 10) startMonth = "0" + startMonth;
        if(startDay < 10) startDay = "0" + startDay;

        paymentSearchStartDate = startYear+'-'+startMonth+'-'+startDay;
        paymentSearchEndDate   = year+'-'+month+'-'+day;

    }
    else if("E"==param){
        // 최근90일
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        toDate.setDate(toDate.getDate() - 90);
        year  = toDate.getFullYear();
        month = toDate.getMonth() + 1;
        day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchStartDate = year+'-'+month+'-'+day;
    }
    else if("F"==param){
        //F:이번달
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchEndDate   = year+'-'+month+'-'+day;

        // 검색 시작일자
        paymentSearchStartDate = year+'-'+month+'-01';
    }
    else if("G"==param){
        // G:올해
        // 검색 종료일자
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        let day   = toDate.getDate();

        if(month < 10) month = "0" + month;
        if(day < 10) day = "0" + day;

        paymentSearchEndDate   = year+'-'+month+'-'+day;
        // 검색 시작일자
        paymentSearchStartDate = year+'-01-01';
    }
    else if("H"==param){
        // H:지난주, I:지난달
        // 검색 종료일자
        let toDate = new Date();
        let startDate = new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate() - toDate.getDay() - 6); // 지난주 월요일
        let endDate = new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate() - toDate.getDay()); // 지난주 일요일

        // 종료일자 설정
        let year = endDate.getFullYear();
        let month = endDate.getMonth() + 1; // JS의 getMonth()는 0부터 시작하므로 +1
        let day = endDate.getDate();

        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        paymentSearchEndDate = year + '-' + month + '-' + day;

        // 시작일자 설정
        year = startDate.getFullYear();
        month = startDate.getMonth() + 1;
        day = startDate.getDate();

        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        paymentSearchStartDate = year + '-' + month + '-' + day;
    }
    else if("I"==param){
        // I:지난달
        // I: 지난달
        let currentDate = new Date();
        let currentYear = currentDate.getFullYear();
        let currentMonth = currentDate.getMonth();

        // 지난달의 첫째 날
        let firstDayOfLastMonth = new Date(currentYear, currentMonth - 1, 1);
        let year = firstDayOfLastMonth.getFullYear();
        let month = firstDayOfLastMonth.getMonth() + 1; // JS는 월을 0부터 시작하므로 +1
        let day = firstDayOfLastMonth.getDate();

        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        paymentSearchStartDate = year + '-' + month + '-' + day;

        // 지난달의 마지막 날
        let lastDayOfLastMonth = new Date(currentYear, currentMonth, 0);
        year = lastDayOfLastMonth.getFullYear();
        month = lastDayOfLastMonth.getMonth() + 1;
        day = lastDayOfLastMonth.getDate();

        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        paymentSearchEndDate = year + '-' + month + '-' + day;
    }

    $("#paymentSearchStartDate").val(paymentSearchStartDate).trigger("change");
    $("#paymentSearchEndDate").val(paymentSearchEndDate).trigger("change");
}
/****************************************************************************
 * 정렬 이벤트
 ****************************************************************************/
function fn_alignEvent(param, param2){
    let align = "";

    if("A"==param){
        align = "오늘";

        fn_paymentSetDate('A');
    }
    else if("B"==param){
        align = "최근30일";

        fn_paymentSetDate('D');
    }
    else if("C"==param){
        align = "최근90일";

        fn_paymentSetDate('E');
    }
    else if("D"==param){
        align = "이번주";

        fn_paymentSetDate('C');
    }
    else if("E"==param){
        align = "이번달";

        fn_paymentSetDate('F');
    }
    else if("F"==param){
        align = "올해";

        fn_paymentSetDate('G');
    }
    else if("G"==param){
        align = "지난주";

        fn_paymentSetDate('H');
    }
    else if("H"==param){
        align = "지난달";

        fn_paymentSetDate('I');
    }
    else{
        align = "";
    }
    $("#paymentSearchDateType").val(param);
    $("#paymentSearchDateType").siblings("button").text(align);
}
function fn_formatAmount(amount){
    let data = typeof amount === 'number'?amount:amount.value;
    return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
/****************************************************************************
 * 초기화하기
 ****************************************************************************/
function fn_paymentReset(){
    fn_paymentSetDate('A');
    $("#paymentSearchDateType option:eq(0)").prop("selected", true);

    $("#paymentSearchKeyword").val("");

    fn_paymentSearch();
}
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_removeDuplicateWord(param){
    let originalString = param.value;

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

    return uniqueArray.join(', ');

}
/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_paymentOk(){
    fn_paymentReset();
}
function fn_detailPaymentPopup(data){
    let reqParam =  {
        "paymentNumber" : data.paymentNumber,
        "muUserId" : data.muUserId,
        "reserveDate" : data.reserveDate,
        "userName":data.userName
    };

    if("Y"==selectUseYn){
        // 수정가능
        paymentDetailModal.popup(function(obj, reqParam) {
            fn_paymentOk();
        }, reqParam);
    }

}
let paymentColumnDefs = [
    { field: "checkbox", headerName:"", minWidth:55, maxWidth:55, headerCheckboxSelection: true, checkboxSelection: true },
    /* { field: "rowNum", headerName:"번호", minWidth:80,maxWidth:80, sortable: false }, */
    {field: "rowNum", headerName:"번호", minWidth:60,maxWidth:100,sortable: false, cellStyle:{textAlign: 'center'}},
    { field: "reserveDate", headerName:"진료일", minWidth:100, maxWidth:100 },
    { field: "paymentDate", headerName:"결제일", minWidth:100, maxWidth:100 },
    { field: "paymentCategoryItemName", headerName:"결제구분",/*valueFormatter:fn_removeDuplicateWord,*/ minWidth:90,cellStyle:{cursor: 'pointer', color:'#3985EA'} },
    { field: "userName", headerName:"고객 이름", minWidth:120, maxWidth:120,cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    { field: "muUserId",hide:true},
    { field: "treatmentName", headerName:"진료유형", minWidth:90,cellRenderer:formatTreatmentProcedure},
    { field: "treatmentProcedureNm", headerName:"시술(상품)명", minWidth:230,cellRenderer:formatTreatmentProcedure},
    { field: "reserveMemberName", headerName:"담당의사", minWidth:120, maxWidth:120 },
    { field: "muMemberName", headerName:"담당자", minWidth:120, maxWidth:120 },
    { field: "etc", headerName:"결제 메모", minWidth:230},
    { 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){ //셀 클릭 이벤트
        /* alert(event.column.colId); */
        if('paymentCategoryItemName'==event.column.colId){
            fn_detailPaymentPopup(event.data);
        }
        if('userName'==event.column.colId){
            fn_userPaymentMenu(event.data.muUserId);
        }

    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

        paymentSelectId = '';
        for(let i=0; i<selectRows.length; i++){
            paymentSelectId += selectRows[i].muPaymentId + ",";
        }
        paymentSelectId = paymentSelectId.substring(0, paymentSelectId.lastIndexOf(','));
    },
    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_paymentSearch();
    }
};

// lookup the container we want the Grid to use
let paymentGridDiv = document.querySelector('#paymentGrid');

// create the grid passing in the div to use together with the columns & data we want to use
new agGrid.Grid(paymentGridDiv, paymentGridOptions);

function fn_userPaymentMenu(userId){
    let spans = document.querySelectorAll('#menu_list span');

    spans.forEach(function(span) {
        if (span.textContent.trim() === '고객') {
            // 텍스트가 "고객"인 경우 해당 요소를 출력
            let groupCode=span.parentElement.getAttribute('id').replace('menu','');
            fn_selectuserPaymentMenu(groupCode,userId)
        }
    });
}
/****************************************************************************
 * 메뉴 조회
 ****************************************************************************/
function fn_selectuserPaymentMenu(param,userId){
    let formData = new FormData();
    formData.append("type", "C");
    formData.append("groupCode", param);

    $.ajax({
        url: encodeURI('/webmenu/selectListMenu.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                let listHTML = '';
                if(data.rows.length>1){
                    let action;
                    let menuCode;
                    for(let i = 0; i < data.rows.length; i++){
                        if('수납내역'===data.rows[i].menuName){
                            action   = data.rows[i].action+"?muUserId="+userId;
                            menuCode = data.rows[i].menuCode;
                        }
                        if(action&&menuCode)
                            fn_leftFormAction2(menuCode,action);

                    }

                    if(6 == menuClass.length){
                        menuClass = data.rows[0].subMenuCode;
                    }
                }

            }
            else if(data.msgCode=='-1'){
                modalEvent.warning("조회 오류", data.msgDesc);
            }
            else{
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){

        },
        complete:function(){

        }
    });
}

/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit(){
    // 날짜 datepicker
    fn_searchDatePicker("#divPaymentSearchStartDate", "#divPaymentSearchEndDate");

    if(!paymentSearchDateType){
        $("#li_A").click();
    }else{
        fn_alignEvent(paymentSearchDateType);
    }

    // 초기 페이징 처리
    $("#paymentSearchKeyword").val(paymentSearchKeywordParam);

    fn_paymentSearch("A");
}

/****************************************************************************
 * 옵션선택
 ****************************************************************************/
function fn_OptionSelection(target,e) {
    // 옵션 선택 이벤트 핸들러
    $(target).closest('.select_box').find('.label').text( $(target).text());
    $(target).closest('.select_box').find('input').val($(target).attr('id')??$(target).text());
    // $(target).closest('.select_box').find('.option_list_item').removeClass('selected');
    // $(target).addClass('selected');
    // $(target).closest('.select_option_list').hide();
    // e.stopPropagation();

}
/****************************************************************************
 * 수납상세 드롭다운 열기
 ****************************************************************************/
function openView(){
    $('.total_list').toggleClass('open');
    $('.view_btn').toggleClass('open');
}
/****************************************************************************
 * select box 선택 이벤트
 ****************************************************************************/
function fn_clickSelectBox(target) {
    $(target).find('.select_option_list').toggle();
}

function fn_clickEvent() {
    // $('.select_box').off('click');
    // //$(document).off('click');
    //
    // $('.select_box').on('click', function () {
    //     fn_clickSelectBox($(this));
    //     $('.select_box').not(this).find('.select_option_list').hide();
    // });
    // 옵션 선택 이벤트
    $('.select_box').on('click', 'li', function (e) {
        fn_OptionSelection($(this), e);
    });

// 다른 곳을 클릭했을 때 옵션 숨기기
//     $(document).on('click', function (event) {
//         if (!$(event.target).closest('.select_box').length) {
//             $('.payment .select_option_list').hide();
//         }
//     });
}
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_SearchEnter(e, type){
    if(e.which){
        // 파이어폭스
        if(e.which==13) {
            //로그인 액션 스크립트
                fn_paymentSearch();
        }
    }else{
        // 윈도우, 사파리, 크롬
        if(event.keyCode==13) {
            //로그인 액션 스크립트
                fn_paymentSearch();
        }
    }
}
/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent(){
    let treatmentOption = fn_selectListTreatmentOption2();
    setTreatmentOption(treatmentOption);

    // 검색 input
    $(document).on('keypress','#paymentSearchKeyword',function(e){
        fn_paymentEnter(e);
    });
    fn_clickEvent();
    // 검색 조회 버튼
    $("#btnSearchPayment").click(function () {
        fn_paymentSearch();
    });
    $("#paymentSearchKeywordParam").on("keypress",function (e) {
        fn_SearchEnter(e);
    });

    // 엑셀다운로드
    $("#btnDownLoad").click(function () {
        fn_downloadExcel();
    });

    // 기간 선택 콤보 이벤트
    const target = $("#paymentSearchDateType").siblings("ul.select_option_list");
    target.find("li.option_list_item").click(function (){
        let selectIdArr = $(this).prop("id").split('_');
        let selectId    = selectIdArr[1];
        let selectName  = $(this).text();

        $(this).parent().siblings("button").text(selectName);
        $(this).parent().siblings("input").val(selectId);

        fn_alignEvent(selectId);
    });
}

$(function(){
    // 페이지 event
    fn_pageEvent();
    // 페이지 init
    fn_pageInit();
});