<%--
  Class Name : IpFilePopup.jsp
  Description : 파일 첨부 팝업  화면
  Modification Information
 
      수정일         수정자                   수정내용
    -------    --------    ---------------------------
     2018.06.11   ITN              최초 생성
 
    author   : ITN
    since    : 2018.06.11
--%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Language" content="ko">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>첨부파일</title>
<link rel="stylesheet" href="/direct/css/font.css">
<link rel="stylesheet" href="/direct/css/reset.css">
<link rel="stylesheet" href="/direct/css/enroll_popup.css">
<link rel="stylesheet" href="/direct/css/index.css">
<script src="<c:url value='/js/jquery-1.12.4.min.js' />"></script>
<script src="<c:url value='/js/ncms_common.js' />"></script>
<script type="text/javaScript" language="javascript">
$( document ).ready(function(){
	{
	    var w = $('.enroll_popup').width();
	    var h = $('.enroll_popup').height();
	    window.resizeTo(w+25, h+50);
	}

	var objDragAndDrop = $(".upload_area");
	$(document).on("dragenter",".upload_area",function(e){
	    e.stopPropagation();
	    e.preventDefault();
	    $(this).css('border', '2px solid #0B85A1');
	});
	$(document).on("dragover",".upload_area",function(e){
	    e.stopPropagation();
	    e.preventDefault();
	});
	$(document).on("drop",".upload_area",function(e){
	    $(this).css('border', '2px dotted #0B85A1');
	    e.preventDefault();
	    var files = e.originalEvent.dataTransfer.files;
	    handleFileUpload(files,objDragAndDrop);  //파일업로드
	});
	 
	$(document).on('dragenter', function (e){
	    e.stopPropagation();
	    e.preventDefault();
	});
	$(document).on('dragover', function (e){
	  e.stopPropagation();
	  e.preventDefault();
	  objDragAndDrop.css('border', '2px dotted #0B85A1');
	});
	$(document).on('drop', function (e){
	    e.stopPropagation();
	    e.preventDefault();
	});
	 
	

	<c:if test="${!empty fileList}">
	 	$('.no_img_box').hide();  //list 박스 형식 변경
     	$('.asset_no_use_pro_table').show();
		
		$('.file_name_text').each(function(index, item){
			$(this).parent().find('img').attr('src',  getfile_img($(this).text())) ; //이미지 변경
		});
		$('.file_size_text').each(function(index, item){
			$(this).text(getStrFileSize($(this).text())) ;
			
		});
		
		var totalfileSize = 0;
       	$('.totalfileCount').text($('.item_file_size').length) ;
       	$('.item_file_size').each(function(){
       		totalfileSize += $(this).val()*1 ;
       	});
       	$('.totalfileSize').text(getStrFileSize(totalfileSize)) ; 
	</c:if>
	
	 $(function(){  //단일 파일업로드
		$('#file_temp').change(function(e){
	   	   var objUpload = $(".upload_area");
	   	   var files = $('#file_temp')[0].files;
	   	   handleFileUpload(files,objUpload);  //파일업로드 
	   	});
	 });
	 
});

/* 파일등록 */
var _fileIdx = 0;
var _fileForm2 = new Array();
function handleFileUpload(files,obj)  //업로드 function
{
   var limitsize = 50*1024*1024;  //파일 제한 체크(50개, 50MB)
   var limitcount = 50;
   if($('#tbody_fiielist').find('tr').length + files.length > limitcount ){
	   alert("업로드 파일은 최대 50개 입니다.");
	   return ;
   } 
   for (var i = 0; i < files.length; i++){ 
	   if(files[i].size > limitsize){
		   alert(files[i].name+"파일 사이즈가"+getStrFileSize(files[i].size)+"로 50MB이하만 업로드 가능합니다.");
		   return ;
	   }
   }
	
   for (var i = 0; i < files.length; i++)
   {
        var fd = new FormData();
        fd.append('file', files[i]);
        var tmpObj = new Object();
        tmpObj.name = "file_" + _fileIdx;
        tmpObj.fileObj = files[i];
        
        _fileForm2.push(tmpObj);
        sendFileToServer(fd, obj, files[i], _fileIdx);
        _fileIdx++;
        
        var totalfileSize = 0;
       	$('.totalfileCount').text($('.item_file_size').length) ;
       	$('.item_file_size').each(function(){
       		totalfileSize += $(this).val()*1 ;
       	});
       	$('.totalfileSize').text(getStrFileSize(totalfileSize)) ; 
   }
}

