<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager" %>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
	String rmsMenuAuth = (String)request.getAttribute("rmsMenuAuth");
%>

<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/service/subMessageMan.json" />';
var url_view = '<c:url value="/onl/admin/service/subMessageMan.view" />';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var admin;
var isDetail = false;
var isClone = false;


function init(key,callback){

	$.ajax({
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_COLUMN'},
		success:function(json){
			const table = $("#dynamicTable");
			console.log(table)
			let comboNames = "";
			console.log(json.list);
			json.list.forEach(function(element){
				var trStr = '<tr><th width="15%">' + element.COLUMNDESC;
				if (element.ISKEY == 'Y') {
					trStr += '<small>(*)</small>';
				}

				if(element.COMBONAME != null && element.COMBONAME.trim() != '') {
					var options = "";
					element.comboList.forEach(function (opt) {
						options = options+'<option value="'+opt.CODE+'">['+opt.CODE+']'+opt.NAME+'</option>'
					});
					trStr = trStr+'</th><td><div class="select-style"><select name="'+ element.COLUMNNAME+'" id="'+element.COLUMNNAME+'">'+options+'</select></div></td></tr>';
				}else{
					const placeholderMessage = '<%= localeMessage.getString("subMessage.fieldPlaceHolder") %>'.formatLocale(element.COLUMNLENGTH);
					trStr = trStr+'</th><td><input type="text" name="' + element.COLUMNNAME+'" id="'+element.COLUMNNAME+'" value="'+element.COLUMNDEFAULT+'" placeholder="'+placeholderMessage+'"/></td></tr>';
				}

				table.append(trStr);
			});
		},
		error:function(e){
			alert(e.responseText);
		}
	});

	$.ajax({
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_DETAIL_COMBO'},
		success:function(json){
			{
				var arrRoleID	= roleString.split(",");
				for(var i = 0; i < arrRoleID.length; i++)
				{
					if(arrRoleID[i] == "admin")
						admin = true;
				}
				if(admin){
					$(".table_detail").find("TR").first().show();
				}else{
					$(".table_detail").find("TR").first().hide();
				}
			}
			if (typeof callback === 'function') {
				callback(key);
			}
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}
function detail(key){
	if (!isDetail)return;
	$.ajax({
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'DETAIL', bzwkSvcKeyName : key},
		success:function(json){
			var rows = json.rows;
			var keys = json.keys;
			var data=[];
			var keyData=[];


			$("input[name=bzwkSvcKeyName]").attr('readonly',true);
			$("input[name=bzwkSvcKeyName]").val(data[name.toUpperCase()]);

			for(var i=0;i<rows.length;i++){
				if (i==0) data["BZWKSVCKEYNAME"] = rows[0].BZWKSVCKEYNAME;
				data[rows[i].COLUMNNAME.toUpperCase()]= rows[i].COLUMNVALUE;
			}

			$("#ajaxForm input,#ajaxForm textarea,#ajaxForm select").each(function(){
				var name = $(this).attr("name");
				var tag  = $(this).prop("tagName").toLowerCase();
				var val = data[name.toUpperCase()];
				if (val) {
					$(tag+"[name='"+name+"']").val(data[name.toUpperCase()]);
				}

				//console.log(name+","+data[name.toUpperCase()])
				//isKey check ==> disable
				for(var i=0;i<keys.length;i++){
					if(name == keys[i].COLUMNNAME && keys[i].ISKEY == "Y" ){
						if( tag == "input")
							$("[name='"+keys[i].COLUMNNAME+"']").attr('readonly',true);
						else
							$("[name='"+keys[i].COLUMNNAME+"']").prop('disabled',true);
					}
				}
			});			
		},
		error:function(e){
			alert(e.responseText);
		}

	});

}
	function isValid(){
		if ($('input[name=bzwkSvcKeyName]').val()==""){
			alert("업무서비스키값을 입력하여 주십시요.");
			$('input[name=bzwkSvcKeyName]').focus();
			return false;
		}
		return true;
	}

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

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


	$("#btn_modify").click(function(){
		if (!isValid())return;

		if (isDetail && isClone) {
			if ( confirm( "복제하시겠습니까?" ) != true ) return;
		} else if (isDetail) {
			if ( confirm( '<%=localeMessage.getString("common.checkModify")%>' ) != true ) return;
		} else {
			if ( confirm( '<%=localeMessage.getString("common.checkInsert")%>' ) != true ) return;
		}


		// disable이면 serializeArray에 속하지 않음.
		$('#ajaxForm select[disabled]').each(function(){
			$(this).prop('disabled','');
		});
		var postData = $('#ajaxForm').serializeArray();

		$('#ajaxForm select[disabled]').each(function(){
			$(this).prop('disabled','disabled');
		});

		if (isDetail && isClone){
			postData.push({ name: "cmd" , value:"INSERT"});
		} else if (isDetail) {
			postData.push({ name: "cmd" , value:"UPDATE"});
		} else {
			postData.push({ name: "cmd" , value:"INSERT"});
		}
		var replacePostData = new Object();

		for(var i=0; i<postData.length;i++){
			var param_name = postData[i].name;
			var param_value = postData[i].value;

			var param_replace_name = param_name.replace(/-/gi,".");
			console.log(param_replace_name);
			replacePostData[param_replace_name] = param_value;
		}

		$.ajax({
			type : "POST",
			url:url,
			data:replacePostData,
			success:function(args){
				alert("<%= localeMessage.getString("common.saveMsg") %>");
				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("삭제 되었습니다.");
				goNav(returnUrl);//LIST로 이동

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

	$("#btn_clone").click(function(){
		// 복제할 메시지메타구분코드
		var newBzwkSvcKeyName = $("input[name=bzwkSvcKeyNameClone]").val();

		// 복제할 메시지메타구분코드 입력여부 체크.
		if(newBzwkSvcKeyName == "")
		{
			alert("복제할 업무서비스키를 입력하여 주십시요.");
			$("input[name=bzwkSvcKeyNameClone]").focus();
			return;
		}else{
			alert("복제시 데이터는 수정버튼을 클릭해야 DB에 저장됩니다.");
			$("input[name=bzwkSvcKeyName]").val(newBzwkSvcKeyName);
			$("input[name=bzwkSvcKeyNameClone]").val("");
		}


		$('#ajaxForm input[readonly]').each(function(){
			$(this).prop('readonly','');
		});

		$('#ajaxForm select[disabled]').each(function(){
			$(this).prop('disabled','');
		});

		$("input[name=eaiSvcName]").attr('readonly',true);

		//초기화 삭제버튼 숨김처리
		$("#btn_delete").hide();

		isClone = true;

	});

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

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

});

</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">
				<div class="search_wrap">
					<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_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("subMessage.title") %><span class="tooltip"><%= localeMessage.getString("stdMsg.tooltip") %></span></div>

				<form id="ajaxForm">
					<table class="table_row" cellspacing="0">
						<%
						if("R".equals(rmsMenuAuth)) {
						%>
						<tr>
							<th style="width:15%;"><%= localeMessage.getString("stdMsg.bizSvcKey") %></th>
							<td style="width:85%;" colspan="3"><input type="text"  name="bzwkSvcKeyName"/></td>
						</tr>
						<%
						}
						else {
						%>
						<tr>
							<th style="width:15%;"><%= localeMessage.getString("stdMsg.bizSvcKey") %></th>
							<td style="width:85%;" colspan="3"><input type="text"  name="bzwkSvcKeyName"/></td>
						</tr><tr>
							<th><%= localeMessage.getString("stdMsg.cloneKey") %></th>
							<td colspan="3">
								<input type="text" name="bzwkSvcKeyNameClone" style="width : 90%"/>
<%-- 								<img id="btn_clone" src="<c:url value="/img/btn_clone1.png"/>" level="W" status="DETAIL"/> --%>
								<button type="button" class="cssbtn smallBtn2" id="btn_clone" style="vertical-align:middle; font-weight:bold;" level="W" status="DETAIL"><i class="material-icons">content_copy</i><%= localeMessage.getString("button.clone2") %></button>
							</td>
						</tr>
						<%
						}
						%>						
					</table>
					<table id="dynamicTable" class="table_row" cellspacing="0">
					</table>

				</form>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->
	</body>
</html>

