<%@ 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/portalmain/portalMainMan.json"/>';
      var url_view = '<c:url value="/onl/apim/portalmain/portalMainMan.view"/>';
      var isDetail = false;

      function selectService(selectedServices) {
        if(!selectedServices) {
            return;
        }

        // 먼저 기존 그리드의 모든 데이터를 지웁니다
        $("#serviceGrid").jqGrid('clearGridData');

        // 선택된 서비스들만 다시 추가합니다
        selectedServices.forEach(function(service) {
          $("#serviceGrid").jqGrid('addRowData', service.id, service, "last");
        });
      }

      function componentRenderingInit() {
        $('#serviceGrid').jqGrid({
          datatype: "json",
          colNames: ['서비스 ID',
            '서비스명',
            '서비스 설명'
          ],
          colModel: [
            { name: 'id', align: 'center', width:'100', key:true},
            { name: 'groupName', align: 'left', width:'150'},
            { name: 'groupDesc', align: 'left'}
          ],
          rowNum: 10000,
          autoheight: true,
          height: "160",
          autowidth: true,
          multiselect: true,
          viewrecords: true
        });
      }

      function detail() {
        $.ajax({
          type: "POST",
          url: url,
          dataType: "json",
          data: {cmd: 'DETAIL'},
          success: function(json) {
            var serviceList = json.services || [];
            var keywordList = json.searchTags || '';

              $("#serviceGrid").jqGrid('clearGridData');

              // 각 서비스의 고유 ID를 행 ID로 사용
              serviceList.forEach(function(service) {
                  $("#serviceGrid").jqGrid('addRowData', service.id, service);
              });

            // 키워드 리스트를 콤마로 구분된 문자열로 변환하여 input에 설정
            $("#keywordList").val(keywordList);
          },
          error: function(e) {
            alert(e.responseText);
          }
        });
      }

      $(document).ready(function() {
        componentRenderingInit();
        detail();

        $("#btn_save").click(function() {
          var serviceData = $("#serviceGrid").jqGrid('getRowData');
          var keywordString = $("#keywordList").val();

          var serviceIds = [];
          for(var i=0; i<serviceData.length; i++) {
            serviceIds.push({id: serviceData[i].id});
          }

          let postData = [];
          postData.push({name: "services", value: JSON.stringify(serviceIds)});
          postData.push({name: "searchTags", value: keywordString});
          postData.push({name: "cmd", value: "INSERT"});

          $.ajax({
            type: "POST",
            url: url,
            data: postData,
            success: function(args) {
              alert("저장되었습니다.");
              detail();
            },
            error: function(e) {
              alert(e.responseText);
            }
          });
        });

          $("#btn_add_service").click(function() {
            // 현재 선택된 서비스 목록 가져오기
            var currentServices = $("#serviceGrid").jqGrid('getRowData');
            var selectedIds = currentServices.map(function(service) {
                return service.id;
            }).join(',');

            const popupUrl = url_view + "?cmd=POPUP&selectedIds=" + encodeURIComponent(selectedIds);

            const args = {
              title: 'API 그룹 선택',
              callback: function(selectedData) {
                if(selectedData) {
                  $("#serviceGrid").jqGrid('clearGridData');
                  selectedData.forEach(function(service) {
                    $("#serviceGrid").jqGrid('addRowData', service.id, service, "last");
                  });
                }
              }
            };
            showModal(popupUrl, args, 1280, 860);
          });

        $("#btn_delete_service").click(function() {
          var selectedIds = $("#serviceGrid").jqGrid('getGridParam', 'selarrrow');
          if (selectedIds.length > 0) {
            // 선택된 행의 ID를 복사한 배열을 사용
            var idsToDelete = selectedIds.slice();

            for (var i = 0; i < idsToDelete.length; i++) {
              $("#serviceGrid").jqGrid('delRowData', idsToDelete[i]); // 선택된 각 행을 삭제
            }
          } else {
            alert("Please select at least one row to delete.");
          }
        });
      });
    </script>
</head>
<body>
<div class="right_box">
    <div class="content_top">
        <ul class="path">
            <li><a href="#">${rmsMenuPath}</a></li>
        </ul>
    </div>
    <div class="content_middle">
        <div class="search_wrap">
            <button type="button" class="cssbtn" id="btn_save" level="W">
                <i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %>
            </button>
        </div>
        <div class="title">포털 메인 관리</div>
        <div style="margin-top:15px;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px">
                <div class="table_row_title" style="margin-bottom: 0px">메인 서비스 목록</div>
                <div style="text-align: end;">
                    <button type="button" class="cssbtn" id="btn_delete_service" level="W">
                        <i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
                    </button>
                    <button type="button" class="cssbtn" id="btn_add_service" level="W">
                        <i class="material-icons">add</i> <%= localeMessage.getString("button.add") %>
                    </button>
                </div>
            </div>
            <table id="serviceGrid"></table>
        </div>

        <div style="margin-top:15px;">
            <div class="table_row_title">메인 키워드 목록</div>
            <table class="table_row" cellspacing="0">
                <tr>
                    <th style="width:180px;">키워드</th>
                    <td>
                        <input type="text" id="keywordList" style="width:100%" placeholder="쉼표(,)로 구분하여 입력">
                        <div class="help-text" style="color:#666; font-size:12px; margin-top:5px;">
                            예시: #인증, #대출, #예금
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>
</body>
</html>
