<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<div class="container">
    <div class="subHeader">
        <h1 class="logo">안동시 교통정보센터</h1>
        <div class="pageLocation">
            <%@ include file="/WEB-INF/jsp/egovframework/include/adminSubMenu.jsp" %>
        </div>
    </div>
    <div class="subContent">
        <%@ include file="/WEB-INF/jsp/egovframework/include/adminMenu.jsp" %>
        <div class="pageTitle">
            <h2>접속통계</h2>
            <p>안동시 첨단교통센터 <span>관리자</span> 정보입니다.</p>
        </div>
        <div class="adminWrap">
            <div class="src-wrap">
                <span class="label">검색일</span>
                <select id="year" name="year" class="statis-search-select" onchange="selectDateChanger(true)">
                    <c:forEach begin="${thisYear-5}" end="${thisYear}" varStatus="status">
                        <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisYear}">selected</c:if>>
                                ${status.current}년
                        </option>
                    </c:forEach>
                </select>
                <select id="month" name="month" class="statis-search-select" onchange="selectDateChanger(false)">
                    <c:forEach begin="1" end="${thisMonth}" varStatus="status">
                        <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisMonth}">selected</c:if>>
                            <fmt:formatNumber pattern="00" value="${status.current}"/>월
                        </option>
                    </c:forEach>
                </select>
                <select id="date" name="date" class="statis-search-select">
                    <c:forEach begin="1" end="${thisDate}" varStatus="status">
                        <option value="<fmt:formatNumber pattern="00" value="${status.current}"/>" <c:if test="${status.current == thisDate}">selected</c:if>>
                            <fmt:formatNumber pattern="00" value="${status.current}"/>일
                        </option>
                    </c:forEach>
                </select>
                <input type="button" value="조회" class="search-btn" onclick="searchStatusData()">
            </div>
            <div class="admin-tabWrap">
                <ul class="admin-tab">
                    <li><a href="javascript:showStatsList('hhStats', $('.admin-tab').children().eq(0).children().eq(0), true, true)" class="selected">일 통계</a></li>
                    <li><a href="javascript:showStatsList('ddStats', $('.admin-tab').children().eq(1).children().eq(0), true, false)">월 통계</a></li>
                    <li><a href="javascript:showStatsList('mnStats', $('.admin-tab').children().eq(2).children().eq(0), false, false)">년 통계</a></li>
                    <li class="statistics-date">
                        검색 날짜 : ${thisYear}년 <fmt:formatNumber pattern="00" value="${thisMonth}"/>월 <fmt:formatNumber pattern="00" value="${thisDate}"/>일
                    </li>
                </ul>
                <div class="road-stats-table">
                    <div class="table-header">
                        <table class="stats-tit-tbl">
                            <caption>접속통계 일 통계표</caption>
                            <tbody class="table-columns">
                            </tbody>
                        </table>
                    </div>
                    <div class="scroller">
                        <table class="stats-tit-tbl">
                            <caption>접속통계 일 통계표</caption>
                            <tbody class="table-data">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="no-data" style="display: none">
                <img width="50" src="/images/main/no_info_icon.png">
                <div style="font-size: 18px;">표출할 데이터가 없습니다.</div>
            </div>
            <div id="loading" style="position: absolute; background-color: rgba(0, 0, 0, 0.2); width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                <img src="/images/ajax_loading.gif">
            </div>
        </div>
    </div>
</div>

