<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%@ 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");

	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>
var url      = '<c:url value="/onl/admin/rule/transform2/transform2Man.json" />';
var url_view = '<c:url value="/onl/admin/rule/transform2/transform2Man.view" />';
var url_excel= '<c:url value="/onl/admin/rule/transform2/transform2Man.excel"/>';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;
var stageSvr	= <%=SystemUtil.isStagingServer()%>;
var adminOnly   = <%=adminOnly%>;

$(document).ready(function() {	
	
	var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
	
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : postData,
		colNames:[
                  '<%=localeMessage.getString("transformMan.eaibzwkdstcd")%>',
                  '<%=localeMessage.getString("transformMan.telCngMappCd")%>',
                  '<%=localeMessage.getString("transformMan.telCngMappDesc")%>',
                  '<%=localeMessage.getString("transformMan.ifSvcCd")%>',
                  '<%=localeMessage.getString("transformMan.ifSvcDesc")%>',
                  '<%=localeMessage.getString("transformMan.eaiSvrDiv")%>',
                  '<%= localeMessage.getString("combo.useYn")%> ',
                  '<%=localeMessage.getString("transformMan.modifyDate")%>',
                  '<%=localeMessage.getString("transformMan.verInfo")%>',
                  'cnvsnType',
                  'flag'
                  ],
		colModel:[
				{ name : 'EAIBZWKDSTCD' , align:'center' ,sortable:false , width:"30"},
				{ name : 'CNVSNNAME'    , align:'left'   , width:"100" },
				{ name : 'CNVSNDESC'    , align:'left'   , width:"100" },
				{ name : 'EAISVCNAME'   , align:'left'   , width:"70" },
				{ name : 'EAISVCDESC'   , align:'left'   , width:"100"},
				{ name : 'EAISEVRDSTCD' , hidden : true },
				{ name : 'USEYN', align:'center', width:30 ,editoptions:{value:"0:<%= localeMessage.getString("combo.usen")%>;1:<%= localeMessage.getString("combo.usey")%>"}, formatter:"select"},
				{ name : 'LASTAMNDHMS'  , align:'center'  , width : "60" },
				{ name : 'VERINFO'  , align:'center'  , width : "30" },
				{ name : 'CNVSNTYPE'   , hidden : true },
				{ name : 'FLAG'   , hidden : true }
				],
        jsonReader: {
             repeatitems:false
        },	          
		pager : $('#pager'),
		page : '${param.page}',
		rowNum : '${rmsDefaultRowNum}',
	//	height : '500',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		//toppager: true,
		rowList : eval('[${rmsDefaultRowList}]'),
		multiselect: true,
		multiboxonly: false,
		gridComplete:function (d){
			var colModel = $(this).getGridParam("colModel");
			for(var i = 0 ; i< colModel.length; i++){
				$(this).setColProp(colModel[i].name, {sortable : false});			
			}
		
		},
		loadComplete:function (){
			var ids=$("#grid").jqGrid('getDataIDs');
			for(var i=0;i<ids.length;i++){
				var rowObject = $("#grid").getRowData(ids[i]);
				if(rowObject.FLAG=="X"){
					var cbs = $("tr#"+ids[i]+".jqgrow>td>input.cbox",$("#grid")[0]);
					cbs.attr("disabled","disabled");
				}
			}
		},	
		beforeSelectRow:function(rowId,e){
			var cbsdis = $("tr#"+rowId+".jqgrow>td>input.cbox:disabled",$("#grid")[0]);
			if(cbsdis.length === 0){
				return true;
			}else{
				return false;
			}
		},
		ondblClickRow: function(rowId) {
			var rowData = $(this).getRowData(rowId); 
            var cnvsnName = rowData['CNVSNNAME'];
            var eaiSvcName = rowData['EAISVCNAME'];
            var eaiSvcDesc = rowData['EAISVCDESC'];
            var cnvsnDesc = rowData['CNVSNDESC'];
            var eaiSevrDStcd = rowData['EAISEVRDSTCD'];
            var useYn = rowData['USEYN'];
            var verInfo = rowData['VERINFO'];
            
            var url2 = url_view;
            url2 += '?cmd=DETAIL';
            url2 += '&page='+$(this).getGridParam("page");
            url2 += '&returnUrl='+getReturnUrl();
            url2 += '&menuId='+'${param.menuId}';
			//검색값
            url2 += '&' + getSearchUrl();
			
            //key값
            url2 += '&cnvsnName='+cnvsnName;
            url2 += '&eaiSvcName='+eaiSvcName;
            //url2 += '&eaiSvcDesc='+eaiSvcDesc;
            url2 += '&eaiSvcDesc='+encodeURIComponent(eaiSvcDesc);
            url2 += '&cnvsnDesc='+cnvsnDesc;
            url2 += '&eaiSevrDStcd='+eaiSevrDStcd;
            url2 += '&useYn='+useYn;
            url2 += '&verInfo='+verInfo;
    		goNav(url2);
        },loadError: function (jqXHR, textStatus, errorThrown) {
        	
        	var location ='<%=request.getContextPath()%>/';
        	comloadError(jqXHR, textStatus, errorThrown ,location);
        	
    	},onSelectAll:function(rowId,status){
    		if(status){ 
    			var cbs = $("tr.jqgrow>td>input.cbox:disabled",$("grid")[0]);
    			cbs.removeAttr("checked");
	    		$("#grid")[0].p.selarrow = $("#grid").find("tr.jqgrow:has(td > input.cbox:checked)").map(function(){
	    			return this.id;
		    	}).get();
    		}else{
    			$("#grid")[0].p.selarrow = "";
    		}
    		
    	}		
	});
	
	resizeJqGridWidth('grid','content_middle','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 url2 = url_view;
		url2 += '?cmd=NEW';
		url2 += '&page='+$("#grid").getGridParam("page");
		url2 += '&returnUrl='+getReturnUrl();
        url2 += '&menuId='+'${param.menuId}';
		//검색값
        url2 += '&'+getSearchUrl();
		
		goNav(url2);
	});
	
	$("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['CNVSNNAME']);
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			if(confirm("변환매핑코드가 선택되지 않았습니다. 전체 초기화 하겠습니까?")){
				$.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_cmsave').click(onclickBtnCmSave);
	$('#btn_clone').click(onclickBtnClone);
	
	$("#btn_delete").click(function(){
    	if(!confirm("삭제하시겠습니까?")){
			 return;
       	}
       	
		var id = "grid";
		var cnvsnNameArr = new Array();
		var eaiSvcNameArr = new Array();
		var cnvsnTypeArr = 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]);
				cnvsnNameArr.push(rowObject['CNVSNNAME']);
				eaiSvcNameArr.push(rowObject['EAISVCNAME']);
				cnvsnTypeArr.push(rowObject['CNVSNTYPE']);
				chkcnt++;
			}
		}
		
		if(chkcnt == 0){
			alert("<%= localeMessage.getString("standardLayout.message4") %>");
			return false;
		}
		
		if(confirm("<%= localeMessage.getString("common.confirmMsg")%>")){  
			var postData = [];
			postData.push({ name: "cmd" 		, value:"DELETE_LIST"});
			postData.push({ name: "cnvsnNames" 	, value : cnvsnNameArr});
			postData.push({ name: "eaiSvcNames" , value : eaiSvcNameArr});
			postData.push({ name: "cnvsnTypes" 	, value : cnvsnTypeArr});
			
			$.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;
		}
		
		
	});
	$("#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"),'transform');
		return false;
	});
	buttonControl();
	setBtnHide(roleString, "admin", "btn_initialize");
	
	if(devSvr || stageSvr){
 		if (adminOnly) {
 			setBtnHide(roleString, "admin", "btn_clone");
 		}
	}else{
		$("#btn_clone").hide();
	}
	//setBtnControl(roleString, "admin", "btn_cmsave");
	//if(!devSvr){
	//	$("#btn_cmsave").hide();
	//}
});

