<%@ 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");
%>
<html>
<head>
    <title></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>
        .url-cell { display:inline-block; max-width:380px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; vertical-align:middle; }
        .succ-y { color:#1a73e8; font-weight:bold; }
        .succ-n { color:#d93025; font-weight:bold; }
    </style>
    <script language="javascript">
        var url = '<c:url value="/onl/apim/webhook/webhookSendLogMan.json" />';
        var url_view = '<c:url value="/onl/apim/webhook/webhookSendLogMan.view" />';
        var combo;
		
        function escapeHtmlJs(s) { return $('<div>').text(s == null ? '' : s).html(); }
        function escapeAttr(s) { return escapeHtmlJs(s).replace(/"/g, '&quot;'); }

        function formatTargetUrl(cellvalue, options, rowObject) {
            var v = cellvalue || '';
            return '<span class="url-cell" title="' + escapeAttr(v) + '">' + escapeHtmlJs(v) + '</span>';
        }

        // 이벤트유형 코드 → 모니터링 공통코드(EVENT_TYPE) 코드명
        function formatEventType(cellvalue, options, rowObject) {
            if (!combo || !combo.eventTypeList) {
                return escapeHtmlJs(cellvalue);
            }
            for (var i = 0; i < combo.eventTypeList.length; i++) {
                if (combo.eventTypeList[i].CODE == cellvalue) {
                    return escapeHtmlJs(combo.eventTypeList[i].NAME);
                }
            }
            return escapeHtmlJs(cellvalue);
        }

        function formatSuccess(cellvalue, options, rowObject) {
            if (cellvalue === true) return '<span class="succ-y">성공</span>';
            if (cellvalue === false) return '<span class="succ-n">실패</span>';
            return '';
        }


        function init() {
        	
        	$("#startDatepicker").datepicker().inputmask("yyyy-mm-dd",{'autoUnmask':true});
            $("#endDatepicker").datepicker().inputmask("yyyy-mm-dd",{'autoUnmask':true});
            
            var today = getToday();
            
            $("input[name=searchStartYYYYMMDD]").val(today.substring(0,6)+"01");
            $("input[name=searchEndYYYYMMDD]").val(today);
            $("input[name=searchStartDate]").val(today.substring(0,6)+"01");
            $("input[name=searchEndDate]").val(today);
            
            $.ajax({
                type: "POST", url: url, dataType: "json",
                data: {cmd: 'LIST_INIT_COMBO'},
                success: function (json) {
                    combo = json;
                    new makeOptions("CODE", "NAME").setObj($("select[name=searchEventType]"))
                        .setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>")
                        .setData(json.eventTypeList).rendering();

                    // 뒤로가기 등으로 이전 검색조건 파라미터가 있으면 기본값을 덮어씀
                    putSelectFromParam();

                    // 콤보(이벤트유형) 로드 후 그리드 생성 — formatEventType 경합 방지
                    buildGrid();
                },
                error: function (e) { alert(e.responseText); }
            });
        }

        function buildGrid() {
            $('#grid').jqGrid({
                datatype: "json", 
                mtype: 'POST', 
                url: url,
                postData: getSearchForJqgrid("cmd", "LIST"),
                colNames: ['id', 'No.', '기관명', '이벤트유형', 'Target URL', 'Proxy URL', 'Status', '성공여부', '발송서버', '발송일시'],
                colModel: [
                    {name: 'id', align: 'center', key: true, hidden: true},
                    {name: 'rowNum', align: 'center', width: 45, sortable: false},
                    {name: 'orgName', align: 'left', width: 140},
                    {name: 'eventType', align: 'center', width: 120, formatter: formatEventType},
                    {name: 'targetUrl', align: 'left', width: 300, formatter: formatTargetUrl},
                    {name: 'proxyUrl', align: 'left', width: 300, formatter: formatTargetUrl},
                    {name: 'statusCode', align: 'center', width: 60},
                    {name: 'success', align: 'center', width: 70, formatter: formatSuccess},
                    {name: 'sendBy', align: 'center', width: 100},
                    {name: 'sentAt', align: 'center', width: 140}
                ],
                jsonReader: {repeatitems: false},	
                pager: $('#pager'),
                page: '${param.page}',
                rowNum: '${rmsDefaultRowNum}',
                autoheight: true,
                height: $("#container").height(),
                autowidth: true,
                viewrecords: true,
                rowList: eval('[${rmsDefaultRowList}]'),
                ondblClickRow: function (rowId) {
                    var rowData = $(this).getRowData(rowId);
                    var id = rowData['id'];
                    var url2 = url_view + '?cmd=DETAIL';
                    url2 += '&page=' + $(this).getGridParam("page");
                    url2 += '&returnUrl=' + getReturnUrl();
                    url2 += '&menuId=' + '${param.menuId}';
                    url2 += '&id=' + id;
                    url2 += '&' + getSearchUrl();
                    goNav(url2);
                },
                loadComplete: function () {
                    var page = $(this).getGridParam('page');
                    var rowNum = $(this).getGridParam('rowNum');
                    var rows = $(this).getDataIDs();
                    var colModel = $(this).getGridParam("colModel");
                    for (var i = 0; i < rows.length; i++) {
                        var number = ((page - 1) * rowNum + i) + 1;
                        $(this).setCell(rows[i], 'rowNum', number);
                    }
                    // 서버 고정 정렬(등록일시 역순) — 컬럼 정렬 비활성
                    for (var i = 0; i < colModel.length; i++) {
                        $(this).setColProp(colModel[i].name, {sortable: false});
                    }
                },
                loadError: function (jqXHR, textStatus, errorThrown) {
                    var location = '<%=request.getContextPath()%>/';
                    comloadError(jqXHR, textStatus, errorThrown, location);
                }
            });
            resizeJqGridWidth('grid', 'content_middle', '1000');
        }

        $(document).ready(function () {
            init();

            $("#btn_search").click(function () {
                var start = $("input[name=searchStartYYYYMMDD]").val().replace(/-/gi, "");
                var end = $("input[name=searchEndYYYYMMDD]").val().replace(/-/gi, "");

                if (start && start > getToday()) {
                    alert("시작일이 오늘 이후입니다. 시작일을 확인해주세요.");
                    $("input[name=searchStartYYYYMMDD]").focus();
                    return false;
                }
                if (start && end && start > end) {
                    alert("조회기간 종료일은 시작일보다 커야합니다.");
                    $("input[name=searchEndYYYYMMDD]").focus();
                    return false;
                }
                $("input[name=searchStartDate]").val(start);
                $("input[name=searchEndDate]").val(end);

                var postData = getSearchForJqgrid("cmd", "LIST");
                $("#grid").setGridParam({url: url, postData: postData, page: 1}).trigger("reloadGrid");
            });

            $("select[name^=search]").change(function () { $("#btn_search").click(); });
            $("input[name^=search]").keydown(function (key) {
                if (key.keyCode == 13) { $("#btn_search").click(); }
            });

            

            buttonControl();
        });
    </script>
</head>
<body>
<div class="right_box">
    <div class="content_top">
        <ul class="path"><li><a href="#">${rmsMenuPath}</a></li></ul>
    </div><!-- end content_top -->
    <div class="content_middle" id="content_middle">
        <div class="search_wrap">
            <button type="button" class="cssbtn" id="btn_search" level="R"><i class="material-icons">search</i> <%= localeMessage.getString("button.search") %></button>
        </div>
        <div class="title">웹훅 발송 로그<span class="tooltip">외부로 발송된 웹훅 이력을 조회합니다.</span></div>
        <form id="ajaxForm" onsubmit="return false;">
            <table class="search_condition" cellspacing=0;>
                <colgroup>
                    <col style="width:120px;"><col style="width:200px;">
                    <col style="width:120px;"><col style="width:200px;">
                    <col style="width:120px;"><col style="width:200px;">
                </colgroup>
                <tbody>
                <tr>
                    <th>기관명</th>
                    <td><input type="text" name="searchOrgName" autocomplete="off"></td>
                    <th>이벤트유형</th>
                    <td>
                        <div class="select-style">
                            <select name="searchEventType"></select>
                        </div>
                    </td>
                    <th>성공여부</th>
                    <td>
                        <div class="select-style">
                            <select name="searchSuccess">
                                <option value="">전체</option>
                                <option value="Y">성공</option>
                                <option value="N">실패</option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>Target URL</th>
                    <td><input type="text" name="searchTargetUrl" autocomplete="off" style="width:95%;"></td>
                    <th>발송기간</th>
                    <td>
                        <input type="text" name="searchStartYYYYMMDD" id="startDatepicker" readonly="readonly" value="" size="10" style="width:40%; border:1px solid #ebebec;">
                        ~
                        <input type="text" name="searchEndYYYYMMDD" value="" id="endDatepicker" size="10" readonly="readonly" style="width:40%; border:1px solid #ebebec;">
                        <input type="hidden" name="searchStartDate" value="">
                        <input type="hidden" name="searchEndDate" value="">
                    </td>
                    <th></th>
                    <td></td>
                </tr>
                </tbody>
            </table>
        </form>
        <table id="grid"></table>
        <div id="pager"></div>
    </div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>
