<%--
  Class Name : AstHdCdPopup.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" />
<link href="<c:url value='/'/>css/jstree/themes/default/style.min.css" rel="stylesheet" type="text/css">
<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/jstree.min.assetlocshow.js' />"></script>
<script type="text/javascript" src="/js/audit/audit.common.js"></script>
<script src="<c:url value='/js/EgovCalPopup.js' />"></script>   
<script type="text/javaScript" language="javascript">
var delAutItemId = new Array();
var atchFileIds = new Array();
$(window).bind("beforeunload", function (e){
	$('.imsi').each(function(index, item){
		atchFileIds.push($(this).attr('value')) ;
	});
	
	if(atchFileIds.length !=0){
		$.ajax({
		    type: "POST",
		    url: "/uss/itsm/asset/AssetFileClsDeleteAjax.do",
		    data:{  "del": atchFileIds.toString()},
		    dataType:'jsonp',
		    cache: false,
		    async: false,
		    success: function (returnData, status) {
		    	if(status == 'success'){
		        	if(returnData.result == 'fail'){
		        	}else if(returnData.result == 'auth_fail'){
		        	}else if(returnData.result =='success'){
		        	}
		        }else{
		        }
		    },
		    error: function (e) {
		    } 
		});
	}
});

$( document ).ready(function(){
	{
	    var w = $('.enroll_popup').width();
	    var h = $('.enroll_popup').height();
	    window.resizeTo(w+25, h+50);
	}

	//상단 selectbox change 이벤트 
	/* $("#upload_list").on( "change", function() {  
		$('#upload_list_detail').html($('#span_option_'+this.value).html().trim())
	}); */
	
	
	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();
	});
	 
	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]);
	        sendFileToServer(fd, obj, files[i]);
	        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)
	{
		formData.append('astId', '${assetVO.astId}'); //데이터 추가
		formData.append('fileType', '${fileVO.fileType}');
		
		var uploadURL = "/uss/itsm/asset/AssetFileInsertAjax.do"; //Upload URL
	    var extraData ={}; //Extra Data.
	    var jqXHR=$.ajax({
	            xhr: function() {
	            var xhrobj = $.ajaxSettings.xhr();
	            if (xhrobj.upload) {
	                    xhrobj.upload.addEventListener('progress', function(event) {
	                        var percent = 0;
	                        var position = event.loaded || event.position;
	                        var total = event.total;
	                        if (event.lengthComputable) {
	                            percent = Math.ceil(position / total * 100);
	                        }
	                    }, false);
	                }
	            return xhrobj;
	        },
	        url: uploadURL,
	        type: "POST",
	        dataType:'jsonp',
	        contentType:false,
	        processData: false,
	        cache: false,
	        data: formData,
	        async: false,
	        success: function(returnData , status){
	            if(returnData.result == 'auth_fail'){
	            	alert("세션이 종료되었습니다.");
	            }else if(returnData.result == 'success'){
	    			 $('.no_img_box').hide();  //list 박스 형식 변경
			         $('.asset_no_use_pro_table').show();
			         var list_html = "";
			         list_html += '<tr class="tr_upload_'+returnData.fileVO.atchFileId+'">';
			         /* list_html += '<td class="file_check_asset"><input type="checkbox" id="'+returnData.fileVO.atchFileId+'"><label for="'+returnData.fileVO.atchFileId+'"></label></td>'; */
			         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(\''+returnData.fileVO.atchFileId+'\' , \'tr_upload_\'); return false;"></td>';
		        	 list_html += '<input type="hidden" class="item_file_size" value="'+fileObj.size+'">';
		        	 list_html += '<input type="hidden" name="atchFileIds" class="imsi" value="'+returnData.fileVO.atchFileId+'">';
		        	 list_html += '</tr>';
		        	 $('#tbody_fiielist').append(list_html);
	    		}
	        }
	    }); 
	}

	<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').change(function(e){
	   	   var objUpload = $(".upload_area");
	   	   var files = $('#file')[0].files;
	   	   handleFileUpload(files,objUpload);  //파일업로드 
	   	});
	 });
	 
});

