<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
    <meta name="description" content="포항시 교통정보센터입니다"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>포항시 교통정보센터</title>
    <th:block th:include="include/head.html"></th:block>
    <th:block th:include="include/daterangepicker.html"></th:block>
    <th:block th:include="include/highchart.html"></th:block>
    <link rel="stylesheet" th:href="@{/css/conn-statistics.css}">
    <script th:src="@{/js/export/xlsx-0.18.12.min.js}"></script>
</head>
<body id="body">
<th:block th:include="include/admin-header.html"></th:block>
<div class="statWrap">
    <div class="container">
        <h2 class="admin-header">접속자 통계</h2>
        <div class="admin-content">
            <div class="title">
                <select name="type" title="구분" class="type">
                    <option value="date" selected>일별</option>
                    <option value="6">최근 6개월</option>
                    <option value="_month">월별</option>
                    <option value="_year">년별</option>
                </select>
                <select name="year_from" title="연별 시작년" class="_year from_year" onchange="setMonthOption(this, 'from')">
                    <option th:each="year : ${yearList}" th:unless="${year.rate} == ${#calendars.format(#calendars.createNow(), 'yyyy')}" th:value="${year.rate}" th:title="${year.rate + '년'}" th:text="${year.rate + '년'}"></option>
                    <option th:each="year : ${yearList}" th:if="${year.rate} == ${#calendars.format(#calendars.createNow(), 'yyyy')}"
                            th:value="${year.rate}" th:title="${year.rate + '년'}" th:text="${year.rate + '년'}" selected></option>
                </select>
                <select name="month" title="월별 시작월" class="_month from_month">
                    <option th:each="num : ${#numbers.sequence(1, month)}" th:unless="${month} == ${num}" th:value="${num}" th:title="${num + '월'}" th:text="${num + '월'}"></option>
                    <option th:each="num : ${#numbers.sequence(1, month)}" th:if="${month} == ${num}" selected th:value="${num}" th:title="${num + '월'}" th:text="${num + '월'}"></option>
                </select>
                <div class="wave">&nbsp;~&nbsp;</div>
                <select name="year_to" title="연별 종료년" class="_year to_year" onchange="setMonthOption(this, 'to')">
                    <option th:each="year : ${yearList}" th:unless="${year.rate} == ${#calendars.format(#calendars.createNow(), 'yyyy')}" th:value="${year.rate}" th:title="${year.rate + '년'}" th:text="${year.rate + '년'}"></option>
                    <option th:each="year : ${yearList}" th:if="${year.rate} == ${#calendars.format(#calendars.createNow(), 'yyyy')}"
                            th:value="${year.rate}" th:title="${year.rate + '년'}" th:text="${year.rate + '년'}" selected></option>
                </select>
                <select name="month" title="월별 종료월" class="_month to_month">
                    <option th:each="num : ${#numbers.sequence(1, month)}" th:unless="${month} == ${num}" th:value="${num}" th:title="${num + '월'}" th:text="${num + '월'}"></option>
                    <option th:each="num : ${#numbers.sequence(1, month)}" th:if="${month} == ${num}" selected th:value="${num}" th:title="${num + '월'}" th:text="${num + '월'}"></option>
                </select>
                <input id="date" class="date on" type="text" placeholder="날짜를 선택해주세요.">
                <label for="date" style="display: none"></label>
                <div th:class="button" onclick="searchStat()">조회</div>
                <div th:class="excel-button" th:onclick="download()">
                    <img width="25" height="25" th:src="@{/images/icon/excel.png}" alt="엑셀 다운로드" style="margin-right: 5px;">저장
                </div>
            </div>
            <div class="chart-box">
                <div id="chart"></div>
            </div>
            <div class="list">
                <table id="table">
                    <thead>
                        <tr>
                            <th>기준일자</th>
                            <th>방문자수</th>
                        </tr>
                    </thead>
                    <tbody class="list-content">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include/footer.html"></th:block>
