<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ page import="com.eactive.eai.common.util.SystemUtil"%>
<%@ page import="com.eactive.eai.rms.common.context.MonitoringContext"%>
<%@ page import="com.eactive.eai.rms.common.util.CommonUtil"%>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");

	MonitoringContext monitoringContext = (MonitoringContext)CommonUtil.getBean(request, "monitoringContext");
	String deployYnStr = monitoringContext.getStringProperty(MonitoringContext.IOMAP_DEPLOY_YN_BY_RMS, "N");
	boolean deployYn = "Y".equalsIgnoreCase(deployYnStr);
%>
<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"/>
<link href="<c:url value="/addon/bootstrap-5.3.2/css/bootstrap.min.css"/>" rel="stylesheet"/>
<script src="<c:url value="/addon/bootstrap-5.3.2/js/bootstrap.bundle.min.js"/>"></script>
<!-- FilePond stylesheet -->
<link href="<c:url value="/addon/filepond/filepond.min.css"/>" rel="stylesheet">
<!-- FilePond JavaScript library -->
<script src="<c:url value="/addon/filepond/filepond.min.js"/>"></script>
<!-- FilePond plugin for file validation -->
<script src="<c:url value="/addon/filepond/plugin/filepond-plugin-file-validate-type.min.js"/>"></script>
<script language="javascript" >
var url      ='<c:url value="/onl/admin/adapter/adapterMan.json" />';
var url_view ='<c:url value="/onl/admin/adapter/adapterMan.view" />';
var url_excel='<c:url value="/onl/admin/adapter/adapterMan.excel"/>';
var url_file ='<c:url value="/onl/admin/adapter/adapterMan.file"/>';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;
var stageSvr	= <%=SystemUtil.isStagingServer()%>;
var selectName = "searchEaiBzwkDstcd";

var select_useYn = new Array();
var select_adptrMsgPtrnCdRows = new Array();
//var select_testMasterYnRows = new Array();

function init(callback) {
	return $.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:{cmd: 'LIST_SEARCH_INIT_COMBO'},
		success:function(json){
			new makeOptions("CODE","NAME").setObj($("select[name=searchAdptrIoDstCd]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.adptrIoDstcdRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchAdptrMsgPtrnCd]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.adptrMsgPtrnCdRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchAdptrUseYn]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.useYnRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchEaiBzwkDstcd]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.bzwkCodeRows).setFormat(codeName3OptionFormat).rendering();
			new makeOptions("CODE","NAME").setObj($("select[name=searchAdptrMsgDstCd]")).setNoValueInclude(true).setNoValue("", "<%=localeMessage.getString("combo.all")%>").setData(json.msgTypeRows).setFormat(codeName3OptionFormat).rendering();

			select_useYn['value'] = ": ;"+getGridSelectText("CODE","NAME", json.useYnRows);
			select_adptrMsgPtrnCdRows['value'] = ": ;"+getGridSelectText("CODE","NAME", json.adptrMsgPtrnCdRows);
			//select_testMasterYnRows['value'] = ": ;"+getGridSelectText("CODE","NAME", json.testMasterYnRows);
			
			setSearchable(selectName);
			putSelectFromParam();
			
			if (typeof callback === 'function') {
				callback();
			}
		},
		error:function(e){
			alert(e.responseText);
		}
	});
}

