<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ 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 url      = '<c:url value="/onl/admin/control/controlMan.json" />';
var url_view = '<c:url value="/onl/admin/control/controlMan.view" />';
var url_excel= '<c:url value="/onl/admin/control/controlMan.excel"/>';
// var startTime;

var selectName = "searchEaiBzwkDstcd";	// selectBox Name

function init() {
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_INIT_COMBO'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=searchControlType]")).setData(json.controlList).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchIo]")).setData(json.ioList).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchEaiBzwkDstcd]")).setData(json.bizList).setNoValueInclude(true).setNoValue("A", "전체").setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchControlSelectType]")).setData(json.controlSelectList).setFormat(codeName3OptionFormat).rendering();
			
			setSearchable(selectName);	// 콤보에 searchable 설정
			
			if(typeof callback === 'function') {
				callback(key);
			}			
		},
		error:function(e){
			alert(e.responseText);
		}
	});
	
}

// 체크된 grid Cell에 있는 EAISVCNAME값을 배열에 저장.
function getRowArray()
{
	var chkList			= new Array();
	var rowIdx			= 0;
	var arrIdx			= 0;
	
	$("input[type=checkbox][name*=jqg_grid_]").each(function(idx){
	
		if($(this).is(":checked"))
		{
			rowIdx = idx+1;
			chkList[arrIdx] = $("#grid").jqGrid("getCell", rowIdx, "EAISVCNAME");
			
			arrIdx++;
		}
	});
	
	return chkList;
}

function fnControlType(){
	if ($("select[name=searchControlType]").val() =="I"){
		$("select[name=searchIo]").attr("disabled",true);
	}else{
		$("select[name=searchIo]").attr("disabled",false);
	}
}

function startEndTimeFormat(cellvalue, options, rowObject){
	if(cellvalue == null || cellvalue == '')
		return ''
	const cells = cellvalue.split('|');
	const index = options.colModel.timeType == 'start' ? 5 : 6;
	const value = cells[index];
	return value.substring(0, 2)+':'+value.substring(2);
}

