/****************************************************************************
 * 예약내역 조회
 ****************************************************************************/
function fn_selectListReservationJson(){
    let formData = new FormData();
    $.ajax({
        url: encodeURI('/mobilereservation/selectListReservation.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: false,
        success: function(data){
            if('0'==data.msgCode){
                const presentWrapper = $('.present_reservation');
                presentWrapper.empty();
                if(0<data.totalCount){
                    let innerHtml = '<p class="title">예약 내역</p>';
                    data.rows.forEach((reserveData,index)=>{
                        const data = JSON.stringify(reserveData)
                        if('R'===reserveData.status) {
                            innerHtml+=`<div class="reservation_box promise_completed" onclick=fn_selectPromiseCompletedPopup(${JSON.stringify(reserveData)})><!-- promise_completed : 접수완료 box -->
                                            <div class="left_box">
                                                <p class="date">${reserveData.reserveDate}</p>
                                                <p>${reserveData.reserveTime} ${reserveData.treatmentName}-${reserveData.treatmentProcedureName} 예약</p>
                                            </div>
                                            <div class="right_box">
                                                <p>진료대기고객</p>
                                                <p>${reserveData.waitingCount}명</p>
                                            </div>
                                        </div>`
                        }else{
                            innerHtml+=`<div class="reservation_box promise_pending" onclick=${'T'===reserveData.status}?fn_selectReservePendingPopup(${data}):fn_selectPastReservePopup(${data})><!-- promise_pending : 접수대기 box -->
                                            <div class="left_box">
                                                <p class="date">${reserveData.reserveDate}</p>
                                                <p>${reserveData.reserveTime} ${reserveData.treatmentName}-${reserveData.treatmentProcedureName} 예약</p>
                                            </div>
                                            <div class="right_box">
                                                <p>상태</p>
                                                <p>${fn_setReserveStatus(reserveData.status)}</p>
                                            </div>
                                        </div>`
                        }
                    })
                    presentWrapper.append(innerHtml)
                } else {
                    const innerHtml = '<p class="title">예약 내역</p>' +
                                              '<div style="padding: 15px 20px; margin-top: 10px;"><span>예약내역이 없습니다.</span></div>';
                    presentWrapper.append(innerHtml);
                    presentWrapper.hide();
                }
            } else if (data.msgCode == '-1') {
                modalEvent.warning("조회 오류", data.msgDesc);
            } else {
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            }
        },
        error: function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){

        },
        complete:function(){

        }
    });
}
/****************************************************************************
 * 지난 예약 내역 조회
 ****************************************************************************/
function fn_selectListReservationHistoryJson(){
    let formData = new FormData();
    formData.append('searchDate',searchDate)
    $.ajax({
        url: encodeURI('/mobilereservation/selectListReservationHistory.do'),
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        type: 'POST',
        async: false,
        success: function(data){
            $('.past_reservation .reservation_box').remove();
            const pastWrapper = $('.past_reservation');
            if('0'==data.msgCode){
                if(0<data.totalCount){
                    data.rows.forEach((reserveData,index)=>{
                        const innerHtml =`<div class="reservation_box past_promise" onclick=fn_selectPastReservePopup(${JSON.stringify(reserveData)})><!-- past_promise : 진료끝 box -->
                                            <div class="left_box">
                                                <p class="date">${reserveData.reserveDate}</p>
                                                <p>${reserveData.reserveTime} ${reserveData.treatmentName}-${reserveData.treatmentProcedureName} 예약</p>
                                            </div>
                                            <div class="right_box">
                                                <p>${fn_setReserveStatus(reserveData.status)}</p>
                                            </div>
                                        </div>`
                        pastWrapper.append(innerHtml)
                    })

                }else{
                    const innerHtml = '<div class="reservation_box" style="border: none; padding: 15px 20px; margin-top: 10px;"><span>조회결과가 없습니다.</span></div>';
                    pastWrapper.append(innerHtml)
                }
            } else if (data.msgCode=='-1'){
                modalEvent.warning("조회 오류", data.msgDesc);
            }
            else{
                modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            }
        },
        error : function(xhr, status, error) {
            modalEvent.danger("조회 오류", "조회 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
        },
        beforeSend:function(){

        },
        complete:function(){

        }
    });
}
/****************************************************************************
 * 접수 대기 상세 팝업
 ****************************************************************************/
function fn_selectReservePendingPopup(param){
    selectReservePendingModal.popup(function (obj, param) {
        fn_selectListReservationJson();
    }, param);
}

/****************************************************************************
 * 진료끝 상세 팝업
 ****************************************************************************/
function fn_selectPastReservePopup(param){
    selectPastReserveModal.popup(function (obj, param) {
        fn_selectListReservationJson();
    }, param);
}

/****************************************************************************
 * 접수 완료 상세 팝업
 ****************************************************************************/
function fn_selectPromiseCompletedPopup(param){
    selectPromiseCompletedModal.popup(function (obj, param) {
        fn_selectListReservationJson();
    }, param);
}
/****************************************************************************
 * 예약상태 표시
 ****************************************************************************/
function fn_setReserveStatus(param){
    switch (param) {
        case 'T':
            return '예약';
        case 'TN':
            return '예약취소';
        case 'R':
            return '접수';
        case 'RN':
            return '접수취소';
        case 'G':
            return '진료중';
        case 'Y':
            return '진료끝';
        default:
            return '알 수 없는 상태';  // 예상치 못한 코드에 대한 처리
    }
}

/****************************************************************************
 * 검색하기
 ****************************************************************************/
function fn_ReservationHistorySearch(param){
    fn_selectListReservationHistoryJson();
}

/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit(){
    if($('.notify_box').hasClass('open')){
        $('main').addClass('short');
    }else{
        $('main').addClass('short2');
    }

    if(isMobile.Android()){
        // 안드로이드
        let value;
        let year;
        let month;

        $("#mmDatepicker").click(function(e){
            e.preventDefault();
            value = prompt("monthPicker");

            if(null === value || !value){
                // 오늘
                let toDate = new Date();
                year  = toDate.getFullYear();
                month = toDate.getMonth() + 1;
                if(month < 10) month = "0" + month;

            }else{
                let valueArr = value.split("-");
                year  = valueArr[0];
                month = valueArr[1];
                if(month < 10) month = "0" + month;
            }

            searchDate = year+"-"+month;
            $(this).val(searchDate);

            fn_ReservationHistorySearch();
        });

    }else if(isMobile.IOS()){
        // IOS
        let value; /**/
        let year;
        let month;

        $("#mmDatepicker").change(function(){
            value = $(this).val();
            if(!value){
                // 오늘
                let toDate = new Date();
                year  = toDate.getFullYear();
                month = toDate.getMonth() + 1;
                if(month < 10) month = "0" + month;
            }else{
                let valueArr = $(this).val().split("-");
                year  = valueArr[0];
                month = valueArr[1];
                if(month < 10) month = "0" + month;
            }

            searchDate = year+"-"+month;
            $(this).val(searchDate);

            fn_ReservationHistorySearch();
        });
    }

    if(searchDate){
        $("#mmDatepicker").val(searchDate)
    }else{
        // 오늘
        let toDate = new Date();
        let year  = toDate.getFullYear();
        let month = toDate.getMonth() + 1;
        if(month < 10) month = "0" + month;
        $("#mmDatepicker").val(year+'-'+month);

        searchDate = year+'-'+month;
    }

    //예약내역조회
    fn_selectListReservationJson();
    //지난예약조회
    fn_ReservationHistorySearch();
}

/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent(){

}

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

    // 페이지 event
    fn_pageEvent();
});