<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<html>
<head>
    <title>Token Issuance Status Detail</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <jsp:include page="/jsp/common/include/css.jsp"/>
    <jsp:include page="/jsp/common/include/script.jsp"/>
    <style>
        .token-container {
            white-space: nowrap;
            width: 100%;
        }
        .token-cell {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: inline-block;
            max-width: calc(100% - 60px); /* [전체보기] 링크 공간 확보 */
            vertical-align: middle;
        }
        .token-view-link {
            color: #4A90E2 !important;
            margin-left: 5px;
            display: inline-block;
            vertical-align: middle;
        }
    </style>
    <script language="javascript">
        var url = '<c:url value="/onl/admin/tokenissuance/tokenIssuanceStatusMan.json" />';

        $(document).ready(function () {
            var clientId = '${param.clientId}';
            var gridPostData = { cmd: "DETAIL", clientId: clientId };

            // 토큰 다이얼로그 초기화
            $("#token-dialog").dialog({
                autoOpen: false,
                modal: true,
                width: 800,
                height: 400,
                buttons: {
                    "닫기": function() {
                        $(this).dialog("close");
                    }
                }
            });

            $.ajax({
                type: "POST",
                url: url,
                data: gridPostData,
                dataType: "json",
                success: function(response) {
                    var detail = response.detail;
                    populateStatusInfo(detail.statusUI);
                    initializeLogGrid(detail.logs);
                },
                error: function(e) {
                    alert("Error loading details: " + e.responseText);
                }
            });

            $("#btn_unrestrict").click(function() {
                var clientName = $("#clientName").text();
                var confirmMessage = clientName + "의 제한 체크 목록이 초기화됩니다. 진행하시겠습니까?";

                if (confirm(confirmMessage)) {
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: { cmd: "EXEMPT_RESTRICTION", clientId: clientId },
                        dataType: "json",
                        success: function(response) {
                            if (response.success) {
                                alert(response.message);
                                location.reload();
                            } else {
                                alert("제한 해제 중 오류가 발생했습니다.");
                            }
                        },
                        error: function(e) {
                            alert("제한 해제 요청 중 오류가 발생했습니다: " + e.responseText);
                        }
                    });
                }
            });

            $("#btn_previous").click(function() {
                goNav(getReturnUrlForReturn());
            });

            buttonControl();
        });

        function showFullToken(token) {
            $("#token-dialog pre").text(token);
            $("#token-dialog").dialog("option", "title", "토큰 전체보기").dialog("open");
        }

        function populateStatusInfo(statusUI) {
            $("#orgName").text(statusUI.orgName);
            $("#clientName").text(statusUI.clientName);
            $("#dailyTokenLimit").text(statusUI.dailyTokenLimit);
            $("#requestCount").text(statusUI.requestCount);
            $("#successCount").text(statusUI.successCount);
            $("#failedCount").text(statusUI.failedCount);
            $("#restrictionStatus").text(statusUI.restricted ? '제한 중' : '정상');
            $("#restrictionStatus").css('color', statusUI.restricted ? 'red' : 'green');
        }

        function initializeLogGrid(logs) {
            $('#logGrid').jqGrid({
                datatype: "local",
                data: logs,
                colNames: ['발급일시', 'APP명', '성공여부', 'IP주소', '기관명', 'Grant Type', 'Scope', '결과메시지', '액세스 토큰'],
                colModel: [
                    {name: 'issuanceDateTime', index: 'issuanceDateTime', width: 150, align: "center"},
                    {name: 'appName', index: 'appName', width: 100},
                    {name: 'successYn', index: 'successYn', width: 60, align: "center"},
                    {name: 'ipAddress', index: 'ipAddress', width: 100},
                    {name: 'orgName', index: 'orgName', width: 100},
                    {name: 'grantType', index: 'grantType', width: 100},
                    {name: 'scope', index: 'scope', width: 100},
                    {name: 'resultMessage', index: 'resultMessage', width: 250},
                    {name: 'accessToken', index: 'accessToken', width: 150, formatter: function(cellvalue, options, rowObject) {
                            if (cellvalue) {
                                return '<div class="token-container">' +
                                    '<span class="token-cell">' + cellvalue + '</span>' +
                                    '<a href="javascript:void(0);" class="token-view-link" onclick="showFullToken(\'' +
                                    cellvalue.replace(/'/g, "\\'") +
                                    '\')">[전체보기]</a>' +
                                    '</div>';
                            }
                            return '';
                        }}
                ],
                pager: '#logPager',
                rowNum: 10,
                rowList: [10, 20, 30],
                sortname: 'issuanceDateTime',
                sortorder: "desc",
                viewrecords: true,
                autoheight: true,
                height: 300,
                autowidth: true,
                autoencode: true,
                caption: "토큰 발급 현황 (Last 24 Hours)"
            });

            resizeJqGridWidth('logGrid', 'content_middle', '1400');
        }
    </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">
        <div class="search_wrap">
            <button type="button" class="cssbtn" id="btn_unrestrict" level="W"><i class="material-icons">lock_open</i> 제한해제</button>
            <button type="button" class="cssbtn" id="btn_previous" level="R"><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button>
        </div>
        <div class="title" id="title" style="font-size:1.4em">${rmsMenuName} 상세</div>
        <table class="table_row" cellspacing="0">
            <tr>
                <th style="width:180px;">기관명</th>
                <td id="orgName"></td>
                <th style="width:180px;">APP명</th>
                <td id="clientName"></td>
            </tr>
            <tr>
                <th>제한건수</th>
                <td id="dailyTokenLimit"></td>
                <th>요청건수</th>
                <td id="requestCount"></td>
            </tr>
            <tr>
                <th>성공건수</th>
                <td id="successCount"></td>
                <th>실패건수</th>
                <td id="failedCount"></td>
            </tr>
            <tr>
                <th>제한상태</th>
                <td colspan="3" id="restrictionStatus"></td>
            </tr>
        </table>

        <div style="margin-top: 20px;">
            <table id="logGrid"></table>
            <div id="logPager"></div>
        </div>
    </div>
</div>
</body>
<!-- 토큰 다이얼로그 추가 -->
<div id="token-dialog" style="display:none;">
    <pre style="white-space:pre-wrap; word-wrap:break-word; max-height:300px; overflow:auto;"></pre>
</div>
</html>