$(document).ready(function() {
	init();	
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		colNames:[
				  '<%= localeMessage.getString("control.bizCode") %>',
                  '<%= localeMessage.getString("control.bizCodeName") %>',
                  '<%= localeMessage.getString("control.code") %>',
                  '<%= localeMessage.getString("control.description") %>',
                  '<%= localeMessage.getString("control.startTime") %>',
                  '<%= localeMessage.getString("control.endTime") %>',
                  '<%= localeMessage.getString("control.status") %>'
                  ],
		colModel:[
				{ name : 'EAIBZWKDSTCD'  , align:'left',width:'25' },
				{ name : 'BZWKDSTICNAME' , align:'left',width:'70' },
				{ name : 'EAISVCNAME'    , align:'left',width:'55' },
				{ name : 'EAISVCDESC'    , align:'left' },
				{ name : 'EAICTRLDSTICCTNT', align:'center', width:'25', formatter: startEndTimeFormat, timeType: 'start' },
				{ name : 'EAICTRLDSTICCTNT2', align:'center', width:'25', formatter: startEndTimeFormat, timeType: 'end' },
				{ name : 'STATUS'        , align:'center',width:'15', cellattr:function(rowId, tv, rowObject, cm, rdata){if(rowObject.STATUS == "통제") return 'style="color:red"'}}
				],
        jsonReader: {
             repeatitems:false,
             total: "total"
        },	          
		rowNum : 10000,
		rownumbers : true,
	    //autoheight: true,
	    //width: 1090,
	    height: 500,
		autowidth: true,
// 		viewrecords: true,
		multiselect : true,
		multiboxonly: false,
		//loadonce:true,
		gridview:true,
		gridComplete:function (d){
			var colModel = $(this).getGridParam("colModel");
			for(var i = 0 ; i< colModel.length; i++){
				$(this).setColProp(colModel[i].name, {sortable : false});	//그리드 헤더 화살표 삭제(정렬X)		
			}
		
		},			
		ondblClickRow: function(rowId) {
        },
        loadComplete:function(){
//       		var endTime = new Date().getTime();
//       		var resultTime = endTime - startTime;
// 			console.log("resultTime : " + resultTime);
        },
        loadError: function (jqXHR, textStatus, errorThrown) {
        	if(jqXHR.status == 401) {
	    		alert('HTTP status code: ' + jqXHR.status + '\n' +
	                    '에러:  세션이 종료되었습니다. ');
	    		parent.location.href='<%=request.getContextPath()%>/';	
	    	}
        	
    	}
	});
	
	$("#btn_search").click(function(){
		$("#grid").jqGrid("clearGridData");
// 		if($("input[name=searchCode]").val().length == 0){
// 			alert("거래통제 코드를 입력하세요.");
// 			return;
// 		}
// 		if ($("select[name=searchControlType]").val() =="S"){
// 			$("#grid").jqGrid("showCol","EAISVCDESC");
// 			$("#grid").jqGrid("showCol","BZWKDSTICNAME");
// 		}else{
// 			$("#grid").jqGrid("hideCol","EAISVCDESC");
// 			$("#grid").jqGrid("hideCol","BZWKDSTICNAME");
// 		}
// 		startTime = new Date().getTime();
		var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
		$("#grid").setGridParam({ url:url,postData: postData ,page : "1" }).trigger("reloadGrid");
	});
	
	
	$("#btn_upload").click(function(){
		 var args = new Object();
		    var url2 = url_view;
		    url2 += "?cmd=POPUP";
		    //showModal(url2,args,550,600);
		    var ret = showModal(url2,args,750,800, 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;
		        var ret = args.returnValue;
		        init();
		        
		    });
	});


	// 통제 등록
	$("#btn_modify").click(function(e){
// 		var chkList			= $("#grid").getGridParam("selarrrow");
		var chkList;
		var arrEaiSvcName	= new Array();
		var idx				= 0;
		var postData;
		var rowCnt			= $("#grid").getGridParam("reccount");
		
		chkList = getRowArray();
		
		if(rowCnt <= 0)
		{
			alert("조회된 데이터가 없습니다.");
			return false;
		}
		
		if(chkList.length == 0)
		{
			alert("통제코드를 선택하여 주십시요.");
			return false;
		}
		$( '#regist_dialog' ).dialog("open");

		<%-- 
		var r = confirm("통제등록 하시겠습니까?");
		if (r == false){
			chkList = null;
			return false;
		}
		
		postData = getSearchForJqgrid("cmd","INSERT"); //jqgrid에서는 object 로 
		postData["arrEaiSvcName"] = chkList;
		
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(args){
				$("#grid").jqGrid("clearGridData");
				alert("등록 되었습니다.");
				chkList = null;
				$("#btn_search").click();
			},
			error:function(e){
				alert(e.responseText);
			}
		});
		--%>
	});
	
	// 통제 해제
	$("#btn_delete").click(function(e){
// 		var chkList			= $("#grid").getGridParam("selarrrow");
		var chkList;
		var arrEaiSvcName	= new Array();
		var idx				= 0;
		var postData;
		var rowCnt			= $("#grid").getGridParam("reccount");

		chkList = getRowArray();
		
		if(rowCnt <= 0)
		{
			alert("조회된 데이터가 없습니다.");
			return false;
		}
		
		if(chkList.length == 0)
		{
			alert("통제코드를 선택하여 주십시요.");
			return false;
		}
		
		var r = confirm("통제등록을 해제 하시겠습니까?");
		if (r == false){
			return false;
		}
		postData = getSearchForJqgrid("cmd","DELETE"); //jqgrid에서는 object 로  
		postData["arrEaiSvcName"] = chkList;
		
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(args){
				$("#grid").jqGrid("clearGridData");
				alert("해제 되었습니다.");
				chkList = null;
				$("#btn_search").click();
			},
			error:function(e){
				alert(e.responseText);
			}
		});
	});
	
	$("input[name*=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});
	
	$("select[name=searchControlType]").change(function(){
		$("#service").hide();
		if ($(this).val() =="S"){
			$("#service").show();
		}
	});

	$("#cb_grid").unbind("click");
	
	$("#cb_grid").click(function(e){
		var cnt = $("#grid").getGridParam("reccount");
		var check = $(this).is(":checked");
		
// 		if ($(this).is(":checked")){
// 			//check되어 있으면
//  			var r = confirm("전체선택 하시겠습니까?"+"("+cnt+"건)");
//  			if (r == false){
//  				return false;
//  			}
// 		}else{
//  			var r = confirm("전체선택해제 하시겠습니까?"+"("+cnt+"건)");
//  			if (r == false){
//  				return false;
//  			}
// 		}
		
		$("input[type=checkbox][name*=jqg_grid_]").each(function(){
			$(this).prop("checked",check);
		});
		
	});
	$("#allAdd").click(function(e){
		var r = confirm("시스템 전체 거래가 통제됩니다.\n전체등록 하시겠습니까?");
		if (r == false){
			return false;
		}
		var postData = getSearchForJqgrid("cmd","INSERT_CONTROL_ALL"); //jqgrid에서는 object 로 
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(args){
				$("#grid").jqGrid("clearGridData");
				alert("전체등록 되었습니다.");
				$("#btn_search").click();
			},
			error:function(e){
				alert(e.responseText);
			}
		});		
	
	});	
	
	
	$("#allDelete").click(function(e){
		var r = confirm("시스템 전체 거래가 해제됩니다.\n전체해제 하시겠습니까?");
		if (r == false){
			return false;
		}
		
		var postData = getSearchForJqgrid("cmd","DELETE_CONTROL_ALL"); //jqgrid에서는 object 로 
		$.ajax({
			type : "POST",
			url:url,
			data:postData,
			success:function(args){
				$("#grid").jqGrid("clearGridData");
				alert("전체등록해제 되었습니다.");
				$("#btn_search").click();
			},
			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
        //(url,cmd,gridObj,formObject,fileName,merge)
		gridToExcelSubmit2(url_excel,"LIST_GRID_TO_EXCEL",$("#grid"),$("#ajaxForm"),'거래통제');
		return false;
	});		
	
	buttonControl();
	
	$( '#regist_dialog' ).dialog({
		resizable: false,
		autoOpen: false,
		height: 200,
		width: 300,
		modal: true,
		open: ()=>{
			$("input[name=startHHMM]").val('0000');
			$("input[name=endHHMM]").val('0000');
		},
		buttons: {
			"확인": function() {
				registControl();
			},
			"취소": function() {
				closeRegistDialog();
			}
		}
	});
	$("input[name=startHHMM],input[name=endHHMM]").inputmask("hh:mm",{'autoUnmask':true});
});