function setBtnControl(roleString, condiVal, compoId)
{
	var strRole		= roleString;
	var strVal		= condiVal;
	var arrRoleID	= strRole.split(',');
	var arrVal		= strVal.split(',');
	var flag		= false;
	
	$(arrRoleID).each(function(i, role) {
		$(arrVal).each(function(j, val) {
			if (role == val) {
				flag = true;
				return false;
			}
		});
	});
	if(flag)
		$("#"+compoId).show();
	else
		$("#"+compoId).hide();
}

function onclickBtnCmSave() {
	var sel = $('#grid').jqGrid('getGridParam', 'selarrrow');
	var ids = $("#grid").jqGrid('getDataIDs');
	var chkcnt = 0;
	
	for(var i=0;i<ids.length;i++){
		if($("input:checkbox[id='jqg_grid_"+ids[i]+"']").is(":checked")){
			var rowObject = $("#grid").getRowData(ids[i]);
			sel.push(ids[i]);
			chkcnt++;
		}
	}
	
	if (chkcnt == 0) {
		alert('먼저 다운로드할 데이터를 체크해 주세요.');
		return;
	}
	var validEAIBzwkDstCd = 'NONE';
	var cnvsnNames = '';
	for (var i=0; i<sel.length; i++) {
		var eaiBzwkDstCd = ($('#grid').getCell(sel[i], 'EAIBZWKDSTCD')).replace(/^\s+|\s+$/g,"");
		if (eaiBzwkDstCd == 'XXX' || eaiBzwkDstCd == '') {
			continue;
		}
		var cnvsnName = $('#grid').getCell(sel[i], 'CNVSNNAME');
		if(cnvsnName.indexOf("EAI_")!=-1){
			if(roleString.indexOf("admin")==-1){
				alert("EAI 표준오류 변환매핑은 업무 CM 대상이 아닙니다.["+cnvsnName+"]");
				
				return;
			}
		}
		if (validEAIBzwkDstCd == 'NONE') {
			validEAIBzwkDstCd = eaiBzwkDstCd;
			cnvsnNames = cnvsnName;
		} else {
			cnvsnNames += ','+ cnvsnName;
			if (validEAIBzwkDstCd != eaiBzwkDstCd) {
				alert('하나의 업무코드를 선택해야 합니다. \n\r예외:EAI, 업무구분코드 없음');
				return;
			}
		}
	}
	var url2 = '<c:url value="/onl/admin/rule/layoutMan.view"/>';
	/* if (validEAIBzwkDstCd == 'ESS' || validEAIBzwkDstCd == 'ISS') {
		url2 += '?cmd=CM LIST POPUP EX';
	} else {
		url2 += '?cmd=CM LIST POPUP';
	} */
	url2 += '?cmd=CM LIST POPUP';
	var args = new Object();
	args['eaiBzwkDstCd'] = validEAIBzwkDstCd;
	showModal(url2,args,540,400, 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;
	    addCMResource(validEAIBzwkDstCd, args.returnValue, cnvsnNames);
	});
	/*
	//local test하기 위해서 변경함
	var params = new Object();
	params['CmId']='TST999999';
	addCMResource(validEAIBzwkDstCd, params, cnvsnNames);
	*/
}

