<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>
<c:set var="pageKorName" scope="request">단속 파일 등록</c:set>
<div class="d-flex flex-column" data-doctx="${pageName}">
	<div class="d-flex flex-row justify-content-evenly">
		<div class="card h-px-80 w-px-1400">
			<form name="frmFirst" method="post" enctype="multipart/form-data">
				<div class="row g-1">
					<div class="col-md-12">
						<div class="form-check form-switch">
						  <input type="checkbox" is="id-input" name="direct" class="form-check-input" />
						  <label is="name-label" for="direct" class="form-check-label">로컬파일업로드</label>
						</div>
					</div>
				</div>
				<div class="row g-1">
					<div class="col-md-12 d-flex align-items-center flex-nowrap">
						<label is="name-label" for="taskSeCd"
						class="w-px-120 bg-lighter pe-2 col-form-label text-sm-end">과태료업무</label>
					    <select is="id-select" name="taskSeCd" class="form-select" disabled>
							<c:forEach items="${TaskListForSgg}" var="item">
								<option value="${item.code}"
									<c:if test="${item.code eq taskSeCd}"> selected="selected" </c:if>
								>${item.value}</option>
							</c:forEach>
						</select>
						<span id="uploadFilesArea" hidden>
							<label is="name-label" for="uploadFiles"
							class="w-px-120 bg-lighter pe-2 col-form-label text-sm-end">파일</label>
							<input type="file" is="id-input" name="uploadFiles"
							multiple="multiple" class="form-control"/>
						</span>
						<span class="d-flex justify-content-end float-start ms-4">
							<button type="button" name="btnSearch"
							class="btn btn-primary">조회</button>
							<button type="button" name="btnFileUpload"
							class="btn btn-primary" hidden>업로드</button>
						</span>
					</div>
				</div>
			</form>
		</div>
	</div>
	<div class="d-flex flex-row justify-content-evenly">
		<div class="card my-4 px-4 h-px-600 w-px-700">
			<form name="frmGrid">
				<div>
					<span class="container-page-btn">
						<div class="d-flex flex-row justify-content-between">
							<span is="paging-info" name="parsedInfoPagingInfo" class="dataTables_info"></span>
			                <ul name="parsedInfoPaging" class="pagination pagination-primary"></ul>
						</div>
						<span class="container-window-btn-right">
						</span>
				     </span>
				</div>
				<div class="card-datatable text-nowrap">
			        <div class="dataTables_wrapper dt-bootstrap5 no-footer">
						<div name="table-responsive" class="table-responsive ox-scroll oy-scroll h-px-550">
							<table name="table" class="datatables-ajax table table-bordered dataTable no-footer">
								<thead class="sticky-thead">
									<tr>
										<th style="min-width: 80px;">단속자료</th>
										<th style="min-width: 80px;" title="더블클릭시 축소/확대 됩니다."
										class="downsize" ondblclick="FimsSupport.fnDownsizeToggle(this);" href="#">
											파일명 <i class='bx bx-expand'></i>
										</th>
										<th style="min-width: 80px;">타임스탬프</th>
										<th style="min-width: 80px;">파일사이즈</th>
										<th style="min-width: 80px;">파일확장자</th>
										<th style="min-width: 80px;">파일상태</th>
										<th style="min-width: 80px;">총사진갯수</th>
										<th style="min-width: 80px;">파일순번</th>
										<th style="min-width: 80px;">장비코드</th>
										<th style="min-width: 80px;">차량번호</th>
										<th style="min-width: 80px;">사진구분명</th>
										<th style="min-width: 80px;">업체코드</th>
										<th style="min-width: 80px;">위반내용</th>
										<th style="min-width: 80px;">차량속도</th>
										<th style="min-width: 80px;">번호판위치x</th>
										<th style="min-width: 80px;">번호판위치y</th>
										<th style="min-width: 80px;">번호판width</th>
										<th style="min-width: 80px;">번호판height</th>
										<th style="min-width: 80px;">위치좌표x</th>
										<th style="min-width: 80px;">위치좌표y</th>
										<th style="min-width: 80px;">날짜</th>
										<th style="min-width: 80px;">시간</th>
										<th style="min-width: 80px;">단속시작시간</th>
										<th style="min-width: 80px;">단속종료시간</th>
										<th style="min-width: 80px;">어린이보호구역</th>
										<th style="min-width: 80px;">단속장소명</th>
										<th style="min-width: 80px;">단속법정동</th>
										<th style="min-width: 80px;">단속장소(주소)</th>
									</tr>
			                    </thead>
			                    <tbody></tbody>
								<template is="curly-brackets" class="found">
		                    		<tr data-index="DATA-INDEX">
		                    			<td onclick ondblclick class="text-center">TEMP_GROUP_ID</td>
		                    			<td onclick ondblclick title="{FILE_NAME}"
		                    			class="text-start text-truncate max-w-th">FILE_NAME</td>
		                    			<td onclick ondblclick class="text-center">FILE_LAST_MODIFIED</td>
			                    		<td onclick ondblclick class="text-center">FILE_SIZE</td>
			                    		<td onclick ondblclick class="text-start">FILE_EXTENSION</td>
			                    		<td onclick ondblclick class="text-start">FILE_STATUS_NM</td>
			                    		<td onclick ondblclick class="text-end">PHOTO_CNT</td>
			                    		<td onclick ondblclick class="text-center">FILE_SEQ</td>
			                    		<td onclick ondblclick class="text-center">EQPMNT_CD</td>
			                    		<td onclick ondblclick class="text-start">VHRNO</td>
			                    		<td onclick ondblclick class="text-start">PHOTO_TYPE_NM</td>
			                    		<td onclick ondblclick class="text-center">BZENTY_CD</td>
			                    		<td onclick ondblclick class="text-start">VLTN_NM</td>
			                    		<td onclick ondblclick class="text-center">CAR_VELOCITY</td>
			                    		<td onclick ondblclick class="text-end">MOSC_X</td>
			                    		<td onclick ondblclick class="text-end">MOSC_Y</td>
			                    		<td onclick ondblclick class="text-end">PLATE_WIDTH</td>
			                    		<td onclick ondblclick class="text-end">PLATE_HEIGHT</td>
			                    		<td onclick ondblclick class="text-end">GPS_X</td>
			                    		<td onclick ondblclick class="text-end">GPS_Y</td>
			                    		<td onclick ondblclick class="text-center">CRDN_YMD</td>
		                    			<td onclick ondblclick class="text-center">CRDN_TM</td>
										<td onclick ondblclick class="text-center">CRDN_BGNG_TM</td>
			                    		<td onclick ondblclick class="text-center">CRDN_END_TM</td>
			                    		<td onclick ondblclick class="text-start">CRDN_SPAREA_NM</td>
			                    		<td onclick ondblclick class="text-start">CRDN_PLC</td>
			                    		<td onclick ondblclick class="text-start">CRDN_STDG_NM</td>
			                    		<td onclick ondblclick class="text-start">CRDN_ROAD_NM</td>
			                    	</tr>
		                    	</template>
		                    	<template class="notFound">
		                    		<tr>
		                    			<td valign="top" colspan="28" class="dataTables_empty text-center">
		                    			정보를 찾지 못했습니다.
		                    			</td>
		                    		</tr>
		                    	</template>
							</table>
						</div>
					</div>
			    </div>
			</form>
		</div>
		<div name="imageArea" class="card my-4 px-4 w-px-600 h-px-600 justify-content-center">
		</div>

		<div class="card my-4 px-2 w-px-120 h-px-600">
			<div class="d-flex my-2 flex-column">
				<button type="button" name="btnInsertCrdn" class="btn btn-primary my-2">단속등록</button>
				<button type="button" name="btnDelete" class="btn btn-primary my-2">삭제</button>
			</div>
		</div>
	</div>

	<form name="frmMultipart" method="post" enctype="multipart/form-data"></form>
