<!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="theme-color" content="#000000"/>
    <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}">
</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">
                <input id="date" type="text">
                <div th:class="button" onclick="searchStat()">조회</div>
            </div>
            <div class="chart-box">
                <div id="chart"></div>
            </div>
            <div class="list">
                <div>
                    <div>기준일자</div>
                    <div>방문자수</div>
                </div>
                <div class="list-content"></div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="/include/footer.html"></th:block>
</body>
</html>

<script>
    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) {
        let period = Number(getDateDiff(toDt, fromDt));
        let type = "";
        let typeStr = "일";
        let fromDate = dateFormatter(fromDt);
        let 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);
            }
        }

        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>`))
        })
        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]));
    }
</script>