<%@ 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/functions" prefix="fn" %>
<%@ page session="false" %>
<html>
<head>
    <title>장애이력 조회</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.14.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/css/style.css">
    <script src="/js/common/common-all.js"></script>
    <script src="/js/ui.js"></script>
</head>
<body>
<div class="Popup-contents">
    <h1 class="h1">장애이력 조회</h1>
    <div class="formArea searchBox">
        <div class="formItem">
            <label class="label required">지역명</label>
            <div class="form">
                <div class="selectBox" style="width: 120px;">
                    <select id="region_cd">
                        <option>전체</option>
                        <c:forEach items="${region_list}" var="obj">
                            <option value="${obj.regionId}">${obj.regionName}</option>
                        </c:forEach>
                    </select>
                </div>
            </div>
        </div>
        <div class="formItem">
            <label class="label required">교차로 검색</label>
            <div class="form">
                <input type="text" id="int_no">
            </div>
        </div>
        <div class="formItem">
            <label class="label">검색기간</label>
            <div class="form">
                <div class="inpBox datePicker">
                    <input class="fromDt" type="text" id="datepicker">
                </div>
                <span>~</span>
                <div class="inpBox datePicker">
                    <input class="toDt" type="text" id="datepicker2">
                </div>
            </div>
            <div class="radioTy1">
                <input type="radio" name="error-type" id="error-stat" checked onchange="toggleTable('stat')">
                <label for="error-stat">장애 이력</label>
            </div>
            <div class="radioTy1">
                <input type="radio" name="error-type" id="error-cnt" onchange="toggleTable('cnt')">
                <label for="error-cnt">장애 발생 건수</label>
            </div>
        </div>
        <span class="searchBtn"><button class="btn medium primary" onclick="searchErrorStatistics()"><i class="ic ic_search_W"></i>검색</button></span>
    </div>

    <!-- gridArea -->
    <div class="total"><span></span></div>
    <div class="gridArea error-container">
        <table class="tableBody error-stat-table on">
            <caption>테이블 내용 요약</caption>
            <colgroup>
                <col width="15%">
                <col width="40%">
                <col width="25%">
                <col width="14%">
                <col width="6%">
            </colgroup>
            <thead>
                <tr>
                    <th>지역명</th>
                    <th>교차로명</th>
                    <th>이벤트 발생시각</th>
                    <th>상태</th>
                    <th>서버 ID</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <table class="tableBody error-cnt-table">
            <caption>테이블 내용 요약</caption>
            <colgroup>
                <col width="22%">
                <col width="50%">
                <col width="14%">
                <col width="14%">
            </colgroup>
            <thead>
                <tr>
                    <th>지역명</th>
                    <th>교차로명</th>
                    <th>이벤트 발생 건수</th>
                    <th>상태</th>
                </tr>
            </thead>
            <!--//tableHead end -->
            <tbody>
            </tbody>
        </table>
        <div class="showLoading"><img src="/css/themes/classic/throbber.gif" alt="로딩 이미지"></div>
    </div>
    <!--//gridArea end -->
    <div class="error-stat pagination between on">
        <div class="arrowBtn disabled">
            <button type="button" class="backEnd" disabled="" onclick="backEndStat('stat')">맨 뒤로</button>
            <button type="button" class="back" disabled="" onclick="backStat('stat')">뒤로</button>
        </div>
        <div class="pageGroup">
            <a href="#" class="act">1</a>
        </div>
        <div class="arrowBtn">
            <button type="button" class="next" disabled="" onclick="nextStat('stat')">앞으로</button>
            <button type="button" class="nextEnd" disabled="" onclick="nextEndStat('stat')">맨 앞으로</button>
        </div>
    </div>
    <div class="error-cnt pagination between">
        <div class="arrowBtn disabled">
            <button type="button" class="backEnd" disabled="" onclick="backEndStat('cnt')">맨 뒤로</button>
            <button type="button" class="back" disabled="" onclick="backStat('cnt')">뒤로</button>
        </div>
        <div class="pageGroup">
            <a href="#" class="act">1</a>
        </div>
        <div class="arrowBtn">
            <button type="button" class="next" disabled="" onclick="nextStat('cnt')">앞으로</button>
            <button type="button" class="nextEnd" disabled="" onclick="nextEndStat('cnt')">맨 앞으로</button>
        </div>
    </div>
