<%@ 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"%>
<%@ page import="com.eactive.eai.rms.common.context.MonitoringContext"%>
<%@ page import="com.eactive.eai.rms.common.util.CommonUtil"%>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");

	String tranTypeCode = "TRAN_TYPE";
	String detailCmd = "DETAIL"; 
	String rmsMenuAuth = (String)request.getAttribute("rmsMenuAuth"); 
	if( "R".equals(rmsMenuAuth) ) {
		tranTypeCode = "TRAN_TYPE_DEV";
		detailCmd = "DETAILDEV"; 
	}
	
	MonitoringContext monitoringContext = (MonitoringContext)CommonUtil.getBean(request, "monitoringContext");
	String deployYnStr = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DEPLOY_YN_BY_RMS, "N");
	boolean deployYn = "Y".equalsIgnoreCase(deployYnStr);
	String adminOnlyYnStr = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DEPLOY_YN_BY_ADMIN_ONLY, "Y");
	boolean adminOnly = "Y".equalsIgnoreCase(adminOnlyYnStr);
%>
<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/admin/service/eaiMsgMan.json" />';
var url_view = '<c:url value="/onl/admin/service/eaiMsgMan.view" />';
var url_excel= '<c:url value="/onl/admin/service/eaiMsgMan.excel"/>';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;
var stageSvr	= <%=SystemUtil.isStagingServer()%>;
var adminOnly   = <%=adminOnly%>;
var svrInst = new Array();
function init(callback){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_INIT', codeGroupArr : 'SVC_SAME_TIME_TYPE,<%= tranTypeCode %>'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=searchSvcMotivUsedStcd]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.list[0].SVC_SAME_TIME_TYPE).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchPsvintfacdsticName]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.list[0].SVC_SAME_TIME_TYPE).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchFlowControl]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.listFlowControl).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchTranType]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.list[0].<%= tranTypeCode %>).rendering();
			svrInst = json.listInoutType;
			putSelectFromParam();
			if(typeof callback === 'function') {
				callback();
    		}
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}
function fomatter(){
	
}
function formatter (cellvalue, options, rowObject){
	for(var i=0; i<svrInst.length; i++){
		if(cellvalue==svrInst[i].CODE){
			return svrInst[i].NAME;
		}
	}
}	
function list(_page){
	var page="${param.page}";
	if(_page) page=_page
	var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
	$("#grid").setGridParam({ postData: postData ,page : page }).trigger("reloadGrid");
}
function detail(){
	var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
	$("#grid").setGridParam({ url:url, postData: postData, datatype:"json" }).trigger("reloadGrid");
} 
$(document).ready(function() {	
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
	
	var auth="${rmsMenuAuth}";
	gridPostData["rmsMenuAuth"]= auth;
	
	init(detail);
	gridPostData["searchSvcMotivUsedStcd"] = '${param.searchSvcMotivUsedStcd}';
	gridPostData["searchPsvintfacdsticName"] = '${param.searchPsvintfacdsticName}';

	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : gridPostData,
		colNames:['<%= localeMessage.getString("eaiMsg.bizCode")%> ',
                  '<%= localeMessage.getString("eaiMessage.eaiSvcName")%> ',
                  '<%= localeMessage.getString("eaiMessage.eaiSvcDesc")%> ',
                  '<%= localeMessage.getString("eaiMessage.svcMotivUsedStcd")%>',
                  '<%= localeMessage.getString("eaiMessage.psvintfacdsticName")%>',
                  '<%= localeMessage.getString("eaiMessage.queueName")%> ',
                  '<%= localeMessage.getString("eaiMessage.flowCtrlRoutName")%> ',
                  '<%= localeMessage.getString("eaiMessage.tranType")%> ',
                  '<%= localeMessage.getString("combo.useYn")%> ',
                  '<%= localeMessage.getString("eaiMessage.sevrDstCd")%>',
                  '<%= localeMessage.getString("eaiMessage.verInfo")%>'
                  ],
		colModel:[
				{ name : 'EAIBZWKDSTCD'     , align:'center'	,sortable:false, width:20  },
				{ name : 'EAISVCNAME'       , align:'left', width:50  },
				{ name : 'EAISVCDESC'       , align:'left'  },
				{ name : 'SVCMOTIVUSEDSTCD', align:'center', width:50  },
				{ name : 'PSVINTFACDSTICNAME', align:'center', width:50  },
				{ name : 'NONMOTIVROUTURINAME' , align:'left', width:90   },
				{ name : 'FLOWCTRLROUTNAME' , align:'center', width:40  },
				{ name : 'TRANTYPE', align:'center', width:30  },
				{ name : 'USEYN', align:'center', width:30,editoptions:{value:"0:<%= localeMessage.getString("combo.usen")%>;1:<%= localeMessage.getString("combo.usey")%>"}, formatter:"select"},
				{ name : 'EAISEVRDSTCD', align:'center', width:30 , formatter:formatter, hidden:true},
				{ name : 'VERINFO', align:'center', width:30 }
				
				],
        jsonReader: {
             repeatitems:false
        },	          
		pager : $('#pager'),
		page : '${param.page}',
		rowNum : '${rmsDefaultRowNum}',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		multiselect: true,
		multiboxonly: false,
		rowList : eval('[${rmsDefaultRowList}]'),
		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 (d){
		},
        loadError: function (jqXHR, textStatus, errorThrown) {
        	
        	var location ='<%=request.getContextPath()%>/';
        	comloadError(jqXHR, textStatus, errorThrown ,location);
        	
    	},		
		ondblClickRow: function(rowId) {
			var rowData = $(this).getRowData(rowId); 
            var url2 = url_view;
			url2 += '?cmd=<%= detailCmd %>';
            url2 += '&page='+$(this).getGridParam("page");
            url2 += '&returnUrl='+getReturnUrl();
            url2 += '&menuId='+'${param.menuId}';
			//검색값
            url2 += '&'+getSearchUrl();
            
            //key값
            url2 += '&eaiSvcName='+rowData['EAISVCNAME'];
            goNav(url2);
        }		
	});
	
	
	resizeJqGridWidth('grid','content_middle','1000');

	$("#btn_search").click(function(){
		list("1");		
	});
	$("#btn_new").click(function(){
		var url2 = url_view;
		url2 += '?cmd=DETAIL';
		url2 += '&page='+$("#grid").getGridParam("page");
		url2 += '&returnUrl='+getReturnUrl();
        url2 += '&menuId='+'${param.menuId}';
		//검색값
		url2 += '&'+getSearchUrl();
		
        goNav(url2);
	});
	//검색값  enter시  조회
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});
	
	$("#btn_initialize").click(function(){
		
		var id = "grid";
		var chkArr = new Array();
		var ids = $("#grid").jqGrid('getDataIDs');
		var chkcnt = 0;
		
		for(var i=0;i<ids.length;i++){
			if($("input:checkbox[id='jqg_"+id+"_"+ids[i]+"']").is(":checked")){
				var rowObject = $("#grid").getRowData(ids[i]);
				chkArr.push(rowObject['EAISVCNAME']);
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			if(confirm("<%= localeMessage.getString("eaiMessage.confirm1")%>")){
				$.ajax({  
					type : "POST",
					url:url,
					dataType:"json",
					data:{cmd: 'INITIALIZES'},
					success:function(json){
						alert(json.message);
					},
					error:function(e){
						alert(e.responseText);
					}
				});	
			}
			return false;
		}else{
			if(confirm("<%= localeMessage.getString("eaiMessage.confirm2")%>")){  
				var postData = [];
				postData.push({ name: "cmd" , value:"LIST_INITIALIZE"});
				postData.push({ name: "chkItems" , value : chkArr});
				$.ajax({  
					type : "POST",
					url:url,
					dataType:"json",
					data:postData,
					success:function(json){
						alert(json.message);
					},
					error:function(e){
						alert(e.responseText);
					}
				});	
			}else{
				return false;
			}
		}
			
		
	});	
	
	$("#btn_excel").click(function(event) {
        event.stopPropagation(); // Do not propagate the event.
        // Create an object that will manage to download the file.
        var target = "excelDown" ; // iframe의 name
        //(url,cmd,gridObj,formObject,fileName,merge)
		gridToExcelSubmit2(url_excel,"LIST_GRID_TO_EXCEL",$("#grid"),$("#ajaxForm"),'EAI Message');
		return false;
	});		

	$('#btn_clone').click(onclickBtnClone);
	
	$("#btn_delete").click(function(){
		var id = "grid";
		var eaiSvcNameArr = new Array();
		var ids = $("#grid").jqGrid('getDataIDs');
		var chkcnt = 0;
		
		for(var i=0;i<ids.length;i++){
			if($("input:checkbox[id='jqg_"+id+"_"+ids[i]+"']").is(":checked")){
				var rowObject = $("#grid").getRowData(ids[i]);
				eaiSvcNameArr.push(rowObject['EAISVCNAME']);
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			alert("<%= localeMessage.getString("eaiMessage.alert16")%>");
			return false;
		}
		
		if(confirm("<%= localeMessage.getString("common.confirmMsg")%>")){  
			var postData = [];
			postData.push({ name: "cmd" , value:"DELETE_LIST"});
			postData.push({ name: "eaiSvcName" , value:eaiSvcNameArr});
			
			$.ajax({
				type : "POST",
				url : url,
				dataType : "json",
				data : postData,
				success : function(json) {
					alert(json.message);
					$("#btn_search").click();
				},
				error : function(e) {
					alert("error"+e.responseText);
				}
			});
		}else{
			return false;
		}
		
		
	});
	
	buttonControl();

 	if(devSvr || stageSvr){
 		if (adminOnly) {
 			setBtnHide(roleString, "admin", "btn_clone");
 		}
	}else{
		$("#btn_clone").hide();
	}
});

