<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="kr.co.hsnc.common.sql.*" %>
<%@ page import="kr.co.hsnc.common.util.*"%>
<%@ page import="kr.co.hsnc.common.config.*"%>
<%@ page import="com.udapsoft.waf.system.HandlerStorage" %>
<%@ include file="/jsp/work/taglib.jsp" %>
<jsp:useBean id="ctx" class="com.udapsoft.waf.system.context.SessionContext" scope="session" />
<%
    ctx.init(request, response);

	ValueObject params = null;
	ValueObject user = null;
	String message = null;
	String event   = null;

	HandlerStorage storage = ctx.getHandlerStorage();

	//user = storage.getUser();
	event = storage.getEvent();
	params = storage.getParams();
	String delHidden = "";
	String noHidden = ", Hidden:\"True\"";
	if( !params.get("IS_MODIFY").equals("Y") ) {
		delHidden = ", Hidden:\"True\"";
		noHidden = "";
	}
	
	RowSet fileListRowSet = storage.getRowSet("FileListRowSet");

	
	int size = (fileListRowSet != null ? fileListRowSet.size() : 0);
	
	String iframeID = params.get("iframeID");
	int defaultFileSize = params.getInt("file_size");
	
	if(defaultFileSize <= 0){
		defaultFileSize = WAFConfig.getInt("waf.repository.file.size");
	}
	
	String multi_yn = params.get("multi_yn");
	//params.get("obj_id")
	
	String user_fileName = "";
	// params.get("user_filename");
	
	/* String userAgent = request.getHeader("User-Agent");
	user _fileName =  params.get("user_filename");*/
	
	/* if (userAgent != null && ((userAgent.indexOf("MSIE 7.0") > -1 && userAgent.indexOf("InfoPath") <= -1) || userAgent.indexOf("MSIE 8.0") > -1 || userAgent.indexOf("MSIE 9.0") > -1)) { // MS IE 5.5 이하
		user_fileName = Translator.translate("iso-8859-1", "ksc5601",ctx.get("user_filename"));
    } else if (userAgent != null && userAgent.indexOf("Trident") > -1) { // MS IE (보통은 6.x 이상 가정)
    	user_fileName = Translator.translate("iso-8859-1", "UTF-8",ctx.get("user_filename"));
    } else { // 모질라나 오페라
    	user_fileName = Translator.translate("iso-8859-1", "UTF-8",ctx.get("user_filename"));
    } */
	
    String zipDownYn = params.get("zip_down_yn");
    String zipDownName = params.get("zip_down_name");
%>


<style type="text/css">
.view_title {
    BACKGROUND-COLOR            : #5F86B6                                   ;
    FONT-FAMILY                 : "굴림", "Verdana"                         ;
    FONT-SIZE                   : 9pt                                       ;
    COLOR                       : #ffffff                                   ;
    TEXT-INDENT                 : 9px                                      ;
}
</style>
<SCRIPT language="JavaScript">

var m_enc = "multipart/form-data";
var a_enc = "application/x-www-form-urlencoded";

