<%@ 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" %>
<%
	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"/>
	<style>
		.jexcel tbody {
			font-size: 13px;
		}
	</style>

	<script language="javascript" >
		var isPop = "${param.pop}";
		var isDetail = false;
		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)%>";
		let userId = '<%=SessionManager.getUserId(request) %>';
		var returnUrl = getReturnUrlForReturn();
		var sevrArr = new Array();

		let grid;
		let columnNames = [];

		function detail(layoutName){
			$.ajax({
				type : "POST",
				url:url,
				dataType:"json",
				data:{cmd: 'DETAIL', layoutName: layoutName},
				success:function(json){
					var data = json.detail;
					$("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function(){
						var name = $(this).attr("name");
						var tag  = $(this).prop("tagName").toLowerCase();
						// var key = name.toUpperCase();
						var key = name;
						let value = data[key];
// 						if(key == 'createDatetime' || key == 'updateDatetime'){
// 							$(tag+"[name="+name+"]").attr('timestamp', value);
// 							const dateFormat = new Date(value);
// 							value = dateFormat.toLocaleString();
// 						}
						$(tag+"[name="+name+"]").val(value);
					});

					initializeEditGrid(json);
					// setDataTotalLen();
				},
				error:function(e){
					alert(e.responseText);
				}
			});
		}

		function initializeEditGrid(layoutData){
			const itemTypes = [{id:2, name:'Field'}, {id:3, name:'Group'}, {id:4, name:'Grid'}, {id:5, name:'Field Array'}, {id:9, name:'Biz Data'}];
			const fieldTypes = [{id:1, name:'Element'}, {id:2, name:'Attribute'}];
			const dataTypes = [{id:1, name:'String'}, {id:2, name:'Number'},{id:11, name:'ZZ String'}, {id:12, name:'LL Number'}];
			let columns = [ // for columnData prop
				{
					title: '<%= localeMessage.getString("standardLayout.itemName") %>',
					name: 'itemName',
					type: 'text',
					width: 200,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.itemDesc") %>',
					name: 'itemDesc',
					type: 'text',
					width: 260,
					align: 'left'
				},
				{
					title: '<%= localeMessage.getString("standardLayout.itemLevel") %>',
					name: 'itemLevel',
					type: 'text',
					width: 60,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.itemType") %>',
					name: 'itemType',
					type: 'dropdown',
					source: itemTypes,
					width: 80,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.arraySize") %>',
					name: 'arraySize',
					type: 'text',
					width: 60,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.fieldType") %>',
					name: 'fieldType',
					type: 'dropdown',
					source: fieldTypes,
					width: 100,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.dataLength") %>',
					name: 'dataLength',
					type: 'numeric',
					width: 70,
					align: 'center',
				},
				{
					title: '<%= localeMessage.getString("standardLayout.dataType") %>',
					name: 'dataType',
					type: 'dropdown',
					source: dataTypes,
					width: 100,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.refFieldPath") %>',
					name: 'refFieldPath',
					type: 'text',
					align: 'left',
					width: 180,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.refValue") %>',
					name: 'refValue',
					type: 'text',
					align: 'left',
					width: 80,
				},
				{
					title: '<%= localeMessage.getString("standardLayout.defaultValue") %>',
					name: 'defaultValue',
					type: 'text',
					align: 'left',
					width: 180,
				}
			];

			const toolbarHtml='<button type="button" class="cssbtn smallBtn" id="btn_item_add" onClick="itemAdd()" style="margin-right:5px; vertical-align:middle; font-weight:bold;"><i class="material-icons">add</i><%= localeMessage.getString("common.itemAdd") %></button>'
					+ '<button type="button" class="cssbtn smallBtn" id="btn_item_delete" onClick="itemDel()" style="margin-right:5px; vertical-align:middle; font-weight:bold;"><i class="material-icons">delete</i><%= localeMessage.getString("common.itemRemove") %></button>'
					+'<br/>';

			for (let i = 0; i < columns.length; i++) {
				columnNames[i] = columns[i].name;
			}

			grid = defaultEditGrid($('#editGrid'), columns, toolbarHtml, 'itemLevel', layoutData.rows);
			initDialog();
		}

		function itemDel(){
			const selectionRows = grid.getSelectedRows();
			if(selectionRows){
				const idx = selectionRows[0].rowIndex - 1;
				const len = selectionRows.length;
				grid.deleteRow(idx, len);
			}
		}

		function closeAddRowDialog(){
			$( '#add_row_dialog' ).dialog("close");
		}

		function addNewRow(){
			var cnt = $("input[name=add_row_count]").val();
			if(cnt == "" || cnt == undefined) return;
			const ncnt = Number(cnt);

			if (grid.getJson().length == 0){
				const ncnt = Number(cnt) -1;
				grid.setData([{}]);
				if (ncnt !=0){
					grid.insertRow(ncnt);
				}
			}else{
				const ncnt = Number(cnt);
				grid.insertRow(ncnt);
			}

			$( '#add_row_dialog' ).dialog("close");
			closeAddRowDialog();
		}

		function initDialog(){
			$( '#add_row_dialog' ).dialog({
				resizable: false,
				autoOpen: false,
				height: "auto",
				width: 400,
				modal: true,
				buttons: {
					"Add": function() {
						addNewRow();
					},
					Cancel: function() {
						closeAddRowDialog();
					}
				}
			});

			$("input[name=add_row_count]").keydown(function(key){
				if (key.keyCode == 13){
					addNewRow();
				}
			});
		}

		function itemAdd(){
			grid.resetSelection();
			$("input[name=add_row_count]").val("");
			$( '#add_row_dialog' ).dialog("open");
		}

		$(document).ready(function() {
			var layoutName ="${param.layoutName}";
			if (layoutName != "" && layoutName !="null"){
				isDetail = true;
				$("input[name=layoutName]").attr('readonly',true);
			}else{
				$("#btn_deploy").hide();
			}

			//신규
			if(!layoutName){
				$('#writerName').val(userId);
				initializeEditGrid({rows:[]});
			}else {
				detail(layoutName);
			}

			$("#btn_modify").click(function(){
				var postData = $('#ajaxForm').serializeArray();
				if (isDetail){
					postData.push({ name: "cmd" , value:"UPDATE"});
				}else{
					postData.push({ name: "cmd" , value:"INSERT"});
				}

				for ( var i = 0; i < postData.length; i++) {
					var field = postData[i];
					if(field.name == 'createDatetime' || field.name == 'updateDatetime'){
						field.value = $("input[name="+field.name+"]").attr('timestamp');
					}
				}

				var data = grid.getData();
				var gridData = new Array();
				for ( var i = 0; i < data.length; i++) {
					const row = data[i];
					const inputRow = {};

					for (let j = 0; j < row.length; j++) {
						const columnName = columnNames[j];
						let value = String(row[j]);

						if(value == null || value == ''){
							switch (columnName){
								case 'itemLevel': value = '1'; break;
								case 'itemType': value = '2'; break;
								case 'arraySize': value = '1'; break;
								case 'fieldType': value = '1'; break;
								case 'dataLength': value = '0'; break;
								case 'dataType': value = '1'; break;
							}
						}
						if(value == ''){
							value = null;
						}
						inputRow[columnName] = value

					}

					const index = String(i+1);
					inputRow['itemKey'] = { layoutName, itemNo: index};

					gridData.push(inputRow);
				}

				postData.push({
					name : "gridData",
					value : JSON.stringify(gridData)
				});

				$.ajax({
					type : "POST",
					url:url,
					data:postData,
					success:function(args){
						alert("<%=localeMessage.getString("common.saveMsg")%>");
						goNav(returnUrl);//LIST로 이동
					},
					error:function(e){
						alert(e.responseText);
					}
				});
			});

			$("#btn_deploy").click(function(){
				if(confirm("<%= localeMessage.getString("standardLayout.message1") %>".formatLocale($("input[name=layoutName]").val()))){
					var postData = $('#ajaxForm').serializeArray();
					postData.push({ name: "cmd" , value:"DEPLOY"});
					$.ajax({
						type : "POST",
						url:url,
						data:postData,
						success:function(args){
							alert("<%= localeMessage.getString("standardLayout.message2") %>".formatLocale($("input[name=layoutName]").val()));
							goNav(returnUrl);//LIST로 이동
						},
						error:function(e){
							alert(e.responseText);
						}
					});
				}else{
					return false;
				}
			});

			$("#btn_delete").click(function(){
				if(confirm("<%= localeMessage.getString("common.confirmMsg")%>")){
					var postData = $('#ajaxForm').serializeArray();
					postData.push({ name: "cmd" , value:"DELETE"});
					$.ajax({
						type : "POST",
						url:url,
						data:postData,
						success:function(args){
							alert("<%=localeMessage.getString("common.deleteMsg")%>");
							goNav(returnUrl);//LIST로 이동

						},
						error:function(e){
							alert(e.responseText);
						}
					});
				}else{
					return false;
				}
			});
			$("#btn_previous").click(function(){
				if(isPop == "true")
					window.close();
				else
					goNav(returnUrl);//LIST로 이동

			});
			$("#btn_initialize").click(function(){
				$.ajax({
					type : "POST",
					url:url,
					dataType:"json",
					data:{cmd: 'INITIALIZE',layoutName:$("input[name=layoutName]").val()},
					success:function(json){
						alert(json.message);
					},
					error:function(e){
						alert(e.responseText);
					}
				});

			});
			$("#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
				gridToExcelSubmit(url_excel,"LIST_GRID_TO_EXCEL",$("#tree"),$("#ajaxForm2"),$("input[name=layoutName]").val());
				return false;

			});
			buttonControl(isDetail);
			//titleControl(isDetail);

			setBtnHide(roleString, "admin", "btn_initialize");
			setBtnHide(roleString, "admin", "btn_modify");
			$('body').css("overflow-x","hidden");
		});

	</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 id="content_middle" class="content_middle">
		<div class="search_wrap">
