<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	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 selectName = "bjobBzwkDstcd,uapplCd";	// selectBox Name
var isDetail = false;
var lastsel2;
var isPopup = "${param.ispop}";

function isValid() {

	if( $('input[name=bjobMsgDstcd]').val().trim() == "" ) {
		alert("인터페이스ID를 입력하여 주십시요.");
		return false;
	} else if( $('select[name=bjobBzwkDstcd]').val() == "" ) {
		alert("업무그룹코드를 선택하여 주십시요.");
		return false;
	} else if( $('select[name=bjobInstiDstcd]').val() == "" ) {
		alert("대외기관코드를 선택하여 주십시요.");
		return false;
	} else if( $('input[name=bjobTranDstcdName]').val() == "" ) {
		alert("BATCH작업메시지구분코드를 입력하여 주십시요.");
		return false;
	} else if( $('input[name=bjobMsgDsticName]').val() == "" ) {
		alert("BATCH작업메시지구분명을 입력하여 주십시요.");
		return false;
	} else if( $('input[name=bjobTelgmHdrSize]').val() == "" ) {
		alert("BATCH작업전문헤더크기를 입력하여 주십시요.");
		return false;
	} else if( $('input[name=bjobTelgmRecSize]').val() == "" ) {
		alert("BATCH작업전문데이터크기를 입력하여 주십시요.");
		return false;
	} else if( $('input[name=uapplCd]').val() == "" ) {
		alert("APPLICATION CODE를 선택하여 주십시요.");
		return false;
	} 
	
	return true;
}

function gridRendering() {
	$('#grid').jqGrid({
		datatype: "local",
		loadonce: true,
		rowNum: 10000,
		editurl: "clientArray",
		colNames: ['프라퍼티명',
				   '프라퍼티설명',
				   '프라퍼티값'
				  ],
		colModel: [
					{ name : 'PRPTYNAME' , align:'left' },
					{ name : 'PRPTYDESC' , align:'left' },
					{ name : 'PRPTY2VAL' , align:'left', editable : true }
				  ],
		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: '300',
		autowidth: true,
		viewrecords: true
	});

	resizeJqGridWidth('grid','title','1000');
}

function init(url,key) {
	$.ajax({
		type: "POST",
		url: url,
		dataType: "json",
		data: { cmd: 'LIST_INIT_COMBO' },
		success: function(json) {
	//		new makeOptions("CODE","NAME").setObj($("select[name=bjobBzwkDstcd]")).setData(json.bjobBzwkDstcd).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=bjobBzwkDstcd]")).setData(json.bjobBzwkDstcd).rendering(); // 업무구분코드
			// new makeOptions("CODE","NAME").setObj($("select[name=bjobInstiDstcd]")).setFormat(codeName3OptionFormat).setData(json.bjobInstiDstcd).rendering(); // 대외기관코드
			//new makeOptions("BIZCODE","BIZNAME").setObj($("select[name=EAIBZWKDSTCD]")).setFormat(codeName3OptionFormat).setData(json.bizRows).rendering(); // 업무구분코드
			new makeOptions("CODE","NAME").setObj($("select[name=bJobCycleGb]")).setData(json.bJobCycleGb).rendering(); // BATCH작업주기구분(BAP_CYCLE_GB)

//			new makeOptions("CODE","NAME").setObj($("select[name=groupCoCd]")).setData(json.groupCoCd).rendering();
// 			new makeOptions("CODE","NAME").setObj($("select[name=sysCd]")).setNoValueInclude(true).setNoValue('','없음').setData(json.sysCd).rendering();
 			new makeOptions("CODE","NAME").setObj($("select[name=uapplCd]")).setData(json.uapplCd).rendering(); // 어플리케이션코드
 			
			if ( isDetail ) {
				detail(url, key);
			} else {
				$.ajax({
					type: "POST",
					url: url,
					dataType: "json",
					data: { cmd: 'LIST_PROP',
							bjobBzwkDstcd : $("select[name=bjobBzwkDstcd]").val(),
							bjobMsgDstcd : $("input[name=bjobMsgDstcd]").val()
					},
					success: function(json) {
						$("#grid")[0].addJSONData(json.propMap);
						$("select[name=bjobInstiDstcd] option").remove();
						new makeOptions("CODE","NAME").setObj($("select[name=bjobInstiDstcd]")).setFormat(codeName3OptionFormat).setData(json.InstMap.rows).rendering(); // 대외기관코드
						$("input[name=prptyGroupName]").val("TelegramInfo{" + detail["BJOBMSGDSTCD"] + "}");
						// $("input[name=thisMsgChrgIDs]").val(' ');
						// $("input[name=intfID]").val(' ');
						$("input[name=msgPrcssPrity]").val('999');
						$("input[name=dupCnt]").val('0');
						$("input[name=endCnt]").val('0');
					},
					error: function(e) {
						alert(e.responseText);
					}
				});
			}
		},
		error: function(e) {
			alert(e.responseText);
		}
	});
	setSearchable(selectName);	// 콤보에 searchable 설정
}

