<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ 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_custom.jsp"/>
    <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/portalorg/portalOrgMan.json" />';

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

        $(document).ready(function() {
            var urlParams = new URLSearchParams(window.location.search);
            var selectedOrgIds = urlParams.get("selectedOrgIds");

            if (selectedOrgIds) {
                selectedOrgIds = selectedOrgIds.split(','); // 콤마로 구분된 ID들을 배열로 변환
            } else {
                selectedOrgIds = [];
            }

            $('#grid').jqGrid({
                datatype: "json",
                mtype: 'POST',
                url: url,
                postData: getSearchForJqgrid("cmd", "POPUP_LIST"),
                colNames: ['법인 ID', '법인명', '제휴기관코드', '법인 상태'],
                colModel: [
                    {name: 'id', hidden: true},
                    {name: 'orgName', align: 'center', width: "180"},
                    {name: 'orgCode', align: 'center', width: "100"},
                    {name: 'orgStatus', align: 'center', width: "80", formatter: function(cellvalue) {
                            switch(cellvalue) {
                                case 'READY': return '준비';
                                case 'ACTIVE': return '정상';
                                case 'REMOVED': return '탈퇴';
                                case 'INACTIVE': return '휴면';
                                default: return cellvalue;
                            }
                        }}
                ],
                jsonReader: {
                    repeatitems: false
                },
                pager: $('#pager'),
                page: '${param.page}',
                rowNum: '${rmsDefaultRowNum}',
                autoheight: true,
                height: 'auto',
                width: 410,
                autowidth: false,
                viewrecords: true,
                shrinkToFit: false,
                multiselect: true,
                multiboxonly: false,
                loadComplete: function(data) {
                    var $grid = $(this);
                    $.each($grid.getDataIDs(), function(_, id) {
                        var rowData = $grid.getRowData(id);
                        if ($.inArray(rowData.id, selectedOrgIds) !== -1) {
                            $grid.jqGrid('setSelection', id, true);
                        }
                    });
                }
            });

            $("#btn_search").click(search);

            $("#btn_save").click(function() {
                var selectedRows = $('#grid').getGridParam('selarrrow');

                // 7개 초과 선택 체크
                if (selectedRows.length > 7) {
                    alert('최대 7개의 법인만 선택할 수 있습니다.');
                    return;
                }

                var selectedOrgs = [];
                if (selectedRows.length > 0) {
                    selectedOrgs = selectedRows.map(function(rowid) {
                        var rowData = $('#grid').getRowData(rowid);
                        return {
                            id: rowData.id,
                            orgName: rowData.orgName
                        };
                    });
                }
                // 부모 창의 selectOrg 함수 호출
                if (window.parent && typeof window.parent.selectOrg === "function") {
                    window.parent.selectOrg(selectedOrgs);
                    window.close();
                }
            });

            $("#btn_close").click(function () {
                window.close();
            });
            
            // 검색어 입력 후 엔터 키 처리
            $("input[name=searchOrgName]").keydown(function(key) {
                if (key.keyCode == 13) {
                    search();
                }
            });
        });
    </script>
</head>
<body>
<div class="popup_box">
    <div class="search_wrap">
        <button type="button" class="cssbtn" id="btn_save" level="W">
            <i class="material-icons">save</i> <%= localeMessage.getString("button.save") %>
        </button>
        <button type="button" class="cssbtn" id="btn_search" level="R">
            <i class="material-icons">search</i> <%= localeMessage.getString("button.search") %>
        </button>
        <button type="button" class="cssbtn" id="btn_close" level="R" status="DETAIL"><i
                class="material-icons">close</i> <%= localeMessage.getString("button.close") %>
        </button>
    </div>
    <div class="title"></div>
   <%-- <div class="title">공개 법인 선택</div>--%>
    <table class="search_condition" cellspacing="0">
        <tr>
            <th style="width:50px;">법인명</th>
            <td>
                <input type="text" name="searchOrgName" value="${param.searchOrgName}">
            </td>
        </tr>
    </table>
    <table id="grid"></table>
    <div id="pager"></div>
</div>
</body>
</html>