<%@ 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>
        .mask-email  { color:#1a73e8; font-weight:bold; }
        .mask-phone  { color:#d93025; font-weight:bold; }
        .mask-digits { color:#9334e6; font-weight:bold; }
        .msg-cell { display:inline-block; max-width:380px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; vertical-align:middle; }
    </style>
    <script language="javascript">
        var url = '<c:url value="/onl/apim/messagerequest/messageRequestMan.json" />';
        var url_view = '<c:url value="/onl/apim/messagerequest/messageRequestMan.view" />';

        function escapeHtmlJs(s) { return $('<div>').text(s == null ? '' : s).html(); }
        function escapeAttr(s) { return escapeHtmlJs(s).replace(/"/g, '&quot;'); }

        // 제목: 없으면 messageCode, 마우스오버에 코드명(코드) 표기
        function formatSubject(cellvalue, options, rowObject) {
            var code = rowObject.messageCode || '';
            var subject = (cellvalue && cellvalue !== '') ? cellvalue : '';
            var title = rowObject.messageCodeName ? (rowObject.messageCodeName + ' (' + code + ')') : code;
            if (subject) {
                // 제목이 있으면 2줄: 제목 + 하단에 메세지코드
                var codeLine = code ? '<br><span style="color:#888;font-size:0.85em;">' + escapeHtmlJs(code) + '</span>' : '';
                return '<span title="' + escapeAttr(title) + '">' + escapeHtmlJs(subject) + codeLine + '</span>';
            }
            // 제목이 없으면 메세지코드만
            return '<span title="' + escapeAttr(title) + '">' + escapeHtmlJs(code) + '</span>';
        }

        // 본문: 서버에서 마스킹+escape 된 안전 HTML 그대로 렌더
        function formatMessage(cellvalue, options, rowObject) {
            return '<span class="msg-cell">' + (rowObject.messageHtml || '') + '</span>';
        }

        // 수신자 정보: 휴대폰 / 이메일 / 메신저ID (모두 마스킹됨)
        function formatReceiverInfo(cellvalue, options, rowObject) {
            var parts = [];
            if (rowObject.phone)       parts.push(escapeHtmlJs(rowObject.phone));
            if (rowObject.email)       parts.push(escapeHtmlJs(rowObject.email));
            if (rowObject.messengerId) parts.push(escapeHtmlJs(rowObject.messengerId));
            return parts.join('<br>');
        }

        function formatRequestDate(cellvalue, options, rowObject) {
            return '<span title="' + escapeAttr(rowObject.requestDateFull || '') + '">' + escapeHtmlJs(rowObject.requestDateShort || '') + '</span>';
        }
        function formatSentDate(cellvalue, options, rowObject) {
            return '<span title="' + escapeAttr(rowObject.sentDateFull || '') + '">' + escapeHtmlJs(rowObject.sentDateShort || '') + '</span>';
        }

        function init() {
            $.ajax({
                type: "POST", url: url, dataType: "json",
                data: {cmd: 'LIST_INIT_COMBO'},
                success: function (json) {
                    new makeOptions("CODE", "NAME").setObj($("select[name=searchRequestStatus]"))
                        .setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>")
                        .setData(json.statusList).rendering();
                    new makeOptions("CODE", "NAME").setObj($("select[name=searchMessageCode]"))
                        .setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>")
                        .setData(json.messageCodeList).rendering();

                    putSelectFromParam();

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

        function buildGrid() {
            $('#grid').jqGrid({
                datatype: "json", mtype: 'POST', url: url,
                postData: getSearchForJqgrid("cmd", "LIST"),
                colNames: ['id', 'No.', '제목', '메세지 내용', '수신자명', '수신자 정보', '유형', '상태', '요청시간', '발송시간'],
                colModel: [
                    {name: 'id', align: 'center', key: true, hidden: true},
                    {name: 'rowNum', align: 'center', width: 45, sortable: false},
                    {name: 'subject', align: 'left', width: 160, formatter: formatSubject},
                    {name: 'messageHtml', align: 'left', width: 300, formatter: formatMessage},
                    {name: 'username', align: 'center', width: 80},
                    {name: 'receiverInfo', align: 'left', width: 150, formatter: formatReceiverInfo},
                    {name: 'messageType', align: 'center', width: 60},
                    {name: 'requestStatus', align: 'center', width: 70},
                    {name: 'requestDateShort', align: 'center', width: 110, formatter: formatRequestDate},
                    {name: 'sentDateShort', align: 'center', width: 110, formatter: formatSentDate}
                ],
                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;
                    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 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><div class="select-style"><select name="searchRequestStatus"></select></div></td>
                    <th>메세지 코드</th>
                    <td><div class="select-style"><select name="searchMessageCode"></select></div></td>
                    <th>수신자명</th>
                    <td><input type="text" name="searchRecipient" autocomplete="off"></td>
                </tr>
                <tr>
                    <th>유형</th>
                    <td>
                        <div class="select-style">
                            <select name="searchMessageType">
                                <option value="">전체</option>
                                <option value="EMAIL">EMAIL</option>
                                <option value="SMS">SMS</option>
                                <option value="KAKAO">KAKAO</option>
                                <option value="MESSENGER">MESSENGER</option>
                            </select>
                        </div>
                    </td>
                    <th>요청기간</th>
                    <td colspan="3">
                        <input type="date" name="searchFromDate"> ~ <input type="date" name="searchToDate">
                    </td>
                </tr>
                </tbody>
            </table>
        </form>
        <table id="grid"></table>
        <div id="pager"></div>
    </div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>