function list(_page)
{   
	var page = "${param.page}";
	if(_page) page = _page;
	var postData = getSearchForJqgrid("cmd","LIST"); //jqgrid에서는 object 로 
	
	postData["sortName"] ='${param.sortName}';
    postData["sortOrder"]="${param.sortOrder}";
	$("#grid").setGridParam({ url:url, postData: postData ,sortName:'${param.sortName}', sortOrder:"${param.sortOrder}",page : page }).trigger("reloadGrid");
}
function onclickBtnClone() {
	var sel = $('#grid').jqGrid('getGridParam', 'selarrrow');
	if (sel.length == 0) {
		alert('<%= localeMessage.getString("eaiMessage.alert17")%>');
		return;
	}
	var selectedAdapterNames = [];
	$(sel).each(function(index, i) {
		var adapterName = $('#grid').getCell(i, 'ADPTRBZWKGROUPNAME');
		selectedAdapterNames.push(adapterName);
	});
	var url2 = url_view;
	url2 += "?cmd=POPUP CALENDAR";
	var args = new Object();
	args['selectedAdapterName'] = selectedAdapterNames.join(',');
	showModal(url2,args,540,280, function(arg){
		var args = null;
	    if(arg == null || arg == undefined ) {
	    	//chrome
	        args = this.dialogArguments;
	        args.returnValue = this.returnValue;
	    } else {
	    	//ie
	        args = arg;
	    }
	    if( !args || !args.returnValue ) return;
	    deployAdapters(args.returnValue);
	});
}
function deployAdapters(ret) {
	var params = ret;
	params['cmd'] = 'CLONETOPROD'; 
	$.ajax({  
		type : "POST",
		url:url,
		dataType:"json",
		data:params,
		success:function(json){
			alert(json.message);
			list($("#grid").getGridParam("page"));
		},
		error:function(xhr,status,error){
			if (xhr.responseText != null) {
				try {
					alert(JSON.parse(xhr.responseText).errorMsg);	
				} catch (e) {
					alert(error);
				}
			}
		}
	});	
}

$(document).ready(function() {
	
	init().done(function(result) {
		jqGridInit();
	});
	

	$('#btn_clone').click(onclickBtnClone);
	
	$("#btn_excel").click(function(event) {
        event.stopPropagation(); // Do not propagate the event.
        // Create an object that will manage to download the file.
        var target = "excelDown" ; // iframe의 name
        //(url,cmd,gridObj,formObject,fileName,merge)
		gridToExcelSubmit2(url_excel,"LIST_GRID_TO_EXCEL",$("#grid"),$("#ajaxForm"),'<%= localeMessage.getString("adapter.title")%>');
		return false;
	});
	$("#btn_search").click(function(){
		list("1");
	});
	$("#btn_new").click(function(){
		var url2 = '<c:url value="/onl/admin/adapter/adapterMan.view"/>';
		url2 += '?cmd=DETAIL';
		url2 += '&page='+$("#grid").getGridParam("page");
		url2 += '&returnUrl='+getReturnUrl();
        url2 += '&menuId='+'${param.menuId}';
        url2 += '&sortName='+$("#grid").getGridParam("sortname");
        url2 += '&sortOrder='+$("#grid").getGridParam("sortorder");
		//검색값
        url2 += '&'+getSearchUrl();
		
        goNav(url2);
	});
	
	$("input[name^=search]").keydown(function(key){
		if (key.keyCode == 13){
			$("#btn_search").click();
		}
	});

	buttonControl();

	if(devSvr || stageSvr){
 		setBtnHide(roleString, "admin", "btn_clone");
	}else{
		$("#btn_clone").hide();
	}

	// 25.12.11 파일 가져오기 할 때 중복 검사 기능추가.
    FilePond.registerPlugin(FilePondPluginFileValidateType);

    let uploadErrors = [];
    let processedCount = 0;
    let totalFiles = 0;

    // FilePond 인스턴스 생성
    const pond = FilePond.create(document.querySelector('.filepond'), {
        instantUpload: false,
        allowRevert: false,
        acceptedFileTypes: ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/json'],

     	// 서버 설정
		server: {
			process: {
				url: url_file + '?cmd=LIST_IMPORT_FILE&serviceType=' + sessionStorage["serviceType"],
				method: 'POST',
				ondata: (formData) => {
                    const chkBox = document.querySelector('#uploadModal input[name="importDupliCheck"]'); 
                    const isChecked = chkBox ? chkBox.checked : false;
                    formData.append('importDupliCheck', isChecked);
                    return formData;
                },
                onerror: (response) => {
                    return response;
                }
            }
        }
    });

    // 파일 처리 결과 수신
    pond.on('processfile', (error, file) => {
        processedCount++;

        if (error) {
            let errorMsg = '';
            
            if (error.body) {
				errorMsg = error.body;
            } else if (typeof error === 'string') {
                errorMsg = error;
            } else {
				errorMsg = '가져오기 중 오류가 발생 했습니다.';
            }
            
            let fileName = 'UnKnown';
            if (file) {
				if(file.filename) fileName = file.filename;
				else if (file.file && file.file.name) fileName = file.file.name;
            }

            uploadErrors.push('파일명 [ ' + fileName + '] \n MESSAGE : ' + errorMsg);
        }

        // 모든 파일 처리 완료 시
        if (processedCount >= totalFiles) {
            setTimeout(() => {
                if (uploadErrors.length > 0) {
                    const msg = "파일 처리 중 오류가 발생했습니다. \n" + uploadErrors.join('\n');

                    // 실패 시 변수 초기화
                    uploadErrors = [];
                    processedCount = 0;

                    $('#btn_search').click();
                    alert(msg);

                } else {
                    alert('모든 파일이 성공적으로 업로드 되었습니다.');
                    $('#uploadModal').modal('hide');
                    $('#btn_search').click();
                }
            }, 100);
        }
    });

    // 업로드 버튼 클릭 이벤트
    document.getElementById('uploadButton').addEventListener('click', function(e) {
        e.stopPropagation(); 
        
        uploadErrors = [];
        processedCount = 0;

        const currentFiles = pond.getFiles();
        totalFiles = currentFiles.length;

        if (totalFiles === 0) {
            alert("업로드 할 파일을 선택하세요.");
            return;
        }

        const chkBox = document.getElementById('importDupliCheck');

        if (chkBox && !chkBox.checked) {
            if (!confirm("중복검사를 체크하지 않는 경우 기존 값은 덮어 씌워집니다. \n진행하시겠습니까?")) {
                return; 
            }
        }

        pond.processFiles();
    });

    // 모달이 닫힐 때만 초기화
    $('#uploadModal').on('hidden.bs.modal', function(e) {
        resetPond();
    });

    function resetPond() {
        pond.removeFiles(); 

        const chkBox = document.getElementById('importDupliCheck');
        if (chkBox) chkBox.checked = false;

        processedCount = 0;
        totalFiles = 0;
        uploadErrors = [];
    }

});