function closeRegistDialog(){
	console.log($("input[name=endHHMM]").val());
	$( '#regist_dialog' ).dialog("close");
}

function registControl(){
	chkList = getRowArray();
	postData = getSearchForJqgrid("cmd","INSERT"); //jqgrid에서는 object 로 
	postData["arrEaiSvcName"] = chkList;
	postData["startTime"] = $("input[name=startHHMM]").val();
	postData["endTime"] = $("input[name=endHHMM]").val();
	
	$("input[name=startHHMM]").attr("readonly",true);
	$("input[name=endHHMM]").attr("readonly",true);
	
	$.ajax({
		type : "POST",
		url:url,
		data:postData,
		success:function(args){
			$("#grid").jqGrid("clearGridData");
			alert("등록 되었습니다.");
			chkList = null;
			$("#btn_search").click();
		},
		error:function(e){
			alert(e.responseText);
		},
	    complete : function() {
	    	$("input[name=startHHMM]").removeAttr("readonly");
	    	$("input[name=endHHMM]").removeAttr("readonly");
	    	closeRegistDialog();
	    }
	});
} 
</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_excel" level="W"><i class="material-icons">table_view</i> <%= localeMessage.getString("button.excel") %></button>
					<button type="button" class="cssbtn" id="btn_upload" level="W"><i class="material-icons">upload</i> <%= localeMessage.getString("button.upload") %></button>
					<button type="button" class="cssbtn" id="btn_modify" level="W"><i class="material-icons">save</i> <%= localeMessage.getString("button.register") %></button>
					<button type="button" class="cssbtn" id="btn_delete" level="W"><i class="material-icons">cancel</i> <%= localeMessage.getString("button.release") %></button>
					<button type="button" class="cssbtn" id="btn_search" level="R"><i class="material-icons">search</i> <%= localeMessage.getString("button.search") %></button>
