<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta id="_csrf" name="_csrf" content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" content="${_csrf.headerName}"/>
 <title>History</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/css/history_new.css">
    <link rel="stylesheet" href="/css/header.css">
    <script type="text/javascript" src="/js/header.js"></script>
<%--    <script type="text/javascript" src="/js/history.js"></script>--%>
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<div class="container">
    <div class="top-tab api-search on">
        <div class="date on" onclick="topTabClick(this, 'date')">일자별 조회</div>
        <div class="api" onclick="topTabClick(this, 'api')">API별 조회</div>
    </div>
    <div class="top-tab system-search">
        <div class="date on" onclick="topTabClick(this, 'date')">일자별 조회</div>
        <div class="server" onclick="topTabClick(this, 'server')">서버별 조회</div>
    </div>
    <div class="content-box">
        <div class="left-tab">
            <div class="api-search on" onclick="leftTabClick(this)">
                <div>API 호출 /</div>
                <div>API Token 인증</div>
            </div>
            <div class="system-search" id="systemResource" onclick="leftTabClick(this)">
                <div>시스템 리소스</div>
                <div>정보</div>
            </div>
        </div>
        <div class="content">
            <div class="search-box">
                <div class="api-search on">
                    <div class="date-box on">
                        <div>조회 기간 : </div>
                        <input type="date" name="searchStartDate" class="searchStartDate">
                        ~
                        <input type="date" name="searchEndDate" class="searchEndDate">
                    </div>
                    <div class="api-box">
                        <div>API 목록: </div>
                        <select name="apiId" class="apiId">
                            <option value="">API 를 선택해주세요</option>
                        </select>
                    </div>
                    <div class="search-button" onclick="drawTable(1)">조회</div>
                </div>
                <div class="system-search">
                    <div class="date-box on">
                        <div>조회 기간 : </div>
                        <input type="date" name="searchStartDate" class="searchStartDate">
                        ~
                        <input type="date" name="searchEndDate" class="searchEndDate">
                    </div>
                    <div class="server-box">
                        서버 목록:
                        <select name="userId" class="userId">
                            <option value="">서버를 선택해주세요</option>
                        </select>
                    </div>
                    <div class="search-button" onclick="drawResourceTable(1)">조회</div>
                </div>
            </div>
            <div class="table-box">
                <div class="search-content">
                    <div class="date-box on">검색기간 : <span class="start"></span> ~ <span class="end"></span></div>
                    <div class="api-box">API ID : <span class="api_id"></span></div>
                    <div class="server-box">SERVER : <span class="server_name"></span></div>
                </div>
                <table class="search-table">
                    <thead>
                        <tr class="api-head api-search on">
                            <th class="invoke-th">발생시각</th>
                            <th class="invoke-th">apiId</th>
                            <th class="invoke-th">apiToken</th>
                            <th class="invoke-th">ip 주소</th>
                            <th class="invoke-th">정상 작동 여부</th>
                        </tr>
                        <tr class="resource-head system-search">
                            <th class="SystemResource-th">수집 시각<br></th>
                            <th class="SystemResource-th">호스트명<br></th>
                            <th class="SystemResource-th">전체 메모리 용량(Gi)</th>
                            <th class="SystemResource-th">사용 메모리 용량(Gi)</th>
                            <th class="SystemResource-th">전체 Disk 용량(Gi)</th>
                            <th class="SystemResource-th">사용 Disk 용량(Gi)</th>
                            <th class="SystemResource-th">메모리 사용량(%)</th>
                            <th class="SystemResource-th">CPU 사용량(%)</th>
                            <th class="SystemResource-th">DISK 사용량(%)</th>
                            <th class="SystemResource-th">실행 타스크 수(EA)</th>
                            <th class="SystemResource-th">실행 스레드 수(EA)</th>
                            <th class="SystemResource-th">시스템 로드 5분 평균</th>
                        </tr>
                    </thead>
                    <tbody class="table-content">
                        <tr>
                            <td colspan="5" class='nullRow'>조회 내용이 없습니다.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="page-div"></div>
        </div>
    </div>
