<%@ 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"%>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");

	String tranTypeCode = "TRAN_TYPE";
	String detailCmd = "DETAIL"; 
	String rmsMenuAuth = (String)request.getAttribute("rmsMenuAuth"); 
	if( "R".equals(rmsMenuAuth) ) {
		tranTypeCode = "TRAN_TYPE_DEV";
		detailCmd = "DETAILDEV"; 
	}
%>
<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/admin/service/ifUploadforStgCopyMan.json" />';
var url_view = '<c:url value="/onl/admin/service/ifUploadforStgCopyMan.view" />';
var roleString	= "<%=SessionManager.getRoleIdString(request)%>";
var devSvr		= <%=SystemUtil.isDevServer()%>;

function getDoc(frame) {
    var doc = null;

    // IE8 cascading access check
    try {
        if (frame.contentWindow) {
            doc = frame.contentWindow.document;
        }
    } catch(err) {
    }

    if (doc) { // successful getting content
        return doc;
    }

    try { // simply checking may throw in ie8 under ssl or mismatched protocol
        doc = frame.contentDocument ? frame.contentDocument : frame.document;
    } catch(err) {
        // last attempt
        doc = frame.document;
    }
    return doc;
}  

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("");
				var data = json;
				if (!data.rows){
					alert(data.message);
					return ;
				}
				$("#grid").jqGrid('clearGridData');
				var rows = $("#grid")[0].rows;
				var index = Number($(rows[rows.length-1]).attr("id"));
				if (isNaN(index)) index=0;
				for(var i=0;i<data.rows.length;i++){
				    var rowid = index + 1 + i;
					$("#grid").jqGrid('addRow', {
			           rowID : rowid,          
			           initdata : data.rows[i],
			           position :"last",    //first, last
			           useDefValues : false,
			           useFormatter : false,
			           addRowParams : {extraparam:{}}
					});
					if(data.rows[i].EXIST=="X"){
						$("#"+rowid).find("td").css("background-color","#FFCC99");
						var cbs=$("#jqg_grid_"+rowid);
						cbs.attr("disabled","disabled");
					}
				}
				
				$("#"+$('#grid').jqGrid('getGridParam','selrow')).focus();
		  		if (typeof callback === 'function') {
					successcallback(data, textStatus, jqXHR);
				}
           },
           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="/onl/admin/service/companyMan.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);
			 }
       });

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

	$('#grid').jqGrid({
		datatype:"json",
		mtype : 'POST',
		colNames:[
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.eaiSvcName") %>',
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.appCd") %>',
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.sysIfCd") %>',
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.sysIfName") %>',
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.eaiSvrDstcd") %>',
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.inoutType") %>',
                  '<%= localeMessage.getString("ifUploadforStgCopyMan.exist") %>'
                  ],
		colModel:[
				{ name : 'EAISVCNAME'   , align:'left'	,sortable:false  },
				{ name : 'APPCODE' , align:'left'  },
				{ name : 'SYSIFCD'  , align:'left'  },
				{ name : 'SYSIFNAME' , align:'left'  },
				{ name : 'EAISEVRDSTCD'  , align:'left'  },
				{ name : 'IOTYPE'  , align:'left'  },
				{ name : 'EXIST'  , align:'left'  }
				],
        jsonReader: {
             repeatitems:false
        },	          
	    autoheight: true,
	    height: $("#container").height(),
		autowidth: true,
		viewrecords: true,
		multiselect: true,
		multiboxonly: true,
		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) {
        },		
		onSelectRow: function(rowId) {
			var rowData = $(this).getRowData(rowId);
			if(rowData['EXIST']=="X"){
				$("#jqg_grid_"+rowId).removeAttr("checked");
			}
       }
	});
	
	
	resizeJqGridWidth('grid','content_middle','1000');

	$("#multiform").on('submit',fileupload);
	$('#btn_upload').click(function(){
		$("#grid").jqGrid('clearGridData');
		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 == ""){
				return;
			}else{
				$("#multiform").submit();
			}
			
		});
	}
	if(window.FormData !== undefined) {
		$("input[name=file]").hide();
	}else{
		$("input[name=file]").show();
	}
	
	$("#btn_previous").click(function(){
		goNav(returnUrl);//LIST로 이동
	});

	$('#btn_clone').click(onclickBtnClone);
	
	$(document).on("click","#cb_grid",function(){
		$("input[type=checkbox]").each(function(){
			if($(this).prop("disabled")==true){
				$(this).prop("checked","");
			}
		});
	});
	
	buttonControl();
/*	
	if(devSvr){
		setBtnHide(roleString, "admin", "btn_clone");
	}else{
		setBtnHide(roleString, " ", "btn_clone");
	}
*/	
	//모든조건에서 안보이게
	setBtnHide(" ", "admin", "btn_clone");
});

function onclickBtnClone() {
	var sel = $('#grid').find("tr.jqgrow:has(td> input.cbox:checked)");
	if (sel.length == 0) {
		alert('<%= localeMessage.getString("ifUploadforStgCopyMan.alert") %>');
		return;
	}
	var selectedSvcNames = [];
	var selectedFlowControls = [];

	$(sel).each(function(index, i) {
		var svcName = $('#grid').getCell(i.id, 'EAISVCNAME');
		selectedSvcNames.push(svcName);
	});
	
	
	var url2 = '<c:url value="/onl/admin/service/eaiMsgMan.view" />';
	url2 += "?cmd=POPUP CALENDAR";
	var args = new Object();
	args['selectedSvcName'] = selectedSvcNames.join(',');
	args['selectedFlowControl'] = selectedFlowControls.join(',');
	showModal(url2,args,540,200, 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;
	    cloneToProd(args.returnValue);
	});
}

function cloneToProd(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);
				}
			}
		}
	});	
}

</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">
				<form id="multiform" method="POST" enctype="multipart/form-data" action="<c:url value="/onl/admin/service/ifUploadforStgCopyMan.file"/>">
					<div class="search_wrap">
						<div style="display:inline-block;">
							<input type="file" name="file" style="display:inline-block"/>
							<input type="text" name="cmd" style="display:none" value="UPLOAD"/>
						</div>
						<button type="button" class="cssbtn" id="btn_upload" level="W"><i class="material-icons">upload</i> <%= localeMessage.getString("button.upload") %></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_upload.png"/>" alt="" id="btn_upload" level="W" /> --%>
					</div>
				</form>
				<div class="title"><%= localeMessage.getString("ifUploadforStgCopyMan.title") %></div>				
				<table id="grid" ></table>
				<div id="pager"></div>
			</div><!-- end content_middle -->
		</div><!-- end right_box -->				
	</body>	
</html>

