<%@ 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/common/propertyMan.json" />';
	var url_view = '<c:url value="/bap/admin/common/propertyMan.view" />';
	var isDetail = false;
	var lastsel2;
	
	var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
	var devSvr		= <%=SystemUtil.isDevServer()%>;
	var prdSvr		= <%=SystemUtil.isProdServer()%>;
	var stgSvr		= <%=SystemUtil.isStagingServer()%>;
	var svrType		= '';
	
	function isValid() {
		if ($('input[name=prptyGroupDesc]').val() == "") {
			alert("프라퍼티 그룹 설명을 입력하여 주십시요.");
			return false;
		}

		return true;
	}
	function isValidGrid() {
		if ($('input[name=prptyName]').val() == "") {
			alert("프러퍼티 키를 입력하여 주십시요.");
			return false;
		} else if ($('input[name=prpty2Val]').val() == "") {
			alert("프러퍼티 값 입력하여 주십시요.");
			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("증복된 프라퍼티키가 존재합니다. 확인하여주십시요.");
				return false;
			}
		}

		return true;
	}
	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' /> />";
	}
	function gridRendering() {
		$('#grid').jqGrid({
			datatype:"local",
			loadonce: true,
			rowNum: 10000,
			editurl : "clientArray",
			colNames : [ '프라퍼티 키', '프라퍼티 값', '삭제여부' ],
			colModel : [ { name : 'PRPTYNAME' , align : 'left', editable : true },
			             { name : 'PRPTY2VAL' , align : 'left', editable : true },
			             { name : 'DELETEYN'  , align : 'center', unformat : unformatterFunction, formatter : formatterFunction } ],
			jsonReader : {
				repeatitems : false
			},
			loadComplete : function() {
			},
	        onSortCol : function(){
	        	return 'stop';	//정렬 방지
	        },   			
			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;

	    },        
			
			height : '500',
			autowidth : true,
			//autoheight : true,
			viewrecords : true
		});

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

		if (!isDetail)
			return;
		$.ajax({
			type : "POST",
			url : url,
			dataType : "json",
			data : {
				cmd : 'DETAIL',
				prptyGroupName : key
			},
			success : function(json) {
				var data = json;
				var detail = json.detail;
				$("input[name=prptyGroupName]").attr('readonly', true);
				$("input,select").each(function(){
					var name = $(this).attr('name').toUpperCase();
					$(this).val(detail[name]);
				});
				//$("input[name=prptyGroupName]").val(detail['PRPTYGROUPNAME']);
				//$("input[name=prptyGroupDesc]").val(detail['PRPTYGROUPDESC']);
				$("#grid")[0].addJSONData(data);
				$("img[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 url = '<c:url value="/bap/admin/common/propertyMan.json" />';
		var key = "${param.prptyGroupName}";

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

		if(devSvr) {
			svrType = "stg";
		} else if (stgSvr){
			svrType = "prod";
		} else if (!prdSvr){
			svrType = "dev";
		}
		
		gridRendering();

		init(url, key, detail);

		$("#btn_modify").click(function() {
			
			if (isDetail) {
				if ( confirm( "수정하시겠습니까?" ) != true ) return;
			} else {
				if ( confirm( "등록하시겠습니까?" ) != 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();
			var gridData = new Array();
			for ( var i = 0; i < data.length; i++) {
				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("저장 되었습니다.");
					goNav(returnUrl);//LIST로 이동
				},
				error : function(e) {
					alert(e.responseText);
				}
			});
		});
		$("#btn_delete").click(function() {
			
			if ( confirm( "삭제하시겠습니까?" ) != true ) return;
			
			var postData = $('#ajaxForm').serializeArray();
			postData.push({
				name : "cmd",
				value : "DELETE"
			});
			$.ajax({
				type : "POST",
				url : url,
				data : postData,
				success : function(args) {
					alert("삭제 되었습니다.");
					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();
			$("img[name=img_" + rowid + "]").click(function() {
				var name = $(this).attr("name");
				var rowId = name.split("_")[1];
				$('#grid').jqGrid('delRowData', rowId);
			});

		});
		$("#btn_download_sql").click(function() {
			
			if ( confirm( "입력쿼리를 다운로드하시겠습니까?" ) != true ) return;	
			
			var postData = $('#ajaxForm').serializeArray();
			var sqlFileName = "BAP_PROPERTY_INPUT_QUERY.sql";
			postData.push({
				name : "cmd",
				value : "LIST_DOWNLOAD_SQL"
			});
			postData.push({
				name : "prptyGroupName",
				value : $("input[name=prptyGroupName]").val()
			});
			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("프로퍼티 입력 SQL문이 다운로드되었습니다.")
				},
				error : function(e) {
					alert(e.responseText);
				}
			});
		});
		$("img[id=btn_clone_"+svrType+"]").click(function() {
			
			if ( confirm( "복사하시겠습니까?" ) != true ) return;
			
			var postData = $('#ajaxForm').serializeArray();
			postData.push({
				name : "cmd",
				value : "LIST_DOWNLOAD_SQL"
			});
			postData.push({
				name : "prptyGroupName",
				value : $("input[name=prptyGroupName]").val()
			});
			postData.push({
				name : "svrType",
				value : svrType
			});
			
			$.ajax({
				type : "POST",
				url : url,
				data : postData,
				success : function(args) {
	 				if (args.result != "" && args.error == "") {
						alert("정상 반영되었습니다.");
					} else if (args.error != "") {
						if ("${fn:contains(args.error,'SqlIntegrityConstraintViolationException')}") {
							alert("이미 존재하여 정상 반영되지 않었습니다.");
						} else {
							alert("오류가 발생하여 정상 반영되지 않았습니다. 오류 : "+args.error);
						}
					}
	 				goNav(returnUrl);
				},
				error : function(e) {
					alert(e.responseText);
				}
			});
			
		});		
		
		buttonControl(key);
		titleControl(key);
		
		if(devSvr) {
			setBtnHide(roleString, " ", "btn_clone_dev");
			setBtnHide(roleString, " ", "btn_clone_prod");
			setBtnHide(roleString, isDetail ? "admin" : " ", "btn_clone_stg");
		} else if (stgSvr){
			setBtnHide(roleString, " ", "btn_clone_dev");
			setBtnHide(roleString, " ", "btn_clone_stg");
			setBtnHide(roleString, isDetail ? "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, isDetail ? "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" status="DETAIL"/>
					<img src="<c:url value="/img/btn_clone_prod.png"/>" alt="" id="btn_clone_prod" level="W" status="DETAIL"/>
					<img src="<c:url value="/img/btn_clone_dev.png"/>" alt="" id="btn_clone_dev" 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">프로퍼티</div>						
				
				<form id="ajaxForm">
					<table class="table_row" cellspacing="0">
						<tr>
							<th style="width:20%;">프라퍼티 그룹명 *</th>
							<td><input type="text" name="prptyGroupName" style="display:inline-block; width:calc(100% - 60px);"/>
								<img id="btn_download_sql" src="<c:url value="/img/icon_download.png"/>" class="btn_img" level="W" status="DETAIL"/>
							</td>
						</tr>
						<tr>
							<th>프라퍼티 그룹설명 *</th>
							<td><input type="text" name="prptyGroupDesc"/></td>
						</tr>
					</table>
				</form>
				<table class="table_row" cellspacing="0">
					<tr>
						<th style="width:20%;">프라퍼티키</th>
						<td><input type="text" name="prptyName" style="width:calc(100% - 85px); margin-right:10px;" /><img src="<c:url value="/img/btn_pop_input.png"/>" id="btn_pop_input" class="btn_img" /></td>						
					</tr>
					<tr>
						<th>프라퍼티 값</th>
						<td><input type="text" name="prpty2Val"/></td>
					</tr>
				</table>
				<!-- grid -->
				<table id="grid"></table>
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->	
	</body>
</html>