<%@ 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/portalnotice/portalNoticeMan.json" />';
		var url_view = '<c:url value="/onl/apim/portalnotice/portalNoticeMan.view" />';
		var combo;
		
		function formatNoticeType(cellvalue, options, rowObject) {
			if (!combo || !combo.noticeTypeList) {
				return cellvalue;
			}
			for (var i = 0; i < combo.noticeTypeList.length; i++) {
				if (combo.noticeTypeList[i].CODE == cellvalue) {
					return combo.noticeTypeList[i].NAME;	
				}
			}
			return cellvalue;
		}
		
		function formatuseYn(cellvalue, options, rowObject) {
			return cellvalue === 'N'
					? '<span style="color: red;">미사용</span>'
					: '<span>사용</span>';
		}
		
		function formatFixYn(cellvalue, options, rowObject) {
			return cellvalue === 'Y'
					? '고정'
					: '';
		}

		function formatFile(cellvalue, options, rowObject) {
			var iconPath = '${pageContext.request.contextPath}/images/icon_file.png';
			var icon = rowObject.hasAttachment ? '<img src="' + iconPath + '" alt="File Attached" style="vertical-align: middle; margin-left: 5px; width: 16px; height: 16px;">' : '';
			return cellvalue + icon;
		}

		function deleteSelectedRows() {
			var selectedIds = $("#grid").jqGrid('getGridParam', 'selarrrow');

			if (selectedIds.length === 0) {
				alert('항목을 선택하세요.');
				return;
			}

			if (!confirm('선택된 ' + selectedIds.length + '개 항목을 삭제하시겠습니까?')) {
				return;
			}

			$.ajax({
				type: "POST",
				url: url,
				dataType: "json",
				data: {
					cmd: 'DELETE_BULK',
					ids: selectedIds.join(',')
				},
				success: function(data) {
					alert('삭제되었습니다.');
					$("#grid").jqGrid('clearGridData', true);
					$("#grid").trigger("reloadGrid");
				},
				error: function(e) {
					alert('삭제 중 오류가 발생했습니다.');
				}
			});
		}


		function init(){
			$.ajax({
				type : "POST",
				url:url,
				dataType:"json",
				data:{cmd: 'LIST_INIT_COMBO'},
				success:function(json){
					console.log('init', json);
					combo = json;
					new makeOptions("CODE","NAME").setObj($("select[name=searchNoticeType]")).setNoValueInclude(true).setNoValue('','<%=localeMessage.getString("combo.all")%>').setData(json.noticeTypeList).rendering();

					putSelectFromParam();

					// 콤보(combo)가 채워진 뒤에 그리드를 생성해야 formatNoticeType 경합이 발생하지 않음
					buildGrid();
				},
				error:function(e){
					alert(e.responseText);
				}
			});
		}

		function buildGrid(){

			$('#grid').jqGrid({
				datatype:"json",
				mtype: 'POST',
				url: url,
				postData : { cmd : 'LIST',
					searchNoticeType: $('select[name=searchNoticeType]').val(),
					searchUseYn: $('select[name=searchUseYn]').val(),
					searchNoticeSubject: $('input[name=searchNoticeSubject]').val(),
					searchNoticeDetail: $('input[name=searchNoticeDetail]').val()
				},
				colNames:['id', 'No.', '게시유형', '제목', '고정여부', '사용', '마지막 수정일', '등록일', '등록자', '조회수'],
				colModel:[
					{ name : 'id'       	   , align:'center', key:true, hidden:true},
					{ name : 'rowNum'          , align:'center', width:60 },
					{ name : 'noticeType'  	   , align:'center', width:60, formatter: formatNoticeType  },
					{ name : 'noticeSubject'   , align:'left'  , width:300, formatter: formatFile },
					{ name : 'fixYn'           , align:'center', width:60, formatter: formatFixYn },
					{ name : 'useYn'           , align:'center', width:60, formatter: formatuseYn },
					{ name : 'lastModifiedDate', align:'center', width:120 , formatter: timeStampFormat},
					{ name : 'createdDate'     , align:'center', width:120, formatter: timeStampFormat },
					{ name : 'inquirerName'    , align:'center', width:100 },
					{ name : 'readCount'       , align:'center', width:80 }
				],
				jsonReader: {
					repeatitems:false
				},
				pager : $('#pager'),
				page : '${param.page}',
				rowNum : '${rmsDefaultRowNum}',
				autoheight: true,
				height: $("#container").height(),
				autowidth: true,
				viewrecords: true,
				rowList : eval('[${rmsDefaultRowList}]'),
				multiselect: true,
				multiboxonly: true,
				ondblClickRow: function(rowId) {
					var rowData = $(this).getRowData(rowId);
					var id = rowData['id'];
					var url2 = url_view;
					url2 += '?cmd=DETAIL';
					url2 += '&page='+$(this).getGridParam("page");
					url2 += '&returnUrl='+getReturnUrl();
					url2 += '&menuId='+'${param.menuId}';
					url2 += '&id='+id;
					goNav(url2);
				},
				gridComplete:function (d){
					var records = $(this).getGridParam('records');
					var page = $(this).getGridParam('page');
					var rowNum = $(this).getGridParam('rowNum');
					var rows = $(this).getDataIDs();

					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);
					}

					var colModel = $(this).getGridParam("colModel");
					var ids = jQuery("#grid").jqGrid('getDataIDs');

					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);
				}
			});

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

		$(document).ready(function() {

			// 콤보 로드 → 콤보 성공 콜백에서 buildGrid() 호출 (경합 방지)
			init();

			$("#btn_search").click(function(){
				var postData = getSearchForJqgrid("cmd","LIST");
				$("#grid").setGridParam({ url:url,postData: postData ,page:1 }).trigger("reloadGrid");
			});

			$("#btn_new").click(function(){
				var url2 = url_view;
				url2 += '?cmd=DETAIL';
				url2 += '&page='+$("#grid").getGridParam("page");
				url2 += '&returnUrl='+getReturnUrl();
				url2 += '&menuId='+'${param.menuId}';
				goNav(url2);
			});

			$("#btn_delete_selected").click(function(){
				deleteSelectedRows();
			});

			$("select[name=searchUseYn], 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>
			<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_delete_selected" level="W" style="background-color: #dc3545; border-color: #dc3545; color: white;"><i class="material-icons">delete_forever</i> 선택 삭제</button>
		</div>
		<div class="title">공지사항 목록<span class="tooltip">공지사항을 관리합니다.</span></div>
		<form id="ajaxForm"  onsubmit="return false;">
			<table class="search_condition" cellspacing=0;>
				<colgroup> 
			        <col style="width:180px;"> 
			        <col style="width:240px;"> 
			        <col style="width:180px;"> 
			        <col style="width:240px;">
			        <col style="width:180px;"> 
			        <col style="width:240px;">
			    </colgroup>
				<tbody>
				<tr>
					<th>게시유형</th>
					<td>
						<div class="select-style">
							<select name="searchNoticeType"></select>
						</div>
					</td>
					<th>제목/내용</th>
					<td><input type="text" name="searchSubjectDetail"></td>
					<th>사용여부</th>
					<td>
						<div class="select-style">
							<select name="searchUseYn">
								<option value="">전체</option>
								<option value="Y">사용</option>
								<option value="N">미사용</option>
							</select>
						</div>
					</td>
				</tr>
				</tbody>
			</table>
		</form>
		<table id="grid" ></table>
		<div id="pager"></div>

	</div><!-- end content_middle -->
</div><!-- end right_box -->
</body>
</html>