/* 페이징 관련 변수 */
let userPaymentTotalCount   = 0;
let userPaymentTotalPages   = 0;

/*aggird*/
let userPaymentAgGridData = [];

let userPaymentSelectId = "";

/****************************************************************************
 * 고객 수납 내역 리스트 조회
 ****************************************************************************/
function fn_selectListPaymentUserJson(){
    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);
    formData.append("muUserId", muUserId);

    $.ajax({
        url: encodeURI('/webpayment/selectListPaymentUser2.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: true,
        success: function(data){
            if('0'==data.msgCode){
                // 페이징 처리
                userPaymentTotalCount  = data.totalCount;
                //$("#txt_userPaymentTotalCount").text(userPaymentTotalCount);
                
                userPaymentAgGridData = data.rows;
                userPaymentAgGridData = data.rows.map((item, index)=> {
                    item.nonPaymentAmount = item.status1==='결제취소'||item.status1==='환불'?item.refundAmount.toLocaleString():
                                            item.status1==='미수'?item.nonpaymentAmount.toLocaleString():'-'
                    item.rowNum= index + 1
                    return item;
                });

                userPaymentGridOptions.api.setRowData(userPaymentAgGridData);
                if(0<data.rows.length){
                    //페이징 처리
                    window.pagObj = $('#userPaymentPagination').twbsPagination({
                        startPage    : ((paymentStart/paymentLimit)+1),
                        totalPages   : (userPaymentTotalPages==0)?1:userPaymentTotalPages,
                        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_userPaymentPagination(page);
                        }
                    }).on('page', function (event, page) {
                    });
                }
                else{

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

        }
    });
}

/****************************************************************************
 * 검색하기
 ****************************************************************************/
function fn_userPaymentSearch(param){
    if("A"!=param && "Y"!=selectUseYn){
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }

    fn_userPaymentPaginReset();

    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_selectListPaymentUserJson();
}
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_userPaymentEnter(e){
    if(e.which){
        // 파이어폭스
        if(13 == e.which) {
            //로그인 액션 스크립트
            fn_userPaymentSearch();
        }
    }
    else{
        // 윈도우, 사파리, 크롬
        if(13 == event.keyCode) {
            //로그인 액션 스크립트
            fn_userPaymentSearch();
        }
    }
}

/****************************************************************************
 * 예약 건 수납 및 수내역 조회 팝업
 ****************************************************************************/
function fn_insertReservePaymentPopup(){
    if(true != fn_emptyCheck(muUserId)){
        modalEvent.warning("등록", "고객 정보가 없습니다.");
        return;
    }

    let reqParam =  {'muUserId':muUserId};
    reservePaymentInsertModal.popup(function(obj, reqParam) {
        location.reload(true);
    }, reqParam);
}

/****************************************************************************
 * 엑셀 다운 다운로드
 ****************************************************************************/
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;
        pagingParam    += "&muUserId="+muUserId;
        
        var url = encodeURI("/webpayment/downloadPaymentExcel.do"+pagingParam);
        $("#userPaymentSelectListForm").prop("action",url);
        $("#userPaymentSelectListForm").submit();
    }
    else{
        modalEvent.warning("", "내려받기 권한이 없습니다.");
        return false;
    }
}

/****************************************************************************
 * 페이징 처리
 ****************************************************************************/
function fn_userPaymentPagination(param){
    paymentStart = (parseInt(param)-1)*paymentLimit;

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

    paymentStart        = 0;
    paymentLimit        = 100;
    userPaymentTotalCount   = 0;
    userPaymentTotalPages   = 0;

    //페이징 초기화
    if($("#userPaymentPagination").data("twbs-pagination")){
        $("#userPaymentPagination").twbsPagination("destroy");
    }
}

/****************************************************************************
 * 진료구분 검색필터 세팅
 ****************************************************************************/
function setTreatmentOption(data){
    const ulElement = document.getElementById('muTreatmentId').nextElementSibling;

    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_userPaymentSetDate(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_userPaymentSetDate('A');
    }
    else if("B"==param){
        align = "최근30일";

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

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

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

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

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

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

        fn_userPaymentSetDate('I');
    }
    else{
        align = "";
    }
    $("#paymentSearchDateType").val(param);
    $("#paymentSearchDateType").siblings("button").text(align);
}

function fn_formatAmount(amount){
    let data = typeof amount === 'number'?amount:amount.value;
    if(data)
        return data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    else
        return '-'
}
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_userPaymentReset(){
    fn_userPaymentSetDate('G');
    $("#paymentSearchDateType option:eq(0)").prop("selected", true);

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

    fn_userPaymentSearch();
}

/****************************************************************************
 * 완료
 ****************************************************************************/
function fn_userPaymentOk(){
    fn_userPaymentReset();
}


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_userPaymentOk();
        }, reqParam);
    }

}

let userPaymentColumnDefs = [
    { 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,sortable: false, cellStyle:{textAlign: 'center'}},
    { field: "reserveDate", headerName:"진료일", minWidth:100, maxWidth:100 },
    { field: "paymentDate", headerName:"결제일", minWidth:100, maxWidth:100 },
    { field: "paymentCategoryItemName", headerName:"결제구분", minWidth:90,/*valueFormatter:fn_removeDuplicateWord,*/cellStyle:{cursor: 'pointer', color:'#3985EA'}},
    { field: "userName", headerName:"고객명", minWidth:120, maxWidth:120},
    { 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 userPaymentGridOptions = {
    suppressRowTransform: true,
    columnDefs: userPaymentColumnDefs,
    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 : userPaymentAgGridData,
    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){
            console.log(event.data);
            fn_detailPaymentPopup(event.data);
        }
    },
    onSelectionChanged: function(event){ //체크박스 선택
        let selectRows = [];
        selectRows = event.api.getSelectedRows();

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

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

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

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

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

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

    fn_userPaymentSearch("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();

}
/****************************************************************************
 * 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) {
//             $('.select_option_list').hide();
//         }
//     });
}
/****************************************************************************
 * 검색 엔터 이벤트
 ****************************************************************************/
function fn_SearchEnter(e, type){
    if(e.which){
        // 파이어폭스
        if(e.which==13) {
            //로그인 액션 스크립트
                fn_userPaymentSearch();
        }
    }else{
        // 윈도우, 사파리, 크롬
        if(event.keyCode==13) {
            //로그인 액션 스크립트
                fn_userPaymentSearch();
        }
    }
}
/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent(){
    let treatmentOption = fn_selectListTreatmentOption2();
    setTreatmentOption(treatmentOption);

    // 검색 input
    $(document).on('keypress','#paymentSearchKeywordParam',function(e){
        fn_userPaymentEnter(e);
    });
    fn_clickEvent();
    // 검색 조회 버튼
    $("#btnSearchUserPayment").click(function () {
        fn_userPaymentSearch();
    });

    $("#btnUserPayment").click(function () {
        fn_insertReservePaymentPopup();
    });

    $("#paymentSearchKeywordParam").on("keypress",function (e) {
        fn_SearchEnter(e);
    });

    // 엑셀다운로드
    $("#btnDownloadUserPaymentExcel").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();
});