</div>
<%--    <div class="search-box">--%>
<%--        <div class="search-header">--%>
<%--        	&nbsp;&nbsp;검색 조건--%>
<%--        </div>--%>
<%--        <div class="search-flex-container">--%>
<%--            <div class="search-select-title">--%>
<%--            	이력 조회 항목 : --%>
<%--            </div>--%>
<%--            <div>--%>
<%--                <select name="serachCategory" class="search-select">--%>
<%--                    <option value="">조회할 이력을 선택 해주세요</option>--%>
<%--                    <option value="apiInvoke">API 호출 / API Token 인증</option>--%>
<%--                    <option value="systemResuource">시스템 리소스 정보</option>--%>
<%--                </select>--%>
<%--            </div>--%>
<%--            <div class="search-during"> --%>
<%--                조회 조건 :--%>
<%--            </div>--%>
<%--                    <select class="search-condition">--%>
<%--                        <option value="">조회 조건을 선택해 주세요</option>--%>
<%--                        <option value="joinDateSearch">일자별 조회</option>--%>
<%--                        <option value="userIdSearch">API 별 조회</option>--%>
<%--                    </select>--%>
<%--                    --%>
<%--                    <div class="search-date-select">--%>
<%--                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;검색 기간 선택 :--%>
<%--                        <input type="date" name="searchStartDate" class="searchStartDate">--%>
<%--                       	~--%>
<%--                        <input type="date" name="searchEndDate" class="searchEndDate">--%>
<%--                    </div>--%>
<%--                    --%>
<%--                     <div class="search-user-select">--%>
<%--							&nbsp;&nbsp;&nbsp;&nbsp; API 목록: --%>
<%--							<select  name="userId" class="userId">--%>
<%--								<option value="">API 를 선택해주세요</option>--%>
<%--							</select>--%>
<%--                    </div>--%>
<%--                    --%>
<%--                    <div class="select-button">--%>
<%--                    </div>--%>
<%--        </div>--%>
<%--    </div>--%>
<%--    --%>
<%--    <div class="result-box">--%>
<%--        <div>--%>
<%--        	&nbsp;&nbsp;검색 결과--%>
<%--        </div>--%>
<%--        <div>--%>
<%--            <table class="search-table">--%>
<%--            --%>
<%--            </table>--%>
<%--        </div>--%>
<%--    </div>--%>
    
