<%@ 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>
<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="sndngSeCd">
								<option value="02">사전통지서</option>
								<option value="03">부과고지서</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="currentOtpt" 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="sndngSeCd" />
	
				
					<span name="zipGlobalStng">
					</span>
				</form>
			</div>
			
			<div class="row mb-3 justify-content-start">
				<div class="col-md-12">
					<div class="float-start">
						<strong>항목</strong>
						<button type="button" name="btnAdd" class="btn btn-info">+ 추가</button>
						<button type="button" name="btnDel" 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="scroll" class="table-responsive ox-scroll oy-scroll h-px-600">
						<table name="table" class="table-layout-fixed compress-cell dataTable table table-bordered">
							<thead class="sticky-thead" name="thead">
							</thead>
							<tbody name="tbody">
							</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:110px">바이트수</th>
			<th style="width:140px">공백문자방향</th>
			<th style="width:350px">포맷팅</th>
			<th class="dummy-th"></th>
		</tr>
	</template>
	
	<template name="found">
		<tr data-key="{OUTSOURCING_FORM_ID}">
			<td data-col="artclOrdr" 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="artclNm" class="text-center">
				<select class="form-select">
				{COMPONENTS}
				</select>
			</td>
			<td data-col="artclSz" class="text-center">
				<input type="number" class="form-control w-px-80" min="1" max="300" value="1" />
			</td>
			<td data-col="paddingDirection" class="text-center">
				<button type="button" class="btn btn-xs btn-outline-dark h-px-25 px-1">◀</button>
				<select class="form-select no-bgi w-automin">
					<option value="left" title="왼쪽">왼쪽</option>
					<option value="right" title="오른쪽">오른쪽</option>
				</select>
				<button type="button" class="btn btn-xs btn-outline-dark h-px-25 px-1">▶</button>
			</td>
			<td data-col="formatting" class="text-center">
				<select class="form-select w-automin">
					<option value="">없음</option>
					<optgroup label="날짜">
						<option value="date(yyyy.MM.dd)">연.월.일</option>
						<option value="date(yyyy.MM.dd HH:mm)">연.월.일 시:분</option>
						<option value="date(yyyy-MM-dd~yyyy-MM-dd)">연-월-일~연-월-일</option>
					</optgroup>
					<optgroup label="금액">
						<option value="amount(comma)">콤마(,) 표시</option>
					</optgroup>
					<optgroup label="기타">
						<option value="zip(hypen)">우편번호 하이픈(-) 표시</option>
						<option value="rgNo(hypen)">등기번호 하이픈(-) 표시</option>
					</optgroup>
				</select>
				
			</td>
			<td class="dummy-td"></td>
		</tr>
	</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.zipGlobalStng = {};
	$P.zipArtclStngMap = {};
	
	$P.$findn("btnSave").attr("disabled","disabled");

	$P.$findn("btnAdd").attr("disabled","disabled");
	$P.$findn("btnDel").attr("disabled","disabled");

	$P.fnLoad = () => {
		
		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		var query = formFields.get();
		ajax.post({
			url : wctx.url("/stng/stng01/030/info.do"),
			data : query,
			success : (resp) => {
				$P.$findn("btnSave").removeAttr("disabled");

				$P.$findn("btnAdd").removeAttr("disabled");
				$P.$findn("btnDel").removeAttr("disabled");
				$P.$findn("currentOtpt").text("");
				$P.$findn("zipGlobalStng").html("");

				$P.$findn("tbody").html("");
				
				$P.$findn("frmEdit").find("[name='sggCd']").val(query.sggCd);
				$P.$findn("frmEdit").find("[name='taskSeCd']").val(query.taskSeCd);
				$P.$findn("frmEdit").find("[name='sndngSeCd']").val(query.sndngSeCd);

				
				$P.$findn("currentOtpt").text(resp.outsourcingStngTitle);
				if(resp.zipGlobalStng != null){
					$P.zipGlobalStng = resp.zipGlobalStng;
				} else {
					$P.zipGlobalStng = {
						OUTSOURCING_BSC_ID : ""
					};
				}
				$P.renderZipGlobalStng($P.zipGlobalStng);
				
				$P.zipArtclStngMap = resp.zipArtclStngMap;

				$P.renderZipArtclStngGrid(
						$P.zipArtclStngMap.predefinedSetList, 
						$P.zipArtclStngMap.dataList);
			}
		});
		
	}
	
	//전역 설정 렌더링
	$P.renderZipGlobalStng = (zipGlobalStng) => {

		var editForm = $P.$findn("frmEdit");
		
		//설정ID
		$P.$findn("zipGlobalStng").append("<input type='hidden' name='outsourcingBscId' />");
		editForm.find("input[name='outsourcingBscId']").val(zipGlobalStng.OUTSOURCING_BSC_ID);

	}
	
	//요소 그리드 렌더링
	$P.renderZipArtclStngGrid = (predefinedSetList, dataList) => {
		
		var components = "<option value=''>선택</option>";
		
		for(var i=0; i < predefinedSetList.length; i++){
			var p = predefinedSetList[i];
			components += "<option value='"+p.artclNm+"' >"+p.artclDscrp+"</option>";
		}
		
		for(var i=0; i < dataList.length; i++){
			var data = dataList[i];
			var found = $P.findn("found").innerHTML;
					
			found = found.replace(/{OUTSOURCING_FORM_ID}/gi, data.OUTSOURCING_FORM_ID);
			found = found.replace(/{COMPONENTS}/gi, components);
			$P.$findn("tbody").append(found);
			
			var lastTr = $P.$findn("tbody").find("tr").last()[0];
			
			$($P.fnGetElement(lastTr,"artclNm")).set(data.ARTCL_NM);
			$($P.fnGetElement(lastTr,"artclSz"))
				.set(!isEmpty(data.ARTCL_SZ) ? data.ARTCL_SZ : 1);
			$($P.fnGetElement(lastTr,"paddingDirection"))
				.set(!isEmpty(data.PADDING_DIRECTION) ? data.PADDING_DIRECTION : "left");
			$($P.fnGetElement(lastTr,"formatting"))
				.set(!isEmpty(data.FORMATTING) ? data.FORMATTING : "");
		}
		
		$P.$findn("tbody").find("tr").each(function(){
			
			var sel = $P.fnGetElement(this,"paddingDirection");
			var toPrev = $(sel).siblings()[0];
			var toNext = $(sel).siblings()[1];
			FimsComponentization.fnMakeSpinnerSelect(sel, toPrev, toNext);
			
			var scrollDivName = "scroll";
			
			var rowSpinButtons = $(this).find("td[data-col='artclOrdr']").find("button");
			
			FimsComponentization.fnMakeRowSpinner(this,rowSpinButtons[0],rowSpinButtons[1],$P.findn(scrollDivName), null);
		});
	}
	
	$P.fnGetElement = (tableRow, colName) => {
		return $(tableRow).find("td[data-col='"+colName+"']").children("input, select").first()[0];
	}
	
	
	//행 추가
	$P.addRow = () => {

		var predefinedSetList = $P.zipArtclStngMap.predefinedSetList;

		var components = "<option value='' data-component-type=''>선택</option>";
		for(var i=0; i < predefinedSetList.length; i++){
			var p = predefinedSetList[i];
			components += "<option value='"+p.artclNm+"' >"+p.artclDscrp+"</option>";
		}
		var template = $P.findn("found").innerHTML;
		template = template.replace(/{OUTSOURCING_FORM_ID}/gi, "");
		template = template.replace(/{COMPONENTS}/gi, components);
		$P.$findn("tbody").append(template);
		
		var lastTr = $P.$findn("tbody").find("tr").last()[0];
		
		var rowSpinButtons = $(lastTr).find("td[data-col='artclOrdr']").find("button");
		FimsComponentization.fnMakeRowSpinner(lastTr,rowSpinButtons[0],rowSpinButtons[1], $P.findn("scroll"), null);

		
		//셀렉트 스피너
		var sel = $P.fnGetElement(lastTr,"paddingDirection");
		var toPrev = $(sel).siblings()[0];
		var toNext = $(sel).siblings()[1];
		FimsComponentization.fnMakeSpinnerSelect(sel, toPrev, toNext);
		
		$P.$findn("scroll").scrollTop($P.findn("scroll").scrollHeight);
		
	}
	
	//행 삭제
	$P.delRow = () => {
		
		if($P.$findn("tbody").find("tr").length <= 0){
			alert('삭제할 항목이 없습니다.');
			return;
		}
		
		if($P.$findn("tbody").find("input[name='del'][type='checkbox']:checked").length <= 0){
			alert('체크된 항목이 없습니다.');
			return;
		}
		
		$P.$findn("tbody").find("tr").filter(function(index, selector){
			if($(selector).find("input[name='del'][type='checkbox']").is(":checked")){
				$(selector).remove();
			}
		});
	}
	
	//요소 설정 값 추출
	$P.getRowData = (formData) => {
		var rowArr = [];
		$P.$findn("tbody").find("tr").each(function(){
			var row = {};

			row.outsourcingFormId = this.dataset.key;
			row.artclOrdr = $($P.fnGetElement(this,"artclOrdr")).val();
			row.artclNm = $($P.fnGetElement(this,"artclNm")).val();
			row.artclSz = $($P.fnGetElement(this,"artclSz")).val();
			row.paddingDirection = $($P.fnGetElement(this,"paddingDirection")).val();
			row.formatting = $($P.fnGetElement(this,"formatting")).val();
			
			row.sggCd = formData.get("sggCd");
			row.taskSeCd = formData.get("taskSeCd");
			row.sndngSeCd = formData.get("sndngSeCd");

			
			rowArr.push(row);
		});
		
		return rowArr;
	}
	
	//설정 저장
	$P.fnSave = () => {
		
		//출력물 전역설정
		var formData = new FormData($P.findn("frmEdit"));
		
		//요소 설정
		var rowArr = $P.getRowData(formData);
		for(var i=0; i<rowArr.length; i++){
			if(rowArr[i].artclNm == ""){
				alert("항목명을 선택하세요.");
				return;
			}
			if(rowArr[i].artclSz == "" || rowArr[i].artclSz == 0){
				alert("바이트 수를 입력하세요.");
				return;
			}
		}
		
		var zipArtclStngList = FimsSupport.fnJsonArrayToFormData(rowArr,"zipArtclStngList");
		var keys = Object.keys(zipArtclStngList);
		for(var i=0; i < keys.length; i++){
			formData.append(keys[i], zipArtclStngList[keys[i]]);
		}
		
		ajax.post({
			url : wctx.url("/stng/stng01/030/save.do"),
			data : formData,
			contentType : false, processData : false,
			success : (resp) => {
				if(resp.saved){
					
					dialog.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='sndngSeCd']").val(formFields.sndngSeCd);

					
					$P.$findn("btnLoad").click();
					
				}
			}
		});
	}
	
	$P.$findn("thead").html($P.findn("theadTr").innerHTML);
	
	$P.$findn("btnLoad").on("click", () => $P.fnLoad() );
	$P.$findn("btnAdd").on("click", () => $P.addRow() );
	$P.$findn("btnDel").on("click", () => $P.delRow() );
	$P.$findn("btnSave").on("click", () => $P.fnSave() );

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

});

</script>