<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ page import="com.eactive.eai.common.util.SystemUtil"%>
<%
	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 roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;
var prdSvr		= <%=SystemUtil.isProdServer()%>;
var stgSvr		= <%=SystemUtil.isStagingServer()%>;
var svrType		= '';

function viewChange(e) {
	if (e.value == "1"){
		$("#clone").show();
		$("input[name=searchTelgmClsName]").css({'background-color' : '#e5e5e5'});
		$("input[name=searchTelgmClsDesc]").css({'background-color' : '#e5e5e5'});
		$("input[name=cloneTelgmClsName]").css({'background-color' : '#e5e5e5'});
		$("input[name=cloneTelgmClsDesc]").css({'background-color' : '#e5e5e5'});
		$("input[name=cloneTelgmClsName]").focus();
    } else {
		$("#clone").hide();
		$("input[name=searchTelgmClsName]").css({'background-color' : ''});
		$("input[name=searchTelgmClsDesc]").css({'background-color' : ''});
    }
}

function getGridData() {
	var id = "grid";
	var data = new Array();
	var ids = $("#grid").jqGrid('getDataIDs');
	
	for(var i=0;i<ids.length;i++){
		if($("input:checkbox[id='jqg_"+id+"_"+ids[i]+"']").is(":checked")){
			data.push($("#grid").getRowData(ids[i]));
		}
	}
	
	return data;
}

 $(document).ready(function() {	
	 
	var url_view = '<c:url value="/bap/admin/message/classInfoMan.view" />';
	
	if(devSvr) {
		svrType = "stg";
	} else if (stgSvr){
		svrType = "prod";
	} else if (!prdSvr){
		svrType = "dev";
	}
	 
	// 일괄전송전문관리 모든 TAB의 조회조건을 특정 업무구분코드로 동기화한다.
	<% String sessionAttr = (String)session.getAttribute("searchbjobBzwkPrcssDstcd"); %>
	var sessionAttr = "<%= sessionAttr %>";
	if (sessionAttr != "null" && sessionAttr != "") {
		$("input[name=searchTelgmClsName]").val(sessionAttr); 
	}  
	 
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: '<c:url value="/bap/admin/message/classInfoMan.json" />',
		postData : gridPostData,
		colNames:['전문클래스명',
                  '전문클래스 설명'
                  ],
		colModel:[
				{ name : 'TELGMCLSNAME'  	, align:'left'	,width:40	,sortable:false  },
				{ name : 'TELGMCLSDESC'     , align:'left'	,width:40  },
				],
        jsonReader: {
             repeatitems:false
        },	          
		pager : $('#pager'),
		page : '${param.page}',
		rowNum : '${rmsDefaultRowNum}',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
/* 		multiselect: true,
		multiboxonly: false, */
		rowList : eval('[${rmsDefaultRowList}]'),
		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) {
			var rowData = $(this).getRowData(rowId); 
            var key = rowData['TELGMCLSNAME'];
            var url = '<c:url value="/bap/admin/message/classInfoMan.view" />';
            url = url + '?cmd=DETAIL';
            url = url + '&page='+$(this).getGridParam("page");
            url = url + '&returnUrl='+getReturnUrl();
            url = url + '&menuId='+'${param.menuId}';
			//검색값
            url = url + '&'+getSearchUrl();
            //key값
            url = url + '&key='+key;
            goNav(url);
        },
		loadError: function (jqXHR, textStatus, errorThrown) {
      		if(jqXHR.status == 401) {
	        		var location ='<%=request.getContextPath()%>/';
		        	comloadError(jqXHR, textStatus, errorThrown ,location);
		    	}	
    	}
	});

	resizeJqGridWidth('grid','content_middle','1000');

	$("#btn_search").click(function(){
	    var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
		$("#grid").setGridParam({ postData: postData ,page : "1" }).trigger("reloadGrid");
	});
	$("#btn_new").click(function(){
		var url = '<c:url value="/bap/admin/message/classInfoMan.view"/>';
		url = url + '?cmd=DETAIL';
		url = url + '&page='+$("#grid").getGridParam("page");
		url = url + '&returnUrl='+getReturnUrl();
        url = url + '&menuId='+'${param.menuId}';
		//검색값
        url = url + '&'+getSearchUrl();
		
        goNav(url);
	});
	
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});

	$("#btn_delete").click(function() {
		
		var data = getGridData();

		if(data.length == 0){
			alert("삭제 대상을 선택해 주세요");
			return false;
		}
		
		if ( confirm( "삭제하시겠습니까?" ) != true ) return;			
		
		var telgmClsNameList = [];
		for (var i = 0; i <data.length; i++) {
			telgmClsNameList.push(data[i]["TELGMCLSNAME"].trim());
		}
		
		var url = '<c:url value="/bap/admin/message/classInfoMan.json" />';
		var postData = $('#ajaxForm').serializeArray();
		postData.push({
			name : "cmd",
			value : "LIST_DELETE"
		});
		postData.push({
			name : "telgmClsNameList",
			value : telgmClsNameList
		});
		$.ajax({
			type : "POST",
			url : url,
			data : postData,
			success : function(args) {
				alert("클래스정보 "+data.length+"건이 삭제 되었습니다.");
				$("#btn_search").click();
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
	});
	
	$("#clonYn").val("0").attr("selected","selected");

	$("#btn_clone").click(function(){
		
		var searchTelgmClsName = $("input[name=searchTelgmClsName]").val().trim();
		var cloneTelgmClsName = $("input[name=cloneTelgmClsName]").val().trim();
		var searchTelgmClsDesc = $("input[name=searchTelgmClsDesc]").val().trim();
		var cloneTelgmClsDesc = $("input[name=cloneTelgmClsDesc]").val().trim();
		
		if (searchTelgmClsName == "") {
			alert("대상 전문클래스명을 입력해 주세요.");
			return;
		} else if (cloneTelgmClsName == "") {
			alert("복제 전문클래스명을 입력해 주세요.");
			return;
		}
		
		var data = getGridData();
		
		if(data.length == 0){
			alert("입력쿼리 다운로드 대상을 선택해 주세요");
			return false;
		}
		
		if ( confirm( "복제하시겠습니까?" ) != true ) return;
		
		for (var i = 0; i <data.length; i++) {
			var postData = $('#ajaxForm').serializeArray();
			var urlPost ='<c:url value="/bap/admin/message/classInfoMan.json" />';

			postData.push({name:"telgmClsName", value:data[i]["TELGMCLSNAME"].replace(searchTelgmClsName,cloneTelgmClsName)});
			postData.push({name:"telgmClsDesc", value:data[i]["TELGMCLSDESC"].replace(searchTelgmClsDesc,cloneTelgmClsDesc)});
			
  			postData.push({name: "cmd", value:"INSERT"});
			$.ajax({
				type : "POST",
				url:urlPost,
				data:postData,
				success:function(args){
				},
				error:function(e){
					alert(e.responseText);
				}
			});
		}
		alert("전문클래스 "+data.length+"건이 복제되었습니다.");
		$("input[name=searchTelgmClsName]").val(cloneTelgmClsName);
		$("input[name=searchTelgmClsDesc]").val(cloneTelgmClsDesc);
		$("#btn_search").click();
		
	});
	
	$("#btn_download_sql").click(function() {
		
		var data = getGridData();
		
		if(data.length == 0){
			alert("입력쿼리 다운로드 대상을 선택해 주세요");
			return false;
		}
		
		if ( confirm( "입력쿼리를 다운로드하시겠습니까?" ) != true ) return;
		
		var telgmClsNameList = [];
		for (var i = 0; i <data.length; i++) {
			telgmClsNameList.push(data[i]["TELGMCLSNAME"].trim());
		}

		var postData = $('#ajaxForm').serializeArray();
		var sqlFileName = "CLASS_INFO_INPUT_QUERY.sql";
		postData.push({
			name : "cmd",
			value : "LIST_DOWNLOAD_SQL"
		});
		postData.push({
			name : "searchTelgmClsNameList",
			value : telgmClsNameList
		});
		postData.push({
			name : "fileName",
			value : sqlFileName
		});

		$.ajax({
			type : "POST",
			url : '<c:url value="/bap/admin/message/classInfoMan.json" />',
			data : postData,
			success : function(args) {
				var filePath = args.path;
				var url2 = url_view + "?cmd=LIST_FILE_DOWNLOAD";
		      	url2 = url2 + '&returnUrl='+getReturnUrl();
		      	url2 = url2 + '&menuId='+'${param.menuId}';
			    url2 = url2 + '&filePath='+filePath;
			    url2 = url2 + '&fileName='+sqlFileName;
		            	
				goNav(url2);
				
				alert("클래스정보 입력 SQL문이 다운로드되었습니다.")
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
	});
	
	$("img[id=btn_clone_"+svrType+"]").click(function() {
		
		var data = getGridData();
		
		if(data.length == 0){
			alert("복사 대상을 선택해 주세요");
			return false;
		}

		if ( confirm( "복사하시겠습니까?" ) != true ) return;
		
		var telgmClsNameList = [];
		for (var i = 0; i <data.length; i++) {
			telgmClsNameList.push(data[i]["TELGMCLSNAME"].trim());
		}
		
		var postData = $('#ajaxForm').serializeArray();
		postData.push({
			name : "cmd",
			value : "LIST_DOWNLOAD_SQL"
		});
		postData.push({
			name : "searchTelgmClsNameList",
			value : telgmClsNameList
		});
		postData.push({
			name : "svrType",
			value : svrType
		});
		
		$.ajax({
			type : "POST",
			url : '<c:url value="/bap/admin/message/classInfoMan.json" />',
			data : postData,
			success : function(args) {
 				if (args.result != "" && args.error == "") {
					alert("클래스정보 "+data.length+"건이 복사되었습니다.");
				} else if (args.error != "") {
					if ("${fn:contains(args.error,'SqlIntegrityConstraintViolationException')}") {
						alert("일부 클래스정보가 이미 존재하여 복사되지 않었습니다.");
					} else {
						alert("오류가 발생하여 복사되지 않았습니다. 오류 : "+args.error);
					}
				}
 				goNav(returnUrl);
			},
			error : function(e) {
				alert(e.responseText);
			}
		});
		
	});
	
	buttonControl();
	
	if(devSvr) {
		setBtnHide(roleString, " ", "btn_clone_dev");
		setBtnHide(roleString, " ", "btn_clone_prod");
		setBtnHide(roleString, "admin", "btn_clone_stg");
	} else if (stgSvr){
		setBtnHide(roleString, " ", "btn_clone_dev");
		setBtnHide(roleString, " ", "btn_clone_stg");
		setBtnHide(roleString, "admin", "btn_clone_prod");			
	} else if (prdSvr){
		setBtnHide(roleString, " ", "btn_clone_stg");
		setBtnHide(roleString, " ", "btn_clone_prod");		
		setBtnHide(roleString, " ", "btn_clone_dev");
	} else {
		setBtnHide(roleString, " ", "btn_clone_stg");
		setBtnHide(roleString, " ", "btn_clone_prod");		
		setBtnHide(roleString, "admin", "btn_clone_dev");
	}
	
}); 
 
</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="content_middle">
				<div class="search_wrap">
					<!-- <img src="<c:url value="/img/btn_clone.png"/>" alt="" id="btn_clone_stg" level="W" /> -->
					<!-- <img src="<c:url value="/img/btn_clone_prod.png"/>" alt="" id="btn_clone_prod" level="W" /> -->
					<!-- <img src="<c:url value="/img/btn_clone_dev.png"/>" alt="" id="btn_clone_dev" level="W" /> -->
					<img src="<c:url value="/img/btn_new.png"/>" alt="" id="btn_new" level="W" />
					<!-- <img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W" /> -->
					<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />	
				</div>
				<div class="title">클래스정보 관리<span class="tooltip">클래스정보를 등록/관리합니다</span></div>
				
				<table class="search_condition" id="search_condition" cellspacing=0;>
					<tbody>
						<tr>
							<th style="width:150px;">전문클래스명</th>
							<td><input type="text" name="searchTelgmClsName" value="${param.searchTelgmClsName}"></td>
							<%-- <th style="width:150px;">전문클래스 설명</th>
							<td><input type="text" name="searchTelgmClsDesc" value="${param.searchTelgmClsDesc}"></td> --%>
							<!-- <th style="width:150px;">복제 사용여부</th>
							<td>
								<div class="select-style">							
								<select name="clonYn" id="clonYn" readonly="readonly" onchange="viewChange(this)">
									<option value="1">사용함</option>
									<option value="0">사용안함</option>
								</select>								
							</td> --><!-- <th style="width:150px;">복제 사용여부</th>
							<td>
								<div class="select-style">							
								<select name="clonYn" id="clonYn" readonly="readonly" onchange="viewChange(this)">
									<option value="1">사용함</option>
									<option value="0">사용안함</option>
								</select>								
							</td> -->
						</tr>
						<tr id="clone" hidden="hidden">
							<th style="width:150px;">복제 전문클래스명</th>
							<td><input type="text" name="cloneTelgmClsName"></td>
							<th style="width:150px;">복제 전문클래스 설명</th>
							<td colspan="3"><input type="text" name="cloneTelgmClsDesc" style="display:inline-block; width:calc(100% - 90px);"/>
								<img id="btn_clone" src="<c:url value="/img/btn_clone1.png" />" level="W" status="LIST" class="btn_img"/>
								<img id="btn_download_sql" src="<c:url value="/img/icon_download.png"/>" class="btn_img" level="W" status="DETAIL"/>
							</td>
						</tr>
					</tbody>
				</table>
				<table id="grid" ></table>
				<div id="pager"></div>	
				
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>