function jqGridInit() {
	$('#grid').jqGrid({
		datatype:"json",
		mtype: 'POST',
		sortable: false,
// 		url: url,
// 		postData : gridPostData,
		colNames:['<%= localeMessage.getString("adapter.adptrBzwkGroupName")%>',
                  '<%= localeMessage.getString("adapter.adptrBzwkGroupDesc")%>',
                  '<%= localeMessage.getString("adapter.adptrIoDstCd")%>',
                  '<%= localeMessage.getString("adapter.adptrMsgpTrnCdType")%>',
                  '<%= localeMessage.getString("adapter.eaiBzwkDstCd")%>',
<%--                   '<%= localeMessage.getString("adapter.adptrCd")%>', --%>
                  '<%= localeMessage.getString("adapter.adptrMsgDstCd")%>',
                  '<%= localeMessage.getString("adapter.adptrUseYn")%>'
<%--                   '<%= localeMessage.getString("adapter.kesauseyn")%>', --%>
                  <%-- '<%= localeMessage.getString("adapter.testmasteryn")%>',
                  '<%= localeMessage.getString("adapter.adptrnickname")%>' --%>
<%--                   '<%= localeMessage.getString("adapterDetail.eaisevrdstcd")%>', --%>
<%--                   '<%= localeMessage.getString("adapterDetail.dradptryn")%>' --%>
                  ],
		colModel:[
				{ name : 'ADPTRBZWKGROUPNAME' , align:'left'   },
				{ name : 'ADPTRBZWKGROUPDESC' , align:'left', width:180},
				{ name : 'ADPTRIODSTCD'       , align:'center', width:100, edittype:'select',editoptions:{value : "I:INBOUND;O:OUTBOUND"}, formatter:"select"},
				{ name : 'ADPTRMSGPTRNCD'     , align:'center', width:70, edittype:'select' , editoptions:select_adptrMsgPtrnCdRows, formatter:"select"},
				{ name : 'EAIBZWKDSTCD'       , align:'center', width:70},
// 				{ name : 'ADPTRCD'            , align:'center'  ,width:70},
				{ name : 'ADPTRMSGDSTCD'      , align:'center', width:70},
				{ name : 'ADPTRUSEYN'         , align:'center' , width:80, edittype:'select', editoptions:select_useYn, formatter:"select"},
// 				{ name : 'KESAUSEYN'          , align:'center'  ,width:100},
//				{ name : 'TESTMASTERYN'       , align:'center'  ,width:100, edittype:'select', editoptions:select_testMasterYnRows, formatter:"select", hidden:true},
//				{ name : 'ADPTRNICKNAME'      , align:'center'  ,width:100, hidden:true},
// 				{ name : 'EAISEVRDSTCD'       , align:'center'  ,width:80 ,formatter : formatter},
// 				{ name : 'DRADPTRYN'          , align:'center'  ,width:100}
				], 
				
        jsonReader: {
             repeatitems:false
        },	          
		pager : $('#pager'),
		page : '${param.page}',
		rowNum : '${rmsDefaultRowNum}',
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		multiselect: true,
		multiboxonly: false,		
		sortname : '${param.sortName}',
		sortorder : '${param.sortOrder}',
		rowList : eval('[${rmsDefaultRowList}]'),
		loadComplete:function (d){
			//$(this).setGridParam({datatype:'local'});
		},
        loadError: function (jqXHR, textStatus, errorThrown) {
        	if(jqXHR.status == 401) {
	    		alert('HTTP status code: ' + jqXHR.status + '\n' +
	                    '에러:  세션이 종료되었습니다. ');
	    		parent.location.href='<%=request.getContextPath()%>/';	
	    	}
        	
    	}, 
		ondblClickRow: function(rowId) {
			var rowData = $(this).getRowData(rowId); 
            var url2 = url_view;
            url2 += '?cmd=DETAIL';
            url2 += '&page='+$(this).getGridParam("page");
            url2 += '&returnUrl='+getReturnUrl();
            url2 += '&menuId='+'${param.menuId}';
        	url2 += '&sortName='+$("#grid").getGridParam("sortname");
        	url2 += '&sortOrder='+$("#grid").getGridParam("sortorder");            
			//검색값
            url2 += '&'+getSearchUrl();
            
            //key값
            url2 += '&adptrBzwkGroupName='+encodeURIComponent(rowData['ADPTRBZWKGROUPNAME']);
            goNav(url2);
            
        },
        onSortCol :function(sidx,colnum,sort_order){
          	var gridPostData = getSearchForJqgrid("cmd","LIST");
          	var sortorder="";
          	if( sort_order == "") 
          		sortorder ='asc';
          	else
          		sortorder = sort_order;
          	gridPostData["sortName"] =sidx;
        	gridPostData["sortOrder"]=sortorder;
        	$("#grid").setGridParam({ url:url, postData: gridPostData, sortname:sidx, sortorder:sortorder, page:"1"}).trigger("reloadGrid");	 
        	 
        	
        }
            		
	});
	
	resizeJqGridWidth('grid','content_middle','1000');
	
	list();
}