function onclickBtnClone() {
	var sel = $('#grid').jqGrid('getGridParam', 'selarrrow');
	if (sel.length == 0) {
		alert('<%= localeMessage.getString("eaiMessage.alert17")%>');
		return;
	}
	var selectedSvcNames = [];
	
	//중단거래
	var stopTran = 0;
	var stopTranSvcNames = [];
	var stopTranFlowControls = [];
	
	$(sel).each(function(index, i) {
		var svcName = $('#grid').getCell(i, 'EAISVCNAME');
		
		//중단거래일경우 confirm Y 일 경우만 복사
		var tranType = $('#grid').getCell(i, 'TRANTYPE');
		if(tranType.indexOf('중단') > -1 || tranType.indexOf('Interrupt') > -1){
			stopTranSvcNames.push(svcName);
			stopTranFlowControls.push(flowControl);
			stopTran++;
		}else{
			selectedSvcNames.push(svcName);
		}
	});
	
	if(stopTran > 0){
		if(confirm('<%= localeMessage.getString("eaiMessage.confirm3")%>')){
			selectedSvcNames = selectedSvcNames.concat(stopTranSvcNames);
		}
	}
	
	var url2 = url_view;
	url2 += "?cmd=POPUP CALENDAR";
	var args = new Object();
	args['selectedSvcName'] = selectedSvcNames.join(',');
	showModal(url2,args,540,280, function(arg){
		var args = null;
	    if(arg == null || arg == undefined ) {
	    	//chrome
	        args = this.dialogArguments;
	        args.returnValue = this.returnValue;
	    } else {
	    	//ie
	        args = arg;
	    }
	    if( !args || !args.returnValue ) return;
	    deployInterfaces(args.returnValue);
	});
}

