<%@ 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">PDF 추출 설정</c:set>
<span data-doctx="${pageName}">
	<div class="d-flex flex-row justify-content-evenly">
		<div class="card p-3">
			<div class="row mb-3 justify-content-start">
				<div class="col-md-12">
					<div class="float-start">
						<form name="frmSearch">
							<input type="hidden" name="sggCd" />
							업무
							<select class="form-select" name="taskSeCd">
								<c:forEach items="${TaskListForSgg}" var="item">
									<option value="${item.code}">${item.value}</option>
								</c:forEach>
							</select>
							템플릿
							<select class="form-select" name="tmplatId">
								<c:forEach items="${TmplatList}" var="item">
									<option value="${item.code}">${item.value}</option>
								</c:forEach>
								<!-- <option value="JU001">사전통지서</option>
								<option value="JU002">본고지(수시분)</option> -->
							</select>
							
							<button type="button" name="btnLoad" class="btn btn-primary">불러오기</button>
						</form>
					</div>
					<div class="float-end">
						<button type="button" name="btnSave" class="btn btn-primary">저장</button>
					</div>
				</div>
			</div>
			
			<div class="d-flex justify-content-between">
				<span name="currentTmplat" class="bg-lighter h3 h-px-30">
				</span>
				<form name="frmEdit">
					<input type="hidden" name="sggCd" />
					<input type="hidden" name="taskSeCd" />
					<input type="hidden" name="tmplatId" />
					<input type="hidden" name="extrBscId" />
	
				</form>
			</div>
			
			<div class="row mb-3 justify-content-start">
				<div class="col-md-12">
					<strong>템플릿 문자열</strong>
					<input type="text" name="mobilePageTmplt" 
					class="w-100" />
				</div>
			</div>
			
			<div class="row mb-3 justify-content-start">
				<div class="col-md-12">
					<div class="float-start">
						<strong>기초 항목</strong>
						<button type="button" name="btnPredefinedAdd"
							class="btn btn-info dropdown-toggle" data-bs-toggle="dropdown">추가</button>
						<ul name="dropdownPredefinedAdd" class="dropdown-menu oy-scroll mh-px-250">
						</ul>
						<button type="button" name="btnPredefinedDel"
						class="btn btn-info">&#x2611; 삭제</button>
					</div>
				</div>
			</div>
			<div class="card-datatable text-nowrap mb-3">
				<div class="dataTables_wrapper dt-bootstrap5 no-footer">
					<div name="scrollPredefined" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="tablePredefined" class="table-layout-fixed compress-cell dataTable table table-bordered">
							<thead class="sticky-thead" name="theadPredefined">
							</thead>
							<tbody name="tbodyPredefined">
							</tbody>
						</table>
					</div>
				</div>
			</div>
			
			<div class="row mb-3 justify-content-start">
				<div class="col-md-12">
					<div class="float-start">
						<strong>사용자 정의 항목</strong>
						<button type="button" name="btnCustomAdd" class="btn btn-info">+ 추가</button>
						<button type="button" name="btnCustomDel" class="btn btn-info">&#x2611; 삭제</button>
					</div>
				</div>
			</div>
			<div class="card-datatable text-nowrap mb-3">
				<div class="dataTables_wrapper dt-bootstrap5 no-footer">
					<div name="scrollCustom" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="tableCustom" class="table-layout-fixed compress-cell dataTable table table-bordered">
							<thead class="sticky-thead" name="theadCustom">
							</thead>
							<tbody name="tbodyCustom">
							</tbody>
						</table>
					</div>
				</div>
			</div>
			
		</div>
	</div>
	
	
	<template name="theadTr">
		<tr>
			<th style="width:150px">순서</th>
			<th style="width:40px"></th>
			<th style="width:200px">추출항목명</th>
			<th style="width:200px">추출항목설명</th>
			<th style="width:110px">유형</th>
			<th style="width:110px">위치(좌)</th>
			<th style="width:110px">위치(상)</th>
			<th style="width:110px">영역(좌우)</th>
			<th style="width:110px">영역(상하)</th>
			
			<th class="dummy-th"></th>
		</tr>
	</template>
	
	<template name="found">
		<tr data-key="{EXTR_FORM_ID}">
			<td data-col="extrArtclOrdr" class="text-center">
				<button type="button">▲</button>
				<input type="text" readonly class="w-px-50 text-center" />
				<button type="button">▼</button>
			</td>
			<td data-col="checkbox" class="text-center">
				<input type="checkbox" name="del" class="form-check-input" />
			</td>
			<td data-col="extrArtclNm" class="text-center">
				<input type="text" class="form-control w-px-180" />
			</td>
			<td data-col="extrArtclDscrp" class="text-center">
				<input type="text" class="form-control w-px-180" />
			</td>
			<td data-col="componentType" class="text-center">
				<input type="text" class="form-control w-px-80" readonly />
			</td>
			<td data-col="leftPstn" class="text-center">
				<input type="number" class="form-control w-px-80" min="0" max="300" />
			</td>
			<td data-col="topPstn" class="text-center">
				<input type="number" class="form-control w-px-80" min="0" max="300" />
			</td>
			<td data-col="widthSz" class="text-center">
				<input type="number" class="form-control w-px-80" min="0" max="300" />
			</td>
			<td data-col="heightSz" class="text-center">
				<input type="number" class="form-control w-px-80" min="0" max="300" />
			</td>
			
			<td class="dummy-td"></td>
		</tr>
	</template>
	
	<template name="dropdownTemplate">
		<li><a class="dropdown-item" onclick="{onclick}">{DSCRP}</a></li>
	</template>

