<%-- portalMainManPopup.jsp --%>
<%@ 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.jsp"/>
    <jsp:include page="/jsp/common/include/script.jsp"/>

    <script language="javascript">
      var url = '<c:url value="/onl/apim/apigroup/apiGroupMan.json"/>';

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

      function list() {
        var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
        $('#grid').jqGrid({
          mtype: 'POST',
          datatype: "json",
          url: url,
          postData: gridPostData,
          colNames: ['서비스 ID', '서비스명', '서비스 설명', '공개여부'],
          colModel: [
            {name: 'id', align: 'center', width: '100'},
            {name: 'groupName', align: 'left', width: '150'},
            {name: 'groupDesc', align: 'left'},
            {
              name: 'displayYn', align: 'center', width: '60', formatter: function(cellvalue) {
                return cellvalue === '1' ? 'Y' : 'N';
              }
            }
          ],
          jsonReader: {
            repeatitems: false
          },
          pager: '#pager',
          rowNum: '${rmsDefaultRowNum}',
          autoheight: true,
          height: $("#container").height(),
          autowidth: true,
          viewrecords: true,
          rowList: eval('[${rmsDefaultRowList}]'),
            multiselect: true,
            loadComplete: function() {
              try {
                // URL에서 selectedIds 파라미터 가져오기
                var urlParams = new URLSearchParams(window.location.search);
                var selectedIds = urlParams.get('selectedIds');

                if(selectedIds) {
                  selectedIds = selectedIds.split(',');
                  var ids = $(this).jqGrid('getDataIDs');

                  ids.forEach(function(id) {
                    var rowData = $(this).jqGrid('getRowData', id);
                    if(selectedIds.includes(rowData.id)) {
                        $(this).jqGrid('setSelection', id, true);
                    }
                  }.bind(this));
                }
              } catch(e) {
                console.error("Failed to sync with parent window:", e);
              }
            },
            ondblClickRow: function(rowId) {
              var rowData = $(this).jqGrid('getRowData', rowId);
              if (window.dialogArguments && window.dialogArguments.callback) {
                window.dialogArguments.callback([rowData]);
              }
              window.close();
            }
        });
      }

      $(document).ready(function() {


        $("#btn_search").click(function() {
          search();
        });

        $("#btn_save").click(function() {
          var selectedRows = $("#grid").jqGrid('getGridParam', 'selarrrow');
          if(selectedRows.length === 0) {
              alert("선택된 서비스가 없습니다.");
              return;
          }

          // 선택된 모든 행의 데이터를 배열로 수집
          var selectedData = selectedRows.map(function(rowId) {
              return $("#grid").jqGrid('getRowData', rowId);
          });

          if(window.dialogArguments && window.dialogArguments.callback) {
              window.dialogArguments.callback(selectedData);
          }
          window.close();
        });

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

        list();

        resizeJqGridWidth('grid', 'content_middle', '1000');
      });
    </script>
</head>
<body>
<div>
    <div class="content_middle" id="content_middle" style="margin-top: 0px">
        <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>
            <button type="button" class="cssbtn" id="btn_save" level="R">
                <i class="material-icons">check</i> <%= localeMessage.getString("button.check") %>
            </button>
        </div>
        <div class="title">API 그룹 선택</div>
        <table class="search_condition" cellspacing="0">
            <tbody>
            <tr>
                <th style="width:180px;">서비스명</th>
                <td>
                    <input type="text" name="searchGroupName">
                </td>
                <th style="width:180px;">서비스 설명</th>
                <td>
                    <input type="text" name="searchGroupDesc">
                </td>
            </tr>
            </tbody>
        </table>
        <table id="grid"></table>
        <div id="pager"></div>
    </div>
</div>
</body>
</html>