function deployInterfaces(ret) {
	var params = ret;
	params['cmd'] = 'CLONETOPROD'; 
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:params,
		success:function(json){
			alert(json.message);
			list($("#grid").getGridParam("page"));
		},
		error:function(xhr,status,error){
			if (xhr.responseText != null) {
				try {
					alert(JSON.parse(xhr.responseText).errorMsg);	
				} catch (e) {
					alert(error);
				}
			}
		}
	});	
}

</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">
					<% if (SystemUtil.isDevServer() && deployYn) { %>
						<button type="button" class="cssbtn" id="btn_clone" level="W"><i class="material-icons">move_up</i> <%= localeMessage.getString("button.copyStage") %></button>
					<% } else if (SystemUtil.isStagingServer() && deployYn) { %>
						<button type="button" class="cssbtn" id="btn_clone" level="W"><i class="material-icons">move_up</i> <%= localeMessage.getString("button.copyProd") %></button>
					<% } %>
					<button type="button" class="cssbtn" id="btn_excel" level="W" status="DETAIL"><i class="material-icons">table_view</i> <%= localeMessage.getString("button.excel") %></button>
					<button type="button" class="cssbtn" id="btn_initialize" level="W"><i class="material-icons">restart_alt</i> <%= localeMessage.getString("button.reset") %></button>
					<button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL,NEW"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>
					<button type="button" class="cssbtn" id="btn_new" level="W"><i class="material-icons">add</i> <%= localeMessage.getString("button.new") %></button>
					<button type="button" class="cssbtn" id="btn_search" level="R"><i class="material-icons">search</i> <%= localeMessage.getString("button.search") %></button>
