<%@ 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 url      ='<c:url value="/onl/admin/adapter/adapterChangeMan.json" />';
var url_view ='<c:url value="/onl/admin/adapter/adapterChangeMan.view" />';

var modify_rowID = 1;

function beforeModify(dev, test) {
	var dev_flag  = dev =="ON"?"1":"0";
	var test_flag = test=="ON"?"1":"0";
	
	return "D"+dev_flag+"T"+test_flag;
}

function list(_page) {   
	var postData = getSearchForJqgrid("cmd", "LIST"); //jqgrid에서는 object 로 
	
	$("#grid").setGridParam({ url:url, postData: postData,datatype:"json"}).trigger("reloadGrid");
}

function dataFormater(cellvalue, options, rowObject) {
	
	if (cellvalue == null || cellvalue==undefined)  {
		return "";
	}
	
	if(cellvalue == '0') {
		return $(document.createElement('span')).attr({ style : "color:red" }).text("OFF").prop('outerHTML');
	}
	
	if(cellvalue == '1') {
		return $(document.createElement('span')).attr({ style : "color:blue" }).text("ON").prop('outerHTML');
	}
	
	return "";
}	

function startStop(postData,rowId) {
	$("#modal-overlay").fadeIn();
	$.ajax({
		type : "POST",
		url : url,
		dataType : "json",
		data : postData,
		success : function(json) {
			$("#modal-overlay").fadeOut();
			alert(json.message);
			list("1");
			reloadDetailGrid(rowId);
			
			// 수정된 row 위치 저장.
			modify_rowID = rowId;			
		},
		error : function(e) {
			$("#modal-overlay").fadeOut();
			alert(e.responseText);
		}
	});
}


//어댑터 상세그리드 함수.
function searchAadaptDetail(adptGroup , eaisevrdstcd) {
	var postData = getSearchForJqgrid("cmd","LIST_SELECT_ADAPTER"); 
	postData["searchAdapterGroup"] = adptGroup;
	postData["eaisevrdstcd"] = eaisevrdstcd;
	$("#gridDetail").setGridParam({ url:url, postData: postData  }).trigger("reloadGrid");
	
}

//어댑터 전환이력 가져오기
function searchUserInfo(adptGroup) {
	var postData = getSearchForJqgrid("cmd","LIST_USER_INFO"); 
	postData["adptrbzwkgroupname"] =adptGroup;
	$("#gridDetail2").setGridParam({ url:url, postData: postData  }).trigger("reloadGrid");
}

function unformatterFunction(cellvalue, options, rowObject) {
	return "";
}

function fontFormatterFunction(cellvalue, options, rowObject) {
	var rowId = options["rowId"];
	if (cellvalue == "true") {
		return "<font color='#0000FF'>" + cellvalue + "</font>";
	} else if (cellvalue == "false") {
		return "<font color='#FF0000'>" + cellvalue + "</font>";
	}
}

function allOffBtnFormatterFunction(cellvalue, options, rowObject) {
	var rowId = options["rowId"];
	return "<img name='img_"+rowId+"' src=<c:url value='/images/bt/pop_operate.gif' /> />";
}

function dateFormater(cellvalue, options, rowObject){ //20190513134307
	if (cellvalue==null|| cellvalue==undefined) return "";
	if (cellvalue.trim().length !=14) return "";
	var display = "";
	display=display+cellvalue.substr(0,4)+"년 ";
	display=display+cellvalue.substr(4,2)+"월 ";
	display=display+cellvalue.substr(6,2)+"일 ";
	display=display+cellvalue.substr(8,2)+":";
	display=display+cellvalue.substr(10,2)+":";
	display=display+cellvalue.substr(12,2);
	return display;
}	

function reloadDetailGrid(rowId){
	
	$('#gridDetail').jqGrid('clearGridData');
	$('#gridDetail2').jqGrid('clearGridData');
	
	var adptGroup		= $("#grid").jqGrid("getCell", rowId, "ADPTRBZWKGROUPNAME");
	var eaisevrdstcd	= $("#grid").jqGrid("getCell", rowId, "EAISEVRDSTCD");
	searchAadaptDetail(adptGroup , eaisevrdstcd);
	searchUserInfo(adptGroup);
	
}

