<%@ 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 uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ 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="/common/acl/user/userMan.json" />';
var userId = window.dialogArguments["userId"];
var arrGridData = new Array();

// 사용자 서비스타입 List Count 조회
 function init()
{
	$.ajax({
		type : "POST",
		url:url,
		data:{ cmd:"LIST_SERVICETYPE_COUNT"},
		success:function(json){
			$("input[name=totalCnt]").val(json.servicetypeCount);
		},
		error:function(e){
			alert(e.responseText);
		}
	});
} 

// 사용자 서비스타입을 추가 및 삭제 할 때 validation 체크
function isGridValid(gridName)
{
	var gridCnt	= 0;
	
	gridCnt = $(gridName).jqGrid("getGridParam", "selarrrow").length;
	if(gridCnt <= 0)
	{
		alert("<%= localeMessage.getString("userPop.checkRequierd1") %>");
		return false;
	}
	
	return true;
}

// 대상 그리드 Reload.
function targetGridReload(){
	var postData = getSearchForJqgrid("cmd","LIST_USER_SERVICETYPE"); //jqgrid에서는 object 로
	postData["userId"] = userId;
	postData["targetGridYn"] = "Y";
	$("#targetGrid").setGridParam({ postData: postData ,page : "1"  }).trigger("reloadGrid");
}

// 대상 그리드 조회
function targetGrid()
{
	var gridPostData = getSearchForJqgrid("cmd", "LIST_USER_SERVICETYPE"); //jqgrid에서는 object 로
	gridPostData["userId"] = userId;
	gridPostData["targetGridYn"] = "Y";
	
	$('#targetGrid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		loadui: "disable",
		postData : gridPostData,
		colNames:['서비스타입',
                  '서비스타입설명',
                  'SAVETYPE',
                  'CHK'
                  ],
		colModel:[
				{ name : 'NAME'   , align:'left'		,key:true	,sortable:false  },
				{ name : 'DESC'   , align:'left'  },
				{ name : 'SAVETYPE'  , hidden:true  },
				{ name : 'CHK'   , hidden:true  }
				],
        jsonReader: {
             repeatitems:false
        },	          
	    autoheight: true,
	    height: $("#container").height(),
	    height: 430,
		autowidth: true,
		viewrecords: true,
		gridview: true,						// jqGrid의 성능 향상 - treeGrid, subGrid, afterInsertRow event의 경우 제외.
		scroll: true,						// 스크롤 사용여부 설정.(default: false)
		rowNum : 10000,						// Grid에 표시될 레코드 수 설정 (-1은 조회된 데이터 전부 그리드에 셋팅).
		multiselect : true,

		loadComplete:function (d){
			var targetGridCnt	= $("#targetGrid").getGridParam("reccount");
			var colModel = $(this).getGridParam("colModel");
			
			for(var i = 0 ; i< colModel.length; i++){
				$(this).setColProp(colModel[i].name, {sortable : false});
			}
			
			arrGridData = $("#targetGrid").getRowData();
			
			// 사용자 업무코드 List Count
			$("input[name=selectCnt]").val(targetGridCnt);
			
		},
        loadError: function (jqXHR, textStatus, errorThrown) {
        	
        	var location ='<%=request.getContextPath()%>/';
        	comloadError(jqXHR, textStatus, errorThrown ,location);
        	
    	},
		gridComplete:function (d){
			$("input[name=selectCnt]").val($("#targetGrid").getGridParam("reccount"));
		},
		onSelectRow: function(rowId){
			// 선택된 row로 이동
			$("#"+$("#targetGrid").jqGrid("getGridParam", "selrow")).focus();
		}
	});
}

