<%@ 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"/>

<script language="javascript" >
var isPop = "${param.pop}";
var isDetail = false;
var lastSelIdx;
var lastrow;
var url      ='<c:url value="/onl/admin/rule/layoutMan.json" />';
var url_view ='<c:url value="/onl/admin/rule/layoutMan.view" />';
var url_excel	= '<c:url value="/onl/admin/rule/layoutMan.excel"/>';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var returnUrl = getReturnUrlForReturn();
var sevrArr = new Array();
function init(key,callback){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_DETAIL_COMBO'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=eaiBzwkDstcd]")).setData(json.bizList).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=loutPtrnName]")).setData(json.typeList).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=useYn]")).setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=eaiSevrDstcd]")).setData(json.eaiSevrCdRows).setFormat(codeName3OptionFormat).rendering();
			sevrArr = json.eaiSevrCdRows;
			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', loutName : key},
		success:function(json){
			var data = json.detail;
			$("input[name=loutName]").attr('readonly',true);
			
			$("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function(){
				var name = $(this).attr("name");
				var tag  = $(this).prop("tagName").toLowerCase();
				$(tag+"[name="+name+"]").val(data[name.toUpperCase()]);
			});
			var rows2 = json.rows2;
			for(var i=0; i<rows2.length; i++){
				var tranSevrCd = rows2[i]['TRANSEVRDSTCD'];
				var eaiSvcSevrCd = rows2[i]['EAISVCSEVRDSTCD'];
				for(var j=0; j<sevrArr.length; j++){
					var sevrCd = sevrArr[j]['CODE'];
					if(tranSevrCd==sevrCd){
						rows2[i]['TRANSEVRDSTCD']='['+sevrCd+'] '+sevrArr[j]['NAME'];
					}
					if(eaiSvcSevrCd==sevrCd){
						rows2[i]['EAISVCSEVRDSTCD']='['+sevrCd+'] '+sevrArr[j]['NAME'];
					}
				}
			}
			$("#grid")[0].addJSONData(json);
			$("#tree")[0].addJSONData(json);

			var TOTAL = {};
			
			var ids = $("#tree").jqGrid('getDataIDs');
			
			for (var i =0; i< ids.length; i++){
				var rowId = ids[i];
				//var rowData = $('#tree').jqGrid('getRowData', rowId);
				
				var parent = $('#tree').jqGrid('getCell', ids[i],'parent');
				var cnt = parseInt($('#tree').jqGrid('getCell', ids[i],'LOUTITEMLENCNT'));
				if(TOTAL[parent] == "undefined" || isNaN(TOTAL[parent]) ) TOTAL[parent] = "0";
				
				TOTAL[parent] = parseInt(TOTAL[parent]) + cnt + "" ;										
				
			}
			for (var i =0; i< ids.length; i++){
				var rowId = ids[i];
				//var rowData = $('#tree').jqGrid('getRowData', rowId);
				
				var occurTimes = $('#tree').jqGrid('getCell', rowId,'LOUTITEMMAXOCCURNOITM'); //rowData.LOUTITEMMAXOCCURNOITM;
				var refInfo = $('#tree').jqGrid('getCell', rowId,'LOUTITEMREFINFO2');	//rowData.LOUTITEMREFINFO2;
				var datatype = $('#tree').jqGrid('getCell', rowId,'LOUTITEMPTRNIDDESC');	//rowData.LOUTITEMPTRNIDDESC;
				var id = $('#tree').jqGrid('getCell', rowId,'id'); 	//rowData.id;
				
				if( datatype == "UNKNOWN" ){
					switch(Number(occurTimes)){
						case 0 : break;
						case 1: break;
						case -1:
							occurTimes = $('#tree').jqGrid('getCell', ids[i-1],'LOUTITEMMAXOCCURNOITM');
							TOTAL[id] = TOTAL[id]+ "*" +refInfo;
							 break;
						default : 
							occurTimes = occurTimes; 	//rowData.LOUTITEMMAXOCCURNOITM;
							TOTAL[id] = TOTAL[id]+ "*" +occurTimes;
							break;					
					}				
				
				}
			
			}
			var totalData="";
			var totVal1 = 0;
			var totVal2 = "";
			var strVal = "";
			
			for (var index in TOTAL){
				
				if(TOTAL[index].indexOf("*") == -1 ){
					totVal1 = totVal1 + parseInt(TOTAL[index]);
				}else{
					try{
						totVal2 = (totVal2==""?"":(totVal2+"+"))+ eval(TOTAL[index]);
					}catch (e){
						strVal = (strVal==""?"":(strVal+"+")) + TOTAL[index];
					}
				}
			}
			totalData = totVal1+ (totVal2==""?"":(" + "+totVal2));			

			totalData = totVal1+ (totVal2==""?"":eval(totVal2));
			if(strVal != "") totalData = totalData + "+" + strVal;
			
			$('#dataTotalLen').text(totalData);
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}
$(document).ready(function() {	
	var key ="${param.loutName}";
	if (key != "" && key !="null"){
		isDetail = true;
	}	
	init(key,detail);
	
	$("select[name=loutPtrnName]").attr("disabled","disabled");
	$("select[name=eaiBzwkDstcd]").attr("disabled","disabled");
	$("select[name=eaiSevrDstcd]").attr("disabled","disabled");
	$("select[name=useYn]").attr("disabled","disabled");
	
	$('#grid').jqGrid({
		datatype : "json",
		mtype : 'POST',
		colNames : [ '전문레이아웃변환매핑코드',
					 '변환매핑코드 서버구분코드',
		             'IF서비스코드',
		             'IF서비스코드 서버구분코드',
		             'IF서비스설명',
		             'SRC/TGT'
		              ],
		colModel : [ 
					{ name : 'CNVSNNAME'       , align : 'center' , width:'100'},
		            { name : 'TRANSEVRDSTCD'      , align : 'center' , width:'50'},
		            { name : 'EAISVCNAME'      , align : 'center' , width:'100'},
		            { name : 'EAISVCSEVRDSTCD'       , align : 'center' , width:'50'},
		            { name : 'EAISVCDESC'      , align : 'left'   },
		            { name : 'SOURCRSULTDSTCD' , align : 'left'   , width:'50'}
		              ],
		jsonReader : {
	    	root : "rows2",
			repeatitems : false
		},
		rowNum : 10000,
		autoheight : true,
		height : "80",
		autowidth : true,
		viewrecords : true,
		ondblClickRow : function(rowId) {
		}
	});
	$('#tree').jqGrid({
	    datatype:'json',
	    loadui: "disable",
	    mtype: 'POST',
	    //colNames: ["번호","항목명(영문)","항목설명","최대발생건수","참조정보","테이타타입","테이터길이","소수점길이","레이아웃명","ID","PARENT"],
	    colNames: [
	    	'<%=localeMessage.getString("layoutMan.num")%>',
            '<%=localeMessage.getString("layoutMan.itmeEn")%>',
            '<%=localeMessage.getString("layoutMan.itemDesc")%>',
            '<%=localeMessage.getString("layoutMan.maxOccCnt")%>',
            '<%=localeMessage.getString("layoutMan.refInfo")%>',
            '<%=localeMessage.getString("layoutMan.dataType")%>',
            '<%=localeMessage.getString("layoutMan.dataLen")%>',
            '<%=localeMessage.getString("layoutMan.decpLen")%>',
            '<%=localeMessage.getString("layoutMan.multilang")%>',
            '<%=localeMessage.getString("layoutMan.layoutName")%>',
	    	 "ID",
	    	 "PARENT"
		],
	    colModel: [
	        {name: "LOUTITEMSERNO"          , width:"30"},
	        {name: "LOUTITEMNAME"           , width:"250"},
	        {name: "LOUTITEMDESC"                      },
	        {name: "LOUTITEMMAXOCCURNOITM"  , width:"60"},
	        {name: "LOUTITEMREFINFO2"       , width:"150"},
	        
	        {name: "LOUTITEMPTRNIDDESC" 	, width:"60"},
	        {name: "LOUTITEMLENCNT"         , width:"60" ,align : 'right'},
	        {name: "DECPTLENCNT"            , width:"60" ,align : 'right'},
	        {name: "MULTILANG"              , width:"60" , align : 'center'},
	        
	        {name: "LOUTNAME"       ,hidden:true },
   	    	{name: "id"             ,hidden:true},
	    	{name: "parent"         ,hidden:true }
	      
	        
			],
	    treeGrid: true,
	    treeGridModel: "adjacency",
	    ExpandColumn: "LOUTITEMNAME",
	    height:"480",
	    rowNum: 10000,
	    autowidth : true,
	    treeIcons: {leaf:'ui-icon-document-b'},
	    jsonReader: {
	        repeatitems: false
	    },
	    loadComplete:function (d){
	    },
        loadError: function (jqXHR, textStatus, errorThrown) {
        	if(jqXHR.status == 401) {
	    		alert('HTTP status code: ' + jqXHR.status + '\n' +
	                    '에러:  세션이 종료되었습니다. ');
	    		parent.location.href='<%=request.getContextPath()%>/';	
	    	}
    	},	    
		ondblClickRow : function(rowId) {
		   /*
			var rowData = $(this).getRowData(rowId); 
            var key = rowData['LOUTNAME'];
            var url = '<c:url value="/onl/admin/rule/layoutMan.view" />';
            url = url + '?cmd=DETAIL_ITEM';
            url = url + '&page='+$(this).getGridParam("page");
            url = url + '&returnUrl='+getReturnUrl();
            url = url + '&menuId='+'${param.menuId}';
			//검색값
			url = url + '&' + getSearchUrl();
            //key값
            url = url + '&loutName='+key;
            url = url + '&loutItemName='+key;
            url = url + '&loutItemSerno='+key;
    		goNav(url);	
    		*/			
		}
	});	
	
	$("#btn_close").click(function(){
		window.close();
	});
	$("#btn_initialize").click(function(){
		$.ajax({  
			type : "POST",
			url:url,
			dataType:"json",
			data:{cmd: 'INITIALIZE',loutName:$("input[name=loutName]").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"),$("#ajaxForm"),$("select[name=loutName]").val());
		return false;
			
	});
	buttonControl(isDetail);
	//titleControl(isDetail);
	
	setBtnHide(roleString, "admin", "btn_initialize");
	$('body').css('overflow-x','hidden');
});
</script>
<style>
#btn_excel {

cursor:pointer
}
</style>
</head>
	<body>
	
	<div class="popup_box">
		<div class="search_wrap">
			<img id="btn_close" src="<c:url value="/img/btn_close.png"/>"         level="R" status="DETAIL,NEW"/>
		</div>
				<div class="title" style="margin-bottom: 5px;">레이아웃 상세</div>	
				
				<form id="ajaxForm">					
					<div class="table_row_title" style="margin-bottom: 5px;"><%=localeMessage.getString("layoutMan.titleDetail2")%></div>	
					<table class="table_row" cellspacing="0" style="margin-bottom: 5px;">
						<tr>
							<th style="width:20%;"><%=localeMessage.getString("layoutMan.layoutCd")%></th>
							<td><input type="text" name="loutName"/> </td>
							<th><%=localeMessage.getString("layoutMan.layoutDesc")%></th>
							<td><input type="text" name="loutDesc" readonly/> </td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("layoutMan.layoutTypeName")%></th>
							<td><div class="select-style"><select name="loutPtrnName"></select></div></td>
							<th style="width:20%;"><%=localeMessage.getString("layoutMan.bzwkdstcdName")%></th>
							<td><div class="select-style"><select name="eaiBzwkDstcd"></select></div></td>
						</tr>
						<tr >
							<th>서버구분코드</th>
							<td>
								<div class = "select-style">
									<select name="eaiSevrDstcd"></select>
								</div>
							</td>
							<th><%=localeMessage.getString("combo.useYn")%></th>
							<td>
								<div class = "select-style">
									<select name="useYn"></select>
								</div>
							</td>
						</tr>
					</table>				
					<div class="table_row_title" style="margin-bottom: 5px;">전문레이아웃 영향도 <span style="font-size:12px;">=> 현재 전문레이아웃을 사용하고 있는 매핑정보를 표시합니다.</span></div> 
					<table id="grid"></table>
					<div>	
						<div class="table_row_title" style="display:inline-block;margin-bottom: 5px;">전문레이아웃 항목 정보</div> 
						<img id="btn_excel" src="<c:url value="/img/btn_excel.png"/>" level="W" status="DETAIL" style="display: inline;width: 70px;top: 6px;position: relative;"/>
					</div>	
					<table id="tree"></table>				
					<table class="table_row" cellspacing="0" style="margin-top:15px;">
						<tr>
							<th style="width:20%;">데이터 총길이</th>
							<td id="dataTotalLen" >	</td>		
						</tr>
					</table>								
				</form>
			</div><!-- end content_middle -->
		
	<iframe name=excelDown width=0 height=0></iframe>
	</body>
</html>