$(document).ready(function() {
	
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
	
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		postData : gridPostData,
		url : url,
		colNames:['어댑터 그룹명',
				  '어댑터 설명',
				  '어댑터 별명',
                  'DEV',
                  'TEST',
                  '모두끄기',
                  '서버구분코드',
                  '업무구분코드',
                  '사용자업무코드권한',
                  '담당자명',
                  '연락처'
                  ],
		colModel:[
				{ name : 'ADPTRBZWKGROUPNAME' 	, align:'left'    ,width:100},
				{ name : 'ADPTRBZWKGROUPDESC' 	, align:'left'    ,width:100 },
				{ name : 'ADPTRNICKNAME' 		, align:'left'    ,width:60  },
				{ name : 'ADPTRUSEYN'        	, align:'center'  ,width:30, formatter: dataFormater },  
				{ name : 'ADPTRUSEYN2'        	, align:'center'  ,width:30, formatter: dataFormater }, 
				{ name : 'OFFALL'        		, align:'center'  ,width:30, formatter: allOffBtnFormatterFunction},
				{ name : 'EAISEVRDSTCD'			, hidden:true},
				{ name : 'EAIBZWKDSTCD'			, hidden:true},
				{ name : 'AUTHCHK'				, hidden:true},
				{ name : 'OSIDINSTIBZWKRSEMPNAME',align:'center'  ,width:70, sortable : false},
				{ name : 'OSIDINSTITELNO'		, align:'center'  ,width:70, sortable : false}
				],
				
        jsonReader: {
             repeatitems:false
        },	          
	    autoheight: true,
	    //height: $("#container").height(),
	    height: "280",
		autowidth: true,
		viewrecords: true,
		rowNum : 5000,
		loadonce:true,
		gridComplete:function (d){
			//GroupHeader 셋팅후 colModel 변경 
			
			/* $("#grid").jqGrid('destroyGroupHeader');
			var colModel = $(this).getGridParam("colModel");
			$(this).jqGrid('setLabel',colModel[2].name, adptInstNm[0]);
		 	$(this).jqGrid('setLabel',colModel[3].name, adptInstNm[1]);
			$(this).jqGrid('setLabel',colModel[4].name, adptInstNm[2]);	
			$(this).jqGrid('setLabel',colModel[5].name, adptInstNm[3]);		
			
			$("#grid").jqGrid('setGroupHeaders', {
		  		useColSpanStyle: true, 
		  		 groupHeaders:[
		 			{startColumnName: 'ADPTRUSEYN1', numberOfColumns: 2, titleText: 'TOBE'},
		 			{startColumnName: 'ADPTRUSEYN3', numberOfColumns: 2, titleText: 'ASIS'},
		 			{startColumnName: 'OSIDINSTIBZWKRSEMPNAME', numberOfColumns: 2, titleText: '대외기관'}
		   		]
			}); */			
		},		
		loadComplete:function (d){
			
			$("#modal-overlay").fadeOut();
			
			if(d.errMsg) {
				alert(d.errMsg);
			}
			
			var rowCnt = $("#grid").getGridParam("reccount");
			if(rowCnt > 0)
			{
				$("#grid").jqGrid("setSelection",modify_rowID, true);
				// 초기화
				modify_rowID = 1;
			}
		},
        loadError: function (jqXHR, textStatus, errorThrown) {
        	
        	alert(textStatus);
        	console.error(errorThrown);
        	
        	if(jqXHR.status == 401) {
	    		alert('HTTP status code: ' + jqXHR.status + '\n' +
	                    '에러:  세션이 종료되었습니다. ');
	    		parent.location.href='<%=request.getContextPath()%>/';	
	    	}
        	
    	},
		ondblClickRow: function(rowId) {
			
        },
        onCellSelect: function(rowId, index, contents, event) {
        	
        	var data = $(this).getRowData(rowId);
        	var cellValue = $(this).getCell(rowId,index);
        	
        	//on 클릭시 기동하고자하는 어댑터 선택하라는 메시지 나옴 
        	//off 클릭시 전부 off 시킨후에 선택어댑터 on 시킴 
        	var modfibfeaisevrname = "";
        	var modfibfeaiInstname = "";
        	
        	var hist_adapterInst = "";   //최종 변경  INST
        	var hist_user  = "";  //최종 변경 이사용자
        	var hist_user_telNo = ""; //전화번호
        	var eaibzwkdstcd =  $("#grid").jqGrid("getCell", rowId, "EAIBZWKDSTCD");
        	var isUserBiz =  $("#grid").jqGrid("getCell", rowId, "AUTHCHK");
        	
        	if(index == 3 || index == 4) { //어댑터 ON/OFF
        		
        		adapter_on_off(rowId, index, data, cellValue);
     			
        	} else if(index == 5) {
        		
        		all_adapter_off(rowId, data, cellValue);
        		
        	} else {
        		
        		reloadDetailGrid(rowId);
        		
        	}
       }
            		
	});
	
	$("#grid").jqGrid('setGroupHeaders', {
  		useColSpanStyle: true, 
  		 groupHeaders:[
 			{startColumnName: 'ADPTRUSEYN', numberOfColumns: 3, titleText: '우체국'},
 			{startColumnName: 'OSIDINSTIBZWKRSEMPNAME', numberOfColumns: 2, titleText: '대외기관'}
   		]
	});

	$("#btn_search").click(function(){
		$('#gridDetail').jqGrid('clearGridData');
		$('#gridDetail2').jqGrid('clearGridData');
        
		list("1");
	});
	
	
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});
	
	$('#gridDetail').jqGrid({
		datatype:"json",
		mtype: 'POST',
		colNames:['엔진 서버구분',
				  '어댑터 그룹명',
                  '어댑터명',
                  '상태',
                  '기동',
                  '엔진 인스턴스명'
                  ],
                  colModel : [
                	  	{
							name : 'EaiServerName',
							align : 'center',
							width : '40',
							sortable : false
						},
						{
							name : 'AdptrBzwkGroupName',
							align : 'left',
							width : '140',
							sortable : false
						},
						{
							name : 'AdptrBzwkName',
							align : 'left',
							width : '170',
							sortable : false
						},
						{
							name : 'Status',
							align : 'center',
							width : '40',
							sortable : false,
							unformat : unformatterFunction,
							formatter : fontFormatterFunction
						},
						{
							name : 'Starting',
							align : 'center',
							width : '55',
							sortable : false
						},
						{
							name : 'EaiSevrInstncName',
							align : 'left',
							width : '100',
							sortable : false
						}
						 ],
				
        jsonReader: {
             repeatitems:false
		},
	    loadError: function (jqXHR, textStatus, errorThrown) {
	    	if(jqXHR.status == 401) {
 	    		alert('HTTP status code: ' + jqXHR.status + '\n' +
 	                    '에러:  세션이 종료되었습니다. ');
 	    		parent.location.href='<%=request.getContextPath()%>/';	
 	    	}
		},
		autowidth: true,
		height: "120",
	 });
	
	//변경이력관리
	$('#gridDetail2').jqGrid({
		datatype:"json",
		mtype: 'POST',
		colNames:['부서명',
				  'ID',
                  '변경자',
                  '연락처',
                  '휴대폰번호',
                  '변경일시',
                  '변경전',
                  '변경후'
                  ],
		colModel:[
				{ name : 'TEAMNAME' 		  , align:'center'  , sortable : false},
				{ name : 'USERID' 		  	  , align:'center'  ,width:100, sortable : false},
				{ name : 'USERNAME' 		  , align:'center'  ,width:100, sortable : false},
				{ name : 'OFCTELNO'        	  , align:'center'  ,width:100, sortable : false},
				{ name : 'CPHNNO'        	  , align:'center'  ,width:100, sortable : false},
				{ name : 'LASTAMNDYMS'        , align:'center'  ,width:100 ,formatter: dateFormater, sortable : false},
				{ name : 'MODFIBFEAISEVRNAME' , align:'center'  ,width:100, sortable : false, formatter: beforeAfterFormatter},
				{ name : 'MODFIAFEAISEVRNAME' , align:'center'  ,width:100, sortable : false, formatter: beforeAfterFormatter}
				],
				
        jsonReader: {
             repeatitems:false
        },  
		autowidth: true,
		height: "100",
	});
	
	buttonControl();
	
});