</body>
</html>

<script th:inline="javascript">

    const yearList = [[${yearList}]];

    const $date = $('#date');
    const $list = $('.list-content');
    let startDate = new Date(new Date().setDate(new Date().getDate() - 9));
    let endDate = new Date();
    const date = $date.daterangepicker({
        timePicker: false,
        startDate: startDate,
        endDate: endDate,
        maxDate : new Date(),
        locale: {
            format: 'YYYY-MM-DD',
            separator: " ~ ",
            applyLabel: "확인",
            cancelLabel : "취소",
            daysOfWeek: ["일", "월", "화", "수", "목", "금", "토"],
            monthNames: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
        },
        disabled : true,
        autoApply: true,
        opens: 'center',
        drops: 'up',
    });

    function getConnStatistics(fromDt, toDt) {
        const $type = $('.type');
        const typeVal = $type.val()
        const $fromYear = $('.from_year');
        const $toYear = $('.to_year');
        const $fromMonth = $('.from_month');
        const $toMonth = $('.to_month');
        let type = "";
        let typeStr = "일";
        let fromDate = null;
        let toDate = null;

        if (typeVal === 'date' || typeVal === '6') {
            let period = Number(getDateDiff(toDt, fromDt));

            fromDate = dateFormatter(fromDt);
            toDate = dateFormatter(toDt);
            if (!isNaN(period)) {
                if (period > 30) {
                    type = 'week';
                    typeStr = "주간";
                }
                if (period > 61) {
                    type = 'month';
                    typeStr = "월";
                    fromDate = fromDate.substring(0, 6);
                    toDate = toDate.substring(0, 6);
                }

                if (period > 365) {
                    type = 'year';
                    typeStr = "년도";
                    fromDate = fromDate.substring(0, 4);
                    toDate = toDate.substring(0, 4);
                }
            }
        }
        else if (typeVal === '_month') {
            let from = $fromMonth.val();
            let to = $toMonth.val();
            if (from < 10) from = "0" + from;
            if (to < 10) to = "0" + to;
            type = 'month';
            typeStr = "월";
            fromDate = $fromYear.val() + from;
            toDate = $toYear.val() + to;
        }
        else if (typeVal === '_year') {
            type = 'year';
            typeStr = "년도";
            fromDate = $fromYear.val();
            toDate = $toYear.val();
        }

        startDate = fromDate;
        endDate = toDate;

        if (fromDate > toDate) {
            return alertError("검색 기간을 확인해주세요.", "접속자 통계 조회", null);
        }
        const param = {
            fromDate : fromDate,
            toDate   : toDate,
            type     : type,
        }
        getDataAsync("/api/common/conn-statistics", "POST", param, typeStr, (jsonData)=>{
            $list.empty();
            if (jsonData && jsonData.length > 0) {
                drawChart(jsonData, typeStr);
            }
        }, null);
    }

    getConnStatistics(startDate, endDate);

    function drawChart(jsonData, word) {
        let categories = [];
        let data = [];
        jsonData.forEach((obj)=>{
            categories.push(obj.conn_dt);
            data.push(obj.conn_cnt);
            // $list.append($(`<div><div>${obj.conn_dt}</div><div>${obj.conn_cnt}</div></div>`))
            $list.append($(`<tr><td>${obj.conn_dt}</td><td>${obj.conn_cnt}</td></tr>`))
        });

        Highcharts.chart('chart', {
            chart: {
                type: 'column'
            },
            title: {
                text: '',
            },
            xAxis: {
                categories: categories,
                crosshair: true,
            },
            yAxis: {
                min: 0,
                title: {
                    text: ''
                },
                tickInterval: 5,
            },
            tooltip: {
                valueSuffix: ' 명'
            },
            legend: {
                layout: 'vertical',
                align: 'center',
                verticalAlign: 'top',
                floating: false,
                visible : false,
                borderWidth: 0,
                shadow: false,
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [
                {
                    name: word + '별접속자수',
                    data: data
                },
            ],
            exporting: {
                enabled: false,
            },
            credits: {
                enabled: false
            },
        });
    }

    function getDateDiff(date1, date2) {
        const diffDate = date1.getTime() - date2.getTime();

        return Math.abs(diffDate / (1000 * 60 * 60 * 24)); // 밀리세컨 * 초 * 분 * 시 = 일
    }

    function searchStat() {
        const dateVal = $('#date').val();
        if (isNull(dateVal)) {
            return alert("조회 기간을 입력해주세요.");
        }
        const dateArr = dateVal.split(" ~ ");
        getConnStatistics(new Date(dateArr[0]), new Date(dateArr[1]));
    }

    /**
     * Table to Excel Dawnload
     */
    function download() {
        const table = document.getElementById('table');
        const wb = XLSX.utils.book_new(); //새 페이지 생성
        const newWorksheet = XLSX.utils.table_to_sheet(table); //테이블 TO SHEET
        XLSX.utils.book_append_sheet(wb, newWorksheet, '접속자 통계'); // 새 페이지, SHEET, SHEET 명칭,
        const wbout = XLSX.write(wb, {bookType:'xlsx', type: 'base64'}); // binary 데이터 생성
        const base64Url = 'data:application/octet-stream;base64,' + wbout;
        const excelFileName = '접속자 통계 (' + startDate + '~' + endDate + ').xlsx';
        const link = document.createElement('a');
        link.href = base64Url;
        link.download = excelFileName;
        $('body').append(link);
        link.click();
        link.remove();
    }

    $('.type').on('change', function() {
        const value = $(this).val();
        const wave = $('.wave');
        let arr = ['date', '_month', '_year'];
        for (let className of arr) {
            const el = $('.' + className);
            if (el.hasClass('on')) {
                el.removeClass('on');
            }
        }
        wave.removeClass('on');

        if (value === '6') {
            const sixMonthAgo = new Date(new Date().setMonth(new Date().getMonth() - 5));
            const beforeDate = getDateFormat(sixMonthAgo).substr(0, 8) + '01';
            const afterDate = getDateFormat(new Date());
            $date.data('daterangepicker').setStartDate(beforeDate);
            $date.data('daterangepicker').setEndDate(afterDate);
            $date.addClass('on');
            $date.attr('readonly', true);
        }
        else {

            const year = $('._year');

            let dateVal;
            switch (value) {
                case 'date' :
                    const start = getDateFormat(new Date(new Date().setDate(new Date().getDate() - 9)));
                    const end = getDateFormat(new Date());
                    $date.data('daterangepicker').setStartDate(start);
                    $date.data('daterangepicker').setEndDate(end);
                    $date.attr('readonly', false);
                    //dateVal =  start + ' ~ ' + end;
                    break;
                case '_month' :
                    year.addClass('on');
                    wave.addClass('on');
                    year.val(new Date().getFullYear());
                    dateVal = new Date().getMonth() + 1;
                    break;
                case '_year' :
                    dateVal = new Date().getFullYear();
                    wave.addClass('on');
                    break;
            }

            const selected = $('.' + value);
            selected.addClass('on');
            if (dateVal) {
                selected.val(dateVal);
            }
        }
    });

   function setMonthOption(el, type) {
       const yearVal = $(el).val();
       const now = new Date();
       let monthLimit = 12;
       if (yearVal === now.getFullYear().toString()) {
           monthLimit = now.getMonth() + 1;
       }
       let str = '';
       const target = $('.' + type + '_month');
       const selected = target.val();
       for (let ii = 1; ii <= monthLimit; ii++) {
           str += `<option value="${ii}" title="${ii}월" >${ii}월</option>`;
       }
       target.empty().html(str);
       target.val(selected);
   }

    function getDateFormat(date) {
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        if (month < 10) month = '0' + month;
        if (day < 10) day = '0' + day;
        return year + '-' + month + '-' + day;
    }
</script>