<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
    <title>대시보드</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/css/dashBoard.css">
    <link rel="stylesheet" href="/css/header.css">
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/highcharts-more.js"></script>
    <script src="https://code.highcharts.com/modules/solid-gauge.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>
    <script type="text/javascript" src="/js/dashBoard.js"></script>
    <script type="text/javascript" src="/js/header.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<%--    <link rel="stylesheet" href="https://code.jquery.com/ui/1.14.0/themes/base/jquery-ui.css">--%>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.14.0/themes/ui-darkness/jquery-ui.css">
    <script src="https://code.jquery.com/ui/1.14.0/jquery-ui.js"></script>
<style>
   html, body {
       height: auto;
   }
</style>
</head>
<body>
    <jsp:include page="header.jsp"></jsp:include>
    <div class="container on">
        <div class="date-box">
            <div style="font-size: 20px; font-weight: bold; margin-left: 10px; user-select: none;">
                통합 대시보드 <i onclick="rotateContainer()" class="fa fa-refresh" aria-hidden="true" style="cursor: pointer"></i>
            </div>
            <div class="date-change" onclick="dropDown()">
                Last 5 minutes
                <span class="drop"></span>
            </div>
            <div class="drop-box">
                <div style="padding:5px 10px; background-color: #111217;">표출정보 설정</div>
                <div class="drop-content">
                    <div>
                        <div>
                            <div>From</div>
                            <div style="display: flex;">
                                <input type="text" class="from-dt" onkeyup="checkValidation()" value="now-5m">
                                <div class="date-img">
                                    <input type="text" class="from-picker" onchange="changeValue(this)" style="display: none">
                                </div>
                            </div>
                            <div class="from-dt-text"></div>
                        </div>
                        <div>
                            <div>To</div>
                            <div style="display: flex;">
                                <input type="text" class="to-dt" onkeyup="checkValidation()" value="now">
    <%--                            <div class="date-img"></div>--%>
                                <div class="date-img">
                                    <input type="text" class="to-picker" onchange="changeValue(this)" style="display: none">
                                </div>
                            </div>
                            <div class="to-dt-text"></div>
                        </div>
                        <div class="apply-btn" onclick="applyDashboard()">
                            <span>적용</span>
                        </div>
                    </div>
                    <div>
                        <div class="range-text-box">
                            <input type="text" id="range-search" placeholder="Search quick ranges" onkeyup="rangeSearch()">
                        </div>
                        <div class="range-select">
                            <div class="on">Last 5 minutes</div>
                            <div>Last 15 minutes</div>
                            <div>Last 30 minutes</div>
                            <div>Last 1 hour</div>
                            <div>Last 3 hours</div>
                            <div>Last 6 hours</div>
                            <div>Last 12 hours</div>
                            <div>Last 24 hours</div>
                            <div>Last 2 days</div>
                            <div>Last 7 days</div>
                            <div>Last 30 days</div>
                            <div>Last 90 days</div>
                            <div>Last 6 months</div>
                            <div>Last 1 year</div>
                            <div>Last 2 years</div>
                            <div>Last 5 years</div>
                            <div>Yesterday</div>
                            <div>Day before yesterday</div>
                            <div>this day last week</div>
                            <div>previous week</div>
                            <div>previous month</div>
                            <div>previous fiscal quarter</div>
                            <div>previous year</div>
                            <div>previous fiscal year</div>
                            <div>Today</div>
                            <div>Today so far</div>
                            <div>This week</div>
                            <div>This week so far</div>
                            <div>This month</div>
                            <div>This month so far</div>
                            <div>This year</div>
                            <div>This year so far</div>
                            <div>This fiscal quarter so far</div>
                            <div>This fiscal quarter</div>
                            <div>This fiscal year so far</div>
                            <div>This fiscal year</div>
                        </div>
                    </div>
                </div>
            </div>
            <select name="refresh" id="refresh" onchange="monitoringChange()" title="갱신 주기 설정">
                <option value="Off">Off</option>
                <option value="Auto">Auto</option>
                <option value="5s" selected>5s</option>
                <option value="10s">10s</option>
                <option value="30s">30s</option>
                <option value="1m">1m</option>
                <option value="5m">5m</option>
                <option value="15m">15m</option>
                <option value="30m">30m</option>
                <option value="1h">1h</option>
                <option value="2h">2h</option>
                <option value="1d">1d</option>
            </select>
        </div>
        <div style="width: 100%; height: 860px; display: flex; align-items: center; justify-content: center;">
            <iframe id="iframe" src="https://tsihub.koroad.or.kr/grafana/d/a2bdde78-ca43-42fb-ad6b-5fed5efe7fe0/34756fc9-4cb9-5aaa-ba23-d1a4d5529448?orgId=1&refresh=5s&from=now-5m&to=now&kiosk" width="100%" height="100%"
            style="border: none"></iframe>
        </div>
        <div class="event-box" style="top: 0;">
            <div class="event-container">
                <div class="menu-box">
                    <div class="menu-on alarm-event">
                        ALARM
                    </div>
                    <div class="menu-off api">
                        API
                    </div>
                    <div class="slide-button">^</div>
                </div>
                <div class="alarm-container">
                    <div class="table-box">
                        <div class="search-bar">
                            <div class='title'>알람 목록</div>
                            <div class="alarm-area on">
                                <span>CODE :</span>
                                <select name="search" class="search-select" >
                                    <option value=''>알람 코드(선택)</option>
                                </select>
                                <div class='all-select'>전체 선택</div>
                                <div class='all-cancle'>선택 해제</div>
                                <div class='all-update-button'>알람 확인</div>
                            </div>
                        </div>
                        <div class="table-round">
                            <div class=alarm-table-box>
                                <table class="alarm-table on" style="text-align: center;">
                                    <tr class="table-column">
                                        <th style="width: 5%">선택</th>
                                        <th style="width: 10%">알람 코드</th>
                                        <th style="width: 15%;">알람 명칭</th>
                                        <th style="width: 15%;">알람 발생 대상</th>
                                        <th style="width: 30%;">알람 발생 값</th>
                                        <th style="width: 15%;">알람 발생 시각</th>
                                        <th style="width: 10%;">알람 확인 여부</th>
                                    </tr>
                                    <tbody class="content">
                                        <tr>
                                            <td class="empty-box" rowspan="4" colspan="8">
                                                알람 데이터가 없습니다.
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                <table class="api-table" style="text-align: center;">
                                    <tr class="table-column">
                                        <th>API-ID</th>
                                        <th>API-TOKEN</th>
                                        <th>IP 주소</th>
                                        <th>호출 발생 시각</th>
                                        <th>오류 여부</th>
                                    </tr>
                                    <tbody class="content">
                                        <tr>
                                            <td class="empty-box" rowspan="4" colspan="8">
                                                알람 데이터가 없습니다.
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="date-box">
            <div style="font-size: 20px; font-weight: bold; margin-left: 10px; user-select: none;">
                상세 대시보드 <i onclick="rotateContainer()" class="fa fa-refresh" aria-hidden="true" style="cursor: pointer"></i>
            </div>
        </div>
        <div>
            <iframe id="iframe-detail" src="https://tsihub.koroad.or.kr/grafana/d/b8c7f506-687f-41e0-8d08-2bcbdfc994d81/eab3b5-eb8ba8-eb8c80-ec8b9c-ebb3b4-eb939c?orgId=1&refresh=5s&kiosk" width="100%" height="100px"
                    style="border: none"></iframe>
        </div>
        </div>
    </div>