<%--					<img src="<c:url value="/img/btn_clone.png"/>" alt="" id="btn_clone"  level="W" style="height:32px;"/> -->
<%-- 					<img id="btn_excel" src="<c:url value="/img/btn_excel.png"/>" level="W" status="DETAIL"/>					 --%>
<%-- 					<img src="<c:url value="/img/btn_initialize.png"/>" alt="" id="btn_initialize" level="W" /> --%>
<%-- 					<img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W" status="DETAIL,NEW"/>	 --%>
<%-- 					<img src="<c:url value="/img/btn_new.png"/>" alt="" id="btn_new" level="W" /> --%>
<%-- 					<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />		 --%>
				</div>
				<div class="title"><%= localeMessage.getString("eaiMessage.title")%></div>
				<form id="ajaxForm"  onsubmit="return false;">
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th style="width:10%; min-width:90px;"><%= localeMessage.getString("eaiMessage.eaiSvcName")%></th>
							<td>
								<input type="text" name="searchEaiSvcName" value="${param.searchEaiSvcName}">
							</td>
							<th style="width:10%; min-width:120px;"><%= localeMessage.getString("eaiMessage.svcMotivUsedStcd")%></th>
							<td><div class="select-style"><select name="searchSvcMotivUsedStcd" value="${param.searchSvcMotivUsedStcd}"></select></div></td>
							<th style="width:10%; min-width:90px;"><%= localeMessage.getString("eaiMessage.tranType")%></th>
							<td><div class="select-style"><select name="searchTranType" value="${param.searchTranType}"></select></div></td>
							
							<th style="width:10%; min-width:90px;"><%= localeMessage.getString("eaiMessage.eaiSvcDesc")%></th>
							<td>
								<input type="text" name="searchEaiSvcDesc" value="${param.searchEaiSvcDesc}">
							</td>
						</tr>	
						<tr>
							<th><%= localeMessage.getString("eaiMessage.searchBzwkDstCd")%></th>
							<td>
								<input type="text" name="searchEaiBzwkDstcd" value="${param.searchEaiBzwkDstcd}">
							</td>
							<th><%= localeMessage.getString("eaiMessage.psvintfacdsticName")%></th>
							<td><div class="select-style"><select name="searchPsvintfacdsticName" value="${param.searchPsvintfacdsticName}"></select></div></td>
							<th><%= localeMessage.getString("eaiMessage.searchFlowControl")%></th>
							<td><div class="select-style"><select name="searchFlowControl" value="${param.searchFlowControl}"></select></div></td>
							<th><%= localeMessage.getString("eaiMessage.queueName")%></th>
							<td>
								<input type="text" name="searchQueueName" value="${param.searchQueueName}">
							</td>
						</tr>
					</tbody>
				</table>
				</form>
				<table id="grid" ></table>
				<div id="pager"></div>
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

