<%@ 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>
							용지
							<select class="form-select" name="paperSeCd">
								<c:forEach items="${FIM078List}" var="item">
									<option value="${item.code}">${item.value}</option>
								</c:forEach>
							</select>
							<button type="button" name="btnLoad" class="btn btn-primary">불러오기</button>
						</form>
					</div>
					<div class="float-end">
						<input type="checkbox" is="id-input" name="viewSample" />
						<label is="name-label" for="viewSample">저장 후 샘플 보기</label>
						<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" />
					<input type="hidden" name="paperSeCd" />
		
	
					<span name="otptGlobalStng">
					</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="btnUniqueAdd"
							class="btn btn-info dropdown-toggle" data-bs-toggle="dropdown">추가</button>
						<ul name="dropdownUniqueAdd" class="dropdown-menu oy-scroll mh-px-250">
						</ul>
						<button type="button" name="btnUniqueDel"
						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="scrollUnique" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="tableUnique" class="table-layout-fixed compress-cell dataTable table table-bordered">
							<thead class="sticky-thead" name="theadUnique">
							</thead>
							<tbody name="tbodyUnique">
							</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="btnMultipleAdd"
						class="btn btn-info">+ 추가</button>
						<button type="button" name="btnMultipleDel"
						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="scrollMultiple" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="tableMultiple" class="table-layout-fixed compress-cell dataTable table table-bordered">
							<thead class="sticky-thead" name="theadMultiple">
							</thead>
							<tbody name="tbodyMultiple">
							</tbody>
						</table>
					</div>
				</div>
			</div>
	
		</div>
	</div>
	
	<span name="tempArea" hidden></span>
	
	<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:110px">위치(좌)</th>
			<th style="width:110px">위치(상)</th>
			<th style="width:110px">영역(좌우)</th>
			<th style="width:110px">영역(상하)</th>
			<th style="width:140px">텍스트정렬</th>
			<th style="width:70px">줄바꿈</th>
			<th style="width:100px">글꼴</th>
			<th style="width:80px">글자크기</th>
			<th style="width:80px">글자색</th>
			<th style="width:110px">글자스타일</th>
			<th class="dummy-th"></th>
		</tr>
	</template>
	
	<template name="found">
		<tr data-key="{OTPT_FORM_ID}">
			<td data-col="otptArtclSeq" 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="otptArtclNm" class="text-center">
				<select class="form-select" onchange="pageObject['${pageName}'].fnChangeComponent(this);">
				{COMPONENTS}
				</select>
			</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 data-col="textSort" 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="center" 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="lineChgYn" class="text-center">
				<input type="checkbox" value="Y" class="form-check-input" />
			</td>
			<td data-col="fontNm" class="text-center">
				<select class="form-select no-bgi w-automin">
					<option value="gulimche">굴림체</option>
					<option value="gulim">굴림</option>
					<option value="batangche">바탕체</option>
					<option value="batang">바탕</option>
					<option value="dotumche">돋움체</option>
					<option value="dotum">돋움</option>
					<option value="gungsuhche">궁서체</option>
					<option value="gungsuh">궁서</option>
				</select>
			</td>
			<td data-col="fontSz" class="text-center">
				<input type="number" class="form-control w-px-60" min="8" max="25" />
			</td>
			<td data-col="fontColr" class="text-center">
				<select class="form-select no-bgi  w-automin">
					<option title="검정" value="BLACK"></option>
					<option title="빨강" value="RED"></option>
					<option title="주황" value="ORANGE"></option>
					<option title="노랑" value="YELLOW"></option>
					<option title="연두" value="YELLOW_GREEN"></option>
					<option title="초록" value="GREEN"></option>
					<option title="청록" value="CYAN"></option>
					<option title="파랑" value="BLUE"></option>
					<option title="보라" value="VIOLET"></option>
					<option title="마젠타" value="MAGENTA"></option>
					<option title="짙은분홍" value="DEEP_PINK"></option>
					<option title="밝은회색" value="DARK_GREY"></option>
					<option title="회색" value="GREY"></option>
					<option title="어두운회색" value="LIGHT_GREY"></option>
					<option title="하양" value="WHITE"></option>
				</select>
			</td>
			<td data-col="fontStyle" class="text-center">
				<select class="form-select no-bgi">
					<option value="FILL">일반</option>
					<option value="FILL_STROKE">굵게</option>
				</select>
			</td>
			<td class="dummy-td"></td>
		</tr>
	</template>
	
	<template name="dropdownTemplate">
		<li><a class="dropdown-item" onclick="{onclick}">{DSCRP}</a></li>
	</template>
	
	<template name="foldLinePstnTemplate">
		<span class="px-2">
			<label class="col-form-label bg-lighter px-2">접는선 위치</label>
			<label>
				<input type="radio" name="foldLinePstnSeCd" value="">
				미표시
			</label>
			<c:forEach items="${FIM080List}" var="item">
				<label>
					<input type="radio" name="foldLinePstnSeCd" value="${item.code}">
					${item.value}
				</label>
			</c:forEach>
		</span>
	</template>
	
	<template name="bcrnTemplate">
		<span class="px-2">
			<label class="col-form-label bg-lighter px-2">배경이미지</label>
			<output name="fileStatus"></output>
			<button type="button" onclick="$(this).next().click();">업로드</button>
			<input type="file" name="backgroundFile" accept="image/*" hidden onchange="pageObject['${pageName}'].fnBgUpload(this);" />
			<button type="button" name="btnBgDown" onclick="pageObject['${pageName}'].fnBgDown();">다운로드</button>
		</span>
	</template>
	
	<template name="photoCntTemplate">
		<span class="px-2">
			<label class="col-form-label bg-lighter px-2">사진 출력 영역</label>
			<input type="number" name="otptPhotoCnt" class="form-control w-px-50" min="0" max="6" /> 장
		</span>
	</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.otptGlobalStng = {};
	$P.otptArtclStngMap = {};

	$P.$findn("btnSave").attr("disabled","disabled");
	$P.$findn("btnUniqueAdd").attr("disabled","disabled");
	$P.$findn("btnUniqueDel").attr("disabled","disabled");
	$P.$findn("btnMultipleAdd").attr("disabled","disabled");
	$P.$findn("btnMultipleDel").attr("disabled","disabled");

	$P.fnLoad = () => {

		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		var query = formFields.get();
		ajax.post({
			url : wctx.url("/stng/stng01/010/info.do"),
			data : query,
			success : (resp) => {
				$P.$findn("btnSave").removeAttr("disabled");
				$P.$findn("btnUniqueAdd").removeAttr("disabled");
				$P.$findn("btnUniqueDel").removeAttr("disabled");
				$P.$findn("btnMultipleAdd").removeAttr("disabled");
				$P.$findn("btnMultipleDel").removeAttr("disabled");
				$P.$findn("currentOtpt").text("");
				$P.$findn("otptGlobalStng").html("");
				$P.$findn("tbodyUnique").html("");
				$P.$findn("tbodyMultiple").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("frmEdit").find("[name='paperSeCd']").val(query.paperSeCd);

				$P.$findn("currentOtpt").text(resp.otptStngTitle);
				if(resp.otptGlobalStng != null){
					$P.otptGlobalStng = resp.otptGlobalStng;
				} else {
					$P.otptGlobalStng = {
						OTPT_BSC_ID : "",
						FOLD_LINE_PSTN_SE_CD : "",
						BCRN_IMG_PATH : "",
						BCRN_IMG_FILE_NM : "",
						OTPT_PHOTO_CNT : ""
					};
				}
				$P.otptArtclStngMap = resp.otptArtclStngMap;

				$P.renderOtptGlobalStng($P.otptGlobalStng);

				$P.renderOtptArtclStngGrid("tbodyUnique",
						$P.otptArtclStngMap.unique.prototypeList,
						$P.otptArtclStngMap.unique.dataList);
				$P.renderOtptArtclStngGrid("tbodyMultiple",
						$P.otptArtclStngMap.multiple.prototypeList,
						$P.otptArtclStngMap.multiple.dataList);
			}
		});

	}

	//출력 전역 설정 렌더링
	$P.renderOtptGlobalStng = (otptGlobalStng) => {
		var paperSeCd = $P.$findn("frmEdit").find("[name='paperSeCd']").val();
		var editForm = $P.$findn("frmEdit");

		//설정ID
		$P.$findn("otptGlobalStng").append("<input type='hidden' name='otptBscId' />");
		editForm.find("input[name='otptBscId']").val(otptGlobalStng.OTPT_BSC_ID);

		//접는선 위치
		$P.$findn("otptGlobalStng").append($P.findn("foldLinePstnTemplate").innerHTML);
		if(paperSeCd == "02"){
			$P.$findn("otptGlobalStng").find("label").eq(3).remove();
		}
		if(otptGlobalStng.FOLD_LINE_PSTN_SE_CD == null){
			otptGlobalStng.FOLD_LINE_PSTN_SE_CD = "";
		}
		editForm.find(":radio[name='foldLinePstnSeCd']")
			.filter("[value='"+otptGlobalStng.FOLD_LINE_PSTN_SE_CD+"']")
			.prop("checked", true);

		//배경이미지
		$P.$findn("otptGlobalStng").append($P.findn("bcrnTemplate").innerHTML);
		if(otptGlobalStng.BCRN_IMG_PATH == null || otptGlobalStng.BCRN_IMG_PATH == ""){
			$P.$findn("fileStatus").text("없음");
			$P.$findn("fileStatus").attr("title","");
			$P.$findn("btnBgDown").attr("hidden","hidden");
		} else {
			$P.$findn("fileStatus").text("있음");
			$P.$findn("fileStatus").attr("title",otptGlobalStng.BCRN_IMG_FILE_NM);
			$P.$findn("btnBgDown").removeAttr("hidden");
		}

		//출력 사진 건 수
		$P.$findn("otptGlobalStng").append($P.findn("photoCntTemplate").innerHTML);
		if(otptGlobalStng.OTPT_PHOTO_CNT == null || otptGlobalStng.OTPT_PHOTO_CNT == ""){
			otptGlobalStng.OTPT_PHOTO_CNT = 0;
		}
		editForm.find("input[name='otptPhotoCnt']").val(otptGlobalStng.OTPT_PHOTO_CNT);
	}

	//출력 요소 그리드 렌더링
	$P.renderOtptArtclStngGrid = (tbodyName, prototypeList, dataList) => {

		var components = "<option value='' data-component-type=''>선택</option>";

		for(var i=0; i < prototypeList.length; i++){
			var p = prototypeList[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(/{OTPT_FORM_ID}/gi, data.OTPT_FORM_ID);
			found = found.replace(/{COMPONENTS}/gi, components);
			$P.$findn(tbodyName).append(found);

			var lastTr = $P.$findn(tbodyName).find("tr").last()[0];

			FimsComponentization.fnMakeOptionStyleSelect($P.fnGetElement(lastTr,"fontNm"));
			FimsComponentization.fnMakeOptionStyleSelect($P.fnGetElement(lastTr,"fontColr"));
			FimsComponentization.fnMakeOptionStyleSelect($P.fnGetElement(lastTr,"fontStyle"));

			$($P.fnGetElement(lastTr,"otptArtclNm")).set(data.OTPT_ARTCL_NM);
			$($P.fnGetElement(lastTr,"componentType")).set(data.COMPONENT_TYPE);

			$($P.fnGetElement(lastTr,"leftPstn"))
				.set(!isEmpty(data.LEFT_PSTN) ? data.LEFT_PSTN : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "leftPstn"));
			$($P.fnGetElement(lastTr,"topPstn"))
				.set(!isEmpty(data.TOP_PSTN) ? data.TOP_PSTN : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "topPstn"));
			$($P.fnGetElement(lastTr,"widthSz"))
				.set(!isEmpty(data.WIDTH_SZ) ? data.WIDTH_SZ : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "widthSz"));
			$($P.fnGetElement(lastTr,"heightSz"))
				.set(!isEmpty(data.HEIGHT_SZ) ? data.HEIGHT_SZ : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "heightSz"));

			$($P.fnGetElement(lastTr,"textSort"))
				.set(!isEmpty(data.TEXT_SORT) ? data.TEXT_SORT : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "textSort"));
			$($P.fnGetElement(lastTr,"lineChgYn"))
				.set(!isEmpty(data.LINE_CHG_YN) ? data.LINE_CHG_YN : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "lineChgYn"));
			$($P.fnGetElement(lastTr,"fontNm"))
				.set(!isEmpty(data.FONT_NM) ? data.FONT_NM : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "fontNm"));
			$($P.fnGetElement(lastTr,"fontSz"))
				.set(!isEmpty(data.FONT_SZ) ? data.FONT_SZ : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "fontSz"));
			$($P.fnGetElement(lastTr,"fontColr"))
				.set(!isEmpty(data.FONT_COLR) ? data.FONT_COLR : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "fontColr"));
			$($P.fnGetElement(lastTr,"fontStyle"))
				.set(!isEmpty(data.FONT_STYLE) ? data.FONT_STYLE : $P.fnGetProto(prototypeList, data.OTPT_ARTCL_NM, "fontStyle"));
		}

		$P.$findn(tbodyName).find("tr").each(function(){

			if(tbodyName == "tbodyUnique"){
				var el = $P.fnGetElement(this,"otptArtclNm");
				$(el).attr("disabled","disabled");
				$(el).addClass("no-bgi");
			}

			var sel = $P.fnGetElement(this,"textSort");
			var toPrev = $(sel).siblings()[0];
			var toNext = $(sel).siblings()[1];
			FimsComponentization.fnMakeSpinnerSelect(sel, toPrev, toNext);

			var scrollDivName = "";
			if(tbodyName == "tbodyUnique"){
				scrollDivName = "scrollUnique";
			} else {
				scrollDivName = "scrollMultiple";
			}

			var rowSpinButtons = $(this).find("td[data-col='otptArtclSeq']").find("button");

			FimsComponentization.fnMakeRowSpinner(this,rowSpinButtons[0],rowSpinButtons[1],$P.findn(scrollDivName), $P.validForBackground);
		});
	}

	$P.fnGetElement = (tableRow, colName) => {
		return $(tableRow).find("td[data-col='"+colName+"']").children("input, select").first()[0];
	}

	$P.fnGetProto = (prototypeList, otptArtclNm, stngItemAttrNm) => {
		if(stngItemAttrNm == "leftPstn" || stngItemAttrNm == "topPstn"){
			var paperSeCd = $P.$findn("frmEdit").find("[name='paperSeCd']").val();
			var paperNm = "";
			if(paperSeCd == "01"){
				paperNm = "a4";
			} else if(paperSeCd == "02"){
				paperNm = "letter";
			}
			var paperObj = prototypeList.find((item) => item.artclNm == otptArtclNm)[paperNm];
			if(paperObj == null){
				return 0;
			}
			if(stngItemAttrNm == "leftPstn"){
				return paperObj["left"];
			}
			if(stngItemAttrNm == "topPstn"){
				return paperObj["top"];
			}
		} else {
			return prototypeList.find((item) => item.artclNm == otptArtclNm)[stngItemAttrNm];
		}
	}

	//출력 요소 선택
	$P.choiceOtptArtclNm = () => {
		$P.$findn("dropdownUniqueAdd").html("");

		var prototypeList = $P.otptArtclStngMap.unique.prototypeList;
		var existArr = [];

		$P.$findn("tbodyUnique").find("tr").each(function(){
			var el = $P.fnGetElement(this,"otptArtclNm");
			existArr.push($(el).val());
		});

		var selectableArr = prototypeList.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("dropdownUniqueAdd").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 + "')");
				li = li.replace(/{DSCRP}/gi, selectableArr[i].artclDscrp);
				$P.$findn("dropdownUniqueAdd").append(li);
			}
		}
	}

	//행 추가
	$P.addRow = (otptArtclNm) => {
		var paperSeCd = $P.$findn("frmEdit").find("[name='paperSeCd']").val();
		var prototypeList;
		var tbodyName;

		if(otptArtclNm == null || otptArtclNm == ""){
			prototypeList = $P.otptArtclStngMap.multiple.prototypeList;
			tbodyName = "tbodyMultiple";
		} else {
			prototypeList = $P.otptArtclStngMap.unique.prototypeList;
			tbodyName = "tbodyUnique";
		}

		var components = "<option value='' data-component-type=''>선택</option>";
		for(var i=0; i < prototypeList.length; i++){
			var p = prototypeList[i];
			components += "<option value='"+p.artclNm+"' data-component-type='"+p.componentType+"'>"+p.artclDscrp+"</option>";
		}
		var template = $P.findn("found").innerHTML;
		template = template.replace(/{OTPT_FORM_ID}/gi, "");
		template = template.replace(/{COMPONENTS}/gi, components);
		$P.$findn(tbodyName).append(template);

		var lastTr = $P.$findn(tbodyName).find("tr").last()[0];

		FimsComponentization.fnMakeOptionStyleSelect($P.fnGetElement(lastTr,"fontNm"));
		FimsComponentization.fnMakeOptionStyleSelect($P.fnGetElement(lastTr,"fontColr"));
		FimsComponentization.fnMakeOptionStyleSelect($P.fnGetElement(lastTr,"fontStyle"));

		var scrollDivName = "";
		if(tbodyName == "tbodyUnique"){
			scrollDivName = "scrollUnique";
		} else {
			scrollDivName = "scrollMultiple";
		}
		var rowSpinButtons = $(lastTr).find("td[data-col='otptArtclSeq']").find("button");
		FimsComponentization.fnMakeRowSpinner(lastTr,rowSpinButtons[0],rowSpinButtons[1],$P.findn(scrollDivName), $P.validForBackground);

		if(otptArtclNm != null && otptArtclNm != ""){

			$($P.fnGetElement(lastTr,"otptArtclNm")).set(otptArtclNm);

			$($P.fnGetElement(lastTr,"componentType"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "componentType"));

			$($P.fnGetElement(lastTr,"leftPstn"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "leftPstn"));
			$($P.fnGetElement(lastTr,"topPstn"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "topPstn"));
			$($P.fnGetElement(lastTr,"widthSz"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "widthSz"));
			$($P.fnGetElement(lastTr,"heightSz"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "heightSz"));

			$($P.fnGetElement(lastTr,"textSort"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "textSort"));
			$($P.fnGetElement(lastTr,"lineChgYn"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "lineChgYn"));
			$($P.fnGetElement(lastTr,"fontNm"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "fontNm"));
			$($P.fnGetElement(lastTr,"fontSz"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "fontSz"));
			$($P.fnGetElement(lastTr,"fontColr"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "fontColr"));
			$($P.fnGetElement(lastTr,"fontStyle"))
				.set($P.fnGetProto(prototypeList, otptArtclNm, "fontStyle"));
		}

		if(tbodyName == "tbodyUnique"){
			var el = $P.fnGetElement(lastTr,"otptArtclNm");
			$(el).attr("disabled","disabled");
			$(el).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 == "tbodyUnique"){
			$P.$findn("scrollUnique").scrollTop($P.findn("scrollUnique").scrollHeight);
		} else {
			$P.$findn("scrollMultiple").scrollTop($P.findn("scrollMultiple").scrollHeight);
		}

		if(otptArtclNm == "background"){ //배경이미지 순서 보정
			if($P.$findn("tbodyUnique").find("tr").length >= 2){
				$P.$findn("tbodyUnique").find("tr").eq(0).before(lastTr);
			}
		}

	}

	//행 삭제
	$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.fnChangeComponent = (selectElement) => {
		if($P.$findn("tbodyMultiple").find(selectElement).length <= 0){
			return;
		}

		var otptArtclNm = $(selectElement).val();
		var tr = $(selectElement).parent().parent()[0];
		var prototypeList = $P.otptArtclStngMap.multiple.prototypeList;

		$($P.fnGetElement(tr,"componentType"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "componentType"));

		$($P.fnGetElement(tr,"leftPstn"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "leftPstn"));
		$($P.fnGetElement(tr,"topPstn"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "topPstn"));
		$($P.fnGetElement(tr,"widthSz"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "widthSz"));
		$($P.fnGetElement(tr,"heightSz"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "heightSz"));

		$($P.fnGetElement(tr,"textSort"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "textSort"));
		$($P.fnGetElement(tr,"lineChgYn"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "lineChgYn"));

		$($P.fnGetElement(tr,"fontNm"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "fontNm"));
		$($P.fnGetElement(tr,"fontSz"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "fontSz"));
		$($P.fnGetElement(tr,"fontColr"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "fontColr"));
		$($P.fnGetElement(tr,"fontStyle"))
			.set($P.fnGetProto(prototypeList, otptArtclNm, "fontStyle"));

	}

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

			row.otptFormId = this.dataset.key;
			row.otptArtclNm = $($P.fnGetElement(this,"otptArtclNm")).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.textSort = $($P.fnGetElement(this,"textSort")).val();

			var lineChgYnEl = $P.fnGetElement(this,"lineChgYn");
			if($(lineChgYnEl).is(":checked")){
				row.lineChgYn = "Y";
			} else {
				row.lineChgYn = "N";
			}

			row.fontNm = $($P.fnGetElement(this,"fontNm")).val();
			row.fontSz = $($P.fnGetElement(this,"fontSz")).val();
			row.fontColr = $($P.fnGetElement(this,"fontColr")).val();
			row.fontStyle = $($P.fnGetElement(this,"fontStyle")).val();
			row.otptArtclSeq = $($P.fnGetElement(this,"otptArtclSeq")).val();

			row.sggCd = formData.get("sggCd");
			row.taskSeCd = formData.get("taskSeCd");
			row.sndngSeCd = formData.get("sndngSeCd");
			row.paperSeCd = formData.get("paperSeCd");

			rowArr.push(row);
		});

		return rowArr;
	}

	//출력 설정 저장
	$P.fnSave = () => {

		//출력물 전역설정
		var formData = new FormData($P.findn("frmEdit"));

		//출력 요소 설정
		var rowArr1 = $P.getRowData("tbodyUnique", formData);
		var rowArr2 = $P.getRowData("tbodyMultiple", formData);
		var rowArr = [...rowArr1, ...rowArr2];
		for(var i=0; i<rowArr.length; i++){
			if(rowArr[i].otptArtclNm == ""){
				alert("출력항목명을 선택하세요.");
				return;
			}
		}

		var otptArtclStngList = FimsSupport.fnJsonArrayToFormData(rowArr,"otptArtclStngList");
		var keys = Object.keys(otptArtclStngList);
		for(var i=0; i < keys.length; i++){
			formData.append(keys[i], otptArtclStngList[keys[i]]);
		}

		ajax.post({
			url : wctx.url("/stng/stng01/010/save.do"),
			data : formData,
			contentType : false, processData : false,
			success : (resp) => {
				if(resp.saved){
					if(!$P.$findn("viewSample").is(":checked")){
						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("frmSearch").find("[name='paperSeCd']").val(formFields.paperSeCd);

					$P.$findn("btnLoad").click();

					if($P.$findn("viewSample").is(":checked")){
						$P.fnMakeSampleFile();
					}
				}
			}
		});
	}

	//샘플파일 생성
	$P.fnMakeSampleFile = () => {

		var formFields = new FimsFormFields($P.selectorn("frmEdit"));
		var submitParam = formFields.get();
		submitParam.crdnIds = "sample";

		var url = "";
		if(submitParam.sndngSeCd == "02"){
			url = wctx.url("/sprt/sprt01/140/makeAdvntcePdf.do");
		} else if(submitParam.sndngSeCd == "03"){
			url = wctx.url("/sprt/sprt01/150/makeNhtPdf.do");
		}

		if(url == ""){
			return;
		}

		var parameter = toQuery(submitParam);
		var filenameInHeader = "";

		fetch(url + "?" + parameter)
		.then((response) => {
			var header = response.headers.get('Content-Disposition');
			if(!header){
				response.json().then((responseJson)=>{
					dialog.alert({
						content: "PDF 파일 생성 중 오류가 발생하였습니다."
								+"<br/>"
								+responseJson.description,
						init: () => { AppSupport.setDialogZindex(); }
					});
				});
				new Error("");
			}

			var parts = header.split(';');
		    filenameInHeader = decodeURIComponent(parts[1].split('=')[1]);
			return response.blob();
		})
		.then((blob) => {
			AppSupport.openPDF(blob, "pdf_sample");
		})
		.catch(()=>{});

	}

	//배경이미지 출력 순서 고정
	$P.validForBackground = (eventInfo) => {
		if(eventInfo.clickedButtonType == "up"){
			if($P.fnGetElement(eventInfo.siblingRow,"otptArtclNm").value == "background"){
				alert("배경이미지 순서는 변경할 수 없습니다.");
				return false;
			}
		}
		if(eventInfo.clickedButtonType == "down"){
			if($P.fnGetElement(eventInfo.currentRow,"otptArtclNm").value == "background"){
				alert("배경이미지 순서는 변경할 수 없습니다.");
				return false;
			}
		}

		return true;
	};

	$P.fnBgDown = () => {
		var a = document.createElement("a");
        a.href = $P.otptGlobalStng.BCRN_IMG_PATH;
        a.download = $P.otptGlobalStng.BCRN_IMG_FILE_NM;
        $P.findn("tempArea").appendChild(a);
        a.click();
        $P.findn("tempArea").removeChild(a);
	}

	$P.fnBgUpload = (fileElement) => {
		if(fileElement.files == null || fileElement.files.length == 0){
			if($P.otptGlobalStng.BCRN_IMG_PATH == null || $P.otptGlobalStng.BCRN_IMG_PATH == ""){
				$P.$findn("fileStatus").text("없음");
				$P.$findn("fileStatus").attr("title","");
				$P.$findn("btnBgDown").attr("hidden","hidden");
			} else {
				$P.$findn("fileStatus").text("있음");
				$P.$findn("fileStatus").attr("title", $P.otptGlobalStng.BCRN_IMG_FILE_NM);
				$P.$findn("btnBgDown").removeAttr("hidden");
			}
		} else {
			$P.$findn("fileStatus").text("이미지 변경됨");
			$P.$findn("fileStatus").attr("title","");
			$P.$findn("btnBgDown").attr("hidden","hidden");
		}
	}

	$P.$findn("theadUnique").html($P.findn("theadTr").innerHTML);
	$P.$findn("theadMultiple").html($P.findn("theadTr").innerHTML);

	$P.$findn("btnLoad").on("click", () => $P.fnLoad() );

	$P.$findn("btnUniqueAdd").on("click", () => $P.choiceOtptArtclNm() );
	$P.$findn("btnMultipleAdd").on("click", () => $P.addRow() );

	$P.$findn("btnUniqueDel").on("click", () => $P.delRow('tbodyUnique') );
	$P.$findn("btnMultipleDel").on("click", () => $P.delRow('tbodyMultiple') );

	$P.$findn("btnSave").on("click", () => $P.fnSave() );

	var markerFinder = function(tr){
		return $P.fnGetElement(tr,"otptArtclSeq");
	};
	var markerSetter = function(marker, value){
		marker.value = value;
	};

	Componentization.fnMakeRowNumberingTable($P.findn("tbodyUnique"), markerFinder, markerSetter);
	Componentization.fnMakeRowNumberingTable($P.findn("tbodyMultiple"), markerFinder, markerSetter);

});

</script>