<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	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 selectName = "searchBjobBzwkDstcd";
var url_excel = '<c:url value="/common/noauth/excel/listGridToExcel.json" />';
var url ='<c:url value="/bap/admin/work/messageProcMan.json" />';

function fileupload(e,successcallback,errorcallback) {
	var formObj = $(this);
	var formURL = formObj.attr("action");
	if(window.FormData !== undefined)  // for HTML5 browsers
	{
		var formData = new FormData(this);
		
		$.ajax({
			url: formURL,
			type: 'POST',
			data: formData,
			encType: "multipart/form-data",
			contentType: false,
			cache: false,
			processData: false,
			success: function(json, textStatus, jqXHR) {
				$("input[name=file]").val("");
				if(textStatus == 'success') {
					alert('정상처리 되었습니다.');
					$("#btn_search").click();
				} else {
					alert('업로드중 에러가 발생하였습니다.');
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				$("input[name=file]").val("");
				if (typeof callback === 'function') {
					errorcallback(jqXHR, textStatus, errorThrown);
				}
			}
		});
		e.preventDefault();
		if (e.unbind) e.unbind();
	} else { //for olden browsers
		formObj.append($("<input type='hidden' name='serviceType' value='" + sessionStorage["serviceType"] + "' />"));
		//generate a random id
		var iframeId = 'unique' + (new Date().getTime());
		//create an empty iframe
		var iframe = $('<iframe src="javascript:false;" id="' + iframeId + '" name="' + iframeId + '" />');

		//hide it
		iframe.hide();

		//set form target to iframe
		formObj.attr('target', iframeId);
		formObj.attr('action', '<c:url value="/loader.file" />');

		//Add iframe to body
		iframe.appendTo('body');
		iframe.load(function(e) {
			var doc = getDoc(iframe[0]);
			var docRoot = doc.body ? doc.body : doc.documentElement;
			var data = docRoot.innerHTML;
			var k = JSON.parse(data);
			$("#grid")[0].addJSONData(k);
			$("input[name=file]").val("");
			//data is returned from server.
			if (typeof callback === 'function') {
				//successcallback(data);
			}
		});
	}
}

function list() {
	var gridPostData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로
	$('#grid').jqGrid({
		datatype: "json",
		mtype: 'POST',
		url: url,
		postData: gridPostData,
		colNames: [ '인터페이스ID',
					'인터페이스설명',
					'수신업무/기관',
					'송신업무/기관',
					'송수신파일명',
					'세부기관코드',
					'레코드 길이',
					'송/수신여부',
					/* '수신여부', */
					'사용여부'
				  ],
		colModel: [
					{ name: 'BJOBMSGDSTCD'       , align: 'center'  },
					{ name: 'BJOBMSGDSTICNAME'   , align: 'left'    },
					{ name: 'BJOBBZWKDSTCD'      , align: 'center'  },
					{ name: 'UAPPLCD'            , align: 'center'  },
					{ name: 'BJOBTRANDSTCDNAME'  , align: 'left'    },
					{ name: 'BJOBINSTIDSTCD'     , align: 'center'  },
					{ name: 'BJOBTELGMRECSIZE'   , align: 'center'  }, 
					{ name: 'EAIFILESENDUSEYN'   , align: 'center'   ,
						formatter: function (cellvalue) {
							if ( cellvalue == '1' ) {
								return '송신';
							} else {
								return '수신';
							}
						}
					},
					{ name: 'THISMSGUSEYN'       , align: 'center'   ,
						formatter: function (cellvalue) {
							if ( cellvalue == '1' ) {
								return '사용';
							} else {
								return '<span style="color:red">사용안함</span>';
							}
						}
					}
				  ],
		jsonReader: {
			repeatitems:false
		},
		pager: $('#pager'),
		page: '${param.page}',
		rowNum: '${rmsDefaultRowNum}',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		multiselect: true,
		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 bjobMsgDstcd = rowData['BJOBMSGDSTCD'].trim();
			var url = '<c:url value="/bap/admin/work/messageProcMan.view" />';
			url += '?cmd=DETAIL';
			url += '&page=' + $(this).getGridParam("page");
			url += '&menuId=' + '${param.menuId}';
			url += '&returnUrl=' + getReturnUrl();
			url += '&bjobMsgDstcd=' + bjobMsgDstcd;
			url += '&' + getSearchUrl();
			//검색값
			goNav(url);
		}
	});
}

function init() {
	$.ajax({
		type: "POST",
		url: url,
		dataType: "json",
		data: { cmd: 'LIST_INIT_COMBO' },
		success: function(json) {
			new makeOptions("CODE","NAME").setObj($("select[name=searchBjobBzwkDstcd]")).setNoValueInclude(true).setNoValue('', '전체').setData(json.bjobBzwkDstcd).rendering(); // 업무구분코드
			list();
		},
		error: function(e) {
			alert(e.responseText);
		}
	});
	setSearchable(selectName);	// 콤보에 searchable 설정
}

