<%@ 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 uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ 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" />

<script language="javascript">
var url      = '<c:url value="/common/property/monitoringPropertyMan.json" />';
var url_view = '<c:url value="/common/property/monitoringPropertyMan.view" />';
var url_excel = '<c:url value="/common/property/monitoringPropertyMan.excel" />';

var isDetail = false;
var lastsel2;
	
	function isValid() {
		if ($('input[name=prptyGroupName]').val() == "") {
			alert("<%= localeMessage.getString("propertyDetail.checkRequired4") %>");
			$('input[name=prptyGroupName]').focus();
			return false;
		}
		if ($('input[name=prptyGroupDesc]').val() == "") {
			alert("<%= localeMessage.getString("propertyDetail.checkRequired1") %>");
			$('input[name=prptyGroupDesc]').focus();
			return false;
		}
		return true;
	}
	function isValidGrid() {
		if ($('input[name=prptyName]').val() == "") {
			alert("<%= localeMessage.getString("propertyDetail.checkRequired2") %>");
			return false;
		} else if ($('input[name=prpty2Val]').val() == "") {
			alert("<%= localeMessage.getString("propertyDetail.checkRequired3") %>");
			return false;
		}
		//중복체크
		if($("#grid tr#" + lastsel2).attr("editable") == 1){ //editable=1 means row in edit mode
			$("#grid").saveRow(lastsel2,false,"clientArray");
		}
		var data = $("#grid").getRowData();
		for ( var i = 0; i < data.length; i++) {
			if (data[i]['PRPTYNAME'] == $('input[name=prptyName]').val()) {
				alert("<%= localeMessage.getString("propertyDetail.checkDuplicate") %>");
				return false;
			}
		}

		return true;
	}
	
	function checkDuplicatePrptyName(data) {
	    var prptyNameSet = new Set();
	    for (var i = 0; i < data.length; i++) {
	        if (prptyNameSet.has(data[i].PRPTYNAME)) {
	            return true; // 중복 발견
	        }
	        prptyNameSet.add(data[i].PRPTYNAME);
	    }
	    return false;
	}
	
	function unformatterFunction(cellvalue, options, rowObject) {
		return "";
	}

	function formatterFunction(cellvalue, options, rowObject) {
		var rowId = options["rowId"];
// 		return "<img id='btn_pop_delete' name='img_"+rowId+"' src='<c:url value="/images/bt/pop_delete.gif"/>' />";
		return "<button type='button' class='cssbtn smallBtn2' id='btn_pop_delete' style='vertical-align:middle; font-weight:bold;' name='img_" + rowId + "'>delete</button>";
	}
	function gridRendering() {
		$('#grid').jqGrid({
			datatype:"local",
			loadonce: true,
			rowNum: 1000,
			editurl : "clientArray",
			colNames : [ '<%= localeMessage.getString("propertyDetail.propertyKey") %>', 
						 '<%= localeMessage.getString("propertyDetail.propertyValue") %>', 
						 '<%= localeMessage.getString("propertyDetail.delYn") %>' ],
			colModel : [ { name : 'PRPTYNAME' ,width:50  , align : 'left', editable : true },
			             { name : 'PRPTY2VAL' ,width:200 , align : 'left', editable : true },
			             { name : 'DELETEYN'  ,width:20  , align : 'center', unformat : unformatterFunction, formatter : formatterFunction } ],
			jsonReader : {
				repeatitems : false
			},
			loadComplete : function() {
			},
			onSelectRow: function(rowid,status){
		    	if (lastsel2 !=undefined){
		            if($("#grid tr#" + lastsel2).attr("editable") == 1){ //editable=1 means row in edit mode
		        	  $("#grid").saveRow(lastsel2,false,"clientArray");
					}
		    	}
	        $('#grid').restoreRow(lastsel2);
	        $('#grid').editRow(rowid,true);
	        	lastsel2=rowid;
		    },		    
	        onSortCol : function(){
	        	return 'stop';	//정렬 방지
	        },   
				height : '500',
				autowidth : true,
				//autoheight : true,
				viewrecords : true
			,
			loadError: function (jqXHR, textStatus, errorThrown) {
	        	
				var location ='<%=request.getContextPath()%>/';
	        	comloadError(jqXHR, textStatus, errorThrown ,location);
	        	
			}
    	});

		resizeJqGridWidth('grid', 'title', '1000');
	}
	function init( key, callback) {
		if (typeof callback === 'function') {
			callback( key);
		}
	}
	function detail( key) {

		if (!isDetail)
			return;
		
		$.ajax({
			type : "POST",
			url : url,
			dataType : "json",
			data : {
				cmd : 'DETAIL',
				prptyGroupName : key
			},
			success : function(json) {
				$("input[name=prptyGroupName]").val(json.PRPTYGROUPNAME).attr('readonly', true);
				$("input[name=prptyGroupDesc]").val(json.PRPTYGROUPDESC);
				$("#grid")[0].addJSONData(json.gridData);
				
				$("button[name*=img]").click(function() {
					var name = $(this).attr("name");
					var rowId = name.split("_")[1];
					$('#grid').jqGrid('delRowData', rowId);
				});
			},
			error : function(e) {
				alert(e.responseText);
			}
		});

	}
	$(document).ready(function() {
		var returnUrl = getReturnUrlForReturn();
		var key = "${param.prptyGroupName}";

		if (key != "" && key != "null") {
			isDetail = true;
		}

		gridRendering();

		init( key, detail);

		$("#btn_modify").click(function() {
			if (!isValid())return;
			
			if (confirm("<%= localeMessage.getString("common.checkModify")%>") != true)
				return;
			
			if($("#grid tr#" + lastsel2).attr("editable") == 1){ //editable=1 means row in edit mode
				$("#grid").saveRow(lastsel2,false,"clientArray");
			}
			var data = $("#grid").getRowData();
			
			// PrptyName 중복 체크
			if (checkDuplicatePrptyName(data)) {
		        alert("<%= localeMessage.getString("propertyDetail.checkDuplicate") %>");
		        return;
		    }
			
			var prptyGroupNameValue = $("input[name=prptyGroupName]").val();
			var gridData = new Array();

			for ( var i = 0; i < data.length; i++) {
				data[i]["PRPTYGROUPNAME"] = prptyGroupNameValue;
				gridData.push(data[i]);
			}

			//공통부만 form으로 구성
			var postData = $('#ajaxForm').serializeArray();

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

			if (isDetail) {
				postData.push({
					name : "cmd",
					value : "UPDATE"
				});
			} else {
				postData.push({
					name : "cmd",
					value : "INSERT"
				});
			}
			$.ajax({
				type : "POST",
				url : url,
				data : postData,
				success : function(args) {
					alert("<%= localeMessage.getString("common.saveMsg") %>");
					alert("<%= localeMessage.getString("monitoringPropDetail.syncMsg") %>"+args.result);
					goNav(returnUrl);//LIST로 이동
				},
				error : function(e) {
					alert(e.responseText);
				}
			});
		});
		$("#btn_delete").click(function() { 
			
			if(confirm('<%=localeMessage.getString("common.confirmMsg")%>')!= true)  
				return;
			
			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") %>");
					alert("<%= localeMessage.getString("monitoringPropDetail.syncMsg") %>"+args.result);
					goNav(returnUrl);//LIST로 이동

				},
				error : function(e) {
					alert(e.responseText);
				}
			});			
		 
		});
		
		$("#btn_previous").click(function() {
			goNav(returnUrl);//LIST로 이동
		});
		$("#btn_pop_input").click(function() {
			if (!isValidGrid()) {
				return;
			}
			var data = new Object();
			data["PRPTYNAME"] = $("input[name=prptyName]").val();
			data["PRPTY2VAL"] = $("input[name=prpty2Val]").val();

			var rows = $("#grid")[0].rows;
			var index = Number($(rows[rows.length - 1]).attr("id"));
			if (isNaN(index))
				index = 0;
			var rowid = index + 1;
			$("#grid").jqGrid('addRow', {
				rowID : rowid,
				initdata : data,
				position : "last", //first, last
				useDefValues : false,
				useFormatter : false,
				addRowParams : {
					extraparam : {}
				}
			});
			$("#" + $('#grid').jqGrid('getGridParam', 'selrow')).focus();
			$("button[name=img_" + rowid + "]").click(function() {
				var name = $(this).attr("name");
				var rowId = name.split("_")[1];
				$('#grid').jqGrid('delRowData', rowId);
			});

		});
		
		$("#btn_excel").click(function(event) {
			var prptyGroupName = $("input[name=prptyGroupName]").val();
			var url_excel = '<c:url value="/common/property/monitoringPropertyMan.excel" />';
	        event.stopPropagation(); // Do not propagate the event.
	        // Create an object that will manage to download the file.
	        var target = "excelDown" ; // iframe의 name
	        //title : 서비스코드_거래처리seq
	        var title = prptyGroupName+"_프라퍼티";
			gridToExcelSubmit(url_excel,"LIST_GRID_TO_EXCEL",$("#grid"),$("#ajaxForm"),title);
			return false;     
		});

		buttonControl(key);
		titleControl(key);

		// 검색 기능
		$("#btn_search").click(function() {
			filterGrid();
		});

		// 엔터키로 검색
		$("#searchText").keypress(function(e) {
			if (e.which == 13) {
				filterGrid();
				return false;
			}
		});

		// 초기화 버튼
		$("#btn_reset").click(function() {
			$("#searchText").val("");
			filterGrid();
		});

		function filterGrid() {
			var searchText = $("#searchText").val().toLowerCase();
			var grid = $("#grid");

			// 모든 행을 순회하며 필터링
			var ids = grid.jqGrid('getDataIDs');
			for (var i = 0; i < ids.length; i++) {
				var rowData = grid.jqGrid('getRowData', ids[i]);
				var prptyName = (rowData.PRPTYNAME || "").toLowerCase();
				var prptyVal = (rowData.PRPTY2VAL || "").toLowerCase();

				// 검색어가 비어있거나, 프로퍼티 키 또는 값에 포함되어 있으면 표시
				if (searchText === "" || prptyName.indexOf(searchText) >= 0 || prptyVal.indexOf(searchText) >= 0) {
					$("#" + ids[i]).show();
				} else {
					$("#" + ids[i]).hide();
				}
			}
		}
	});
