<%@ 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=euc-kr">
<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/transaction/apim/apiInterfaceMan.json"/>';
	var url_view = '<c:url value="/onl/transaction/apim/apiInterfaceMan.view"/>';

	var selectName = "searchEaiBzwkDstcd";	// selectBox Name
	function processSelectedData() {
		var grid = $("#grid");
		var selectedRowIds = grid.jqGrid('getGridParam', 'selarrrow');
		var selectedData = [];

		for(var i = 0; i < selectedRowIds.length; i++) {
			var rowData = grid.jqGrid('getRowData', selectedRowIds[i]);
			selectedData.push({
				bizCode: rowData.eaiBzwkDstcd, // CLINET
				apiId: rowData.eaiSvcName,
				apiDesc: rowData.eaiSvcDesc, // SCOPE-API  
				APIFULLPATH: rowData.apiFullPath,
				BZWKSVCKEYNAME: rowData.bzwksvckeyname
			});
		}

		if(selectedData.length === 0) {
			alert("선택된 항목이 없습니다.");
			return;
		}

		alert("선택한 " + selectedData.length + "건의 API를 추가합니다.");
		window.returnValue = selectedData.length === 1 ? selectedData[0] : selectedData;
		window.close();
	}

	function updateSelectionInfo(gridId) {
		var grid = $(gridId || "#grid");
		var selectedRows = grid.jqGrid('getGridParam', 'selarrrow');
		$("#selected-count").text("총: " + selectedRows.length + " 건");
	}

	function init( callback) {
		$.ajax({
			type : "POST",
			url:url,
			dataType:"json",
			data:{cmd: 'LIST_COMBO'},
			success:function(json){
				new makeOptions("BIZCODE","BIZNAME").setObj($("select[name=searchEaiBzwkDstcd]")).setNoValueInclude(true).setNoValue("","전체").setData(json.bizList).setFormat(codeName3OptionFormat).rendering();

				setSearchable(selectName);	// 콤보에 searchable 설정

				if (typeof callback === 'function') {
					callback();
				}
			},
			error:function(e){
				alert(e.responseText);
			}
		});

	}
	function detail(){
		var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
		$("#grid").setGridParam({ url:url,postData: postData }).trigger("reloadGrid");
	}

	function search(){
		var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
		$("#grid").setGridParam({ url:url,postData: postData ,page:1 }).trigger("reloadGrid");
	}
	function ioFormatter(cellvalue,options,rowObject){
		var serviceType = sessionStorage["serviceType"];
		if(cellvalue == "I"){
			return "타발";
		}else if(cellvalue =="O"){
			return "당발";
		}
	}
	function adapterNameShortFormatter(cellvalue,options,rowObject){
		if(cellvalue == null || cellvalue == '')
			return ''
		return cellvalue.substring(1, 4);
	}

	function list(){
		detail()
		var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
		// gridPostData.searchApiEnableYn = 'Y';
		var urlParams = new URLSearchParams(window.location.search);
		var selectedApiIds = urlParams.get("selectedApiIds");
		$('#grid').jqGrid({
			datatype : "json",
			mtype : 'POST',
			url : url,
			postData : gridPostData,
			colNames : [ '업무구분',
			             '<%= localeMessage.getString("eaiMessage.eaiSvcName")%>',
			             '<%= localeMessage.getString("eaiMessage.eaiSvcDesc")%>',
				         'API FULL PATH',
				         '업무서비스명',
			             '요청',
			             '응답',
			             '작성자',
			             '가상응답여부',
				         'SyncAsyncType',
			              ],
			colModel : [ { name : 'eaiBzwkDstcd'            , align : 'center' , width:'40', sortable:false},
			             { name : 'eaiSvcName'              , align : 'left'   , width:'100'},
			             { name : 'eaiSvcDesc'              , align : 'left'   },
				         { name : 'apiFullPath'              , align : 'left'   , width:'100'},
				         { name : 'bzwksvckeyname'              , align : 'left'   , width:'100', hidden: true},
			             { name : 'fromAdapter'                , align : 'center' , width:'40', formatter:adapterNameShortFormatter },
			             { name : 'toAdapter'                  , align : 'center' , width:'40', formatter:adapterNameShortFormatter },
			             { name : 'author'                , align : 'center' , width:'60' },
			             { name : 'simYn'                   , align : 'center' , width:'40' },
				         { name : 'syncAsyncType'           , align : 'center' , width:'40', hidden: true},
						],
			jsonReader : {
				repeatitems : false
			},
			pager : $('#pager'),
			page : '${param.page}',
			rowNum : '${rmsDefaultRowNum}',
			autoheight : true,
			height : $("#container").height(),
			autowidth : true,
			viewrecords : true,
			multiselect: false,
			multiboxonly: false,
			rowList : eval('[${rmsDefaultRowList}]'),
			loadComplete:function (d){
				var $grid = $(this);
				if(selectedApiIds) {
					const selectedIds = selectedApiIds.split(',');
					$.each($grid.getDataIDs(), function(_, id) {
						var rowData = $grid.getRowData(id);
						if(selectedIds.includes(rowData.eaiSvcName)) {
							$grid.jqGrid('setSelection', id, true);
						}
					});
				}
				var colModel = $(this).getGridParam("colModel");
				for(var i = 0 ; i< colModel.length; i++){
					$(this).setColProp(colModel[i].name, {sortable : false});
				}
				updateSelectionInfo("#grid");
			},
			onSelectRow: function(rowid, status, e) {
				updateSelectionInfo("#grid");
			},
			onSelectAll: function(rowids, status) {
				updateSelectionInfo("#grid");
			},
			ondblClickRow : function(rowId) {
				const rowData = $(this).getRowData(rowId);
				const returnValue = {
					bizCode: rowData.eaiBzwkDstcd,
					apiId: rowData.eaiSvcName,
					apiDesc: rowData.eaiSvcDesc
				};
				//alert("선택한 API를 추가합니다.\nAPI ID: " + rowData.eaiSvcName);
				window.returnValue = returnValue;
				window.close();
			}
		});

	}

	$(document).ready(function() {

		init(list);

		resizeJqGridWidth('grid','content_middle','1000');

		// 업무구분명 선택 시 자동 검색
		$("select[name=searchEaiBzwkDstcd]").change(function() {
			search();
		});
		$("#btn_search").click(function(){
			search();
		});
		$("input[name^=search]").keydown(function(key){
			if (key.keyCode == 13){
				$("#btn_search").click();
			}
		});

		buttonControl();

		$("#btn_select").click(function(){
			processSelectedData();
		});

		$("#btn_close").click(function () {
			window.close();
		});
	});

