<%@ 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 url = '<c:url value="/bap/admin/message/messageItemMan.json" />';
 
 var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
 var devSvr		= <%=SystemUtil.isDevServer()%>;
 var prdSvr		= <%=SystemUtil.isProdServer()%>;
 var stgSvr		= <%=SystemUtil.isStagingServer()%>;
 var svrType		= '';

 $(document).ready(function() {
	 
	if(devSvr) {
		svrType = "stg";
	} else if (stgSvr){
		svrType = "prod";
	} else if (!prdSvr){
		svrType = "dev";
	}
	 
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
	$("#clonYn").val("0").attr("selected","selected");
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: '<c:url value="/bap/admin/message/messageItemMan.json" />',
		postData : gridPostData,
		colNames:[
			      '메시지항목구분명',
                  '메시지컬럼명',
                  '메시지컬럼 속성유형코드',
                  '메시지컬럼값',
                  '당메시지 컬럼 사용여부'
                  ],
		colModel:[
				{ name : 'MSGITEMDSTICNAME'  	, align:'left'		, width:40	,sortable:false  },
				{ name : 'MSGCLMNNAME'          , align:'center'	, width:40  },
				{ name : 'MSGCLMNATTRIPTRNCD'   , align:'center'	, width:40  },
				{ name : 'MSGCLMNVAL'         	, align:'center'  	, width:40  },
				{ name : 'THISMSGCLMNUSEYN'  	, align:'center' 	, width:40   ,
				  formatter: function (cellvalue) {
								  if ( cellvalue == '0' ) {
					                 	return '<span style="color:red">사용안함</span>';
			                       } else if ( cellvalue == '1' ) {
					                 	return '사용';
			                       } else {
			                        	return cellvalue;
			                       }
                              }	
                }
				],
        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 key = rowData['MSGITEMDSTICNAME'];
            var url = '<c:url value="/bap/admin/message/messageItemMan.view" />';
            url = url + '?cmd=DETAIL';
            url = url + '&page='+$(this).getGridParam("page");
            url = url + '&returnUrl='+getReturnUrl();
            url = url + '&menuId='+'${param.menuId}';
			//검색값
            url = url + '&'+getSearchUrl();
            //key값
            url = url + '&key='+key;
            goNav(url);
        }      
	});
	
	resizeJqGridWidth('grid','title','1000');

	$("#btn_search").click(function(){
	    var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
		$("#grid").setGridParam({ postData: postData ,page : "1" }).trigger("reloadGrid");
	});
	$("#btn_new").click(function(){
		var url = '<c:url value="/bap/admin/message/messageItemMan.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_clone").click(function(){

		var searchMsgItemDsticName = $("input[name=searchMsgItemDsticName]").val().trim();
		var cloneMsgItemDsticName = $("input[name=cloneMsgItemDsticName]").val().trim();
		
		if (searchMsgItemDsticName == "") {
			alert("대상 메시지항목 구분명을 입력해 주세요.");
			return;
		} else if (cloneMsgItemDsticName == "") {
			alert("복제 메시지항목 구분명을 입력해 주세요.");
			return;
		}
		
		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;
		
		for (var i = 0; i <data.length; i++) {
			var	postData = $('#ajaxForm').serializeArray();
			postData.push({name:"msgItemDsticName", value:data[i]["MSGITEMDSTICNAME"].replace(searchMsgItemDsticName,cloneMsgItemDsticName)});
			postData.push({name:"msgClmnName", value:data[i]["MSGCLMNNAME"].trim()});
			postData.push({name:"msgClmnAttriPtrnCd", value:data[i]["MSGCLMNATTRIPTRNCD"].trim()});
			postData.push({name:"msgClmnVal", value:data[i]["MSGCLMNVAL"].trim()});
			postData.push({name:"thisMsgClmnUseYn", value:data[i]["THISMSGCLMNUSEYN"] == '사용함' ? '1' : '0'});
			postData.push({name:"cmd", value:"CLONE"});
			
 			$.ajax({
				type : "POST",
				url : url,
				dataType : "json",
				data : postData,
				success : function(args) {
				},
				error : function(e) {
					alert(e.responseText);
				}
			});	
		}
		alert("메시지 항목 "+data.length+"건이 복제되었습니다.");
		
		$("input[name=searchMsgItemDsticName]").val(cloneMsgItemDsticName);
		$("input[name=cloneMsgItemDsticName]").val("");
		
 		$("#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 msgItemDsticNameList = [];
		for (var i = 0; i <data.length; i++) {
			msgItemDsticNameList.push(data[i]["MSGITEMDSTICNAME"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		postData.push({
			name : "cmd",
			value : "LIST_DELETE"
		});
		postData.push({
			name : "msgItemDsticNameList",
			value : msgItemDsticNameList
		});
		$.ajax({
			type : "POST",
			url : url,
			data : postData,
			success : function(args) {
				alert("메시지항목 "+data.length+"건이 삭제 되었습니다.");
				$("#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 msgItemDsticNameList = [];
		for (var i = 0; i <data.length; i++) {
			msgItemDsticNameList.push(data[i]["MSGITEMDSTICNAME"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		var sqlFileName = "BAP_MSGITEM_INPUT_QUERY.sql";
		postData.push({
			name : "cmd",
			value : "LIST_DOWNLOAD_SQL"
		});
			postData.push({
				name : "msgItemDsticNameList",
				value : msgItemDsticNameList
			});
		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+"건의 메시지항목 입력 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 msgItemDsticNameList = [];
		for (var i = 0; i <data.length; i++) {
			msgItemDsticNameList.push(data[i]["MSGITEMDSTICNAME"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		postData.push({
			name : "cmd",
			value : "LIST_DOWNLOAD_SQL"
		});
		postData.push({
			name : "msgItemDsticNameList",
			value : msgItemDsticNameList
		});
		postData.push({
			name : "svrType",
			value : svrType
		});
		$.ajax({
			type : "POST",
			url : url,
			data : postData,
			success : function(args) {
 				if (args.result != "" && args.error == "") {
					alert("메시지항목 "+data.length+"건이 복사되었습니다.");
				} else if (args.error != "") {
					if ("${fn:contains(args.error,'SqlIntegrityConstraintViolationException')}") {
						alert("일부 메시지항목이 이미 존재하여 복사되지 않었습니다.");
					} else {
						alert("오류가 발생하여 복사되지 않았습니다. 오류 : "+args.error);
					}
				}
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
		
	});
	
	buttonControl();

	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">메시지항목 관리<span class="tooltip">메시지항목을 등록 관리합니다</span></div>
				
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>						
							<th style="width:150px;">메시지항목 구분명</th>
							<td><input type="text" name="searchMsgItemDsticName" value="${param.searchMsgItemDsticName}"></td>
							<th style="width:150px;">메시지 컬럼명</th>
							<td><input type="text" name="searchMsgClmnName" value="${param.searchMsgClmnName}"></td>
							<%-- <th>복제 메시지항목 구분명</th>
							<td><input type="text" name="cloneMsgItemDsticName" style="display:inline-block; width:calc(100% - 70px);">
							<img id="btn_clone" src="<c:url value="/img/btn_clone1.png" />" level="W" status="LIST" class="btn_img"/></td> --%>
						</tr>						
					</tbody>
				</table>
				<table id="grid" ></table>
				<div id="pager"></div>	
				
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>