(function() {
    let searchDate = new Date();
    $(document).ready(function () {
        // 초기화
        updateDates(searchDate);
        //Datepicker 설정
        $(document).on("click",".btn-date",function(){
            $('#datepicker').datepicker({
                format: "yyyy-mm-dd",
                todayBtn: true,
                language: "ko",
                autoclose: true,
                todayHighlight: true,

            }).on('changeDate', function() {
                let date = $(this).datepicker('getFormattedDate');
                updateDates(new Date(date));
                searchDate = new Date(date);
                $(".datepicker").hide();
            });
        });
    });

    function formatDate(date) {
        const options = { month: 'long', day: 'numeric', weekday: 'long' };
        let formattedDate = date.toLocaleDateString('ko-KR', options);

        // "요일" 부분을 제거하고 "월 일(요일)" 형식으로 변경
        formattedDate = formattedDate.replace(/요일/, '').replace(/ (\S+)$/, '($1)');
        return formattedDate;
    }

    function valueDate(date) {
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

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

        const result = `${year}${month}${day}`;

        return result;
    }

    function updateDates(searchDate) {
        $(".date-itm").each(function () {
            $(this).removeClass('on');
        });

        const yesterday = new Date(searchDate);
        yesterday.setDate(yesterday.getDate() - 1);
        const tomorrow = new Date(searchDate);
        tomorrow.setDate(tomorrow.getDate() + 1);

        const date1 = document.getElementById('date1');
        const date2 = document.getElementById('date2');
        const date3 = document.getElementById('date3');

        date1.textContent = formatDate(yesterday);
        $(date1).attr("data-value", valueDate(yesterday));

        date2.textContent = formatDate(searchDate);
        $(date2).attr("data-value", valueDate(searchDate));
        $(date2).addClass('on');

        date3.textContent = formatDate(tomorrow);
        $(date3).attr("data-value", valueDate(tomorrow));

        //날짜로 수업시간표 불러오기
        getClassLsnInfo(valueDate(searchDate));
    }

    function convertyyyyMMddToDate(yyyyMMdd) {
        const year = parseInt(yyyyMMdd.toString().substring(0, 4), 10);
        const month = parseInt(yyyyMMdd.toString().substring(4, 6), 10) - 1; // 월은 0부터 시작합니다.
        const day = parseInt(yyyyMMdd.toString().substring(6, 8), 10);

        return new Date(year, month, day);
    }

    $(document).on("click press","#prevDate,#date1",function(){
        searchDate.setDate(searchDate.getDate() - 1);
        updateDates(searchDate);
    });
    $(document).on("click press","#nextDate,#date3",function(){
        searchDate.setDate(searchDate.getDate() + 1);
        updateDates(searchDate);
    });
    // $(document).on("click press",".btn-date",function(){
    //    $("#searchDate").trigger("click");
    // });

    function getClassLsnInfo(date){
        let form = new FormData();
        form.append("searchBgngDate",date);
        form.append("searchEndDate",date);

        fetch('/clsm/clas/adhrnc/selectStdClassLsnInfoByDate.json', {
            method: 'POST',
            cache: 'no-cache',
            processData: false,
            contentType: false,
            body: form // body 부분에 폼데이터 변수를 할당
        })
            .then((response) => response.json())
            .then((data) => {
                if(data.message != null){
                    bootboxAlert({title:'확인',size:'small',message:data.message,
                        callback: function() {
                            if(data.redirectUrl != null){
                                location.href = data.redirectUrl;
                            }
                        }
                    });
                }
                let htmlStr = '';
                if(data.data.result != undefined){
                    data.data.result.forEach((e) => {
                        let trgtGradeCdList = e.trgtGradeCdList.split("|");
                        htmlStr +=
                            `<li class="room-item row">
                                <div class="col-lg-4">
                                    <figure class="room-thumb" style="background-image: url('${e.classImgUrlAddr}')">
                                        <span class="visually-hidden">${e.lsnNm}</span>
                                    </figure>
                                </div>
                                <div class="room-info col-lg-8">
                                    <div class="room-cate">
                                    <span>${e.classCrs}</span>
                                    `;
                        for(k in trgtGradeCdList){
                            htmlStr += `<span>${trgtGradeCdList[k]}</span>`;
                        }
                        htmlStr += `
                                    </div>
                                    <p class="room-tit">
                                        ${e.classTtl}(${e.lsnNm})
                                    </p>
                                    <div class="room-date mb-2">
                                        <span>${e.bgngTm} ~ ${e.endTm} </span>
                                    </div>
                                    <span class="room-tcher">${e.tcherNm} 선생님</span>
                                    <div class="mt-2">
                                        <button type="button" class="btn-room-join border-0" classid="${e.classIdntfNo}"><span>수업방 입장</span></button>
                                    </div>
                                </div>
                            </li>
                        `;
                    })
                }else{
                    htmlStr +=
                        `<li class="room-item row text-center align-items-center" style="min-height: 120px;">
                            <div class="col-lg-12">
                                예정된 수업이 없습니다.
                            </div>
                        </li>
                    `;
                }
                $(".room-list").html(htmlStr);
            })
            .catch((e)=>{
                console.log(e);
            })
    }
    $(document).on("click press",".btn-room-join",function(){
        window.location.href = "/clsm/clas/stdnt/stdntClassMainPge.do?roomId="+$(this).attr("classid")+"&menuSn=92";
    });
}) ()