/**
 * 시트 시작
 */
 var sheet1;
 var sheet1Row;
 var sheet1PageNo = 1;
 var pageLastRowIndex = 1;
 var validationResult = false;
 var filterShow = false;

 
 // 마지막으로 선택된 행의 번호를 기억하고 있음
 var CurMasterRow = 0;
 	
     function _onReady(){
 		gridInit(sheet1);

 		reloadProc();
 		
 		autoResize();
 		
 		
 /*		jQuery(window)
 		
  		$(window).on('beforeunload', function() {
 		    return doClose();
 		}); */
 		
 		$('#myFile').bind('change', function() { 
 			alert(this.files[0].size); 
 			}); 
 		
 	}
     
     function gridInit(sheetName){
 		var init_sheet = {};
 		init_sheet.Cfg = {SearchMode:2, Page:30};
 		init_sheet.Cols = [
							{Header:'상태',				Type:"Status", 			SaveName:"STATUS", 			Width:0, 	Align:"Center",	Hidden:"True"},
							{Header:'삭제',				Type:"DelCheck",		SaveName:"DEL_CHECK", 		Width:50, 	Align:"Center" <%=delHidden%>},
 			       			{Header:'번호',				Type:"Seq", 			SaveName:"NO",				Width:40, 	Align:"Center" <%=noHidden%> },
 			       			{Header:'파일ID',				Type:"Text", 			SaveName:"FILE_ID", 		Width:80, 	Align:"Left",	Edit: 0, 	Hidden:"True"},
 			       			{Header:'파일맵ID',			Type:"Text", 			SaveName:"FILE_MAP_ID", 	Width:80, 	Align:"Left",	Edit: 0, 	Hidden:"True"},
 			       			{Header:'☞ 파일명',			Type:"Text", 			SaveName:"FILE_NAME", 		Width:250, 	Align:"Left", 	Edit: 0},
 			       			{Header:'파일크기',			Type:"Text", 			SaveName:"FILE_SIZE", 		Width:60, 	Align:"Center",	Edit: 0},
 			       			{Header:'생성일시',			Type:"Text", 			SaveName:"CRE_DATE", 		Width:80, 	Align:"Center",	Edit: 0,	Format: "YmdHms"},
 		];

 		init_sheet.HeaderMode = {Sort:1};
 		IBS_InitSheet(sheetName, init_sheet);
 		sheetName.SetDataAutoTrim(0);
 		setGridSize();
 	}
  
  	function setGridSize() {
 		sheet1.FitColWidth();
 	}
  

     function sheet1_OnSearchEnd(code, message) {
 	    if(code == 0) {
 	    	setGridSize();
 		} else {
 			//조회 에러 수행
 			alert(message);
 		}
 	}
     
     function sheet1_OnDblClick(Row, Col, Value, CellX, CellY, CellW, CellH) {
     	if (sheet1.ColSaveName(Col) == "FILE_NAME") {
     		var url="/common/file/FileDownloadServlet";
     		url += "?file_id=" + sheet1.GetCellValue(Row, "FILE_ID");
     		
     		window.open(url, "_fileDown", "toolbar=no, width=400, height=100, top=500, left=400, toolbar=no,directories=no,status=no,scrollbars=yes,resize=no,menubar=no,target=new")
     		
     		//2020.03.12 왜 아래 또 submit 하는지 모르겠음.
     		//var fd = document.getElementById("form_filedown");
     		//fd.target = "_fileDown";
     		//fd.file_id.value = sheet1.GetCellValue(Row, "FILE_ID");
     		//fd.submit();
     	}
     } 
     
 	function sheet1_OnSaveEnd(code, msg) {
	    if(code >= 0) {
	    	alert("파일이 삭제 되었습니다.!");
	    } else {
	    	//alert(msg);
	    	alert("파일 삭제에 실패 하였습니다.");
        }
	}     
 
/**
 * 시트 끝
 */




function saveProc() {
	var f = document.form1;
	if(document.getElementById("multi_yn").value == "N" && sheet1.RowCount() >= 1){
		alert("1개의 첨부파일만 가능합니다.\n추가 된 첨부파일을 삭제후 추가 바랍니다.");
		return;
	}

	if( f.attach_file.value == "" ) {
	
		alert("파일을 선택하세요.");
		return;
	}
	
	if(!checkFile(document.getElementById("attach_file"))) return;
	

    f.fevent.value = "FileListWorker.Save";
    f.target = "worker";

	f.action = "FileListNewSave.screen";
    f.encoding = m_enc;
    f.method = "post";

	formSubmit(f, false);


	
}


function getFileSize(filePath) 
{ 
	var browser=navigator.appName;
	var size = 0;
	if (browser=="Microsoft Internet Explorer")
	{
		try{
			var oas = new ActiveXObject("Scripting.FileSystemObject");
			var filepath = document.getElementById('attach_file').value;
			var e = oas.getFile(filepath);
			size = e.size;
		}catch(e){
			alert("ActiveX 컨트롤을 허용 하시기 바랍니다.\n리플레쉬후 다시 시도 바랍니다.\n"+e);
			size = 1;
		}
	}
	else
	{
		size = "";
		for(var i=0;i<document.getElementById("attach_file").files.length;i++){
			size += document.getElementById("attach_file").files[i].size + ";";
		}

	}
	return size;
} 

function checkFile(obj) 
{ 
  var len = getFileSize(obj.value); 
  var defSize = document.getElementById("defaultFileSize").value;
  var filelist = "";
  var cnt =0;
  if(isNaN(len)){
	  filelist = len.split(";");
	  for(var i=0;i<filelist.length-1;i++){
		  if (filelist[i] > defSize * 1024 * 1024) 
		  { 
		    //alert("파일 크기는 "+defSize+"메가보다 작아야 합니다.");
			  cnt += 1;
		  }
	  }
	  if(cnt > 0){
		  alert("파일 크기는 "+defSize+"메가보다 작아야 합니다.");
		  return false;
	  }else{
		  return true;
	  }
  }else{
	  if (len > defSize * 1024 * 1024) 
	  { 
	  	alert("파일 크기는 "+defSize+"메가보다 작아야 합니다."); 
	    return false;
	  } else{
		return true;
	  }
  }
} 