function sendFileToServer(formData, obj , fileObj, _fileIdx)
{
	$('.no_img_box').hide();  //list 박스 형식 변경
    $('.asset_no_use_pro_table').show();
    var list_html = "";
    var tt = "";
    list_html += '<tr class="tr_upload_'+tt+'">';
    
    list_html += '<td class="file_name"><img src="'+getfile_img(fileObj.name)+'" alt=""><span class="file_name_text">'+fileObj.name+'</span></td>';
	list_html += '<td class="file_date">'+getDate()+'</td>';
	list_html += '<td class="file_size"><span class="file_size_text">'+getStrFileSize(fileObj.size)+'</span></td>';
	list_html += '<td class="file_del"><img src="/direct/img/upload_delect_img.png" alt="" onclick="delete_item(this, '+_fileIdx+')" ></td>';
	list_html += '<input type="hidden" name="fileSize" class="item_file_size" value="'+fileObj.size+'">';
	list_html += '<input type="hidden" name="atchFileIds" class="imsi" value="'+tt+'">';
	list_html += '</tr>';
	$('#tbody_fiielist').append(list_html);
}

/* 임시파일 삭제버튼 클릭시 */
function delete_item(obj, fileIdx){
	$(obj).closest("tr").remove();
	_fileForm2.forEach(function(fobj, idx) {
		if (fobj.name == ("file_" + fileIdx)) _fileForm2[idx] = "";
	});
	
	if($('.item_file_size').length == 0){
		$('.file_upload_box ').show();
        $('.upload_box_text').show();
        $('.asset_no_use_pro_table').hide();
	}else{
		var totalfileSize = 0;
	   	$('.totalfileCount').text($('.item_file_size').length) ;
	   	$('.item_file_size').each(function(){
	   		totalfileSize += $(this).val()*1 ;
	   	});
	   	$('.totalfileSize').text(getStrFileSize(totalfileSize)) ; 	
	}
}

/* 등록되어 있는 파일 삭제버튼 클릭시 */
function delete_upload_item(itemId, delObject){
	if(!confirm("삭제하시겠습니까?")){
		return false;
	}
	
	if($('.item_file_size').length == 0){
	   $('.upload_box_img').show();
       $('.upload_box_text').show();
       $('.uploaded_obj').hide();
	}else{
		var totalfileSize = 0;
	   	$('.totalfileCount').text($('.item_file_size').length) ;
	   	$('.item_file_size').each(function(){
	   		totalfileSize += $(this).val()*1 ;
	   	});
	   	$('.totalfileSize').text(getStrFileSize(totalfileSize)) ; 	
	}
	
 	$.ajax({
        type: "POST",
        url: "/uss/itsm/ip/IpFileDeleteAjax.do",
        data:{ "atchFileId" : itemId}, 
        dataType:'json',
        cache: false,
        async: false,
        timeout: 600000,
        success: function (returnData, status) {
            if(status == 'success'){
            	if(returnData.result == 'fail'){
            		alert("삭제처리가 실패하였습니다.");
            	}else if(returnData.result == 'auth_fail'){
            		alert("세션이 종료되었습니다.");
            	}else if(returnData.result =='success'){
            		$('.'+delObject+itemId).remove();
	        		if(opener.close_del!=undefined){
	        			opener.close_del = false;
	        		}
	        		opener.ipResetFileZone();
            	}
            }else{
            	alert("삭제처리에 실패하였습니다.");
            }
        },
        error: function (e) {
            console.log("ERROR : ", e);
            alert("삭제처리에 실패하였습니다.");
        }
    });
 
 	 
	if($('.item_file_size').length == 0){
		 $('.asset_no_use_pro_table').hide();
         $('.no_img_box').show();
         opener.$('#asset_file_upload').css({'background':'url("/direct/img/asset/asset_file.png")', 
      		'background-repeat': 'no-repeat', 
      		'background-position':'center'
      	});
	}else{
		var totalfileSize = 0;
	   	$('.totalfileCount').text($('.item_file_size').length) ;
	   	$('.item_file_size').each(function(){
	   		totalfileSize += $(this).val()*1 ;
	   	});
	   	$('.totalfileSize').text(getStrFileSize(totalfileSize)) ; 
	}
}


/* 등록버튼 클릭시 임시파일들 N으로 업데이트 */
function insert_confirm(){
	if($('#tbody_fiielist').find('tr').length == 0){
		alert("등록된 첨부파일이 없습니다.");
		return;
	}
	if(!confirm("등록하시겠습니까?")){
		return false;
	}
	
	$('input[name=atchFileIds]').each(function(index, item){ //화면에 있는 파일들 모두 임시없애기
		$(this).removeAttr("class", "imsi") ;
	});

	/* var data = new FormData(document.fileListForm); */
	
	document.fileListSendForm.fmsNm.value =  opener.document.writeForm.fmsNm.value; //제목입력
	document.fileListSendForm.content.value =  opener.document.writeForm.content.value; //내용입력
	document.fileListSendForm.siteId.value =  opener.document.writeForm.siteId.value; //내용입력
	var data = new FormData(document.fileListSendForm);
	_fileForm2.forEach(function(obj, idx) {
		if (obj) data.append("file"+idx, obj.fileObj);
	});
	
	$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        //url: "/uss/itsm/ip/IpFileInsertAjax.do",
        url: "/uss/ion/fms/FmsFileInsertAjax.do",
        data: data,
        dataType:'json',
        async: false,
        processData: false,
        contentType: false,
        cache: false,
        //timeout: 600000,
        success: function (returnData, status) {
			if(status == 'success'){ // status 확인 필요한가. 석세스 안뜨면 에러 가지 않나
				alert("저장 되었습니다.");
				opener.ipResetFileZone();
				window.self.close();
			} else if(status== 'fail'){
				alert("저장에 실패하였습니다.");
			}
		},
        error: function (e) { alert("저장에 실패하였습니다."); console.log("ERROR : ", e); }
    });
}