function adapter_on_off(rowId, index, data, cellValue) {
	
	var cellTextValue = $(cellValue).text(); 
	var useYn_1_textValue = $(data.ADPTRUSEYN).text();
	var useYn_2_textValue = $(data.ADPTRUSEYN2).text();
	
    if(cellValue == "") {
    	alert("어댑터 ON/OFF 상태를 알 수 없습니다.");
		return;
    }

  	//권한체크
	if ("${rmsMenuAuth}" == "R") {
		alert("어댑터전환 권한이 없습니다.");
		return;
	}
    
    if(cellTextValue == "ON") {
		alert("기동하고자 하는 어댑터(ON시키고자 하는 어댑터)를 클릭하십시오.");
		return;
	}
	
	var postData = [];
	postData.push({ name: "cmd" , value:"UPDATE_STARTSTOP"});
	
	var request_dev_useYn = "";
	var request_test_useYn = "";
	
	if(useYn_1_textValue == "OFF" && useYn_2_textValue == "OFF") {
		
		if(index == 3) {
			
			request_dev_useYn = "1";
			request_test_useYn = "0";
			
		} else if (index == 4) {
			
			request_dev_useYn = "0";
			request_test_useYn = "1";
			
		}
		
	} else {
		
		request_dev_useYn 	= useYn_1_textValue == "ON" ? "0" : "1";
		request_test_useYn 	= useYn_2_textValue == "ON" ? "0" : "1";
		
	}
	
	var confirmStr = data.ADPTRBZWKGROUPDESC + "를\n개발 : " + $(dataFormater(request_dev_useYn)).text() + "\n테스트 : " + $(dataFormater(request_test_useYn)).text() + "\n로 변경하시겠습니까?";
	
	if(confirm(confirmStr)){
		
		$.each(data, function(rowId,index) {
			if(index == "ON") {
				modfibfeaisevrname = adptInstMap.get(rowId);
				modfibfeaiInstname = adptInstNmMap.get(rowId);
				
			}
		});
			
		postData.push({ name: "ADPTRBZWKGROUPNAME" , value:data.ADPTRBZWKGROUPNAME});
		postData.push({ name: "DEVUSEYN", value: request_dev_useYn });
		postData.push({ name: "TESTUSEYN", value: request_test_useYn });
		
		// 변경전 어댑터정보
		postData.push({ name : "MODFIBFEAISEVRNAME", value : beforeModify(useYn_1_textValue, useYn_2_textValue)});
		
		startStop(postData, rowId);
	}	
	
}