// 저장
function modify(modifyType, grid)
{
	
	if (confirm("<%= localeMessage.getString("common.checkModify")%>") != true)
	return;
	
	var gridData = new Array();

	if(modifyType == "add")
	{
		gridData = grid;
	}
	
	if(modifyType == "delete")
	{
		var data = $(grid).getRowData();
		for ( var i = 0; i < data.length; i++) {
			gridData.push(data[i]);
			
		}
	}
	
	$.ajax({
		type : "POST",
		url:url,
		data:{ cmd:"TRANSACTION_USER_SERVICETYPE"
			 , userId:userId
			 , gridData:JSON.stringify(gridData)
		
		},
		success:function(){
			alert("<%= localeMessage.getString("common.saveMsg") %>");

			$("#grid").setGridParam({ postData: getSearchForJqgrid("cmd", "LIST_USER_SERVICETYPE") ,page : "1"  }).trigger("reloadGrid");
			targetGridReload();
						
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}

$(document).ready(function() {
	// 업무코드 List Count
	init();
	
	// 전체 업무코드 조회
	var gridPostData = getSearchForJqgrid("cmd","LIST_USER_SERVICETYPE"); //jqgrid에서는 object 로 
	gridPostData["userId"] = userId;
	
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : gridPostData,
		colNames:['서비스타입',
                  '서비스타입설명',
                  'CHK'
                  ],
		colModel:[
				{ name : 'NAME'   , align:'left'	,sortable:false  },
				{ name : 'DESC'   , align:'left'  },
				{ name : 'CHK'   , align:'left' ,hidden:true }
				],
        jsonReader: {
             repeatitems:false
        },	          
	    autoheight: true,
	    height: $("#container").height(),
	    height: 430,
		autowidth: true,
		viewrecords: true,
		gridview: true,						// jqGrid의 성능 향상 - treeGrid, subGrid, afterInsertRow event의 경우 제외.
		scroll: true,						// 스크롤 사용여부 설정.(default: false)
		rowNum : 10000,						// Grid에 표시될 레코드 수 설정 (-1은 조회된 데이터 전부 그리드에 셋팅).
		multiselect : true,

		loadComplete:function (d){
			var colModel = $(this).getGridParam("colModel");
			for(var i = 0 ; i< colModel.length; i++){
				$(this).setColProp(colModel[i].name, {sortable : false});
			}
			
		},
        loadError: function (jqXHR, textStatus, errorThrown) {
        	
        	var location ='<%=request.getContextPath()%>/';
        	comloadError(jqXHR, textStatus, errorThrown ,location);
        	
    	},
		gridComplete:function (d){
			targetGridReload();
		},
	});
	
	// target Grid
	targetGrid();
	
	$("#btn_close").click(function(){
		window.close();
	});
	
	// 조회된 그리드에서 대상 그리드로 업무코드 추가.
	$("input[name=add]").click(function(){
		
		if(!isGridValid("#grid")) return;

	 	var selRowIds = $("#grid").jqGrid("getGridParam", "selarrrow");

		for(var i=0;i<selRowIds.length;i++){
		    $("#grid").jqGrid("setCell", selRowIds[i], "CHK", "true");
		    arrGridData.push($("#grid").getRowData(selRowIds[i]));
		}
		
		modify("add", arrGridData);

	});
	
	// 대상그리드에서 선택된 업무코드 삭제
	$("input[name=remove]").click(function(){
		//if(!isGridValid("#targetGrid")) return;
		
		var targetGrid			= $("#targetGrid");
		var selTargetGridIds	= targetGrid.jqGrid("getGridParam", "selarrrow");

		var chk = 0;
		for(var i=0;i<selTargetGridIds.length;i++){
		    $("#targetGrid").jqGrid("setCell", selTargetGridIds[i], "CHK", "false");
		    if(selTargetGridIds[i] != ''){
		    	 chk++;
		    }
		}
		
		if(chk <= 0)
		{
			alert("<%= localeMessage.getString("userPop.checkRequierd1") %>");
			return false;
		}else{
			modify("delete", "#targetGrid");
		}

		

	});

	$("#btn_close").click(function(){
		window.close();
	});
	buttonControl();
});
</script>
</head>
	<body>
		<div class="popup_box">
			<div class="search_wrap">
<%-- 				<button type="button" class="cssbtn" id="btn_search" level="R"><i class="material-icons">search</i> <%= localeMessage.getString("button.search") %></button> --%>
				<button type="button" class="cssbtn" id="btn_close" level="R" status="DETAIL,NEW"><i class="material-icons">cancel</i> <%= localeMessage.getString("button.close") %></button>
<%-- 				<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />	 --%>
<%-- 				<img id="btn_close" src="<c:url value="/img/btn_close.png"/>"         level="R" status="DETAIL,NEW"/> --%>
			</div>
			<div class="title">사용자 사용서비스 관리</div>
			<table width="98%" style="margin-left:10px;">
				<tr>
					<td width="50%">
						<div id="grid_div"><table id="grid" ></table></div>
					</td>
					<td>
						<input type=button name="add" value=">" style="width:40px"/><br><br>
						<input type=button name="remove" value="<" style="width:40px"/><br><br>
					</td>
					<td width="50%">
						<div id="targetGrid_div"><table id="targetGrid" ></table></div>
					</td>
				</tr>
			</table> 
			<div id="pager"></div>
		</div><!-- end right_box -->	
	</body>
</html>

