<%@ 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"/>
    <script language="javascript">
        var url = '<c:url value="/onl/apim/portaluserterms/portalUserTermsMan.json" />';
        var url_view = '<c:url value="/onl/apim/portaluserterms/portalUserTermsMan.view" />';
        var isUnMasked = false;
        var unmaskReason = '';

        function init() {
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'LIST_INIT_COMBO'},
                success: function (json) {

                    const comboConfigs = [{name: 'searchTermsType', data: json.termsTypeRows}];

                    comboConfigs.forEach(function (config) {
                        new makeOptions("CODE", "NAME")
                            .setObj($("select[name=" + config.name + "]"))
                            .setNoValueInclude(true)
                            .setNoValue("", "<%=localeMessage.getString("combo.all")%>")
                            .setData(config.data)
                            .setFormat(nameOptionFormat).rendering();
                    });

                    select_termsType = ": ;" + getGridSelectText("CODE", "NAME", json.termsTypeRows);
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });
        }

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

            $('#grid').jqGrid({
                datatype: "json",
                mtype: 'POST',
                url: url,
                postData: {cmd: 'LIST'},
                colNames: ['No.', 'id', '법인명', '동의자명', '약관동의자 이메일 아이디', '종류', '버전', '동의일시'],
                colModel: [
                    {name: 'rowNum', align: 'center', width: 40, sortable: false},
                    {name: 'id', align: 'center', hidden: true, key: true},
                    {name: 'userOrgName', align: 'center', width: 100},
                    {name: 'createdByName', align: 'center', width: 80},
                    {name: 'createdByLoginId', align: 'center', width: 100},
                    {name: 'termsTypeName', align: 'center'},
                    {name: 'termsVersion', align: 'center', width: 40},
                    {name: 'agreementDate', align: 'center', width: 100, formatter: timeStampFormat}
                ],
                jsonReader: {
                    repeatitems: false
                },
                pager: $('#pager'),
                page: '${param.page}',
                rowNum: '${rmsDefaultRowNum}',
                autoheight: true,
                height: $("#container").height(),
                autowidth: true,
                viewrecords: true,
                rowList: eval('[${rmsDefaultRowList}]'),
                rowId: function (obj) {
                    return obj.id;
                },
                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;
                        // var reverseNumber = records - ((page - 1) * rowNum + i);
                        $(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');

            $("input[name=searchAgreementVersion]").on('keypress', function (e) {
                if (e.which !== 8 && e.which !== 9 && (e.which < 48 || e.which > 57)) {
                    e.preventDefault();
                    return false;
                }
            })
                .on('paste', function (e) {
                    e.preventDefault();
                    const pastedData = (e.originalEvent || e).clipboardData.getData('text/plain');
                    if (!/^\d*$/.test(pastedData)) {
                        return false;
                    }
                    $(this).val(pastedData.replace(/[^\d]/g, ''));
                });

            $("#btn_search").click(function () {
                var postData = getSearchForJqgrid("cmd", isUnMasked ? "UNMASK" : "LIST");
                if (isUnMasked) {
                    postData.reason = unmaskReason;
                }
                $("#grid").setGridParam({url: url, postData: postData, page: 1}).trigger("reloadGrid");
            });

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


            $("#btn_unmask").click(function () {
                var reason = prompt("마스킹 해제 사유를 입력해 주세요");

                if (reason != null && reason.trim() !== '') {
                    const postData = getSearchForJqgrid("cmd", "UNMASK");
                    postData.reason = reason;

                    $.ajax({
                        type: "POST",
                        url: url,
                        dataType: "json",
                        data: postData,
                        success: function (response) {
                            isUnMasked = true;
                            unmaskReason = reason;

                            buttonControl();
                            $('#btn_unmask').prop('disabled', true);

                            const reloadData = getSearchForJqgrid("cmd", "UNMASK");
                            reloadData.reason = reason;
                            $("#grid").setGridParam({
                                postData: reloadData
                            }).trigger("reloadGrid");
                        },
                        error: function (e) {
                            alert("마스킹 해제 중 오류가 발생했습니다. " + e.responseText);
                        }
                    });
                } else if (reason !== null) {
                    alert("마스킹 해제 사유를 입력해 주세요");
                }
            });

            // select 박스 변경시 자동 검색
            $("select[name=searchTermsType]").change(function () {
                $("#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_unmask" level="W" status="DETAIL"><i class="material-icons">lock_open</i>
                마스킹해제
            </button>
            <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">약관동의 이력</div>
        <form id="ajaxForm" onsubmit="return false;">
            <table class="search_condition" cellspacing=0;>
                <tbody>
                <tr>
                    <th style="width:10%;">약관종류</th>
                    <td style="width:15%;">
                        <div class="select-style">
                            <select type="text" name="searchTermsType" value="${param.searchTermsType}"></select>
                        </div>
                    </td>
                    <th style="width:10%;">버전</th>
                    <td style="width:15%;">
                        <input type="text" name="searchAgreementVersion" style="width:200px;"/>
                    </td>
                    <th style="width:10%;">아이디</th>
                    <td style="width:15%;">
                        <input type="text" name="searchLoginId" style="width:200px;"/>
                    </td>
                    <th style="width:10%;">이름</th>
                    <td style="width:15%;">
                        <input type="text" name="searchUserName" style="width:200px;"/>
                    </td>
                </tr>
                </tbody>
            </table>
        </form>
        <table id="grid"></table>
        <div id="pager"></div>

    </div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>