</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_select" level="R" ><i class="material-icons">check</i> <%= localeMessage.getString("button.check") %></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" id="title" >${rmsMenuName}</div>
				<!-- 선택 정보 표시 영역 추가 -->
				<div style="margin-bottom: 5px;">
					<span id="selected-count" style="color: #666; font-size: 12px;"></span>
				</div>
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th style="width:180px;">업무구분명</th>
							<td>
								<select name="searchEaiBzwkDstcd" value="${param.searchEaiBzwkDstcd}">
								</select>
							</td>
							<th style="width:180px;"><%= localeMessage.getString("eaiMessage.eaiSvcName")%></th>
							<td>
								<input type="text" name="searchEaiSvcName" value="${param.searchEaiSvcName}">
							</td>
						</tr>
						<tr>
							<th style="width:180px;"><%= localeMessage.getString("eaiMessage.eaiSvcDesc")%></th>
							<td>
								<input type="text" name="searchEaiSvcDesc" value="${param.searchEaiSvcDesc}">
							</td>
							<th style="width:180px;">API FULL PATH</th>
			                <td>
			                    <input type="text" name="searchApiFullPath" value="${param.searchApiFullPath}">
			                </td>
						</tr>
					</tbody>
				</table>
				<table id="grid" ></table>
				<div id="pager"></div>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->
	</body>
</html>