<%--<script src="/js/highcharts/highcharts.js"  type="text/javascript"></script>--%>
<%--<script src="/js/highcharts/exporting.js"   type="text/javascript"></script>--%>
<script type="text/javascript">
    const year          = $('#year');
    const month         = $('#month');
    const date          = $('#date');
    const tableColumns  = $('.table-columns');
    const tableData     = $('.table-data');
    const noData        = $('.no-data');
    const searchBtn     = $('.search-btn');
    const statisticDate = $('.statistics-date');

    showStatsList('hhStats', null, true, true);

    function showStatsList(dateType, selectTab, showMonth, showDate) {
        const yearVal   = year.val();
        const monthVal  = month.val();
        const dateVal   = date.val();
        const now       = new Date();
        const nowYear   = now.getFullYear();
        let startIdx    = 0;
        let lastMonth   = 12;
        let lastDate    = new Date(yearVal, monthVal, 0).getDate();
        let lastHours   = 23;
        let range       = null;
        let searchDate  = yearVal + monthVal + dateVal;
        let word        = '시';

        if (Number(nowYear) === Number(yearVal)) {
            lastMonth = now.getMonth() + 1;
            if (Number(monthVal) === Number(now.getMonth()+1)) {
                lastDate = now.getDate();
                if (Number(dateVal) === Number(lastDate)) {
                    lastHours = now.getHours();
                }
            }
        }

        range = lastHours;

        if (selectTab) {
            const selectedTab = $('.admin-tab > li > a[class="selected"]');
            selectedTab.removeClass('selected');
            selectTab.addClass('selected');

            month.hide();
            date.hide();

            searchDate = yearVal;
            word       = '월';
            range      = lastMonth;
            startIdx   = 1;

            if (showMonth) {
                month.show();
                searchDate += monthVal;
                word        = '일';
                range       = lastDate;
            }

            if (showDate) {
                date.show();
                searchDate += dateVal;
                word        = '시';
                range       = lastHours;
                startIdx    = 0;
            }
        }

        // const color = ["#884a4a", "#50647d", "#8ab047", "#c23d38", "#673ab7", "#00bcd4", "#8bc34a", "#ffeb3b", "#795548", "#ffc107", "#607d8b", "#009ea5"];
        $.ajax({
            type:"POST",
            url:'/admin/getStatsList.do',
            data: {
                dateType: dateType,
                date: searchDate
            },
            success: function(jsonData) {
                if (jsonData && jsonData.length > 0) {
                    if (noData.css('display') === 'flex') {
                        noData.hide();
                    }

                    let tableColumnStr = '<tr><th class="stats-tit">웹페이지/' + word + '</th></tr>';
                    let tableDataStr   = ' <tr><th class="stats-tit">계</th>';

                    for (let ii = startIdx; ii <= range; ii++) {
                        let rangeVal = Number(ii) < 10 ? '0' + ii : ii;
                        tableDataStr += '<th class="stats-tit">' + rangeVal + '</th>';
                    }

                    tableDataStr += '</tr>';

                    if (!showDate) range--;

                    jsonData.forEach((obj)=>{
                        tableColumnStr += '<tr><th>' + obj.title + '</th></tr>';
                        tableDataStr   += '<tr><td>' + obj.total_connCnt + '</td>';
                        if (obj.statsInArr && obj.statsInArr.length > 0) {
                            obj.statsInArr.forEach((stat, idx)=>{
                                if (Number(idx) <= range) {
                                    tableDataStr += '<td>' + stat + '</td>';
                                }
                            })
                        }
                        tableDataStr += '</tr>';
                    })

                    tableColumns.empty().html(tableColumnStr);
                    tableData.empty().html(tableDataStr);
                }
                else {
                    noData.show();
                }
            }, beforeSend: function () {
                $('#loading').show();
            },
            complete: function () {
                $('#loading').hide();
                statisticDate.text('검색 날짜 : '+getResultText(searchDate));
            },
            error: function(e) {
                tableColumns.empty();
                tableData.empty();
                noData.show();
                alert('접속통계 데이터를 가져오는데 오류가 발생하였습니다.');
            }
        });
    }

    function searchStatusData() {
        $('.admin-tab > li > a[class="selected"]')[0].click();
    }

    /**
     * 년도 날짜에 따른 월, 일 범위값 설정
     * @param(boolean) isSetMonth 일만 변경할건지
     */
    function selectDateChanger(isSetMonth) {
        let now 	 		= new Date();
        let nowDay   		= now.getDate();
        let nowYear  		= now.getFullYear();
        let nowMonth 		= now.getMonth() + 1;
        let dayVal   		= date.val();
        let monthVal 		= month.val();
        let lastDate        = new Date(year.val(), month.val(), 0);
        let minDay 	    	= lastDate.getDate();
        let minMonth        = 12;

        if (nowYear.toString() === year.val()) {
            minMonth = nowMonth;
            if (nowMonth === Number(monthVal)) minDay = nowDay;
        }
        if (isSetMonth) {
            setSelectOption(minMonth, monthVal, month, '월');
        }
        setSelectOption(minDay, dayVal, date, '일');
    }


    function setSelectOption(min, value, target, word) {
        let option = getOption(min, word);
        target.html(option);
        if (min < Number(value)) {
            target.val('01');
        }
        else {
            target.val(value);
        }
    }

    function getOption(rate, word) {
        let option = ''
        for ( let ii = 1; ii <= rate; ii++) {
            let value = ii;
            if (ii < 10) {
                value = ('0'+ii);
            }
            option += '<option value="'+value+'">'+value + word + '</option>';
        }
        return option;
    }

    function getResultText(text) {
        if (!text) return text;

        let formatText = text.substring(0, 4) + '년';
        if (text.length > 4) {
            formatText += ' ' + text.substring(4, 6) + '월';
            if(text.length > 6) {
                formatText += ' ' + text.substring(6, 8) + '일';
            }
        }
        return formatText;
    }
</script>
