<%@ 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"%>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");

	request.setCharacterEncoding("UTF-8");

%>
<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/rule/standardLayoutMan.json"/>';
var url_view	= '<c:url value="/onl/admin/rule/standardLayoutMan.view"/>';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;
var svrInst = new Array();


function dateFormater(cellvalue, options, rowObject){
	if (cellvalue==null|| cellvalue==undefined) return "";
	if (cellvalue.trim().length < 16) return "";
	var display = "";
	display=display+cellvalue.substr(0,4)+"-";
	display=display+cellvalue.substr(4,2)+"-";
	display=display+cellvalue.substr(6,2)+" ";

	display=display+cellvalue.substr(8,2)+":";
	display=display+cellvalue.substr(10,2)+":";
	display=display+cellvalue.substr(12,2)+".";
	display=display+cellvalue.substr(14,2);

	return display;
}
function init (){
	$.ajax({
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'GET_DEPLOY'},
		success:function(json){
			if(json == null || Object.keys(json).length === 0 || json.layoutName == null || json.layoutName.length == 0){
				$('#deployLayoutName').text('<%= localeMessage.getString("standardLayout.message3") %>');
			} else {
				$('#deployLayoutName').text(json.layoutName);
				$('#deployLayoutDesc').text('(' + json.layoutDesc + ')');
			}
		},
		error:function(e){
			console.log(e);
		}
	});
}

function timeFormatter (cellvalue, options, rowObject){
	const dateFormat = new Date(cellvalue);
	return dateFormat.toLocaleString();
}	

$(document).ready(function() {
	init();
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : { cmd : 'LIST'
			       , searchLoutName     	: $('input[name=searchLoutName]').val()
			       , searchLoutDesc     	: $('input[name=searchLoutDesc]').val()
		},
		colNames:['<%= localeMessage.getString("standardLayout.layoutName") %>',
                  '<%= localeMessage.getString("standardLayout.layoutDesc") %>',
                  '<%= localeMessage.getString("standardLayout.writerName") %>',
                  '<%= localeMessage.getString("user.createOn") %>',
                  '<%= localeMessage.getString("user.updateOn") %>'
                  ],
		colModel:[
				{ name: 'layoutName', align: 'center', sortable: false },
				{ name: 'layoutDesc', align: 'left'  },
				{ name: 'writerName', align: 'left', width: "60"  },
				{ name: 'createDatetime', align: 'left', width: "60"},
				{ name: 'updateDatetime', align: 'left', width: "60"}
				],
        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}]'),
		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 layoutName = rowData['layoutName'];
            var url2 = url_view;
            url2 += '?cmd=DETAIL';
            url2 += '&page='+$(this).getGridParam("page");
            url2 += '&returnUrl='+getReturnUrl();
            url2 += '&menuId='+'${param.menuId}';
			//검색값
			url2 += '&' + getSearchUrl();
            //key값
            url2 += '&layoutName='+layoutName;
    		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=DETAIL';
		url2 += '&page=1';
		url2 += '&returnUrl='+getReturnUrl();
        url2 += '&menuId='+'${param.menuId}';
		//검색값
        url2 += '&'+getSearchUrl();

        goNav(url2);
	});

	$("#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['layoutName']);
				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("초기화 하시겠습니까?")){
				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;
			}
		}
	});

	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});

	$('#btn_cmsave').click(onclickBtnCmSave);

	$("#btn_delete").click(function(){
		// var id = "grid";
		// var delArr = 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]);
		// 		delArr.push(rowObject['LOUTNAME']);
		// 		chkcnt++;
		// 	}
		// }

		const selRowId = $("#grid").getGridParam( "selrow" );

		if(selRowId == null){
			alert("<%= localeMessage.getString("standardLayout.message4") %>");
			return false;
		}

		const rowSelectData = $("#grid").getRowData( selRowId );
		const targetName = rowSelectData["layoutName"];

		if(confirm(targetName + " <%= localeMessage.getString("common.confirmMsg")%>")){
			var postData = [];
			postData.push({ name: "cmd" , value:"DELETE"});
			postData.push({ name: "layoutName" , value: targetName});
			postData.push({ name: "layoutDesc" , value: targetName});

			$.ajax({
				type : "POST",
				url : url,
				data : postData,
				success : function(args) {
					alert(targetName + " <%=localeMessage.getString("common.deleteMsg")%>");
					$("#btn_search").click();
				},
				error : function(e) {
					alert("error"+e.responseText);
				}
			});
		}else{
			return false;
		}
	});

	buttonControl();
	setBtnHide(roleString, "admin", "btn_download");
	setBtnHide(roleString, "admin", "btn_initialize");
	setBtnControl(roleString, "admin,dept_developer", "btn_import");
	//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 = new Array();
	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('<%= localeMessage.getString("standardLayout.message5") %>');
		return false;
	}
	//var sel = $('#grid').jqGrid('getGridParam', 'selarrrow');

	var validEAIBzwkDstCd = 'NONE';
	var loutNames = '';
	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 loutName = $('#grid').getCell(sel[i], 'LOUTNAME');
		if(loutName.indexOf("EAI_")!=-1){
			if(roleString.indexOf("admin")==-1){
				alert("<%= localeMessage.getString("standardLayout.message6") %>".formatLocale(loutName));
				return;
			}
		}
		if (validEAIBzwkDstCd == 'NONE') {
			validEAIBzwkDstCd = eaiBzwkDstCd;
			loutNames = loutName;
		} else {
			loutNames += ',' + loutName;
			if (validEAIBzwkDstCd != eaiBzwkDstCd) {
				alert('<%= localeMessage.getString("standardLayout.message7") %>');
				return;
			}
		}
	}
	var url2 = url_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, loutNames);
	});
	/*
	//local test하기 위해서 변경함
	var params = new Object();
	params['CmId']='TST999999';
	addCMResource(validEAIBzwkDstCd, params, loutNames);
	*/
}

function addCMResource(eaiBzwkDsdCd, obj, loutNames) {
	var params = new Object();
	params['cmd'] = 'CHANGE_EXPORT';
	params['eaiBzwkDstCd'] = eaiBzwkDsdCd;
	params['cmId'] = obj.CmId;
	params['loutNames'] = loutNames;
	$.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);
				}
			}
		}
	});
}

 
</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">
					<%-- <img id="btn_import" src="<c:url value="/img/btn_import.png"/>" level="W" />&nbsp; --%>
					<!-- img id="btn_cmsave" src="<c:url value="/img/btn_cmsave.png"/>" level="R" /-->&nbsp;&nbsp;&nbsp;
<%--					<img id="btn_initialize" src="<c:url value="/img/btn_initialize.png"/>" alt="" level="W" />--%>
						<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_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 id="btn_search" src="<c:url value="/img/btn_search.png"/>" alt="" level="R" />--%>
				</div>
				<div class="title"><%= localeMessage.getString("standardLayout.title1") %><span class="tooltip"><%= localeMessage.getString("standardLayout.tooltip") %></span></div>
				<div style="font-size: 24px"><%= localeMessage.getString("standardLayout.currentStandardLayout") %> : <span style="font-weight: bold;color:#d43f3a;" id="deployLayoutName"></span><span style="color:#8a6d3b" id="deployLayoutDesc"></span></div>

				<table id="grid"></table>
				<div id="pager"></div>			
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