</span>
<script>
var FIM054 = new CommonCodes(${FIM054});
var FIM047 = new CommonCodes(${FIM047});
var FIM078 = new CommonCodes(${FIM078});
var FIM080 = new CommonCodes(${FIM080});

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

$(document).ready(function(){

	var $P = pageObject["${pageName}"];
	$P.extrArtclStngMap = {};
	
	$P.$findn("btnSave").attr("disabled","disabled");
	
	$P.$findn("btnPredefinedAdd").attr("disabled","disabled");
	$P.$findn("btnPredefinedDel").attr("disabled","disabled");
	$P.$findn("btnCustomAdd}").attr("disabled","disabled");
	$P.$findn("btnCustomDel").attr("disabled","disabled");

	$P.fnLoad = () => {
		
		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		var query = formFields.get();
		ajax.post({
			url : wctx.url("/stng/stng01/020/info.do"),
			data : query,
			success : (resp) => {
				$P.$findn("btnSave").removeAttr("disabled");
				$P.$findn("btnPredefinedAdd").removeAttr("disabled");
				$P.$findn("btnPredefinedDel").removeAttr("disabled");
				$P.$findn("btnCustomAdd").removeAttr("disabled");
				$P.$findn("btnCustomDel").removeAttr("disabled");
				$P.$findn("currentTmplat").text("");
				
				$P.$findn("tbodyPredefined").html("");
				$P.$findn("tbodyCustom").html("");
				
				$P.$findn("frmEdit").find("[name='sggCd']").val(query.sggCd);
				$P.$findn("frmEdit").find("[name='taskSeCd']").val(query.taskSeCd);
				$P.$findn("frmEdit").find("[name='tmplatId']").val(query.tmplatId);
				
				$P.$findn("frmEdit").find("[name='extrBscId']").val(resp.EXTR_BSC_ID);
				
				$P.$findn("mobilePageTmplt").val(resp.MOBILE_PAGE_TMPLT);
				
				$P.$findn("currentTmplat").text(resp.extrStngTitle);
				
				$P.extrArtclStngMap = resp.extrArtclStngMap;

				$P.renderExtrArtclStngGrid("tbodyPredefined", 
						$P.extrArtclStngMap.predefined.dataList);
				$P.renderExtrArtclStngGrid("tbodyCustom", 
						$P.extrArtclStngMap.custom.dataList);
			}
		});
		
	}
	
	
	//추출 요소 그리드 렌더링
	$P.renderExtrArtclStngGrid = (tbodyName, dataList) => {
		
		for(var i=0; i < dataList.length; i++){
			var data = dataList[i];
			var found = $P.findn("found").innerHTML;
					
			found = found.replace(/{EXTR_FORM_ID}/gi, data.EXTR_FORM_ID);
			$P.$findn(tbodyName).append(found);
			
			var lastTr = $P.$findn(tbodyName).find("tr").last()[0];
			
			$($P.fnGetElement(lastTr,"extrArtclNm")).set(data.EXTR_ARTCL_NM);
			$($P.fnGetElement(lastTr,"extrArtclDscrp")).set(data.EXTR_ARTCL_DSCRP);
			
			if(data.EXTR_ARTCL_NM == "photoArea"){
				$($P.fnGetElement(lastTr,"componentType")).set("사진");
			} else {
				$($P.fnGetElement(lastTr,"componentType")).set("텍스트");
			}
			
			$($P.fnGetElement(lastTr,"leftPstn")).set(!isEmpty(data.LEFT_PSTN) ? data.LEFT_PSTN : "0");
			$($P.fnGetElement(lastTr,"topPstn")).set(!isEmpty(data.TOP_PSTN) ? data.TOP_PSTN : "0");
			$($P.fnGetElement(lastTr,"widthSz")).set(!isEmpty(data.WIDTH_SZ) ? data.WIDTH_SZ : "0");
			$($P.fnGetElement(lastTr,"heightSz")).set(!isEmpty(data.HEIGHT_SZ) ? data.HEIGHT_SZ : "0");
			
		}
		
		$P.$findn(tbodyName).find("tr").each(function(){

			if(tbodyName == "tbodyPredefined"){	
				$($P.fnGetElement(this,"extrArtclNm")).attr("disabled","disabled").addClass("no-bgi");
				$($P.fnGetElement(this,"extrArtclDscrp")).attr("disabled","disabled").addClass("no-bgi");
			}
			
			var scrollDivName = "";
			if(tbodyName == "tbodyPredefined"){
				scrollDivName = "scrollPredefined";
			} else {
				scrollDivName = "scrollCustom";
			}
			
			var rowSpinButtons = $(this).find("td[data-col='extrArtclOrdr']").find("button");
			
			FimsComponentization.fnMakeRowSpinner(this,rowSpinButtons[0],rowSpinButtons[1],$P.findn(scrollDivName), $P.valid);
		});
	}
	
	$P.fnGetElement = (tableRow, colName) => {
		return $(tableRow).find("td[data-col='"+colName+"']").children("input, select").first()[0];
	}
	

	//추출 요소 선택
	$P.choiceExtrArtclNm = () => {
		$P.$findn("dropdownPredefinedAdd").html("");
		
		var predefinedSetList = $P.extrArtclStngMap.predefinedSetList;
		var existArr = [];
		
		$P.$findn("tbodyPredefined").find("tr").each(function(){
			var el = $P.fnGetElement(this,"extrArtclNm");
			existArr.push($(el).val());
		});
		
		var selectableArr = predefinedSetList.filter(item => existArr.indexOf(item.artclNm) == -1);
		
		var template = $P.findn("dropdownTemplate");
		
		if(selectableArr.length < 1){
			var li = template.innerHTML;
			li = li.replace(/{onclick}/gi, "");
			li = li.replace(/{DSCRP}/gi, "추가할 수 있는 항목이 없습니다.");
			$P.$findn("dropdownPredefinedAdd").append(li);
		} else {
			for(var i=0; i < selectableArr.length; i++){
				var li = template.innerHTML;
				li = li.replace(/{onclick}/gi, "pageObject['${pageName}'].addRow('" + selectableArr[i].artclNm + "','"+selectableArr[i].artclDscrp+"')");
				li = li.replace(/{DSCRP}/gi, selectableArr[i].artclDscrp);
				$P.$findn("dropdownPredefinedAdd").append(li);
			}
		}
	}
	
	//행 추가
	$P.addRow = (extrArtclNm, extrArtclDscrp) => {
		
		var tbodyName;
		
		if(extrArtclNm == null || extrArtclNm == ""){
			tbodyName = "tbodyCustom";
		} else {
			tbodyName = "tbodyPredefined";
		}

		var template = $P.findn("found").innerHTML;
		template = template.replace(/{EXTR_FORM_ID}/gi, "");
		
		$P.$findn(tbodyName).append(template);
		
		var lastTr = $P.$findn(tbodyName).find("tr").last()[0];
		
		
		var scrollDivName = "";l
		if(tbodyName == "tbodyPredefined"){
			scrollDivName = "scrollPredefined";
		} else {
			scrollDivName = "scrollCustom";
		}
		var rowSpinButtons = $(lastTr).find("td[data-col='extrArtclOrdr']").find("button");
		FimsComponentization.fnMakeRowSpinner(lastTr,rowSpinButtons[0],rowSpinButtons[1],$P.findn(scrollDivName), $P.valid);
		
		if(extrArtclNm != null && extrArtclNm != ""){	
			
			$($P.fnGetElement(lastTr,"extrArtclNm")).set(extrArtclNm);
			$($P.fnGetElement(lastTr,"extrArtclDscrp")).set(extrArtclDscrp);
			
			var componentType = (extrArtclNm == "photoArea" ? "사진" : "텍스트");
			$($P.fnGetElement(lastTr,"componentType")).set(componentType);

			$($P.fnGetElement(lastTr,"leftPstn")).set("0");
			$($P.fnGetElement(lastTr,"topPstn")).set("0");
			$($P.fnGetElement(lastTr,"widthSz")).set("0");
			$($P.fnGetElement(lastTr,"heightSz")).set("0");
		} else {
			$($P.fnGetElement(lastTr,"componentType")).set("텍스트");
		}
		
		if(tbodyName == "tbodyPredefined"){
			$($P.fnGetElement(lastTr,"extrArtclNm")).attr("disabled","disabled").addClass("no-bgi");
			$($P.fnGetElement(lastTr,"extrArtclDscrp")).attr("disabled","disabled").addClass("no-bgi");
		}
		
		//셀렉트 스피너
		var sel = $P.fnGetElement(lastTr,"textSort");
		var toPrev = $(sel).siblings()[0];
		var toNext = $(sel).siblings()[1];
		FimsComponentization.fnMakeSpinnerSelect(sel, toPrev, toNext);
		
		if(tbodyName == "tbodyPredefined"){
			$P.$findn("scrollPredefined").scrollTop($P.findn("scrollPredefined").scrollHeight);
		} else {
			$P.$findn("scrollCustom").scrollTop($P.findn("scrollCustom").scrollHeight);
		}
		
		
	}
	
	//행 삭제
	$P.delRow = (tbodyName) => {
		
		if($P.$findn(tbodyName).find("tr").length <= 0){
			alert('삭제할 항목이 없습니다.');
			return;
		}
		
		if($P.$findn(tbodyName).find("input[name='del'][type='checkbox']:checked").length <= 0){
			alert('체크된 항목이 없습니다.');
			return;
		}
		
		$P.$findn(tbodyName).find("tr").filter(function(index, item){
			if($(item).find("input[name='del'][type='checkbox']").is(":checked")){
				$(item).remove();
			}
		});
	}
	

	
	//추출 요소 설정 값 추출
	$P.getRowData = (tbodyName, formData) => {
		var rowArr = [];
		$P.$findn(tbodyName).find("tr").each(function(){
			var row = {};

			row.extrFormId = this.dataset.key;
			row.extrArtclNm = $($P.fnGetElement(this,"extrArtclNm")).val();
			row.extrArtclDscrp = $($P.fnGetElement(this,"extrArtclDscrp")).val();
			row.leftPstn = $($P.fnGetElement(this,"leftPstn")).val();
			row.topPstn = $($P.fnGetElement(this,"topPstn")).val();
			row.widthSz = $($P.fnGetElement(this,"widthSz")).val();
			row.heightSz = $($P.fnGetElement(this,"heightSz")).val();
			
			row.extrArtclOrdr = $($P.fnGetElement(this,"extrArtclOrdr")).val();

			row.sggCd = formData.get("sggCd");
			row.taskSeCd = formData.get("taskSeCd");
			row.tmplatId = formData.get("tmplatId");
			
			rowArr.push(row);
		});
		
		return rowArr;
	}
	
	//추출 설정 저장
	$P.fnSave = () => {
		
		var formData = new FormData($P.findn("frmEdit"));
		
		//템플릿 문자열
		formData.append("mobilePageTmplt",$P.$findn("mobilePageTmplt").val());
		
		//추출 요소 설정
		var rowArr1 = $P.getRowData("tbodyPredefined", formData);
		var rowArr2 = $P.getRowData("tbodyCustom", formData);
		var rowArr = [...rowArr1, ...rowArr2];
		for(var i=0; i<rowArr.length; i++){
			if(rowArr[i].extrArtclNm == ""){
				alert("추출항목명을 입력하세요.");
				return;
			}
			if(rowArr[i].extrArtclDscrp == ""){
				alert("추출항목설명을 입력하세요.");
				return;
			}
		}
		
		var extrArtclStngList = FimsSupport.fnJsonArrayToFormData(rowArr,"extrArtclStngList");
		var keys = Object.keys(extrArtclStngList);
		for(var i=0; i < keys.length; i++){
			formData.append(keys[i], extrArtclStngList[keys[i]]);
		}
		
		ajax.post({
			url : wctx.url("/stng/stng01/020/save.do"),
			data : formData,
			contentType : false, processData : false,
			success : (resp) => {
				if(resp.saved){
					
					alert("저장되었습니다.");
					
					var formFields = new FimsFormFields($P.selectorn("frmEdit")).get();
					$P.$findn("frmSearch").find("[name='sggCd']").val(formFields.sggCd);
					$P.$findn("frmSearch").find("[name='taskSeCd']").val(formFields.taskSeCd);
					$P.$findn("frmSearch").find("[name='tmplatId']").val(formFields.tmplatId);
			
					$P.$findn("btnLoad").click();
				}
			}
		});
	}
	
	//
	$P.valid = (eventInfo) => {
		return true;
	};
	

	$P.$findn("theadPredefined").html($P.findn("theadTr").innerHTML);
	$P.$findn("theadCustom").html($P.findn("theadTr").innerHTML);
	
	$P.$findn("btnLoad").on("click", () => $P.fnLoad() );
	
	$P.$findn("btnPredefinedAdd").on("click", () => $P.choiceExtrArtclNm() );
	$P.$findn("btnCustomAdd").on("click", () => $P.addRow() );
	
	$P.$findn("btnPredefinedDel").on("click", () => $P.delRow('tbodyPredefined') );
	$P.$findn("btnCustomDel").on("click", () => $P.delRow('tbodyCustom') );
	
	$P.$findn("btnSave").on("click", () => $P.fnSave() );

	var markerFinder = function(tr){
		return $P.fnGetElement(tr,"extrArtclOrdr");
	};
	var markerSetter = function(marker, value){
		marker.value = value;
	};
	
	Componentization.fnMakeRowNumberingTable($P.findn("tbodyPredefined"), markerFinder, markerSetter);
	Componentization.fnMakeRowNumberingTable($P.findn("tbodyCustom"), markerFinder, markerSetter);

});

</script>