</div>


<script>
LoadScript("crdn05020Script",wctx.url("/resources/js/fims/crdn/crdn05020.js?ver=${ver}"));

pageObject["${pageName}"] = newDoctxFinder("${pageName}");

$(document).ready(function(){

	var $P = pageObject["${pageName}"];

	$P.tempGroup = {};

	/**************************************************************************
	* DatasetControl, DatasetSupport, FormFields
	**************************************************************************/
	var ctrl = newCrdn05020Control($P);

	ctrl.dataset.onDatasetChange = (obj, option) => {

		var t = $P.getGridTemplate();
		var trs = Apply.fromDataset.getTbody(ctrl.dataset, t.found, t.notFound, t.replacer);
		$P.renderParsedInfoList(obj?.Paging?.totalSize, ctrl.dataset.length, trs);

		$P.pagingSupport.setPagingInfo(obj);
	};

	ctrl.dataset.onCurrentChange = (dataItem) => {
		$P.$findn("imageArea").html("");

		if(dataItem && dataItem.data){
			var dataIndex = dataItem.index;

			$P.$findn("table-responsive").find("tbody").setCurrentRow(dataIndex);

			if(dataItem.data.FILE_GROUP_TYPE == "BIN"){
				var srcArr = [];

				for(var i=1; i <= dataItem.data.PHOTO_CNT; i++){
					srcArr.push("data:image/jpg;base64," + dataItem.data["B64IMAGE"+i])
				}

				$P.renderImage(srcArr);
			} else {
				var dataKey = dataItem.data.FILE_NAME;
				if(!dataKey.endsWith(".txt") && !dataKey.endsWith(".TXT")){
					var src = dataItem.data.FILE_PATH;
					$P.renderImage(src);
				}
			}

		}
	};

	$P.pagingSupport = new FimsPagingSupport({
		doq: $P,
        linkContainer: "[name='parsedInfoPaging']"
	});

	/**************************************************************************
	* pageObject.function
	**************************************************************************/

	//ftp체크
	$P.checkFTP = () => {

		ajax.post({
			url : wctx.url("/${taskSeCd}/crdn/crdn05/020/importFileFromServer.do"),
			data : {
				taskSeCd : $P.$findn("taskSeCd").val()
			},
			success : (resp) => {
				if(resp.saved){
					$P.searchFileList();
				} else {
					dialog.alert({
						content : "파일 조회에 실패하였습니다.",
						init : function(){
							AppSupport.setDialogZindex();
							AppSupport.focusClose();
						}
					});
				}
			}
		});

	}

	//로컬파일업로드
	$P.uploadLocalFile = () => {

		if($P.$findn("uploadFiles").val() == ""){
			dialog.alert({
				content : "파일이 없습니다.",
				init : function(){
					AppSupport.setDialogZindex();
					AppSupport.focusClose();
				}
			});
			return;
		}

		var formData = new FormData($P.findn("frmFirst"));
		formData.append("taskSeCd", "${taskSeCd}");

		ajax.post({
			url : wctx.url("/${taskSeCd}/crdn/crdn05/020/importFileFromClient.do"),
			contentType : false, processData : false,
			data : formData,
			success : (resp) => {
				if(resp.saved){
					$P.$findn("uploadFiles").val("");
					$P.searchFileList();
				} else {
					dialog.alert({
						content : "파일 업로드에 실패하였습니다.",
						init : function(){
							AppSupport.setDialogZindex();
							AppSupport.focusClose();
						}
					});
					return;
				}
			}
		});

	}

	//서버에 등록된 파일 조회
	$P.searchFileList = () => {

		ctrl.dataset.setData([]);

		ajax.post({
			url : wctx.url("/${taskSeCd}/crdn/crdn05/020/list.do"),
			data : {
				taskSeCd : $P.$findn("taskSeCd").val()
			},
			success : (resp) => {
				ctrl.dataset.setData(resp);
			}
		});
	}

	$P.getGridTemplate = () => {
		var notFound = [$P.$findn("table-responsive").find("template.notFound")[0].innerHTML];
		var found = $P.$findn("table-responsive").find("template.found")[0].innerHTML;
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickParsedInfoList('{DATA-INDEX}');");

		return {
			found : found,
			notFound : notFound,
			replacer : replacer
		};
	}

	//테이블 렌더링
	$P.renderParsedInfoList = (total, listLength, trs) => {

		$P.$findn("table-responsive").find("tbody").html(trs);

		if(listLength != 0){
			FimsSupport.fnDownsizeCheck($P.$findn("table-responsive").find("table")[0]);
		}

	}

	//사진 표시
	$P.renderImage = (src) => {

		if(Array.isArray(src)){
			var div = document.createElement("div");
			div.style["margin-top"] = "20px";
			div.style["margin-bottom"] = "20px";
			div.style["overflow-y"] = "scroll";
			for(var i=0; i < src.length; i++){
				var span = document.createElement("span");
				span.style["max-width"] = "260px";
				span.style["max-height"] = "260px";
				var img = document.createElement("img");
				img.style["object-fit"] = "contain";
				img.style["max-width"] = "inherit";
				img.style["max-height"] = "inherit";
				img.src = src[i];
				span.appendChild(img);
				div.appendChild(span);
			}
			$P.$findn("imageArea").append(div);
		} else {

			var img = document.createElement("img");
			img.style["object-fit"] = "contain";
			img.src = src;
			$P.$findn("imageArea").append(img);
		}

	}

	$P.clickParsedInfoList = (dataIndex) => {
		if(dataIndex == ""){
			return;
		}

		ctrl.dataset.setCurrent(dataIndex);
	};

	$P.createCrdn = () => {

		if($.isEmptyObject($P.tempGroup)){
			dialog.alert({
				content : "모든 자료가 처리 완료되었습니다.",
				init : function(){
					AppSupport.setDialogZindex();
					AppSupport.focusClose();
				}
			});
			return;
		}

		var firstGroupKey = Object.keys($P.tempGroup)[0];
		var formData = new FormData($P.findn("frmMultipart"));
		formData.append("taskSeCd", "${taskSeCd}");
		formData.append("fileGroupType", $P.tempGroup[firstGroupKey][0].FILE_GROUP_TYPE);
		formData.append("fileLayoutId", $P.tempGroup[firstGroupKey][0].FILE_LAYOUT_ID);
		if($P.tempGroup[firstGroupKey].length == 1){
			formData.append("linkFileInfos", JSON.stringify({}));
		}
		for(var i=0; i<$P.tempGroup[firstGroupKey].length; i++){
			formData.append("linkFileInfos", JSON.stringify($P.tempGroup[firstGroupKey][i]));
		}

		ajax.post({
			url : wctx.url("/${taskSeCd}/crdn/crdn05/020/create.do"),
			contentType : false, processData : false,
			data : formData,
			success : (resp) => {

				let removedFileNameArr = $P.tempGroup[firstGroupKey].map(item => item.FILE_NAME);

				delete $P.tempGroup[firstGroupKey];

				if(resp.saved){

					$P.removeCallback(removedFileNameArr);

		        	if(resp.alertMessage){
		        		alert(resp.alertMessage);
		        	}
				} else {
					alert(resp.failReason);
				}

				//다음자료 진행
				$P.createCrdn();
			}
		});
	};

	$P.deleteFile = () => {
		var current = ctrl.dataset.getCurrent();
		if(current == null) return;

		var fileName = current.FILE_NAME;
		var fileLayoutId = current.FILE_LAYOUT_ID;

		ajax.get({
			url : wctx.url("/${taskSeCd}/crdn/crdn05/020/remove.do"),
			data : {
				taskSeCd : $P.$findn("taskSeCd").val(),
				fileLayoutId : fileLayoutId,
				fileName : fileName
			},
			success : (resp) => {
				if(resp.saved){
					$P.removeCallback([fileName]);
				}
			}
		});
	}

	$P.removeCallback = (removedFileNameArr) => {
		let removedDataIndexArr = [];
		for(var i = 0; i < removedFileNameArr.length; i++){
			let dii = ctrl.dataset.getDataset("item").filter(item=>item.data.FILE_NAME == removedFileNameArr[i])[0].index;
			removedDataIndexArr.push(dii);
		}

		ctrl.dataset.remove(removedDataIndexArr);
		$P.removeTableRow(removedDataIndexArr);
	}

	$P.removeTableRow = (removedDataIndexArr) => {

		var fileListTable = $P.$findn("table-responsive").find("table")[0];

		for(var i = 0; i < removedDataIndexArr.length; i++){
			var target = removedDataIndexArr[i];
			var tr = $(fileListTable).find("tbody").find("tr[data-index='"+target+"']");
			var trIndex = $(fileListTable).find("tbody tr").index(tr);
			fileListTable.deleteRow(trIndex+1);
		}

	}

	/**************************************************************************
	* element.on
	**************************************************************************/
	$P.$findn("btnSearch").on("click", function(){ $P.checkFTP(); });

	$P.$findn("btnFileUpload").on("click", function(){ $P.uploadLocalFile(); });

	$P.$findn("btnInsertCrdn").on("click", function(){
		$P.tempGroup = Object.groupBy(ctrl.dataset.getDataset(), ({ TEMP_GROUP_ID }) => "temp"+TEMP_GROUP_ID);

		if($.isEmptyObject($P.tempGroup)){
			alert("처리할 자료가 없습니다.");
			return;
		}

		$P.createCrdn();
	});

	$P.$findn("btnDelete").on("click", function(){ $P.deleteFile(); });

	$P.$findn("direct").on("click", function(){
		if($(this).is(":checked")){
			$("#uploadFilesArea").removeAttr("hidden");
			$P.$findn("btnFileUpload").removeAttr("hidden");
			$P.$findn("btnSearch").attr("hidden","hidden");
		} else {
			$("#uploadFilesArea").attr("hidden","hidden");
			$P.$findn("btnFileUpload").attr("hidden","hidden");
			$P.$findn("btnSearch").removeAttr("hidden");
			$P.$findn("uploadFiles").val("");
		}
	});

	ctrl.dataset.setData([]);
});

</script>