function detail(url,key) {
	if ( !isDetail ) return;
	$.ajax({  
		type: "POST",
		url: url,
		dataType: "json",
		data: { cmd: 'DETAIL',
				bjobMsgDstcd : key
		},
		success: function(json) {
			var data = json;
			var detail = json.detail;

			//adapterType
			$("input[name=bjobMsgDstcd]").attr('readonly',true);
			$("select[name=bjobBzwkDstcd]").attr('disabled',false);
			$("input[name=bjobTranDstcdName]").attr('readonly',false);
			$("input,select").each(function() {
				try {
					var name = $(this).attr('name').toUpperCase();
					$(this).val(detail[name]);
				} catch (e) {}
			});
			// 파일 송수신 구분
			$("select[name=fileSndRcvGbn]").val(detail["FILESENDUSEYN"] == 1 ? "S" : "R");
			// 대외기관코드 change 및 값 설정
			$("select[name=bjobInstiDstcd]").attr('disabled',false);
			$("input[name=bjobInstiDstVal]").val(detail["BJOBINSTIDSTCD"]); // 임시로 저장
			$("select[name=bjobBzwkDstcd]").val($("select[name=bjobBzwkDstcd]").val()).trigger("change");
			
			if ( $("input[name=dupCnt]").val().trim() == "" ) $("input[name=dupCnt]").val('0');
			if ( $("input[name=endCnt]").val().trim() == "" ) $("input[name=endCnt]").val('0');

			//Prop 
			$("#grid")[0].addJSONData(data.rows);
		},
		error: function(e) {
			alert(e.responseText);
		}
	});
}

var submitData = {};