</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">
					<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_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,NEW"><i class="material-icons">save</i> <%= localeMessage.getString("button.modify") %></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>
<%-- 					<img src="<c:url value="/img/btn_excel.png" />" alt="" id="btn_excel" 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="W" status="DETAIL,NEW" />				 --%>
<%-- 					<img src="<c:url value="/img/btn_previous.png"/>" alt="" id="btn_previous" level="R" status="DETAIL,NEW"/>	 --%>
				</div>
				<div class="title"><%= localeMessage.getString("monitoringPropDetail.title") %></div>	
				
				<form id="ajaxForm">
					<table class="table_row" cellspacing="0">
						<tr>
							<th style="width:180px;"><%= localeMessage.getString("property.propertyGroupName") %> *</th>
							<td><input type="text" name="prptyGroupName" />
							</td>
						</tr>
						<tr>
							<th><%= localeMessage.getString("property.propertyGroupDesc") %> *</th>
							<td><input type="text" name="prptyGroupDesc"/>
							</td>
						</tr>
					</table>
				</form>
			
				<table class="table_row" cellspacing="0">
					<tr>
						<th style="width:180px;"><%= localeMessage.getString("propertyDetail.propertyKey") %></th>
						<td>
							<input type="text" name="prptyName" style="width:calc(100% - 70px);" /> 
