<%@ 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" %>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ page import="com.eactive.eai.common.util.SystemUtil"%>
<%
   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>

var url      = '<c:url value="/common/acl/deploy/deployResourceSearchMan.json" />';
var url_view = '<c:url value="/common/acl/deploy/deployResourceSearchMan.view" />';

$(document).ready(function() {
   
   var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
   
   $('#sourceGrid').jqGrid({
      datatype:"json",
      mtype: 'POST',
      url: url,
      postData : gridPostData,
      colNames:[
                '<%= localeMessage.getString("deployResourceSearchMan.resourceApp") %>'
             ,   '<%= localeMessage.getString("deployResourceSearchMan.resourceType") %>'
                ,  '<%= localeMessage.getString("deployResourceSearchMan.resourceName") %>'
             ,  '<%= localeMessage.getString("deployResourceSearchMan.resourceDesc") %>'
             ,  '<%= localeMessage.getString("deployResourceSearchMan.resourcePath") %>'
             ,  '<%= localeMessage.getString("deployResourceSearchMan.interfaceName") %>'
             ,   '<%= localeMessage.getString("deployResourceSearchMan.interfaceDesc") %>'
             ,  '<%= localeMessage.getString("deployResourceSearchMan.userId") %>'
             ,  'downloadable'
             ],
      colModel:[
               { name : 'resourceApp'  , align:'center', width: 80}
            ,   { name : 'resourceType' , align:'center', width: 100}
            ,   { name : 'resourceName' , align:'left', width: 250}
            ,   { name : 'resourceDesc' , align:'left', width: 250}
            ,   { name : 'resourcePath' , hidden: true }
            ,   { name : 'interfaceName', align:'center' }
            ,   { name : 'interfaceDesc', hidden: true }
            ,   { name : 'userId' , align:'center', width: 100}
            ,   { name : 'downloadable' , hidden: true},
             ],
        jsonReader: {
             repeatitems:false
        },             
      rowNum : 10000,
       height: "650",
      viewrecords: true,
      multiselect: true,
      gridComplete:function (d){
         var colModel = $(this).getGridParam("colModel");
         for(var i = 0 ; i< colModel.length; i++){
            $(this).setColProp(colModel[i].name, {sortable : false});   //그리드 헤더 화살표 삭제(정렬X)      
         }
      },
      beforeRequest: function() {
         $("div.ui-jqgrid-hbox table thead tr th input[type='checkbox']").remove();
      },
      loadComplete:function (d){
         
         var ids = $(this).jqGrid('getDataIDs');
           for (var i = 0; i < ids.length; i++) {
               var rowId = ids[i];
               var rowData = $(this).jqGrid('getRowData', rowId);
               if (rowData.downloadable === 'false') {
                   $("#" + rowId).find("input[type=checkbox]").attr("disabled", true);
               }
           }
           
           $("#sourceGrid").tuiTableRowSpan("6");
           
           // rowspan 된 영역 클릭시 해당 record 모두 선택되도록
           $('#sourceGrid').on('click', 'tr.jqgrow td:nth-child(7)', function() {
              
               var rowId = $(this).closest('tr').attr('id');
               var rowspan = $(this).attr('rowspan') || 1;
               rowspan = parseInt(rowspan, 10);

               // 현재 클릭된 셀부터 rowspan 개수만큼의 행 선택
               var currentRow = $(this).closest('tr');
               for (var i = 0; i < rowspan; i++) {
                   var currentRowId = currentRow.attr('id');
                   if (!currentRow.find('input[type=checkbox]').is(':disabled') && rowId != currentRowId) {
                       // 체크박스가 disabled되지 않았다면 해당 행 선택
                       $("#sourceGrid").jqGrid('setSelection', currentRowId, true);
                   }
                   currentRow = currentRow.next();
               }
           });
           
      },
        loadError: function (jqXHR, textStatus, errorThrown) {
           var location ='<%=request.getContextPath()%>/';
           comloadError(jqXHR, textStatus, errorThrown ,location);
       },
       beforeSelectRow: function (rowid, e) {
          var cb = $('#jqg_sourceGrid_' + rowid);
          if (cb.is(':disabled')) {
             return false;
         }
        },
        onCellSelect: function (rowid, iCol, cellcontent, e) {
           
        }

   });
   
   jQuery("#sourceGrid").jqGrid( 'setGridWidth', $("#sourceGrid_wrapper").width());
   
   $('#targetGrid').jqGrid({
      datatype:"json",
      colNames:[
              '<%= localeMessage.getString("deployResourceSearchMan.resourceApp") %>',
              '<%= localeMessage.getString("deployResourceSearchMan.resourceType") %>',
              '<%= localeMessage.getString("deployResourceSearchMan.resourceName") %>',
              '<%= localeMessage.getString("deployResourceSearchMan.resourcePath") %>',
              '<%= localeMessage.getString("deployResourceSearchMan.deleteBtn") %>'
                  ],
      colModel:[ 
            { name : 'resourceApp',      hidden: true},
            { name : 'resourceType',      align:'center', width: 80},
            { name : 'resourceName',      align:'left'  , width: 150},
            { name : 'resourcePath',    align:'left'  , width: 150},
            { name : 'deleteBtn',       align:'center', width: 50, 
               formatter: (cellvalue, options, rowObject) => {
                  var rowId = options["rowId"];
                  return "<img id='btn_pop_delete' name='img_"+rowId+"' src=<c:url value='/images/bt/pop_delete.gif' /> />";
               },
               unformat: (cellvalue, options, rowObject) => {
                  return "";
               }
            }
            ],
        jsonReader: {
             repeatitems:false
        },                
      rowNum : 10000,
       height: 650,
      viewrecords: true,
      gridComplete:function (d){
         var colModel = $(this).getGridParam("colModel");
         for(var i = 0 ; i< colModel.length; i++){
            $(this).setColProp(colModel[i].name, {sortable : false});   //그리드 헤더 화살표 삭제(정렬X)      
         }
      
      },
      loadComplete : function (data) {
         
        },
        loadBeforeSend : function (xhr,settings){
         if(this.p.url ==null || this.p.url == ""){
            this.p.loadBeforeSend = null;
            return false;
         }
      },
        loadError: function (jqXHR, textStatus, errorThrown) {
           var location ='<%=request.getContextPath()%>/';
           comloadError(jqXHR, textStatus, errorThrown ,location);
       },
        onSelectRow : function(rowid, status){
           
        },
      onCellSelect: function (rowid, iCol, cellcontent, e) {
         
        }
   });
   
   jQuery("#targetGrid").jqGrid( 'setGridWidth', $("#targetGrid_wrapper").width());
   
   $("#btn_search").click(function(){
      
      var postData = getSearchForJqgrid("cmd","LIST");
      $("#sourceGrid").setGridParam({ postData: postData ,page : "1"  }).trigger("reloadGrid");
      
      $('#sourceGrid').on('click', 'tr.jqgrow td:nth-child(7)', function() {
           
            var rowId = $(this).closest('tr').attr('id');
            var rowspan = $(this).attr('rowspan') || 1;
            rowspan = parseInt(rowspan, 10);

            // 현재 클릭된 셀부터 rowspan 개수만큼의 행 선택
            var currentRow = $(this).closest('tr');
            for (var i = 0; i < rowspan; i++) {
                var currentRowId = currentRow.attr('id');
                if (!currentRow.find('input[type=checkbox]').is(':disabled') && rowId != currentRowId) {
                    // 체크박스가 disabled되지 않았다면 해당 행 선택
                    $("#sourceGrid").jqGrid('setSelection', currentRowId, true);
                }
                currentRow = currentRow.next();
            }
        });

   });
   
   $("input[name^=search]").keydown(function(key){
      if (key.keyCode == 13){
         $("#btn_search").click();
      }
   });
   
   $("#addBtn").click(function(){
       var selectedRows = $("#sourceGrid").jqGrid('getGridParam', 'selarrrow'); // SourceGrid에서 선택된 행의 ID 배열

       for(var i = 0; i < selectedRows.length; i++) {
           var rowData = $("#sourceGrid").jqGrid('getRowData', selectedRows[i]);
           var key = rowData.resourceName;

           // TargetGrid에서 동일한 키를 가진 행이 있는지 확인
           var isDuplicate = false;
           var targetGridData = $("#targetGrid").jqGrid('getRowData');
           for (var j = 0; j < targetGridData.length; j++) {
               if (targetGridData[j].resourceName === key) {
                   isDuplicate = true;
                   break;
               }
           }

           // 중복되지 않은 경우에만 TargetGrid에 행 추가
           if (!isDuplicate) {
               $("#targetGrid").jqGrid('addRowData', rowData.id, rowData);
           } else {
               //alert('중복된 항목이 존재합니다: ' + key);
           }
       }
       
       var ids = $('#targetGrid').jqGrid('getDataIDs');
        for (var i = 0; i < ids.length; i++) {
            var rowid = ids[i];
            $("img[name=img_" + rowid + "]").click(function() {
            var name = $(this).attr("name");
            var rowId = name.split("_")[1];
            $('#targetGrid').jqGrid('delRowData', rowId);
         });
        }
       
   });
   
   $("#btn_download").click(function() {
      
      var targetGridData = $("#targetGrid").jqGrid('getRowData');
      
      const postData = new FormData();
      postData.append('cmd', 'DOWNLOAD_RESOURCES_ZIP');
      postData.append('gridData', JSON.stringify(targetGridData));
      postData.append('serviceType', sessionStorage["serviceType"]);
      
      fetch(url, {
          method: 'POST',
//          headers: {
//              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
//          },
          body: postData
      })
      .then(response => {
           const contentDisposition = response.headers.get('Content-Disposition');
           let filename = 'noname.txt';
           if (contentDisposition) {
               const filenameMatch = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
               if (filenameMatch && filenameMatch[1]) {
                   filename = filenameMatch[1].replace(/['"]/g, '');
               }
           }
           
           return response.blob().then(blob => {
               return { blob, filename };
           });
       })
       .then(({ blob, filename }) => {
           const url = window.URL.createObjectURL(blob);
           const a = document.createElement('a');
           a.href = url;
           a.download = filename;
           document.body.append(a);
           a.click();
           a.remove();
           window.URL.revokeObjectURL(url);
       })
       .catch(error => console.error('Download error:', error));
      
   });
   
   buttonControl();
   
   $(window).on('resize.jqGrid', function () {
         jQuery("#sourceGrid").jqGrid( 'setGridWidth', $("#sourceGrid_wrapper").width());
         jQuery("#targetGrid").jqGrid( 'setGridWidth', $("#targetGrid_wrapper").width());
      });
   
});

</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"><%= localeMessage.getString("deployResourceSearchMan.title") %></div>
            
            <table class="search_condition" cellspacing=0;>
               <tbody>
                  <tr>
                     <th style="width:180px;"><%= localeMessage.getString("deployResourceSearchMan.resourceApp") %></th>
                     <td><input type="text" name="searchResourceApp" value="${param.searchResourceApp}"></td>
                     
                     <th style="width:180px;"><%= localeMessage.getString("deployResourceSearchMan.resourceName") %></th>
                     <td><input type="text" name="searchResourceName" value="${param.searchResourceName}"></td>
                     
                     <th style="width:180px;"><%= localeMessage.getString("deployResourceSearchMan.resourceDesc") %></th>
                     <td><input type="text" name="searchResourceDesc" value="${param.searchResourceDesc}"></td>
                     
                  </tr>
                  <tr >
                     <th style="width:180px;"><%= localeMessage.getString("deployResourceSearchMan.resourceType") %></th>
                     <td>
                        <div class="select-style">
                           <select name="searchResourceType" value="${param.searchResourceType}">
                              <option value="">ALL</option>
                              <option value="interface">interface</option>
                              <option value="transform">transform</option>
                              <option value="layout">layout</option>
                           </select>
                        </div>
                     </td>
                     
                     <th style="width:180px;"><%= localeMessage.getString("deployResourceSearchMan.interfaceName") %></th>
                     <td><input type="text" name="searchInterfaceName" value="${param.searchInterfaceName}"></td>
                     
                     <th style="width:180px;"><%= localeMessage.getString("deployResourceSearchMan.interfaceDesc") %></th>
                     <td><input type="text" name="searchInterfaceDesc" value="${param.searchInterfaceDesc}"></td>
                     
                  </tr>
               </tbody>
            </table>
            
            <div style="text-align: right; margin-bottom: 15px;">
               <button type="button" class="cssbtn" id="btn_download" level="W" ><i class="material-icons">download</i> Download</button> 
            </div>
            
            <div style="display: flex; justify-content: space-between;">
               <div id="sourceGrid_wrapper" style="width: 65%;">
                  <table id="sourceGrid" ></table>
               </div>
               <div style="width: 5%; text-align: center;">
                  <button type="button" class="cssbtn" id="addBtn" level="W" style="min-width: 50px; margin-bottom: 2px; margin-top: 90px; display: inline-block;">
                         <i class="material-icons">keyboard_double_arrow_right</i>
                      </button>
               </div>
               <div id="targetGrid_wrapper" style="width: 30%;">
                  <table id="targetGrid" ></table>
               </div>
            </div>
            
         </div><!-- end content_middle -->
      </div><!-- end right_box -->
   </body>
</html>