<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
%>
<!DOCTYPE html>
<html>
<head>
    <title>API 통계 목록</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <jsp:include page="/jsp/common/include/css.jsp"/>
    <jsp:include page="/jsp/common/include/script.jsp"/>
    <jsp:include page="/jsp/common/include/portal.jsp"/>
    <script language="javascript">
        var url = '<c:url value="/onl/apim/portalstatistics/portalStatisticsApiTableMan.json" />';
        var grid;

        $(document).ready(function() {
            // Datepicker 초기화
            $("input[name=startDate], input[name=endDate]").datepicker({
                format: "yyyy-mm-dd",
                autoclose: true,
                todayHighlight: true,
                language: "ko"
            });

            function setActiveDateRangeButton() {
                var startDate = $("input[name=startDate]").datepicker('getDate');
                var endDate = $("input[name=endDate]").datepicker('getDate');
                var diffDays = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24));

                $('.btn-date-range').removeClass('active');

                if (diffDays === 30) {
                    $('#btn_month').addClass('active');
                } else if (diffDays === 7) {
                    $('#btn_week').addClass('active');
                } else if (diffDays === 0) {
                    $('#btn_today').addClass('active');
                }
            }

            function setDateRange(days) {
                var now = new Date();
                var endDate = now;
                var startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - days);

                $("input[name=startDate]").datepicker('setDate', startDate);
                $("input[name=endDate]").datepicker('setDate', endDate);

                setActiveDateRangeButton();
            }

            $("#btn_month").click(function() {
                setDateRange(30);
                loadData();
            });

            $("#btn_week").click(function() {
                setDateRange(7);
                loadData();
            });

            $("#btn_today").click(function() {
                setDateRange(0);
                loadData();
            });

            setDateRange(0);

            function initGrid(data) {
                if (grid) {
                    grid.destroy();
                }

                var columns = [
                    { id: 'apiName', name: 'API 명', sort: true,
                        formatter: (cell) => gridjs.html('<b>'+cell+'</b>')},
                    {
                        id: 'totalRequests',
                        name: '총 요청 수',
                        sort: true,
                        formatter: (cell) => gridjs.html('<span style="color: #0a53be;">'+cell+'</span>')
                    },
                    {
                        id: 'totalFailures',
                        name: '오류 건수',
                        sort: true,
                        formatter: (cell) => gridjs.html('<span style="color: #dc3545;">'+cell+'</span>')
                    },
                    {
                        id: 'successRate',
                        name: '성공 률 (%)',
                        sort: true
                    }
                ];

                grid = new gridjs.Grid({
                    columns: columns,
                    data: data,
                    sort: true,
                    pagination: {
                        limit: 10
                    },
                    search: true,
                    style: {
                        table: {
                            border: '3px solid #ccc'
                        },
                        th: {
                            'background-color': 'rgba(0, 0, 0, 0.1)',
                            color: '#000',
                            'border-bottom': '3px solid #ccc',
                            'text-align': 'center'
                        },
                        td: {
                            'text-align': 'center'
                        }
                    }
                }).render(document.getElementById('wrapper'));

                addExportButton(grid);
            }

            function updateSummary(summary) {
                $("#totalApis").text(summary.totalApis);
                $("#totalRequests").text(summary.totalRequests.toLocaleString());
                $("#totalFailures").text(summary.totalFailures.toLocaleString());
                $("#overallSuccessRate").text(summary.overallSuccessRate.toFixed(2));
            }

            function loadData() {
                var startDate = $("input[name=startDate]").val().replace(/-/g, '');
                var endDate = $("input[name=endDate]").val().replace(/-/g, '');

                $.ajax({
                    url: url,
                    type: "POST",
                    data: {
                        cmd: "LIST",
                        startDate: startDate,
                        endDate: endDate
                    },
                    success: function(response) {
                        updateSummary(response.summary);
                        initGrid(response.apiStats);
                    },
                    error: function(xhr, status, error) {
                        console.error("Error fetching data:", error);
                        alert("데이터를 불러오는 중 오류가 발생했습니다.");
                    }
                });
            }

            $("#btn_search").click(function (){
                setActiveDateRangeButton();
                loadData();
            });

            loadData(); // 초기 데이터 로드
        });
    </script>
</head>
<body>
<div class="right_box">
    <div class="content_top">
        <ul class="path">
            <li><a href="#">${rmsMenuPath}</a></li>
        </ul>
    </div>
    <div class="content_middle" id="content_middle">
        <h2 class="mb-4">API 별 통계 목록</h2>

        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-hdd-stack card-icon text-primary"></i>
                        <h5 class="card-title">총 API 수</h5>
                        <p class="card-text">
                            <span id="totalApis">0</span> 개
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-arrow-repeat card-icon text-success"></i>
                        <h5 class="card-title">총 요청 수</h5>
                        <p class="card-text">
                            <span id="totalRequests">0</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-exclamation-triangle card-icon text-danger"></i>
                        <h5 class="card-title">총 실패 수</h5>
                        <p class="card-text">
                            <span id="totalFailures">0</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card text-center h-100">
                    <div class="card-body">
                        <i class="bi bi-graph-up card-icon text-info"></i>
                        <h5 class="card-title">전체 성공률</h5>
                        <p class="card-text">
                            <span id="overallSuccessRate">0</span>%
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <div class="search-panel mb-4">
            <h5 class="mb-3">검색 조건</h5>
            <div class="row g-3 align-items-center">
                <div class="col-md-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-calendar"></i></span>
                        <input type="text" name="startDate" class="form-control" data-required data-warning="시작 날짜를 입력하여 주십시오." placeholder="시작 날짜"/>
                    </div>
                </div>
                <div class="col-auto">
                    <span>~</span>
                </div>
                <div class="col-md-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-calendar"></i></span>
                        <input type="text" name="endDate" class="form-control" data-required data-warning="종료 날짜를 입력하여 주십시오." placeholder="종료 날짜"/>
                    </div>
                </div>
                <div class="col-auto">
                    <button type="button" id="btn_month" class="btn btn-outline-secondary btn-date-range">
                        <i class="bi bi-calendar-month"></i> 한달
                    </button>
                    <button type="button" id="btn_week" class="btn btn-outline-secondary btn-date-range">
                        <i class="bi bi-calendar-week"></i> 한주
                    </button>
                    <button type="button" id="btn_today" class="btn btn-outline-secondary btn-date-range">
                        <i class="bi bi-calendar-day"></i> 금일
                    </button>
                </div>
                <div class="col-auto">
                    <button type="button" id="btn_search" class="btn btn-primary">
                        <i class="bi bi-search"></i> 조회
                    </button>
                </div>
            </div>
        </div>

        <div id="wrapper"></div>

    </div>
</div>
</body>
</html>