<%-- 							<img id="btn_pop_input" src="<c:url value="/img/btn_pop_input.png"/>" class="btn_img" /> --%>
							<button type="button" class="cssbtn smallBtn2" id="btn_pop_input" style="vertical-align:middle; font-weight:bold;"><i class="material-icons">input</i><%= localeMessage.getString("button.input") %></button>
						</td>
					</tr>
					<tr>
						<th><%= localeMessage.getString("propertyDetail.propertyValue") %></th>
						<td colspan="3"><input type="text" name="prpty2Val" />
						</td>
					</tr>
				</table>

				<!-- 검색 박스 추가 -->
				<div class="search-box">
					<input type="text" id="searchText" placeholder="<%= localeMessage.getString("propertyDetail.propertyKey") %> 또는 <%= localeMessage.getString("propertyDetail.propertyValue") %> 검색" />
					<button type="button" class="cssbtn smallBtn2" id="btn_search"><i class="material-icons">search</i> 검색</button>
					<button type="button" class="cssbtn smallBtn2" id="btn_reset"><i class="material-icons">refresh</i> 초기화</button>
				</div>

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

		<style>
		.search-box {
			margin: 10px 0;
			padding: 10px;
			background-color: #f5f5f5;
			border-radius: 4px;
		}
		.search-box input[type="text"] {
			width: 300px;
			padding: 5px 10px;
			border: 1px solid #ddd;
			border-radius: 3px;
		}
		.search-box button {
			margin-left: 5px;
		}
		</style>
	</body>
</html>