<%--			<img src="<c:url value="/img/btn_initialize.png"/>" alt="" id="btn_initialize" level="W" status="DETAIL" />--%>
<%--			<img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W" status="DETAIL"/>--%>
<%--			<img src="<c:url value="/img/btn_modify.png"/>" alt="" id="btn_modify" level="R" status="DETAIL,NEW"/>--%>
<%--			<img src="<c:url value="/img/btn_previous.png"/>" alt="" id="btn_previous" level="R" status="DETAIL,NEW"/>--%>

			<button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL" ><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button><!-- 삭제 -->
			<button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL" ><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></button><!-- 수정 -->
			<button type="button" class="cssbtn" id="btn_deploy" level="W" status="DETAIL" ><i class="material-icons">system_update_alt</i> <%= localeMessage.getString("button.deploy") %></button><!-- 배포 -->
			<button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW" ><i class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %></button><!%-- 이전화면 -->
		</div>
		<div class="title"><%= localeMessage.getString("standardLayout.title") %></div>

		<form id="ajaxForm">
			<div class="table_row_title" style="display: inline;margin-bottom: -8px;"><%= localeMessage.getString("standardLayout.subTitle1") %></div>
			<table class="table_row" cellspacing="0">
				<tr>
					<th style="width:10%; min-width: 130px;"><%= localeMessage.getString("standardLayout.layoutName") %></th>
					<td style="width:25%; min-width: 200px;"><input type="text" name="layoutName"/> </td>
					<th style="width:10%; min-width: 130px;"><%= localeMessage.getString("standardLayout.layoutDesc") %></th>
					<td colspan="3"><input type="text" name="layoutDesc"/> </td>
				</tr>
				<tr>
					<th><%= localeMessage.getString("standardLayout.writerName") %></th>
					<td><input type="text" id="writerName" name="writerName" readonly="true"/> </td>
					<th style="width:10%; min-width: 130px;"><%= localeMessage.getString("standardLayout.createDatetime") %></th>
					<td><input type="text" name="createDatetime" readonly="true"/> </td>
					<th style="width:10%; min-width: 130px;"><%= localeMessage.getString("standardLayout.updateDatetime") %></th>
					<td><input type="text" name="updateDatetime" readonly="true"/> </td>
				</tr>
			</table>
			<div class="table_row_title" style="display: inline;"><%= localeMessage.getString("standardLayout.subTitle2") %></div>
			<div id="editGrid"></div>
		</form>
		</form>
	</div><!-- end content_middle -->
</div><!-- end right_box -->
<div id="add_row_dialog" title="<%= localeMessage.getString("standardLayout.appendRow") %>">
	<%= localeMessage.getString("common.countAppendRow") %> : <input type="text" name="add_row_count" style="width:30px" />
</div>
</body>
</html>

