(function() {
    let today = new Date();
    let fullYear = today.getFullYear();
    $(document).ready(function () {
        //날짜 Datepicker 설정
        $('.input-group.date').datepicker({
            format: "yyyy-mm-dd",
            todayBtn: "linked",
            language: "ko",
            autoclose: true,
            todayHighlight: true
        });

        initClassStatForm();
    });

    function initClassStatForm(){
        //근년도 옵션 세팅
        let optionStr = "";
        for(let i=0;i<3;i++){
            let selected = "";
            let tempYear = new Date().getFullYear() - i;
            if(tempYear == new Date().getFullYear()){
                selected = "selected";
            }
            optionStr += `<option value="${tempYear}" ${selected}>${tempYear}</option>`;
        }
        $(".semester-year").html(optionStr);
        // 검색 기간 세팅
        if($('#searchBgnDt').val() == ''){
            let today = new Date();
            $('#searchBgnDt').val(today.getFullYear() + '-01-01');
        }
        if($('#searchEndDt').val() == ''){
            let today = new Date();
            $('#searchEndDt').val(today.getFullYear() + '-12-31');
        }
        setTimeout(()=>{
            getSemesterClassStat(fullYear+"0101",fullYear+"1231");//학기별 수업통계
            getSchlClsfClassStat(fullYear+"0101",fullYear+"1231");//학교급별 수업통계
        },500);
    }

    //학기별 연도 변경시
    $(document).on("change",".semester-year",function(){
        getSemesterClassStat($(this).val()+"0101",$(this).val()+"1231");
    });

    //학교급별 수업 검색 click시
    $(document).on("click press","#btnSearchClassStat",function(){
        if($('#searchBgnDt').val() === ''){
            bootboxAlert({ title: '확인', message: "검색 시작일을 입력해주세요." , size: 'small' });
            return false;
        }
        if($('#searchEndDt').val() === ''){
            bootboxAlert({ title: '확인', message: "검색 종료일을 입력해주세요." , size: 'small' });
            return false;
        }
        getSchlClsfClassStat($('#searchBgnDt').val().replaceAll("-",""),$('#searchEndDt').val().replaceAll("-",""));
    });

    //학기별 수업통계
    function getSemesterClassStat(bgngDate,endDate){
        $("#semester-chart").html(`<div class="spinnerBox"><div class="spinner-border"></div></div>`);

        let form = new FormData();
        form.append("searchBgnDt",bgngDate);
        form.append("searchEndDt",endDate);

        fetch('/scnt/schl/semesterClassStats.json', {
            method: 'POST',
            cache: 'no-cache',
            processData: false,
            contentType: false,
            body: form // body 부분에 폼데이터 변수를 할당
        })
        .then((response) => response.json())
        .then((data) => {
            if(data.success){
                let list = data.data.resultList;
                let categories = [];
                let series = [];
                let classCnt = [];
                let adhrncCnt = [];
                for(const i in list){
                    categories.push(list[i].semesterCdNm);
                    classCnt.push(list[i].cnt)
                    adhrncCnt.push(list[i].adhrncCnt)
                }
                let tempJson1 = {
                    "name": '수업 수',
                    "data":classCnt
                }
                let tempJson2 = {
                    "name": '학생 수',
                    "data": adhrncCnt
                }
                series.push(tempJson1);
                series.push(tempJson2);
                //categories.push(srvyStats.srvyQstnList[i].qstnTtl);
                drawChartArea("bar","semester-chart","학기별 수업 통계",categories,series);
            }
        })
        .catch((e)=>{
            console.log(e);
        })
    }

    //학교급별 수업통계
    function getSchlClsfClassStat(bgngDate,endDate){

        $("#grade-chart").html(`<div class="spinnerBox"><div class="spinner-border"></div></div>`);

        let form = new FormData();
        form.append("searchBgnDt",bgngDate);
        form.append("searchEndDt",endDate);


        fetch('/scnt/schl/schlClsfClassStats.json', {
            method: 'POST',
            cache: 'no-cache',
            processData: false,
            contentType: false,
            body: form // body 부분에 폼데이터 변수를 할당
        })
        .then((response) => response.json())
        .then((data) => {
            if(data.success){
                let list = data.data.resultList;
                let categories = [];
                let series = [];
                let classCnt = [];
                let adhrncCnt = [];
                for(const i in list){
                    categories.push(list[i].gradeCdNm);
                    classCnt.push(list[i].cnt)
                    adhrncCnt.push(list[i].adhrncCnt)
                }
                let tempJson1 = {
                    "name": '수업 수',
                    "data":classCnt
                }
                let tempJson2 = {
                    "name": '학생 수',
                    "data": adhrncCnt
                }
                series.push(tempJson1);
                series.push(tempJson2);
                //categories.push(srvyStats.srvyQstnList[i].qstnTtl);
                drawChartArea("column","grade-chart","학교급별 수업 통계",categories,series);
            }
        })
        .catch((e)=>{
            console.log(e);
        })
    }

    /**
     * 차트 그리기
     * @param type
     * @param targetId
     * @param title
     * @param categories
     * @param series
     * @returns
     */
    function drawChartArea(type="pie",targetId,title,categories,series) {
        const el = document.getElementById(targetId);
        //20240104 xss 보안약점 조치
        el.textContent='';
        var chartWidth = el.getBoundingClientRect().width;
        let data = {
            categories,
            series,
        }
        const theme = {
            series: {
                barWidth: 10,
                areaOpacity: 1,
                colors: ['#1F5AA0', '#ffc107'],
                hover: {
                    color: '#dc3545',
                    borderWidth: 1,
                    shadowColor: 'rgba(0, 0, 0, 0.7)',
                    shadowOffsetX: 4,
                    shadowOffsetY: 4,
                    shadowBlur: 6,
                    groupedRect: {
                        color: '#F0DCBC',
                        opacity: 0.5,
                    },
                },
                select: {
                    color: '#6610f2',
                    borderWidth: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.7)',
                    shadowOffsetX: 4,
                    shadowOffsetY: 4,
                    shadowBlur: 6,
                    groupedRect: {
                        color: '#74521A',
                        opacity: 0.2,
                    },
                    restSeries: {
                        areaOpacity: 0.5,
                    },
                    areaOpacity: 0.8,
                },
            },
        };

        const options = {
            legend:{visible:false},
            lang:{noData: '데이터가 없습니다.'},
            series: {
                selectable: true,
                dataLabels: {
                    visible: true,
                    pieSeriesName: {
                        visible: true,
                    }
                }
            },
            exportMenu: {
                filename: title
            },
            theme,

        };
        let chart;
        switch (type){
            case "pie":
                chart = toastui.Chart.pieChart({el, data, options});
                break;
            case "bar":
                chart = toastui.Chart.barChart({ el, data, options });
                break;
            case "column":
                chart = toastui.Chart.columnChart({ el, data, options });
                break;
        }

    }
}) ()