// Form Lock 풀기
function resetFormProc() {

	resetFormSubmit();
}

function delProc() {
	
	if(sheet1.RowCount("D") <= 0){
		alert("삭제할 파일이 없습니다.");
		return;
	}
	
	if (confirm("삭제하시겠습니까?")) {
		jQuery("#fevent").val("FileListWorker.Del");
		
		var url = Modular.model.PageContext.CONTEXT_ROOT + "/common/file/FileListNewDelete.screen";
		var result = Modular.view.IBSheet7.doSave(sheet1, url, jQuery("#form1"), false);
	}
	
}

function resetProc(){
	var f = document.form1;
	f.attach_file.value="";
}

function reloadProc() {

	jQuery("#form1").attr("encoding", a_enc);
	jQuery("#fevent").val("GET_FILE_LIST");
	var url = Modular.model.PageContext.CONTEXT_ROOT + "/common/file/FileListNewData.screen";
	Modular.view.IBSheet7.doSearch(sheet1, url, jQuery("#form1"), 10, "");
}

function viewFileListClose(layerID){
	var obj = parent.document.getElementById("<%=params.get("obj_id")%>");
	if(obj == null && '<%=iframeID%>' != ''){
		var childDiv = parent.document.getElementById("<%=params.get("iframeID")%>_divcontent");
		var objChild = childDiv.getElementsByTagName("iframe")[0];
		var objDoc = objChild.contentWindow || objChild.contentDocument;
		obj = eval(objDoc.document.getElementById("<%=params.get("obj_id")%>"));
	}

	
	if( obj != null ){
		if( obj.type == "textarea" ) {
			obj.value = "";
			
			for(var i = 1; i<=sheet1.RowCount(); i++){
				var str =  i + " : " + sheet1.GetCellValue(i, "FILE_NAME") + " ( "+sheet1.GetCellValue(i, "FILE_SIZE")+" )";
				obj.value += str + "\n";
			}
		}else{
			var strHtml = "";
			for(var i = 1; i<=sheet1.RowCount(); i++){
				var temp =  i + " : " + sheet1.GetCellValue(i, "FILE_NAME") + " ( "+sheet1.GetCellValue(i, "FILE_SIZE")+" )";
				strHtml += "<li><a href=\"javascript:fileDown('"+sheet1.GetCellValue(i, "FILE_ID")+"');\">" + temp +"</a></li>\n";
			}
			strHtml = "<ul>\n" + strHtml + "</ul>";
			obj.innerHTML = strHtml;
		}
	}
	
	parent.fLayerPopClose(layerID);
}

function viewFileListClose1(layerID){
	var obj = parent.document.getElementById("<%=params.get("obj_id")%>");
	if(obj == null && '<%=iframeID%>' != ''){
		var childDiv = parent.document.getElementById("<%=params.get("iframeID")%>_divcontent");
		var objChild = childDiv.getElementsByTagName("iframe")[0];
		var objDoc = objChild.contentWindow || objChild.contentDocument;
		obj = eval(objDoc.document.getElementById("<%=params.get("obj_id")%>"));
	}

	
	if( obj != null ){
		
		if( obj.type == "hidden" || obj.type == "text") {
			obj.value = "";
			
			for(var i = 1; i<=sheet1.RowCount(); i++){
				var str =  i + " : " + sheet1.GetCellValue(i, "FILE_NAME") + " ( "+sheet1.GetCellValue(i, "FILE_SIZE")+" )";
				obj.value += str + "\n";
			}
		}else if( obj.type == "textarea" ) {
			obj.value = "";
			
			for(var i = 1; i<=sheet1.RowCount(); i++){
				var str =  i + " : " + sheet1.GetCellValue(i, "FILE_NAME") + " ( "+sheet1.GetCellValue(i, "FILE_SIZE")+" )";
				obj.value += str + "\n";
			}
		}else{
			var strHtml = "";
			for(var i = 1; i<=sheet1.RowCount(); i++){
				var temp =  i + " : " + sheet1.GetCellValue(i, "FILE_NAME") + " ( "+sheet1.GetCellValue(i, "FILE_SIZE")+" )";
				strHtml += "<li><a href=\"javascript:fileDown('"+sheet1.GetCellValue(i, "FILE_ID")+"');\">" + temp +"</a></li>\n";
			}
			strHtml = "<ul>\n" + strHtml + "</ul>";
			obj.innerHTML = strHtml;
		}
	}
	

	
	parent.fLayerPopClose(layerID);
}