/* ********************************************************
* PROTOTYPE JS FUNCTION
******************************************************** */
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g, "");
}

String.prototype.replaceAll = function(src, repl){
	 var str = this;
	 if(src == repl){return str;}
	 while(str.indexOf(src) != -1) {
	 	str = str.replace(src, repl);
	 }
	 return str;
}
/* 취소버튼 클릭 */
function click_cancel(){
	self.close();
}	
</script>
</head>
<body>
<form name="fileListForm" id="fileListForm" method="post">
<input type="hidden" name="ipId" id="ipId" value="${ipVO.ipId}">
<input type="hidden" name="atchFileId" id="atchFileId" value="${fileVO.atchFileId}">

	<div class="enroll_popup edu_popup_detail asset_popup_no_use_pro">
		<div class="enroll_popup_title asset_popup_title">
			<img src="/direct/img/enroll_popup_title_bg.png" alt="">첨부파일 업로드 
			<!-- <div class="enroll_popup_title_btns">
				<ul>s
					<li><img src="/direct/img/popup_little_icon.png" alt=""></li>
					<li><img src="/direct/img/popup_full_icon.png" alt=""></li>
					<li><img src="/direct/img/popup_close_icon.png" alt=""></li>
				</ul>
			</div> -->
		</div>
		<div class="enroll_input_left asset_no_use_pro upload_area">
			<ul>
				<li>
					<input type="button" value="파일추가" class="asset_no_use_file_upload" onclick="document.all.file_temp.click();"  style="margin-left: 582px;"	>
             		<input type="file" name="file_temp" id="file_temp" style="display:none" class="file">
				</li>
				<li>
					<div class="file_upload_box no_img_box">
						<img class="upload_box_img" src="/direct/img/upload_img.png" alt="" style="margin-top: 60px;">
						<div class="upload_box_text">
							<span class="file_upload_text_1">첨부파일 올리기</span><br>
							<span class="file_upload_text_2">(파일을 끌어다 놓으세요)</span>
						</div>
					</div>
				</li>
			</ul>
			<div class="asset_no_use_pro_table" style="display:none">
			<table class="uploaded_obj">
					<table class="uploaded_obj">
						<thead>
							<tr>
								<!-- <th class="file_check_asset"><input type="checkbox"><label for=""></label></th> -->
								<th class="file_name">파일명</th>
								<th class="file_date">등록일시</th>
								<th class="file_size">크기</th>
								<th class="file_del">삭제</th>
							</tr>
						</thead>
					</table>
					<div class="file_list uploaded_obj">
						<table>
							<tbody id="tbody_fiielist">
							 	<c:forEach var="fileList" items="${fileList}" varStatus="status">
                        			<tr class="tr_upload_${fileList.atchFileId}">
										<td class="file_name">
											<img src="/direct/img/upload_hwp_img.png" alt="" /><span class="file_name_text">${fileList.orignlFileNm}</span>
										</td>
										<td class="file_date">${fileList.regdt}</td>
										<td class="file_size"><span class="file_size_text">${fileList.fileSize}</span></td>
										<td class="file_del">
											<img src="/direct/img/upload_delect_img.png" alt=""
											onclick="delete_upload_item('${fileList.atchFileId}' , '${fileList.fileSn}', 'tr_upload_'); return false;"
											>
										</td>
										<input type="hidden" name="fileSize" class="item_file_size" value="${fileList.fileSize}" >
									</tr>
                        		</c:forEach>
							</tbody>
						</table>
					</div>
					<table class="uploaded_obj">
						<tfoot>
							<tr>
								<td>최대 <span class="upload_number">50</span>개 ｜ <span class="upload_number">50MB(개당)</span> 제한</td>
								<td><span class="upload_number totalfileCount">0</span>개 ｜ <span class="upload_number totalfileSize">0MB</span></td>
							</tr>
						</tfoot>
					</table>
				</table>
			</div>
		</div>

		<div class="main1_btn_div">
			<input type="button" class="save_btn" value="저장" onclick="insert_confirm(); return false;">
			<input type="button" class="close_btn" value="닫기" onclick="click_cancel(); return false;">
		</div>
	</div>
</form>

<form name="fileListSendForm" id="fileListSendForm" method="post">
	<input type="hidden" name="fmsId id="fmsId" value="${fmsFileVO.fmsId}">
	<input type="hidden" name="userId" id="userId" value="${fmsFileVO.userId}">
	<input type="hidden" name="url" id="url" value="${fmsFileVO.url}">
	<input type="hidden" name="fmsNm" id="fmsNm" value="">
	<input type="hidden" name="content" id="content" value="">
	<input type="hidden" name="siteId" id="siteId" value="">
</form>
	
</body>
</html>