function all_adapter_off(rowId, data, cellValue) {
	
	var useYn_1_textValue = $(data.ADPTRUSEYN).text();
	var useYn_2_textValue = $(data.ADPTRUSEYN2).text();
	
	if(useYn_1_textValue == "" || useYn_2_textValue == "") {
		alert("어댑터 ON/OFF 상태를 알 수 없습니다.");
		return;
	}
	
	if(confirm("개발, 테스트 어댑터를 모두 끕니다. 진행하시겠습니까?")) {
		
		var postData = [];
		postData.push({ name: "cmd" , value : "UPDATE_STARTSTOP" });
	
		postData.push({ name: "ADPTRBZWKGROUPNAME" , value: data.ADPTRBZWKGROUPNAME});
		postData.push({ name: "DEVUSEYN"	, value: "0" });
		postData.push({ name: "TESTUSEYN"	, value: "0" });
		
		postData.push({ name: "MODFIBFEAISEVRNAME", value : beforeModify(useYn_1_textValue, useYn_2_textValue)});
		
		startStop(postData, rowId);
	}
	
}

function beforeAfterFormatter(cellvalue, options, rowObject) {
	return cellvalue.replace("D", "개발 : ").replace("T", "테스트 : ").replaceAll("1", "ON ").replaceAll("0", "OFF ");
}

</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">
					<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />
				</div>
				<div class="title">어댑터 전환 관리</div>
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th style="width:100px;">어댑터 그룹명</th> <!-- 3자리만 입력가능하게  -->
							<td style="width:250px;">
								<input type="text" name="searchAdptrBzwkGroupName" value="${param.searchAdptrBzwkGroupName}" >
							</td> 
							<th style="width:100px;">어댑터 설명</th>
							<td style="width:250px;">
								<input type="text" name="searchAdptrBzwkGroupDesc" value="${param.searchAdptrBzwkGroupDesc}">
							</td>
						</tr>
					</tbody>
				</table>
				<table id="grid" ></table>
				<div style="color:blue;text-align:right;height:20px;">- 연결유지형 소켓의 세션이 없는경우 상태가 false 로 보임(상대기관의 서버상태 확인필요)</div>
				<table id="gridDetail" ></table>
				<div style="height:10px;"></div>	
					<table id="gridDetail2" ></table>
				<div id="pager"></div>				
			</div><!-- end content_middle -->			
		</div><!-- end right_box -->
		<div id="modal-overlay">wait</div>
	</body>		
</html>