function addCMResource(eaiBzwkDsdCd, obj, cnvsnNames) {
	var params = new Object();
	params['cmd'] = 'CHANGE_EXPORT';
	params['eaiBzwkDstCd'] = eaiBzwkDsdCd;
	params['cmId'] = obj.CmId;
	params['cnvsnNames'] = cnvsnNames;
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:params,
		success:function(json){
			alert(json.message);
		},
		error:function(xhr,status,error){
			if (xhr.responseText != null) {
				try {
					alert(JSON.parse(xhr.responseText).errorMsg);	
				} catch (e) {
					alert(error);
				}
			}
		}
	});	
}

function onclickBtnClone() {
	var sel = $('#grid').jqGrid('getGridParam', 'selarrrow');
	if (sel.length == 0) {
		alert('<%= localeMessage.getString("eaiMessage.alert17")%>');
		return;
	}
	var selectedTransformNames = [];
	
	$(sel).each(function(index, i) {
		var cnvsnName = $('#grid').getCell(i, 'CNVSNNAME');
		selectedTransformNames.push(cnvsnName);
	});
	
	var url2 = url_view;
	url2 += "?cmd=POPUP CALENDAR";
	var args = new Object();
	args['selectedCnvsnName'] = selectedTransformNames.join(',');
	showModal(url2,args,540,270, 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;
	    deployTransforms(args.returnValue);
	});
}

function deployTransforms(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_cmsave.png"/>" id="btn_cmsave" level="R" /-->&nbsp;&nbsp;&nbsp;
<%-- 					<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("transformMan.title")%><span class="tooltip"><%=localeMessage.getString("transformMan.tooltip")%></span></div>
				<form id="ajaxForm"  onsubmit="return false;">
					<table class="search_condition" cellspacing=0;>
						<tbody>
							<tr>
								<th style="width:180px;"><%=localeMessage.getString("transformMan.telCngMappCd")%> </th>
								<td>
									<input type="text" name="searchCnvsnName" value="${param.searchCnvsnName}">
								</td>
								<th style="width:180px;"><%=localeMessage.getString("transformMan.eaibzwkdstcd")%> </th>
								<td>
									<input type="text" name="searchBizCode" value="${param.searchBizCode}">
								</td>
							</tr>
							<tr>
								<th style="width:180px;"><%=localeMessage.getString("transformMan.telCngMappDesc")%> </th>
								<td>
									<input type="text" name="searchCnvsnDesc" value="${param.searchCnvsnDesc}">
								</td>
								<th style="width:180px;"><%=localeMessage.getString("transformMan.ifSvcCd")%> </th>
								<td>
									<input type="text" name="searchIfSvcCd" value="${param.searchIfSvcCd}">
								</td>
							</tr>
						</tbody>
					</table>
				</form>
				<table id="grid" ></table>
				<div id="pager"></div>			
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