$(document).ready(function() {

	resizeJqGridWidth('grid', 'title', '1000');
	init();

	$("#btn_search").click(function() {
		var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
		$("#grid").setGridParam({url:url, postData: postData,page:"1" }).trigger("reloadGrid");
	});

	$("#btn_new").click(function() {
		var url = '<c:url value="/bap/admin/work/messageProcMan.view"/>';
		url += '?cmd=DETAIL';
		url += '&page=' + $("#grid").getGridParam("page");
		url += '&returnUrl=' + getReturnUrl();
		url += '&menuId=' + '${param.menuId}';
		//검색값
		url += '&'+getSearchUrl();

		goNav(url);
	});
	
	$("input[name^=search]").keydown(function(key) {
		if (key.keyCode == 13) {
			$("#btn_search").click();
		}
	});

	$("input[name^=like]").keydown(function(key) {
		if (key.keyCode == 13) {
			$("#btn_search").click();
		}
	});
	
	$("#btn_excel").click(function(event) {
		event.stopPropagation(); // Do not propagate the event.
		// Create an object that will manage to download the file.
		var merge = new Array();
		gridToExcelSubmit(url_excel, "LIST_GRID_TO_EXCEL", $("#grid"), $("#ajaxForm"), "송수신 파일 관리", merge);
		return false;
	});

	$("#btn_download").click(function() {
		let selectedVal = "";
		const rowIds = $("#grid").getGridParam("selarrrow");
		
		rowIds.forEach(rowId => {
			selectedVal += "," + $("#grid").getRowData(rowId).BJOBMSGDSTCD;
		});
		
		if(selectedVal != "") selectedVal = selectedVal.substring(1);
		
		var url ='<c:url value="/loader.do" />';
		url += '?cmd=messageProcMan';
		url += '&control=download';
		url += '&serviceType=' + sessionStorage["serviceType"];
		url += '&fileName=messageProcMan';
		url += '&selectedVal=' + selectedVal;
		url += '&' + getSearchUrl();

		goNav(url);
	});
	
	$("#multiform").on('submit', fileupload);
	$('#btn_upload').click(function() {
		if( confirm( "동일한 이름의 경우 기존내용을 수정합니다.\n\n업로드 하시겠습니까?" ) != true ) return;
		
		if(window.FormData !== undefined) {
			$("input[name=file]").click();
		} else {
			if($("input[name=file]").val() == "") return;
			$("#multiform").submit();
		}
	});

	if(window.FormData !== undefined) {
		$("input[name=file]").change(function(ev) {
			var filename = $(this).val().split('\\').pop();
			
			if (!filename.startsWith('messageProcMan')) {
				alert("송수신 파일관리 JSON 파일을 선택하십시오.\n\n[파일명 : messageProcMan.json]")
				return false;
			}
			
			if(filename == "") return;
			else $("#multiform").submit();
		});
	}

	if(window.FormData !== undefined) {
		$("input[name=file]").hide();
	} else {
		$("input[name=file]").show();
	}

	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="title">
			<form id="multiform" method="POST" enctype="multipart/form-data" action="<c:url value="/loader.file"/>">
			<div class="search_wrap">
				<input type="file" id="file" name="file" style="display:inline-block"/>
				<input type="hidden" name="cmd" value="messageProcMan"/>
				<input type="hidden" name="control" value="upload"/>
				<img src="<c:url value="/img/btn_excel.png"/>" id="btn_excel" level="R" />
				<img src="<c:url value="/img/btn_upload.png"/>" alt="" id="btn_upload" level="W" />
				<img src="<c:url value="/img/btn_download.png"/>" alt="" id="btn_download" level="R" />
				<img src="<c:url value="/img/btn_new.png"/>" alt="" id="btn_new" level="W" />
				<img src="<c:url value="/img/btn_search.png"/>" alt="" id="btn_search" level="R" />
			</div>
			</form>
			<div class="title">송수신 파일 관리<span class="tooltip">일괄 전송에서 사용하는 송수신 파일을 관리 하는 화면입니다</span></div>
			
			<table class="search_condition" cellspacing=0;>
				<tbody>
					<tr>
						<th style="width:150px;">인터페이스ID</th>
						<td><input type="text" name="likeBjobMsgDstcd" value="${param.likeBjobMsgDstcd}"></td>
						<th style="width:150px;">업무구분코드</th>
						<td>
							<div class="select-style">
								<select name="searchBjobBzwkDstcd" value="${param.searchBjobBzwkDstcd}"></select>
							</div>
						</td>
						<th style="width:150px;">세부기관코드</th>
						<td><input type="text" name="likeBjobInstiDstcd" value="${param.likeBjobInstiDstcd}"></td>
					</tr>
					<tr>
						<th style="width:150px;">송수신파일설명</th>
						<td><input type="text" name="likeBjobTranDstcdName" value="${param.likeBjobTranDstcdName}"></td>
						<th style="width:150px;">인터페이스설명</th>
						<td><input type="text" name="likeBjobMsgDsticName" value="${param.likeBjobMsgDsticName}"></td>
						<th style="width:150px;">사용여부</th>
						<td style="width:350px;">
						<div class="select-style">
							<select name="searchThisMsgUseYn" value="${param.searchThisMsgUseYn}">
								<option value="">전체</option>
								<option value="1">사용</option>
								<option value="0">사용안함</option>
							</select>
						</div>
						</td>
					</tr>
					<tr>
						<th style="width:150px;" hidden="hidden">어플리케이션코드</th>
						<td hidden="hidden"><input type="text" name="likeUapplCd" value="${param.likeUapplCd}"></td>
						<th style="width:150px;" hidden="hidden">담당자ID</th>
						<td hidden="hidden"><input type="text" name="likeThisMsgChrgIDs" value="${param.likeThisMsgChrgIDs}"></td>
						<th style="width:150px;" hidden="hidden"></th>
						<td hidden="hidden"></td>
					</tr>
				</tbody>
			</table>
			
			<table id="grid" ></table>
			<div id="pager"></div>
			
		</div><!-- end content_middle -->
	</div><!-- end right_box -->
</body>
</html>

