<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ 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 language="javascript" >

var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;
var prdSvr		= <%=SystemUtil.isProdServer()%>;
var stgSvr		= <%=SystemUtil.isStagingServer()%>;
var svrType		= '';

function list(){
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: '<c:url value="/bap/admin/work/systemIDMan.json" />',
		postData : gridPostData,
		colNames:[
				  '시스템ID',
				  '시스템명',
              '업무구분코드',
                  '업무구분명',
                  '대외기관코드',
                  '대외기관명',
                  'NDM노드명'
                  ],
		colModel:[
				{ name : 'SYSTEMID'           	, align:'left'	,sortable:false},	
				{ name : 'SYSTEMNAME'        	, align:'left'  },
				{ name : 'BJOBBZWKDSTCD'        , align:'left'  },
				{ name : 'BJOBBZWKNAME'         , align:'left'  },
				{ name : 'OSIDINSTIDSTCD'       , align:'left'  },
				{ name : 'OSIDINSTINAME'        , align:'left'	},
				{ name : 'RMTNODENAME'        	, align:'center'} 
				],
        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)		
			}
		},			
		ondblClickRow: function(rowId) {
			var rowData = $(this).getRowData(rowId); 
            var systemId = rowData['SYSTEMID'].trim();
            var url = '<c:url value="/bap/admin/work/systemIDMan.view" />';
            url = url + '?cmd=DETAIL';
            url = url + '&page='+$(this).getGridParam("page");
            url = url + '&menuId='+'${param.menuId}';
	    	url = url + '&returnUrl='+getReturnUrl();
            url = url + '&systemId='+systemId;
            url = url + '&'+getSearchUrl();
		    //검색값
            goNav(url);
        }
	});
}