<%-- 					<img id="btn_excel"  src="<c:url value="/img/btn_excel.png"/>"  level="W" />	 --%>
<%-- 					<img id="btn_upload" src="<c:url value="/img/btn_upload.png"/>" level="W"> --%>
<%-- 					<img id="btn_modify" src="<c:url value="/img/btn_regist.png"/>" level="W"> --%>
<%-- 					<img id="btn_delete" src="<c:url value="/img/btn_release.png"/>" level="W"> --%>
<%-- 					<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" /> --%>
				</div>
				<div class="title"><%= localeMessage.getString("control.title") %></div>
				<div style="margin-bottom:15px;">
<!-- 					<input type="button" name="allAdd" class="btn_img btn_allAdd"> -->
<!-- 					<input type="button" name="allDelete" class="btn_img btn_allDelete"> -->
					<button type="button" class="cssbtn" id="allAdd"><i class="material-icons">check_box</i> <%= localeMessage.getString("button.allReg") %></button>
					<button type="button" class="cssbtn" id="allDelete"><i class="material-icons">check_box_outline_blank</i> <%= localeMessage.getString("button.allRel") %></button>
				</div>
				
				<form id="ajaxForm"  onsubmit="return false;">
				<table class="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th width="15%"><%= localeMessage.getString("control.type") %></th>
							<td colspan="3">
								<div class="select-style">	
									<select name="searchControlType" onChange="fnControlType();">
									</select>
								</div>
							</td>							
						</tr>	
						<tr>
							<th width="15%"><%= localeMessage.getString("control.io") %></th>
							<td width="35%">
								<div class="select-style">	
									<select name="searchIo">
									</select>
								</div>
							</td>
							<th width="15%"><%= localeMessage.getString("control.bizCode") %></th>
							<td width="35%">
								<div style="position: relative;">
									<div class="select-style">	
										<select name="searchEaiBzwkDstcd">
										</select>
									</div>
								</div>								
							</td>	
						</tr>
						<tr>
							<th width="15%"><%= localeMessage.getString("control.select") %></th>
							<td width="35%">
								<div class="select-style">	
									<select name="searchControlSelectType">
									</select>
								</div>
							</td>		
							<th width="15%"><%= localeMessage.getString("control.code") %></th>
							<td width="35%">
								<input type="text" name="searchCode">
							</td>	
						</tr>	
					</tbody>
				</table>
				</form>
				<table id="grid" ></table>
				<div id="pager"></div>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->			
		
		<div id="regist_dialog" class="dialog" title="통제등록">
			<h4>통제시간 : 24시간제로 입력 (00:00-00:00 무제한)</h4>
			<span>
				시작시간 
				<input type="text" name="startHHMM" value="" size="5" style="width:50px; border:1px solid #ebebec;">
				 - 종료시간 
				<input type="text" name="endHHMM" value="" size="5" style="width:50px; border:1px solid #ebebec;">
			</span>
			<p><p>
			통제등록 하시겠습니까? 
		</div>	
	</body>	
</html>