/* 삭제버튼 클릭시 */
function delete_item(itemId, delObject){
	if(!confirm("삭제하시겠습니까?")){
		return false;
	}
	event.preventDefault();
 	$.ajax({
        type: "POST",
        url: "/uss/itsm/asset/AssetFileDeleteAjax.do",
        data:{ "atchFileId" : itemId , "fileType" : '${assetVO.fileType}'}, 
        dataType:'jsonp',
        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;
	        		}
            	}
            }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 frm = document.fileListForm;
	var astUseCodeDate = "";
	var astUseCodeDateYYYYMMDD = document.getElementById('astUseCodeDateYYYYMMDD').value;
	if( astUseCodeDateYYYYMMDD!=""){
		astUseCodeDate = Number(astUseCodeDateYYYYMMDD.replaceAll("-",""))+"000000";
	}
	
	frm.astUseCodeDate.value = astUseCodeDate ;
	//날짜 update
	if(astUseCodeDate != ""){
		$.ajax({
	        type: "POST",
	        url: "/uss/itsm/asset/AssetFileDateUpdateAjax.do",
	        data:{ 'astId':'${assetVO.astId}' , 'astUseCodeDate' : astUseCodeDate ,'fileType':'${assetVO.fileType}'}, 
	        dataType:'jsonp',
	        cache: false,
	        async: false,
	        timeout: 600000,
	        success: function (returnData, status) {
	            if(status == 'success'){
	            	if(returnData.result == 'fail'){
	            	}else if(returnData.result == 'auth_fail'){
	            	}else if(returnData.result =='success'){
	            		opener.$('#astUseCodeDateYYYYMMDD').val(astUseCodeDateYYYYMMDD);
	            	}
	            }else{
	            	alert("등록이 실패하였습니다.");
	            }
	        },
	        error: function (e) {
	            console.log("ERROR : ", e);
	            alert("삭제처리에 실패하였습니다.");
	        }
	    });
	}
	
	if($('.item_file_size').length != 0){
		opener.$('#asset_file_upload').css({'background':'url("/direct/img/asset/asset_file_on.png")', 
     		'background-repeat': 'no-repeat', 
     		'background-position':'center'
     	});
	}
	alert("등록되었습니다.");
	self.close();
}

/* ********************************************************
* 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">
	<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=""> 
			<c:if test="${fileVO.fileType == '1'}">사용상태처리</c:if>
			<c:if test="${fileVO.fileType == '2'}">일괄불용처리</c:if>
			
		</div>
		<div class="enroll_input_left asset_no_use_pro upload_area">
			<ul>
				<li>
					<c:if test="${fileVO.fileType == '1'}">
						사용상태 처리일자
					</c:if>
					<c:if test="${fileVO.fileType == '2'}">
						일괄불용 처리일자
					</c:if>
					<input type="hidden" name="cal_url" id="cal_url" value="<c:url value='/sym/cmm/EgovNormalCalPopup.do'/>" >
					<input type="text" class="asset_no_use_pro_date" name="astUseCodeDateYYYYMMDD" id="astUseCodeDateYYYYMMDD" readonly="readonly" value="${resultAssetVO.astUseCodeDate}">
					<a href="#Redirect" onclick="javascript:fn_egov_NormalCalendar(document.forms.fileListForm, document.forms.fileListForm.astUseCodeDateYYYYMMDD);" class="date_select_btn">
						<img src="/images/egovframework/com/cmm/icon/bu_icon_carlendar.gif" align="middle" style="border:0px;vertical-align: baseline;top:6px;" alt="달력창팝업버튼이미지">
					</a> 
					<input type="hidden" name="astUseCodeDate" id="astUseCodeDate">
					<input type="hidden" name="astUseCodeIds" id="astUseCodeIds" value="${assetVO.astUseCodeIds}"><!-- 일괄불응 -->
						
					<input type="button" value="파일추가" class="asset_no_use_file_upload" onclick="document.all.file.click();"	>
             		<input type="file" name="file" id="file" style="display:none" class="file">
					<!-- <input type="button" value="파일 다운로드" class="asset_no_use_file_down"> -->
				</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_check_asset"><input type="checkbox" id="${fileList.atchFileId}"><label for="${fileList.atchFileId}"></label></td> --%>
										<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.frstRegistPnttm}</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_item('${fileList.atchFileId}' , 'tr_upload_'); return false;"
											>
										</td>
										<input type="hidden" 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>	
</body>
</html>