$(document).ready(function() {	

	if(devSvr) {
		svrType = "stg";
	} else if (stgSvr){
		svrType = "prod";
	} else if (!prdSvr){
		svrType = "dev";
	}
	
	resizeJqGridWidth('grid','title','1000');
	var url ='<c:url value="/bap/admin/work/systemIDMan.json" />';

	$("#btn_search").click(function(){
		var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
		$("#grid").setGridParam({url:url, postData: postData,page:"1" }).trigger("reloadGrid");
	});
	$("#btn_new").click(function(){
		var url = '<c:url value="/bap/admin/work/systemIDMan.view"/>';
		url = url + '?cmd=DETAIL';
		url = url + '&page='+$("#grid").getGridParam("page");
		url = url + '&returnUrl='+getReturnUrl();
        url = url + '&menuId='+'${param.menuId}';
		//검색값
        url = url + '&'+getSearchUrl();

        goNav(url);
	});
	
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});
	
	$("#btn_delete").click(function() {
		
		var id = "grid";
		var data = 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")){
				data.push($("#grid").getRowData(ids[i]));
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			alert("삭제 대상을 선택해 주세요");
			return false;
		}
		
		if ( confirm( "삭제하시겠습니까?" ) != true ) return;			
		
		var systemIDList = [];
		for (var i = 0; i <data.length; i++) {
			systemIDList.push(data[i]["SYSTEMID"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		postData.push({
			name : "cmd",
			value : "LIST_DELETE"
		});
		postData.push({
			name : "systemIDList",
			value : systemIDList
		});
		$.ajax({
			type : "POST",
			url : url,
			data : postData,
			success : function(args) {
				alert("삭제 되었습니다.");
				$("#btn_search").click();
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
	});
	
	$("#btn_download_sql").click(function() {
		
		var id = "grid";
		var data = 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")){
				data.push($("#grid").getRowData(ids[i]));
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			alert("입력쿼리 다운로드 대상을 선택해 주세요");
			return false;
		}
		
		if ( confirm( "입력쿼리를 다운로드하시겠습니까?" ) != true ) return;
		
		var systemIDList = [];
		for (var i = 0; i <data.length; i++) {
			systemIDList.push(data[i]["SYSTEMID"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		var sqlFileName = "BAP_SYSTEMID_INPUT_QUERY.sql";
		postData.push({
			name : "cmd",
			value : "LIST_DOWNLOAD_SQL"
		});
			postData.push({
				name : "systemIDList",
				value : systemIDList
			});
		postData.push({
			name : "fileName",
			value : sqlFileName
		});

		$.ajax({
			type : "POST",
			url : url,
			data : postData,
			success : function(args) {
				var filePath = args.path;
				var url2 = url_view + "?cmd=LIST_FILE_DOWNLOAD";
		      	url2 = url2 + '&returnUrl='+getReturnUrl();
		      	url2 = url2 + '&menuId='+'${param.menuId}';
			    url2 = url2 + '&filePath='+filePath;
			    url2 = url2 + '&fileName='+sqlFileName;
		            	
				goNav(url2);
				
				alert(data.length+"건의 시스템ID 입력 SQL문이 다운로드되었습니다.")
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
	});
	$("img[id=btn_clone_"+svrType+"]").click(function() {

		var id = "grid";
		var data = 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")){
				data.push($("#grid").getRowData(ids[i]));
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			alert("복사 대상을 선택해 주세요");
			return false;
		}
		
		if ( confirm( "복사하시겠습니까?" ) != true ) return;
		
		var systemIDList = [];
		for (var i = 0; i <data.length; i++) {
			systemIDList.push(data[i]["SYSTEMID"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		postData.push({
			name : "cmd",
			value : "LIST_DOWNLOAD_SQL"
		});
		postData.push({
			name : "systemIDList",
			value : systemIDList
		});
		postData.push({
			name : "svrType",
			value : svrType
		});
		$.ajax({
			type : "POST",
			url : url,
			data : postData,
			success : function(args) {
 				if (args.result != "" && args.error == "") {
					alert("시스템ID "+data.length+"건이 정상 복사되었습니다.");
				} else if (args.error != "") {
					if ("${fn:contains(args.error,'SqlIntegrityConstraintViolationException')}") {
						alert("일부 시스템ID가 이미 존재하여 정상 복사되지 않었습니다.");
					} else {
						alert("오류가 발생하여 정상 반영되지 않았습니다. 오류 : "+args.error);
					}
				}
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
		
	});
	
	buttonControl();
	list();

	if(devSvr) {
		setBtnHide(roleString, " ", "btn_clone_dev");
		setBtnHide(roleString, " ", "btn_clone_prod");
		setBtnHide(roleString, "admin", "btn_clone_stg");
	} else if (stgSvr){
		setBtnHide(roleString, " ", "btn_clone_dev");
		setBtnHide(roleString, " ", "btn_clone_stg");
		setBtnHide(roleString, "admin", "btn_clone_prod");			
	} else if (prdSvr){
		setBtnHide(roleString, " ", "btn_clone_stg");
		setBtnHide(roleString, " ", "btn_clone_prod");		
		setBtnHide(roleString, " ", "btn_clone_dev");
	} else {
		setBtnHide(roleString, " ", "btn_clone_stg");
		setBtnHide(roleString, " ", "btn_clone_prod");		
		setBtnHide(roleString, "admin", "btn_clone_dev");
	}
	
});
 
</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="title">
				<div class="search_wrap">
					<!-- <img src="<c:url value="/img/btn_clone.png"/>" alt="" id="btn_clone_stg" level="W" />  -->
					<!-- <img src="<c:url value="/img/btn_clone_prod.png"/>" alt="" id="btn_clone_prod" level="W" /> -->
					<!-- <img src="<c:url value="/img/btn_clone_dev.png"/>" alt="" id="btn_clone_dev" level="W" />  -->				
					<img src="<c:url value="/img/btn_new.png"/>" alt="" id="btn_new" level="W" />
					<img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W" />							
					<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />	
				</div>
				<div class="title">시스템 ID관리<span class="tooltip">일괄 전송에서 사용하는 시스템 ID를 관리 하는 화면입니다</span></div>
				
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th style="width:180px;">시스템ID</th>
							<td><input type="text" name="searchSystemId" value="${param.searchSystemId}"></td>
                     <th style="width:180px;">업무구분명</th>
							<td><input type="text" name="searchBjobBzwkName" value="${param.searchBjobBzwkName}"></td>
                     <th style="width:180px;">대외기관명</th>
							<td><input type="text" name="searchOsidInstiName" value="${param.searchOsidInstiName}"></td>						
						</tr>
						<tr>
                  <th style="width:180px;">업무구분코드</th>
							<td><input type="text" name="searchBjobBzwkDstcd" value="${param.searchBjobBzwkDstcd}"></td>
							<th style="width:180px;">NDM노드명</th>
							<td><input type="text" name="searchRmtNodeName" value="${param.searchRmtNodeName}"></td>
							<th style="width:180px;">시스템명</th>
							<td><input type="text" name="searchSystemName" value="${param.searchSystemName}"></td>
						</tr>
					</tbody>
				</table>
				<table id="grid" ></table>
				<div id="pager"></div>					
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

