<%@ 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="/onl/apim/approvalline/portalApprovalLineMan.json" />';
var url_view = '<c:url value="/onl/apim/approvalline/portalApprovalLineMan.view" />';
var select_approvalType = ""; 

function buttonFormatter(cellvalue, options, rowObject) {
	return '<button type="button" class="cssbtn" level="W" status="DETAIL" onclick="deleteRow(\''
     + options.rowId + '\')"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %></button>';
}

function formatApprovalLineUsers(cellvalue, options, rowObject){
	if (cellvalue && Array.isArray(cellvalue) && rowObject.portalApprovalLineUsers.length > 0){
		return cellvalue.map(user => user.userName).join(' → ');
	}
	return '';
}

function deleteRow(rowId) {
    var rowData = $("#grid").jqGrid('getRowData', rowId);
    
    var postData = {
        id: rowData.id,
        cmd: 'DELETE'
    };
    
    $.ajax({
        type: "POST",
        url: url,
        data: postData,
        success: function(response) {
            alert("삭제되었습니다.");
            $("#grid").trigger("reloadGrid");
        },
        error: function(e) {
            alert("삭제 중 오류가 발생했습니다.");
        }
    });
}


function init(){
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_INIT_COMBO'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=approvalType]"))
			.setData(json.approvalTypeRows).setFormat(nameOptionFormat).rendering();
			
			select_approvalType  = ": ;"+getGridSelectText("CODE","NAME",json.approvalTypeRows);
			
			$('#grid').jqGrid('setColProp', 'approvalType', { editoptions: { value: select_approvalType } });
			$('#grid').trigger('reloadGrid');
		},
		error:function(e){
			alert(e.responseText);
		}
	});
} 

$(document).ready(function() {
	init();
	
    var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 

	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		url: url,
		postData : gridPostData,
		colNames:[
				  'No.',
                  "id",
				  '<%= localeMessage.getString("portalApprovalLine.approvalName") %>',
                  '<%= localeMessage.getString("portalApprovalLine.approvalUserList") %>',
                  '<%= localeMessage.getString("portalApprovalLine.approvalType") %>'
                  ],
		colModel:[
				{ name : 'rowNum'   	 , align:'center'	, width:'30', sortable:false  },
				{ name : 'id'  			 , align:'center'	, key:true, hidden:true},
				{ name : 'approvalName'		 , align:'center'	, width:"100"},
				{ name : 'portalApprovalLineUsers'		 , align:'center'	, width:"100", formatter: formatApprovalLineUsers},
				{ name : 'approvalType'		 , align:'center'	, width:"100", edittype: 'select' , editoptions: { value: select_approvalType }, formatter: "select"}
				],
        jsonReader: {
             repeatitems:false
        },	          
		pager : $('#pager'),
		page : '${param.page}',
		rowNum : '${rmsDefaultRowNum}',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		rowList : eval('[${rmsDefaultRowList}]'),
		loadComplete:function (d){
			var records = $(this).getGridParam('records');
			var page = $(this).getGridParam('page');
			var rowNum = $(this).getGridParam('rowNum');
			var rows = $(this).getDataIDs();
			var colModel = $(this).getGridParam("colModel");

			for (var i = 0; i < rows.length; i++) {
				var number = ((page - 1) * rowNum + i) + 1;
				// var reverseNumber = records - ((page - 1) * rowNum + i);
				$(this).setCell(rows[i], 'rowNum', number);
			}
			for(var i = 0 ; i< colModel.length; i++){
				$(this).setColProp(colModel[i].name, {sortable : false});
			}
			
			$(this).jqGrid('setColProp', 'approvalUserIds', {
		        formatter: function(cellvalue, options, rowObject) {
		            return formatApprovalUsers(cellvalue, options, rowObject);
		        }
		    });
		},		
		ondblClickRow: function(rowId) {
			var rowData = $(this).getRowData(rowId); 
		    var key = rowData['id'];
			
			var args = {};
			var url2 = url_view;
			url2 = url2+'?cmd=DETAIL&status=DETAIL';
			url2 += '&menuId='+'${param.menuId}';
		    url2 += '&id=' + key;
            
		    showModal(url2, args, 800, 650, function(){
				$("#grid").trigger("reloadGrid");
			});
            
        },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"); 
		
        $("#grid").setGridParam({ url:url,postData: postData ,page:1 }).trigger("reloadGrid");
	});
	
	$("#btn_new").click(function(){
		var args = {};
		var url2 = url_view;
		url2 = url2+'?cmd=DETAIL&status=NEW';
		
		showModal(url2, args, 800, 650, function(){
			$("#grid").trigger("reloadGrid");
		});
	});
	
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});
	
	buttonControl();
	
});


</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">
					<button type="button" class="cssbtn" id="btn_new" level="W"><i class="material-icons">add</i> <%= localeMessage.getString("button.new") %></button>
				</div>
				<div class="title"><%= localeMessage.getString("portalApprovalLine.title") %></div>
				
				<table id="grid" ></table>
				<div id="pager"></div>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