</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">
					<% if (SystemUtil.isDevServer() && deployYn) { %>
						<button type="button" class="cssbtn" id="btn_clone" level="W"><i class="material-icons">move_up</i> <%= localeMessage.getString("button.copyStage") %></button>
					<% } else if (SystemUtil.isStagingServer() && deployYn) { %>
						<button type="button" class="cssbtn" id="btn_clone" level="W"><i class="material-icons">move_up</i> <%= localeMessage.getString("button.copyProd") %></button>
					<% } %>
					<button type="button" class="cssbtn" id="btn_import" level="R" data-bs-toggle="modal" data-bs-target="#uploadModal"><i class="material-icons">upload</i>  <%=localeMessage.getString("button.import")%></button>
					<button type="button" class="cssbtn" id="btn_excel" level="R" ><i class="material-icons">table_view</i> <%= localeMessage.getString("button.excel") %></button>				
					<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>						
<%-- 					<img src="<c:url value="/img/btn_clone.png"/>" alt="" id="btn_clone"  level="W" style="height:32px;"/> --%>
<%-- 					<img src="<c:url value="/img/btn_excel.png"/>" id="btn_excel" 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>
				<div class="title"><%= localeMessage.getString("adapter.title")%></div>
				<form id = "ajaxForm">
					<table class="search_condition" cellspacing=0;>
						<tbody>
							<tr>
								<th width="13%"><%= localeMessage.getString("adapter.adptrBzwkGroupName")%></th>
								<td colspan="5"> <input type="text" name="searchAdptrBzwkGroupName" value="${param.searchAdptrBzwkGroupName}"></td>
							</tr>
							<tr>	
								<th width="13%"><%= localeMessage.getString("adapter.adptrBzwkGroupDesc")%></th>
								<td width="20%"><input type="text" name="searchAdptrBzwkGroupDesc" value="${param.searchAdptrBzwkGroupDesc}"></td>
								
								<th width="13%"><%= localeMessage.getString("adapter.adptrIoDstCd")%></th>
								<td width="20%">
									<div class="select-style">
										<select name="searchAdptrIoDstCd" value="${param.searchAdptrIoDstCd}" ></select></td>
									</div>
								</td>
								<th width="13%"><%= localeMessage.getString("adapter.adptrMsgpTrnCdType")%></th>
								<td width="20%">
									<div class="select-style">
										<select name="searchAdptrMsgPtrnCd" value="${param.searchAdptrMsgPtrnCd}" ></select>
									</div>	
								</td>
							</tr>
							<tr>
								<th><%= localeMessage.getString("adapter.adptrMsgDstCd")%></th>
								<td>
									<div class="select-style">
										<select name="searchAdptrMsgDstCd" value="${param.searchAdptrMsgDstCd}">
										</select>
									</div>	
								</td>
								<th><%= localeMessage.getString("adapterDetail.eaibzwkdstcd")%></th>
								<td>
									<div class="select-style">
										<select name="searchEaiBzwkDstcd" value="${param.searchEaiBzwkDstcd}">
										</select>
									</div>	
								</td>
								<th><%= localeMessage.getString("adapter.adptrUseYn")%></th>
								<td>
									<div class="select-style">
										<select name="searchAdptrUseYn" value="${param.searchAdptrUseYn}">
										</select>
									</div>		
								</td>
							</tr>
						</tbody>
					</table>
				</form>
				<table id="grid" ></table>
				<div id="pager"></div>
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->
		<!-- Modal -->
		<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
			<!-- 모달 내용 -->
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title"><i class="material-icons" style="vertical-align: sub; font-size: 25px">publish</i> <%=localeMessage.getString("button.import")%></h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
					<!-- 파일 업로드 시 중복체크 -->
            		<input type="checkbox" id="importDupliCheck" name="importDupliCheck">
            		<label class="form-check-label" for="importDupliCheck">중복검사</label>
						<input type="file" class="filepond" name="file" multiple data-allow-reorder="true" data-max-file-size="3MB" data-max-files="10">
					</div>
					<div class="modal-footer">
						<button id="uploadButton" class="btn btn-primary">IMPORT <%=localeMessage.getString("button.execute")%></button>
					</div>
				</div>
			</div>
		</div>
	</body>	
</html>