</div>
</body>
</html>
<script>
    const _errorStatMap = new Map();
    const _errorCntMap = new Map();
    const yd = new Date(new Date().setDate(new Date().getDate() - 1));
    const yDt = yd.getFullYear() + '-'
                + String(yd.getMonth() + 1).padStart(2, '0') + '-'
                + String(yd.getDate()).padStart(2, '0');
    const $from = $('.fromDt');
    const $to = $('.toDt');
    $from.val(yDt);
    $to.val(yDt);

    function searchErrorStatistics() {
        const isStat = $('#error-stat').is(':checked');
        const url = isStat ? 'getNodeStatistics.do' : 'getNodeStatusCntStat.do';
        const fromDt = $from.val();
        const toDt = $to.val();
        let regionId = $('#region_cd').val()
        let nodeId = $('#int_no').val();

        if (!fromDt || !toDt) {
            return alert('검색 기간을 선택 해주세요.');
        }

        if (fromDt > toDt) {
            return alert('검색 시작일이 종료일보다 클 수 없습니다.');
        }

        const loading = $('.showLoading');
        const param = { fromDt : fromDt, toDt : toDt, regionId : regionId, nodeId : nodeId };
        loading.css('display', 'flex');
        requestService(url, param, (res)=>{
            isStat ? errorStatPaging(res) : errorCntPaging(res);
            loading.css('display', 'none');
            if (res && res.length) {
                $('.total span').text(res.length.toLocaleString());
            }
        }, true, null);
    }


    function errorStatPaging(res) {
        _errorStatMap.clear();
        const rowsPerPage = 10;

        if (res && res.length) {
            let str = '';
            res.forEach((obj, idx)=>{
                if (idx % rowsPerPage === 0 && idx > 0) {
                    let selPage = idx / rowsPerPage;
                    _errorStatMap.set(selPage, str);
                    str = '';
                }

                str += `<tr>
                            <td>\${obj.regionNm}</td>
                            <td>[\${obj.nodeid}] \${obj.name}</td>
                            <td>\${obj.eventDt}</td>
                            <td>\${obj.status}</td>
                            <td>\${obj.serverid}</td>
                        </tr>`;
            });
            if (str) {
                _errorStatMap.set(Number(_errorStatMap.size) + 1, str);
            }

            let pageSize = _errorStatMap.size;

            const isNext = pageSize > 10;
            if (isNext) {
                pageSize = 10;
            }

            makePageStr(false, isNext, 1, pageSize, 1, 'stat');
        }
        else {
            makePageStr(false, false, 1, 1, 1, 'stat');
        }
    }

    function errorCntPaging(res) {
        _errorCntMap.clear();
        const rowsPerPage = 10;

        if (res && res.length) {
            let str = '';
            res.forEach((obj, idx)=>{
                if (idx % rowsPerPage === 0 && idx > 0) {
                    let selPage = idx / rowsPerPage;
                    _errorCntMap.set(selPage, str);
                    str = '';
                }

                let dataCnt = Number(obj.dataCnt).toLocaleString();
                str += `<tr>
                            <td>\${obj.regionNm}</td>
                            <td>[\${obj.nodeid}] \${obj.name}</td>
                            <td>\${dataCnt}</td>
                            <td>\${obj.status}</td>
                        </tr>`

            });
            if (str) {
                _errorCntMap.set(Number(_errorCntMap.size) + 1, str);
            }

            let pageSize = _errorCntMap.size;

            const isNext = pageSize > 10;
            if (isNext) {
                pageSize = 10;
            }

            makePageStr(false, isNext, 1, pageSize, 1, 'cnt');
        }
        else {
            makePageStr(false, false, 1, 1, 1, 'cnt');
        }
    }


    function backStat(type) {
        if ($('.pagination.on .back').attr('disabled')) return;
        const firstPage = Number($('.pagination.on .pageGroup > a:nth-child(1)').text());
        if (!isNaN(firstPage)) {
            const startPage = firstPage - 10;
            const endPage = firstPage - 1;
            makePageStr(startPage !== 1, true, startPage, endPage, endPage, type);
        }
    }

    function backEndStat(type) {
        if ($('.pagination.on .backEnd').attr('disabled')) return;
        makePageStr(false, true, 1, 10, 1, type);
    }

    function makePageStr(isBefore, isNext, start, end, active, type) {
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        let str = '';
        const $back = $('.pagination.on button.back');
        const $backEnd = $('.pagination.on button.backEnd');
        const $next = $('.pagination.on button.next');
        const $nextEnd = $('.pagination.on button.nextEnd');
        $back.attr('disabled', !isBefore);
        $backEnd.attr('disabled', !isBefore);

        $next.attr('disabled', !isNext);
        $nextEnd.attr('disabled', !isNext);

        for (let ii = start; ii <= end; ii++) {
            str += `<a class="\${active === ii ? 'act' : ''}" onclick="showErrorStatPage(\${ii}, this, '\${type}')">\${ii}</a>`;
        }

        let statistics = map.get(active);
        if (!statistics) {
            statistics = '<tr class="empty-box"><td colspan="'+$('table.on thead th').length+'">표출할 정보가 없습니다.</td></tr>'
        }
        $('table.on tbody').html(statistics);
        $('.pagination.on .pageGroup').html(str);
    }

    function nextStat(type) {
        if ($('.pagination.on .next').attr('disabled')) return;
        const beforePage = $('.pagination.on .pageGroup > a:last-child').text();
        let lastPage = Number(beforePage) + 10;
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        let isNext = map.size > lastPage;
        if (!isNext) {
            lastPage = map.size;
        }
        const firstPage = Number(beforePage) + 1;
        makePageStr(true, isNext, firstPage, lastPage, firstPage, type);
    }

    function nextEndStat(type) {
        if ($('.pagination.on .nextEnd').attr('disabled')) return;
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        // const lastPhage = Math.ceil(map.size / 10);
        const firstPage = getFirstPageOfLastGroup(map.size)
        makePageStr(true, false, firstPage, map.size, map.size, type);
    }

    function getFirstPageOfLastGroup(totalPages, groupSize = 10) {
        return Math.floor((totalPages - 1) / groupSize) * groupSize + 1;
    }

    function showErrorStatPage(page, el, type) {
        const beforePage = $('.pagination.on .act');
        if (page === Number(beforePage.text())) return;
        beforePage.removeClass('act');
        $(el).addClass('act');
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        $('table.on tbody').html(map.get(page));
    }


    function toggleTable(type) {
        $('table.on').removeClass('on');
        $('.pagination.on').removeClass('on');
        $('.error-' + type + '-table').addClass('on');
        $('.error-' + type).addClass('on');
        const map = type === 'stat' ? _errorStatMap : _errorCntMap;
        const tot = $('.total span');
        tot.text(map.size ? map.size.toLocaleString() : '');
    }

</script>