</body>
</html>

<script>
    const iframeUrl = 'https://tsihub.koroad.or.kr/grafana/d/a2bdde78-ca43-42fb-ad6b-5fed5efe7fe0/34756fc9-4cb9-5aaa-ba23-d1a4d5529448?orgId=1';

    function rotateContainer() {
        const $iframeDetail = $('#iframe-detail');
        if ($iframeDetail.height() === 1544) {
            $iframeDetail.css('height', '100px');
        }
        else {
            $iframeDetail.css('height', '1544px');
        }
        $('.container').toggleClass('on');
    }

    function rangeSearch() {
        const text = $('#range-search').val();
        const $rangeOptions = $('.range-select > div');
        for (let ii = 0; ii < $rangeOptions.length; ii++) {
            let liText = $rangeOptions.eq(ii).text().toLowerCase();
            if (text === '') {
                $rangeOptions.css('display', 'block');
                break;
            }
            else if (!liText.includes(text.toLowerCase())) {
                $rangeOptions.eq(ii).css('display', 'none');
            }
            else {
                $rangeOptions.eq(ii).css('display', 'block');
            }
        }
    }

    function monitoringChange() {
        const refresh = $('#refresh');
        console.log(refresh.val());
        // if () {
        //     url+= 'refresh=5s&';
        // }
        let url = iframeUrl;
        //iframeUrl + 'from=now-5m&to=now'
        //iframeUrl +='&kiosk';
    }
    const checkWord = [
        'now','-', '+', 'd', 'm', 'M', 'h', 'w', 'fy', 'fQ', 'Q', '/'
    ]
    const checkExpire = /[now,+,d,m,M,h,w,f,f,Q,\-,\/]/g;
    const fromData = [
        'now-5m', 'now-15m', 'now-30m', 'now-1h', 'now-3h',
        'now-6h', 'now-12h', 'now-24h', 'now-2d', 'now-7d',
        'now-30d', 'now-90d', 'now-6M', 'now-1y', 'now-2y',
        'now-5y', 'now-1d/d', 'now-2d/d', 'now-7d/d', 'now-1w/w',
        'now-1M/M', 'now-1Q/fQ', 'now-1y/y', 'now-1y/fy', 'now/d',
        'now/d', 'now/w', 'now/w', 'now/M', 'now/M',
        'now/y', 'now/y', 'now/fQ', 'now/fQ', 'now/fy', 'now/fy',
    ]
    const toData = [
        'now', 'now', 'now', 'now', 'now',
        'now', 'now', 'now', 'now', 'now',
        'now', 'now', 'now', 'now', 'now',
        'now', 'now-1d/d', 'now-2d/d', 'now-7d/d', 'now-1w/w',
        'now-1M/M', 'now-1Q/fQ', 'now-1y/y', 'now-1y/fy', 'now/d',
        'now', 'now/w', 'now', 'now/M', 'now',
        'now/y', 'now', 'now', 'now/fQ', 'now', 'now/fy'
    ]

    const divArr = $('.range-select > div');
    divArr.on('click', function(){
        $('.range-select > div.on').removeClass('on');
        $(this).addClass('on');
        let idx = findRangeSelectIndex();
        if (idx >= 0) {
            divArr.eq(idx).text();
        }
        for (let ii = 0; ii < divArr.length; ii++) {
            if (divArr.eq(ii).hasClass('on')) {
                const refresh = $('#refresh').val();
                const uri = setUri(refresh, fromData[ii], toData[ii]);
                const $from = $('.from-dt');
                const $to = $('.to-dt');
                $from.val(fromData[ii]);
                $to.val(toData[ii]);
                $('.date-change').html(divArr.eq(ii).text()+'<span class="drop on"></span');
                $('#iframe').attr('src', uri);
                dropDown();
            }
        }
    });

    function findRangeSelectIndex() {
        for (let ii = 0; ii < divArr.length; ii++) {
            if (divArr.eq(ii).hasClass('on')) {
               return ii;
            }
        }
    }

    $('.date-img').on('click', function() {

    })

    function setUri(refresh, from, to) {
        return iframeUrl + '&refresh='+ refresh + '&from=' + from + '&to=' + to + '&kiosk';
    }

    function applyDashboard(){
        const isError = checkValidation();
        if (isError) return;
        const fromVal = $('.from-dt').val();
        const toVal = $('.to-dt').val();
        const refreshVal = $('#refresh').val();
        setUri(refreshVal, fromVal, toVal);
    }

    function checkValidation() {
        const $from = $('.from-dt');
        const $to = $('.to-dt');
        const $fromDtWarn = $('.from-dt-text');
        const $toDtWar = $('.to-dt-text');
        $fromDtWarn.removeClass('on');
        $fromDtWarn.text('');
        $toDtWar.removeClass('on');
        $toDtWar.text('');
        $to.removeClass('on');
        $from.removeClass('on');
        let isError = false;
        if (!$from.val() || !$from.val().trim()) {
            validationError($from, $fromDtWarn, '표출 설정 값을 입력해주세요.');
            isError = true;
        }
        if (!$to.val() || !$to.val().trim()) {
            validationError($to, $toDtWar, '표출 설정 값을 입력해주세요.');
            isError = true;
        }

        const fromVal = $from.val().replaceAll(' ', '');
        const toVal   = $to.val().replaceAll(' ', '');

        if (dateValidation(fromVal)) {
            validationError($from, $fromDtWarn, '형식에 맞게 입력해주세요. ex)now or yyyy-MM-dd HH:mm:ss');
            isError = true;
        }

        if (dateValidation(toVal)) {
            validationError($to, $toDtWar, '형식에 맞게 입력해주세요. ex)now or yyyy-MM-dd HH:mm:ss');
            isError = true;
        }

        return isError;
    }

    function dateValidation(val) {
        const extValue = ['s', 'd', 'm', 'M', 'h', 'w', 'y', 'fy', 'fQ', 'Q'];
        let isInvalid = false;
        if (new Date(val).toString() === 'Invalid Date' && val.includes('now')) {
            let replaceWord = val.replace('now', '').trim();
            if (replaceWord !== '') {
                if (!['-', '+', '/'].includes(replaceWord[0])) {
                    isInvalid = true;
                }
                else {
                    let operator = replaceWord[0];
                    replaceWord = replaceWord.substr(1, replaceWord.length).trim();
                    if (replaceWord.length === 0)  {
                        isInvalid = true;
                    }
                    else {
                        if (operator === '/') {
                            isInvalid = true;
                            for (let ext of extValue) {
                                if (ext === replaceWord) {
                                    isInvalid = false;
                                    break;
                                }
                            }
                        }
                        else {
                            for (let ext of extValue) {
                                if (ext === replaceWord) {
                                    isInvalid = true;
                                    break;
                                }
                            }

                            if (isInvalid === false) {
                                if (replaceWord.includes('/')) {
                                    let checkArray = replaceWord.split('/');
                                    if (checkArray.length === 2) {
                                        isInvalid = true;
                                        for (let ext of extValue) {
                                            if (ext === checkArray[1].trim()) {
                                                isInvalid = false;
                                                break;
                                            }
                                        }

                                        if (!isInvalid) {
                                            let trimVal = checkArray[0].trim();
                                            const idx = extValue.findIndex(ext => checkArray[0].trim().includes(ext));
                                            if (idx >= 0) {
                                                const numVal = trimVal.replace(extValue[idx], '');
                                                if (isNaN(Number(numVal))) {
                                                    isInvalid = true;
                                                }
                                            }
                                            else {
                                                isInvalid = true;
                                            }
                                        }
                                    }
                                    else {
                                        isInvalid = true;
                                    }
                                }
                                else {
                                    let idx = extValue.findIndex(ext => replaceWord.includes(ext));
                                    if (idx >= 0) {
                                        let numVal = replaceWord.replace(extValue[idx], '').trim();
                                        if (numVal !== '' && isNaN(Number(numVal))) {
                                            isInvalid = true;
                                        }
                                    }
                                    else {
                                        isInvalid = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
       }
       else {
           isInvalid = true;
           let dateVal = new Date(val);
           if (dateVal instanceof Date && val.length >= 10 && dateVal.toString() !== 'Invalid Date') {
               isInvalid = false;
           }
       }
       return isInvalid;
    }

    function validationError(el, elWord, text) {
        el.addClass('on');
        elWord.addClass('on');
        elWord.text(text);
    }

    const fromPicker = makeDatePicker('.from-picker')
    const toPicker = makeDatePicker('.to-picker')
    function makeDatePicker(el) {
        return $(el).datepicker({
            dateFormat: 'yy-mm-dd',
            showOtherMonths: true,
            showMonthAfterYear: true,
            changeYear: true,
            changeMonth: true,
            showOn: 'button',
            buttonImage: '/image/date_icon.png',
            buttonImageOnly: true,
            dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
            monthNames: ['1월','2월','3월','4월','5월','6월', '7월','8월','9월','10월','11월','12월'],
            monthNamesShort: ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'],
        });
    }


    function changeValue(el) {
        $(el).parent().prev().val($(el).val());
    }

</script>