function zipFileDown(){		
	var url="/common/file/FileDownloadServlet";		
		url += "?mode=zipDown";
		url += "&fileName=<%=zipDownName%>";
 		url += "&fileGB=<%=params.get("file_gb")%>";
 		url += "&ID=<%=params.get("id")%>";
 	
		window.open(url, "_fileDown", "toolbar=no, width=400, height=100, top=500, left=400, toolbar=no,directories=no,status=no,scrollbars=yes,resize=no,menubar=no,target=new");
}

</SCRIPT>
<STYLE>
BODY {
	padding : 0 0 0 0;
}
</STYLE>

<modular:search id="form1">
	<modular:key id="fevent" />
</modular:search>
<FORM id="form1" name="form1" method="post" modular:type="search">
<INPUT type="hidden" name="fevent" id="fevent"     	value="">
<INPUT type="hidden" name="file_gb"   	value="<%= params.get("file_gb") %>">
<INPUT type="hidden" name="id"        	value="<%= params.get("id") %>">
<INPUT type="hidden" name="is_modify" 	value="<%= params.get("is_modify") %>">
<INPUT type="hidden" name="is_corp"   	value="<%= params.get("is_corp") %>">
<INPUT type="hidden" name="is_con"    	value="<%= params.get("is_con") %>">
<INPUT type="hidden" name="is_techreq" 	value="<%= params.get("is_techreq") %>">
<INPUT type="hidden" name="mod_no"    	value="<%= params.get("mod_no") %>">
<INPUT type="hidden" name="sysGb" 	value="<%=params.get("sys_gb")%>">
<INPUT type="hidden" name="defaultFileSize" 	value="<%=defaultFileSize%>">
<INPUT type="hidden" name="multi_yn" 	value="<%=multi_yn%>">
<INPUT type="hidden" name="user_filename" 	value="<%=user_fileName%>">
<INPUT type="hidden" name="zip_down_yn" 	value="<%=zipDownYn%>">
<INPUT type="hidden" name="zip_down_name" 	value="<%=zipDownName%>">

	<%	if( params.get("IS_MODIFY").equals("Y") ) { %>
	<table id="search-table" class="search-form-table">
		<colgroup>
			<col width="100" />
			<col width="400" />
			<col width="*" />
		</colgroup>
		<tr>
			<th>파일선택</th>
			<td>
	        	<input id="attach_file" type="file" name="attach_file" class="input" contenteditable="false" <% if(!"N".equals(params.get("multi_yn"))){ %>multiple<%} %>>
			</td>
			<td class="button">
				<span class="btnSearch center"><a href="javascript:saveProc();" id="btnSave">파일저장</a></span>
				<span class="btnSearch center"><a href="javascript:delProc();" id="btnDel">파일삭제</a></span>
				<%	if (zipDownYn.equals("Y")) { %>
				<span class="btnSearch center"><a href="javascript:zipFileDown();" id="btnZipDown">모두저장(ZIP)</a></span>
				<%} %>
			</td>
		</tr>
	</table>
	<%} else if (zipDownYn.equals("Y")){%>
	<table id="search-table" class="search-form-table">
		<colgroup>
			<col width="*" />
		</colgroup>
		<tr>
			<td class="button" style="text-align: right;">
				<span class="btnSearch center"><a href="javascript:zipFileDown();" id="btnZipDown">모두저장(ZIP)</a></span>
			</td>
		</tr>
	</table>
	<%} %>
	<div id="sheet1_div" style="padding-top:5px; height: auto; min-height: 200px; overflow: auto;">
		<script>createIBSheet('sheet1','100%', '380px');</script>
	</div>
	<IFRAME width="0" height="0"  name="worker" style="display:none;"></IFRAME>

</FORM>
<FORM id="form_filedown" name="form_filedown" method="get" action="/common/file/FileDownloadServlet" style="display:none">
	<input type="hidden" id="file_id" name="file_id"/>
</FORM>