</div>
</body>
</html>
<script>
    const apiStart = $('.api-search .searchStartDate');
    const apiEnd = $('.api-search .searchEndDate');
    const startVal = getBeforeDate(2);
    const endVal = getBeforeDate(1);
    // const searchInfo = $('.search-date');
    const startText = $('.start');
    const endText = $('.end');
    apiStart.val(startVal);
    apiEnd.val(endVal);
    startText.text(startVal);
    endText.text(endVal);
    const resourceStart = $('.system-search .searchStartDate');
    const resourceEnd   = $('.system-search .searchEndDate');
    //searchInfo.text(startVal + ' ~ ' + endVal);
    drawTable(1);
    getData('/api/setOptionApiUser.do', 'GET', null, (data) => recvOption(data, 'apiId'));
    getData('/api/setOptionResourceUser.do', 'GET', null, (data) => recvOption(data, 'userId'));

    $(document).ajaxStart(()=>{
        $('.content').append('<div class="loading-box"><img src="/image/loading.gif" style="width: 100px; height: 100px; filter:brightness(0.2);"></div>');
    })
    $(document).ajaxStop(()=>{
        $('.content > .loading-box').remove();
    })
    function recvOption(data, el) {
        const $apiId = $('.' + el);
        if (data && data.length > 0) {
            for (let obj of data) {
                $apiId.append($('<option value="'+obj+'">'+obj+'</option>'));
            }
        }
    }

    function getBeforeDate(after) {
        const dateVal = new Date(new Date().setDate(new Date().getDate() - after));
        return dateVal.getFullYear() + '-' + twoWordFormat(dateVal.getMonth() + 1) + '-' + twoWordFormat(dateVal.getDate());
    }

    function twoWordFormat(word) {
       word = Number(word);
        if (word < 10) {
            word = '0' + word;
        }
        return word.toString();
    }

    function drawTable(page) {
        const $selectedTab = $('.top-tab.on > div.on');
        let data;
        let url;
        if ($selectedTab.hasClass('date')) {
            let searchStartDate = apiStart.val();
            let searchEndDate = apiEnd.val();
            if (!dateValidation(searchStartDate, searchEndDate)) return;
            startText.text(searchStartDate);
            endText.text(searchEndDate);
            data = {
                searchStartDate : searchStartDate,
                searchEndDate : searchEndDate,
                page : page
            };
            url = '/api/searchDateRecodeInvoke.do';
        }
        else {
            const apiId = $('.apiId').val();
            data = {
                userId : apiId,
                page : page,
            };
            $('.api_id').text(apiId);
            url = '/api/searchCustomerInvoke.do';
        }

        getData(url, 'POST', data, (rec)=>recvDrawTableData(rec, 'api'));
    }

    function drawResourceTable(page) {
        const $selectedTab = $('.top-tab.on > div.on');
        let data = null;
        let url = null;
        if ($selectedTab.hasClass('date')) {
            let searchStartDate = resourceStart.val();
            let searchEndDate = resourceEnd.val();
            if (!dateValidation(searchStartDate, searchEndDate)) return;

            startText.text(searchStartDate);
            endText.text(searchEndDate);
            data = {
                searchStartDate : searchStartDate,
                searchEndDate : searchEndDate,
                page : page
            };
            url = '/api/SystemResourceDateSearch.do';
        }
        else {
            const userId = $('.userId').val();
            if (userId === '') return alert('SERVER ID를 선택해주세요.');

            data = {
                userId : userId,
                page : page,
            };

            $('.server_name').text(userId);
            url = '/api/systemResourceUserSearch.do';
        }

        getData(url, 'POST', data, (rec) => recvDrawTableData(rec, 'resource'));
    }


    function dateValidation(start, end) {
         if (start > end) {
            alert('검색 시작일이 종료일 보다 큽니다.');
            return false;
        }
        return true;
    }

    function recvDrawTableData({currentPage, firstPage, lastPage, tablelist, totPage, pagePerCount, page_CNT}, type) {
        let str = '';
        const $tableContent = $('.table-content');
        $tableContent.empty();
        if (tablelist && tablelist.length > 0) {
            for (let list of tablelist) {
                if (type === 'api') {
                    str += getApiInvokeList(list);
                }
                else if (type === 'resource') {
                    str += getResourceList(list);
                }
            }
            if (tablelist.length < pagePerCount) {
                const difference = pagePerCount - tablelist.length;
                str += '<tr class="empty-box" rowspan="'+difference+'" style="height: calc(100% / 22 * ' + difference + ');"><td></td><td></td><td></td><td></td><td></td></tr>'
            }
        }
        else {
            const length = $('thead > tr.on > th').length;
            str =  `<tr class="empty-box">
                        <td colspan="\${length}" class="nullRow">내용이 없습니다.</td>
                    </tr>`;
        }
        pagination(currentPage, firstPage, lastPage, totPage, page_CNT, type);

        $tableContent.html(str);
    }

    function getApiInvokeList(data) {
        const {eventdt, apiid, apitoken, ipaddr, error} = data;
        let start = '';
        let end = '';
        if (eventdt && eventdt.length > 11) {
            start = eventdt.substring(0,10);
            end = eventdt.substring(11, eventdt.length);
        }
        const errorText = error === '0' ? '정상' : '비정상';

        return `<tr>
                    <td style="max-height:30px;">\${start} \${end}</td>
                    <td style="max-height:30px;">\${apiid}</td>
                    <td style="max-height:30px;">\${apitoken}</td>
                    <td style="max-height:30px;">\${ipaddr}</td>
                    <td style="max-height:30px;">\${errorText}</td>
                </tr>`;
    }

    function getResourceList(data) {
        const {clctDt, hostName, totalMem, useMem, totalDisk, useDisk, useMemRate, useCpuRate, useDiskRate, taskCnt, threadCnt, loadAvg} = data;
        let start = '';
        let end = '';
        if (clctDt && clctDt.length > 11) {
            start = clctDt.substring(0,10);
            end = clctDt.substring(11, clctDt.length);
        }

        return `<tr>
                    <td>\${start} \${end}</td>
                    <td>\${hostName}</td>
                    <td>\${totalMem}</td>
                    <td>\${useMem}</td>
                    <td>\${totalDisk}</td>
                    <td>\${useDisk}</td>
                    <td>\${useMemRate}</td>
                    <td>\${useCpuRate}</td>
                    <td>\${useDiskRate}</td>
                    <td>\${taskCnt}</td>
                    <td>\${threadCnt}</td>
                    <td>\${loadAvg}</td>
                </tr>`;
    }

    function pagination(currentPage, firstPage, lastPage, totPage, page_CNT, type) {
        const $page = $('.page-div');
        $page.empty();
        let pageStr = '';
        let method = '';
        if (type === 'api') {
            method = 'drawTable';
        }
        else if (type === 'resource'){
            method = 'drawResourceTable'
        }
        if (firstPage > page_CNT) {
            pageStr += '<a href="javascript:'+method+'('+(firstPage - page_CNT)+')">[PREV] </a>'
        }
        for (let ii= firstPage; ii <= lastPage; ii++) {
            pageStr += '<a ';
            if (ii === currentPage) {
                pageStr +='style="font-weight:bold;" ';
            }
            pageStr += 'href="javascript:' + method + '('+ii+')"> ['+ii+'] </a>'
        }

        if (totPage > lastPage) {
            pageStr += '<a href="javascript:'+method+ '('+(lastPage + 1)+')"> [NEXT]</a>'
        }
        $page.html(pageStr);
    }

    function topTabClick(el, className) {
        const $this = $(el);
        if ($this.hasClass('on')) {
            return;
        }
        $('.top-tab.on > div.on').removeClass('on');
        $this.addClass('on');
        const $selectBox = $('.search-box > div.on > div.on');

        let removeClassName = $selectBox.attr('class');
        removeClassName = removeClassName.replace(' on', '');
        $('.' + removeClassName).removeClass('on');
        $('.' + className + '-box').addClass('on');
    }

    function getData(url, type, data, callBack) {
        $.ajax({
            url : url,
            type : type,
            data : data,
            success : function (rec) {
                if (callBack) {
                    callBack(rec)
                }
            },
            error: function (error) {
                if (error) {
                    console.error(error);
                }
            }
        })
    }

    function leftTabClick(el) {
        const $selectedTab = $('.left-tab > div.on');
        const className = $selectedTab.attr('class');
        $('.' + className.replace(' on', '')).removeClass('on');
        const selectClassName = $(el).attr('class');
        $('.' + selectClassName).addClass('on');
        const $tableContent = $('.table-content');
        $('.top-tab > div:nth-child(1)').addClass('on');
        $('.top-tab > div:nth-child(2)').removeClass('on');
        $('.search-box > div.on > div.on').removeClass('on');
        $('.search-box > div.on > .date-box').addClass('on');
        $('.search-content > div.on').removeClass('on');
        $('.search-content > .date-box').addClass('on');
        apiStart.val('');
        apiEnd.val('');
        resourceStart.val('');
        resourceEnd.val('');
        $tableContent.empty();
        $('.page-div').empty();
        $('.server_name').text('')
        $('.api_id').text('')
        $('.start').text('')
        $('.end').text('')
        const length = $('thead > tr.on > th').length;
        $tableContent.html(`<tr class="empty-box">
                                <td colspan="\${length}" class='nullRow'>조회 내용이 없습니다.</td>
                            </tr>`);
    }
</script>