$(document).ready(function() {
	var returnUrl = getReturnUrlForReturn();
	var url ='<c:url value="/bap/admin/work/messageProcMan.json" />';
	var key ="${param.bjobMsgDstcd}";
	$("input[name*=Size]").inputmask('decimal',{groupSeparator:',',digits:0,autoGroup:true,prefix:'',rightAlign:false,autoUnmask:true,removeMaskOnSubmit:true});
	if ( key != "" && key !="null" ){
		isDetail = true;
	}

	gridRendering();

	init(url,key);

	$("#btn_modify").click(function(){
		
		if (!isValid()) return;
		
		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]);
		}

		// 파일 송/수신구분 설정
		$("input[name=fileSendUseYn]").val($("select[name=fileSndRcvGbn]").val() == 'S' ? '1' : '0');
		$("input[name=fileRecvUseYn]").val($("select[name=fileSndRcvGbn]").val() == 'R' ? '1' : '0');
	
		//공통부만 form으로 구성
		var postData = $('#ajaxForm').serializeArray();
		postData.push({ name: "gridData"       , value: JSON.stringify(gridData)});
		postData.push({ name: "bjobBzwkDstcd"  , value: $("select[name=bjobBzwkDstcd]").val()});
		postData.push({ name: "prptyGroupName" , value: "TelegramInfo{" + $("input[name=bjobMsgDstcd]").val() + "}"});
		postData.push({ name: "prptyGroupDesc" , value: $("select[name=bjobBzwkDstcd]").val()+"배치 작업의 [" +$("input[name=bjobTranDstcdName]").val() +  "]메시지의  송수신 전문용 프로퍼티 정의"});

		if ( isDetail ) {
			postData.push( { name: "cmd" , value:"UPDATE"} );
	 		$.ajax({
				type: "POST",
				url: url,
				data: postData,
				success: function(args) {
					alert("저장 되었습니다.");
					if ( isPopup == 'Y' ) {
						window.close();
					} else {
						goNav(returnUrl);//LIST로 이동
					}
				},
				error: function(e) {
					alert(e.responseText);
				}
			});
		} else {
			$.ajax({  
				type: "POST",
				url: url,
				dataType: "json",
				data: { cmd: 'INITIALIZE_PK',
						tableName: 'TSEAIBJ01',
						columnName: "BjobMsgDstcd",
						columnValue: $('input[name=bjobMsgDstcd]').val()
				},
				success:function(json) {
					if( json.checkPK == 'Y' ) {
						alert("이미 사용중인 인터페이스ID 입니다.\n\n다른 인터페이스ID를 입력하여 주십시요.");
						return false;
					} else {
				 		$.ajax({
							type: "POST",
							url: url,
							data: postData,
							success: function(args) {
								alert("저장 되었습니다.");
								goNav(returnUrl);//LIST로 이동
							},
							error: function(e) {
								alert(e.responseText);
							}
						});
					}
				}
			});
			postData.push( { name: "cmd" , value:"INSERT"} );
		}
	});
	
	$("#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로 이동
	});

	$("select[name=bjobBzwkDstcd]").change(function() {
		$.ajax({  
			type: "POST",
			url: url,
			dataType: "json",
			data: { cmd: 'LIST_PROP',
					bjobBzwkDstcd : $(this).val(),
					bjobMsgDstcd : $('input[name=bjobMsgDstcd]').val()
			},
			success:function(json) {
				$("#grid")[0].addJSONData(json.propMap);
				$("select[name=bjobInstiDstcd] option").remove();
				new makeOptions("CODE","NAME").setObj($("select[name=bjobInstiDstcd]")).setFormat(codeName3OptionFormat).setData(json.InstMap.rows).rendering(); // 대외기관코드
				$("select[name=bjobInstiDstcd]").val($("input[name=bjobInstiDstVal]").val());
			}
		});
	});
	
	$("#btn_pop_detail").click(function() {
		var popUrl = '<c:url value="/bap/admin/work/messageProcMan.view" />' + '?cmd=POPUP';
		var args = new Object();
		args['data'] = key;
		args['ispop'] = true;

		var result = showModal(popUrl, args, 700, 600, 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;
		});
	});

	buttonControl(isDetail);
	titleControl(isDetail);

	$("#btn_close").click(function() {
		window.close();
	});

	if ( isPopup == 'Y' ) {
		$('#btn_delete').hide();
		$('#btn_modify').show();
		$('#btn_previous').hide();
		$('#btn_close').show();
	} else {
		$('#btn_close').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">
					<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"/>
					<img src="<c:url value="/img/btn_close.png"/>" alt="" id="btn_close" level="R" style="display:none;" />
				</div>
				<div class="title">송수신 파일</div>
				
				<form id="ajaxForm">
					<input type="hidden" name="sndrcvFileName" value=" "/>
					<input type="hidden" name="sndScriptname" />
					<table class="table_row" cellspacing="0">
						<colgroup>
							<col width="15%">
							<col width="30%">
							<col width="5%">
							<col width="15%">
							<col width="35%">
						</colgroup>
						<!-- 공통-->
						<tr>
							<th>인터페이스ID *</th>
							<td colspan="2"><input type="text" name="bjobMsgDstcd" /></td>
							<th>당메시지 사용여부 *</th>
							<td>
								<div class="select-style">
									<select name="thisMsgUseYn">
									<option value="1">사용</option>
									<option value="0">사용안함</option>
									</select>
								</div>
							</td>
						</tr>
						<tr>
							<th>업무구분코드</th>
							<td colspan="2">
								<div class="select-style">
									<select name="bjobBzwkDstcd"></select>
								</div>
							</td>
							<th>대외기관코드</th>
							<td colspan="2">
								<input type="hidden" name="bjobInstiDstVal" />
								<div class="select-style">
									<select name="bjobInstiDstcd"></select>
								</div>
							</td>
						</tr>
						<tr>
							<th>BATCH작업메시지구분코드 *</th>
							<td colspan="2"><input type="text" maxlength="40" name="bjobTranDstcdName" /></td>
							<th>BATCH작업메시지구분명 *</th>
							<td><input type="text" name="bjobMsgDsticName" /></td>
						</tr>
						<tr>
							<th>BATCH작업전문헤더크기 *</th>
							<td colspan="2"><input type="text" name="bjobTelgmHdrSize" /></td>
							<th>BATCH작업전문데이터크기 *</th>
							<td><input type="text" name="bjobTelgmRecSize" /></td>
						</tr>
						<tr>
							<th>BATCH작업전문트레일러크기</th>
							<td colspan="2"><input type="text" name="bjobTelgmTrailSize" /></td>
							<th>BATCH작업주기구분</th>
							<td><div class="select-style"><select name="bJobCycleGb"></select></div></td>
						</tr>
						<tr>
							<input type="hidden" name="fileSendUseYn" />
							<input type="hidden" name="fileRecvUseYn" />
							<th>파일 송/수신 구분</th>
							<td colspan="2">
								<div class="select-style">
									<select name="fileSndRcvGbn">
									<option value="S">송신</option>
									<option value="R">수신</option>
									</select>
								</div>
							</td>
							<th>수신시 알림여부</th>
							<td colspan="2">
								<div class="select-style">
									<select name="recvNotiUseYn">
									<option value="1">사용</option>
									<option value="0">사용안함</option>
									</select>
								</div>
							</td>
						</tr>
						<tr>
							<th>APPLICATION CODE *</th>
							<td colspan="2"><div class="select-style"><select name="uapplCd"></select></div></td>
							<!-- <th>파일명 패턴</th>
							<td>
								<div class="select-style">
									<select name="sndrcvFileName">
									<option value=" ">사용안함</option>
									<option value="yyyy">YYYY</option>
									<option value="yyyyMM">YYYYMM</option>
									<option value="MMdd">MMDD</option>
									<option value="yyyyMMdd">YYYYMMDD</option>
									<option value="001">일련번호</option>
									<option value="yyyy_001">YYYY_일련번호</option>
									<option value="yyyyMM_001">YYYYMM_일련번호</option>
									<option value="MMdd_001">MMDD_일련번호</option>
									<option value="yyyyMMdd_001">YYYYMMDD_일련번호</option>
									</select>
								</div>
							</td> -->
							<th>EAI 인터페이스ID</th>
							<td><input type="text" name="intfID" /></td>
						</tr>
						<tr>
							<th>데이터검증여부</th>
							<td style="border-right: 0px;">
								<div class="select-style">
									<select name="dataVrfyYn">
									<option value="1">사용</option>
									<option value="0">사용안함</option>
									</select>
								</div>
							</td>
							<td><img id="btn_pop_detail" src="<c:url value="/img/btn_pop_detail.png" />" class="btn_img" /></td>
							<th>작업처리 우선순위</th>
							<td><input type="text" name="msgPrcssPrity" /></td>
						</tr>
						<tr>
							<th>처리여부</th>
							<td colspan="2">
								<div class="select-style">
									<select name="procYn">
									<option value="1">사용</option>
									<option value="0">사용안함</option>
									</select>
								</div>
							</td>
							<th>중복횟수</th>
							<td><input type="text" name="dupCnt" /></td>
						</tr>
						<tr>
							<th>종결여부</th>
							<td colspan="2">
								<div class="select-style">
									<select name="endYn">
									<option value="1">사용</option>
									<option value="0">사용안함</option>
									</select>
								</div>
							</td>
							<th>종결횟수</th>
							<td><input type="text" name="endCnt" /></td>
						</tr>
						<tr>
							<th>파일담당자</th>
							<td colspan="4"><input type="text" name="thisMsgChrgIDs" /></td>
						</tr>
						<!-- <tr>
							<th>송신스크립트명</th>
							<td colspan="4"><input type="text" name="sndScriptname" /></td>
						</tr> -->
					</table>
				</form>

				<div class="table_row_title">프라퍼티 정보</div>
				<!-- grid -->
				<table id="grid" ></table>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->
	</body>
</html>