<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" session="false"%>
<%@ include file="/WEB-INF/jsp/include/taglib.jsp"%>
<div class="d-flex flex-column" data-doctx="${pageName}-local">
	<div class="d-flex justify-content-evenly">
		<div class="card w-95" style="padding: .8rem;">
			<form name="frmFirst" method="post" enctype="multipart/form-data" class="d-flex flex-row justify-content-between">
				<div>
					<input type="file" is="id-input" name="uploadFiles" multiple="multiple" class="form-control"/>				
					<label is="name-label" for="doExempt" style="margin-left: .5rem;">
						<input type="checkbox" name="doExempt" checked class="form-check-input" />면제차량 부과제외
					</label>
				</div>
				<button type="button" name="btnInsertCrdn" class="btn btn-primary my-2 enableon-found" style="margin-left: .5rem;">단속등록</button>
			</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>
				<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 h-px-550">
							<table name="table" class="datatables-ajax table table-bordered dataTable no-footer">
								<thead class="sticky-thead">
									<tr><th style="width: 3rem;">NO.</th>
										<th href="#">파일이름</th>
									</tr>
			                    </thead>
			                    <tbody></tbody>
								<template is="curly-brackets" class="found">
		                    		<tr data-index="{id}">
		                    			<td onclick class="text-center">data-no</td>
		                    			<td onclick title="{name}" class="text-start text-truncate max-w-th">name</td>
			                    	</tr>
		                    	</template>
		                    	<template class="notFound"><tr><td valign="top" colspan="2" 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="btnDelete" class="btn btn-primary my-2 enableon-found">삭제</button>
			</div>
		</div>
	</div>

	<form name="frmMultipart" method="post" enctype="multipart/form-data"></form>
</div>
<c:set var="scriptLocal" scope="request">
pageName = "${pageName}-local";
var $L = pageObject[pageName] = newDoctxFinder(pageName);

uploadSet.onDatasetChange = uploadSet.onRemove = obj => {
	var t = $L.getGridTemplate();
	var trs = Apply.fromDataset.getTbody(uploadSet, t.found, t.notFound, t.replacer);
	$L.renderParsedInfoList(uploadSet.length, uploadSet.length, trs);
	$L.findn("btnInsertCrdn").disabled = $L.findn("btnDelete").disabled = uploadSet.length < 1;
};
uploadSet.onCurrentChange = (dataItem) => {
	$L.$findn("imageArea").html("");
	let file = dataItem ? dataItem.data : null;
	if (!file || Object.keys(file).length < 1) return;

	var dataIndex = file.id;
	$L.$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])
		}

		$L.renderImage(srcArr);
	} else {
		var dataKey = file.name;
		if(!dataKey.endsWith(".txt") && !dataKey.endsWith(".TXT")){
			var src = file.url;
			$L.renderImage(src);
		}
	}
};

$L.tempGroup = {};
var ctrl = newCrdn05020Control($L);

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

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

//테이블 렌더링
$L.renderParsedInfoList = (total, listLength, trs) => {
	$L.$findn("table-responsive").find("tbody").html(trs);
	let empty = listLength < 1;
	if (!empty)
		FimsSupport.fnDownsizeCheck($L.$findn("table-responsive").find("table")[0]);
}

//사진 표시
$L.renderImage = (src) => {
	if(Array.isArray(src)){
		var div = document.createElement("div");
		div.style["margin-top"] = 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"] = span.style["max-height"] = "260px";
			var img = document.createElement("img");
			img.style["object-fit"] = "contain";
			img.style["max-width"] = img.style["max-height"] = "inherit";
			img.src = src[i];
			span.appendChild(img);
			div.appendChild(span);
		}
		$L.$findn("imageArea").append(div);
	} else {
		var img = document.createElement("img");
		img.style["object-fit"] = "contain";
		img.src = src;
		$L.$findn("imageArea").append(img);
	}
}

$L.clickParsedInfoList = (dataIndex) => {
	if (!dataIndex) return;

	uploadSet.setCurrent(dataIndex);
};

$L.createCrdn = () => 
	upload({
		url : wctx.url("/crdn/crdn05/020/upload.do"),
		data : {
			taskSeCd: "${taskSeCd}",
			doExempt: document.querySelector('div[data-doctx="' + pageName + '"] input[name="doExempt"]').checked,
			uploadFiles: uploadSet.getDataset()
		},
		success : (resp) => {
					let content = "<ul>" + [
						"업로드 파일수: " + resp.received,
						"분류 건수: " + resp.divided,
						"정상: " + resp.normal,
						"메타파일 누락: " + resp.malformed,
						"",
						"등록 단속건수: " + resp.success,
						"중복 단속건수: " + resp.duplicates
					]
					.map(str => "<li>" + str + "</li>")
					.join("") + "</ul>";
					dialog.alert({
						content: content,
						onOK: () => {},
						onClose: () => uploadSet.clear()
					});
			
			return;
			if (resp.saved) {
				uploadSet.setData([]);
	        	if(resp.alertMessage)
	        		dialog.alert(resp.alertMessage);
	        	else
	        		dialog.alert("등록이 완료됐습니다.");
			} else {
				dialog.alert(resp.failReason);
			}
		}
	});

$L.deleteFile = () => {
	var current = uploadSet.getCurrent();
	if (!current) return;
	
	uploadSet.erase(current.id);
}

$L.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);
	$L.removeTableRow(removedDataIndexArr);
}

$L.removeTableRow = (removedDataIndexArr) => {
	var fileListTable = $L.$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);
	}
}

$L.$findn("btnInsertCrdn").on("click", function(){
	$L.createCrdn();
});

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

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

uploadSet.setData([]);
</c:set>