<%@ 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="content-wrapper" data-doctx="${pageName}">
	<div class="container-xxl flex-grow-1 px-0">
		<div class="card wrapper-list">
	        <form name="mainForm" method="post" enctype="multipart/form-data">
				<div class="card my-2">
					<div class="mx-3 my-2 d-block">
						<span class="h3">
							시군구 정보
						</span>
						<span>
							<button type="button" name="btnSaveSgg" class="btn btn-primary w-px-100 float-end">저장</button>
						</span>
					</div>

					<div class="row g-3 mt-1 mb-3">
						<div class="col-md-6">
							<label class="w-px-140 col-form-label text-sm-end pe-2" for="">시군구명</label>
							<input name="sggID" type="hidden" />
							<input name="sggNm" type="text" class="form-control" readonly />
						</div>
						<div class="col-md-6">
							<label class="w-px-140 col-form-label text-sm-end pe-2" for="">기관명</label>
							<input name="instCd" type="hidden" />
							<input name="instNm" type="text" class="form-control" readonly />
						</div>
						<div class="col-md-4 d-flex align-items-center">
							<label class="w-px-140 col-form-label text-sm-end pe-2">
							직인
							</label>
							<img name="offcsImage"
							alt="" src="" data-orgn-path="" data-orgn-name=""
							class="mw-px-100 mh-px-100 fit-contain" />
							<input type="file" name="offcs" hidden />
						</div>
						<div class="col-md-4 d-flex align-items-center">
							<label class="w-px-140 col-form-label text-sm-end pe-2">
							심볼
							</label>
							<img name="symbolImage"
							alt="" src="" data-orgn-path="" data-orgn-name=""
							class="mw-px-100 mh-px-100 fit-contain" />
							<input type="file" name="symbol" hidden />
						</div>
						<div class="col-md-4 d-flex align-items-center">
							<label class="w-px-140 col-form-label text-sm-end pe-2">
							로고
							</label>
							<img name="logoImage"
							alt="" src="" data-orgn-path="" data-orgn-name=""
							class="mw-px-100 mh-px-100 fit-contain" />
							<input type="file" name="logo" hidden />
						</div>
					</div>

					<div class="row g-3 mt-1 mb-3 superadmin">
						<div class="col-md-6">
							<label class="w-px-140 col-form-label text-sm-end pe-2 text-red" for="">상위시군구코드</label>
							<input name="upSggCd" type="text" class="form-control" />
						</div>
					</div>
				</div>

			</form>

			<div class="card my-2">
				<div class="mx-3 my-2 d-block">
					<span class="h3">
						시군구 업무 정보
					</span>
				</div>

				<div class="nav-align-top my-2 mx-2 flex-row">
					<ul class="nav nav-tabs" role="tablist" name="tabButtonContainer">
					</ul>
					<button type="button" name="btnOpenSelectTaskDialog"
					class="btn btn-darkgray ms-1 superadmin">+ 새 과태료업무 추가</button>
				</div>

				<span class="tab-content" name="tabContentContainer">
				</span>

			</div>

		</div>
	</div>


	<template name="taskTabButtonTemplate">
		<li class="nav-item">
			<button type="button" class="nav-link {active}"
			role="tab" data-bs-toggle="tab" data-bs-target="[data-doctx='${pageName}'] [name='tab{task}']"
			onclick="">
				{taskNm}
			</button>
		</li>
	</template>

	<template name="taskTabContentsTemplate">

		<span name="tab{task}" class="tab-pane {activeshow}" role="tabpanel">
			<div class="mx-3 my-2 d-flex flex-column">
				<div class="float-end">
					<button type="button" data-task="{task}"
					onclick="pageObject['${pageName}'].fnSaveForTask(this);"
					class="btn btn-primary w-px-100 float-end"
					>저장</button>
				</div>
			</div>

			<form name="{task}Form">
				<div class="row g-3 mt-1 mb-3">
					<div class="col-md-3 d-flex">
						<label class="w-px-140 col-form-label text-sm-end" for="">업무명</label>
						<textarea name="taskSeNm" type="text" class="form-control d-flex flex-grow-1" style="resize:none;"></textarea>
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">사전통지일수</label>
						<input name="advntceDayCnt" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">사전통지감경율</label>
						<input name="advntceRdcrt" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">사회적약자감경율</label>
						<input name="wksnRdcrt" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">과태료가산일자</label>
						<input name="ffnlgAdtnYmd" type="text" class="form-control w-px-100" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">과태료가산율</label>
						<input name="ffnlgAdtnRt" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">과태료중가산율</label>
						<input name="ffnlgInadtnRt" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end" for="">과태료중가산최대수</label>
						<input name="ffnlgInadtnMaxCnt" type="text" class="form-control w-px-50" />
					</div>
				</div>
				<div class="row g-3 mt-1 mb-3 superadmin">
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end text-red" for="">세외수입연계<br/>구분코드</label>
						<input name="nxrpLinkSeCd" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-3">
						<label class="w-px-140 col-form-label text-sm-end text-red" for="">세외수입연계<br/>구분상세순번</label>
						<input name="nxrpLinkSeDtlSn" type="text" class="form-control w-px-50" />
					</div>
					<div class="col-md-6"></div>
				</div>
			</form>

			<div class="card-datatable text-nowrap area-photoinspection mx-2 mt-2 mb-3">
		        <div name="{task}Table_0_wrapper" class="dataTables_wrapper dt-bootstrap5 no-footer">
					<div name="{task}table-responsive" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="{task}Table_0"
							class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
							<thead class="sticky-thead">
								<tr>
									<th style="width: 90px;">위반코드</th>
									<th style="width: 300px;">위반항목</th>
									<th colspan="4" style="width: 700px;">위반법</th>
<%--
									<th style="width: 360px;">위반법명</th>
									<th style="width: 160px;">위반법1</th>
									<th style="width: 160px;">위반법2</th>
									<th style="width: 160px;">위반법기타</th>
--%>
									<th colspan="2" style="width: 240px;">회계구분</th>
<%--
									<th style="width: 120px;">회계구분코드</th>
									<th style="width: 120px;">회계구분명</th>
--%>
									<th colspan="2" style="width: 350px;">세목</th>
<%--
									<th style="width: 120px;">세목코드</th>
									<th style="width: 300px;">세목명</th>
--%>
									<th colspan="2" style="width: 350px;">운영항목</th>
<%--
									<th style="width: 120px;">운영항목코드</th>
									<th style="width: 300px;">운영항목명</th>
--%>
									<th colspan="2" style="width: 350px;">특별회계사업</th>
<%--
									<th style="width: 160px;">특별회계사업코드</th>
									<th style="width: 300px;">특별회계사업명</th>
--%>
									<th class="dummy-th"></th>
								</tr>
							</thead>
							<tbody name="{task}tbody"></tbody>
						</table>
					</div>
				</div>
			</div>

		</span>
	</template>

	<template name="taskTbodyTemplate">
		<tr data-key="{VLTN_ID}">
			<td>{VLTN_CD}</td>
			<td data-col="vltnArtcl">
				<input type="text" class="form-control w-100" value="{VLTN_ARTCL}" />
			</td>
			<td data-col="vltnLawNm">
				<input type="text" class="form-control w-100" value="{VLTN_LAW_NM}" placeholder="위반법명"/>
			</td>
			<td data-col="vltnLaw1">
				<input type="text" class="form-control w-100" value="{VLTN_LAW1}" placeholder="위반법1"/>
			</td>
			<td data-col="vltnLaw2">
				<input type="text" class="form-control w-100" value="{VLTN_LAW2}" placeholder="위반법2"/>
			</td>
			<td data-col="vltnLawEtc">
				<input type="text" class="form-control w-100" value="{VLTN_LAW_ETC}" placeholder="위반법기타"/>
			</td>
			<td data-col="acntgSeCd">
				<input type="text" class="form-control w-100" value="{ACNTG_SE_CD}" placeholder="코드"/>
			</td>
			<td data-col="acntgSeNm">
				<input type="text" class="form-control w-100" value="{ACNTG_SE_NM}" placeholder="이름"/>
			</td>
			<td data-col="txitmCd">
				<input type="text" class="form-control w-70" value="{TXITM_CD}" placeholder="코드"/>
			</td>
			<td data-col="txitmNm">
				<input type="text" class="form-control w-100" value="{TXITM_NM}" placeholder="이름"/>
			</td>
			<td data-col="operItemCd">
				<input type="text" class="form-control w-100" value="{OPER_ITEM_CD}" placeholder="코드"/>
			</td>
			<td data-col="operItemNm">
				<input type="text" class="form-control w-100" value="{OPER_ITEM_NM}" placeholder="이름"/>
			</td>
			<td data-col="spclBizCd">
				<input type="text" class="form-control w-100" value="{SPCL_BIZ_CD}" placeholder="코드"/>
			</td>
			<td data-col="spclBizNm">
				<input type="text" class="form-control w-100" value="{SPCL_BIZ_NM}" placeholder="이름"/>
			</td>
		</tr>
	</template>
</div>

<script>
LoadScript("ogdp01010Script",wctx.url("/resources/js/fims/ogdp/ogdp01010.js?ver=${ver}"));

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

$(document).ready(function(){

	if(MY_INFO.institute != "ADMIN00"){
		$(".superadmin").attr("hidden","hidden");
	}

	var $P = pageObject["${pageName}"];
	$P.sggInfo = {};
	$P.taskList = [];
	$P.curSggCd = "";

	if("${sggCd}" == ""){
		$P.curSggCd = MY_INFO.info.sggCd;
	} else {
		$P.curSggCd = "${sggCd}";
	}

	$P.taskDatasets = {};
	var taskCodes = Object.keys(ALL_TASK);
	for(var i=0; i < taskCodes.length; i++){
		$P.taskDatasets[taskCodes[i]+"Dataset"] = new Dataset({
			keymapper : info => info ? info.VLTN_ID : ""
		});
	}

	$P.getSggInfo = async function(){
		return new Promise((resolve, reject) => {
			ajax.get({
				url: wctx.url("/ogdp/getSggStngInfo.do"),
				data: {
					sggCd : $P.curSggCd
				},
				success : function(resp, textStatus, jqXHR) {
					$P.sggInfo = resp.sggInfo;

					$P.$findn("mainForm").find("[name='sggID']").val($P.sggInfo.SGG_CD);
					$P.$findn("mainForm").find("[name='sggNm']").val($P.sggInfo.SGG_NM);
					$P.$findn("mainForm").find("[name='instCd']").val($P.sggInfo.INST_CD);
					$P.$findn("mainForm").find("[name='instNm']").val($P.sggInfo.INST_NM);
					$P.$findn("mainForm").find("[name='upSggCd']").val($P.sggInfo.UP_SGG_CD);

					$P.$findn("offcsImage")
						.attr("data-orgn-name", $P.sggInfo.OFFCS_FILE_NM)
						.attr("data-orgn-path", $P.sggInfo.OFFCS_FILE_PATH);
					$P.$findn("offcs").val("");
					$P.$findn("offcs").trigger("change");

					$P.$findn("symbolImage")
						.attr("data-orgn-name", $P.sggInfo.SYMBOL_FILE_NM)
						.attr("data-orgn-path", $P.sggInfo.SYMBOL_FILE_PATH);
					$P.$findn("symbol").val("");
					$P.$findn("symbol").trigger("change");

					$P.$findn("logoImage")
						.attr("data-orgn-name", $P.sggInfo.LOGO_FILE_NM)
						.attr("data-orgn-path", $P.sggInfo.LOGO_FILE_PATH);
					$P.$findn("logo").val("");
					$P.$findn("logo").trigger("change");

					resolve({resp, textStatus, jqXHR});
				},
				error: function(jqXHR, textStatus, error) {
				}
			});
		});
	};


	$P.getSggTaskInfo = async function(){
		return new Promise((resolve, reject) => {
			ajax.get({
				url: wctx.url("/ogdp/getTasks.do"),
				data: {
					useYn : "Y",
					sggCd : $P.curSggCd
				},
				success : function(resp, textStatus, jqXHR) {
					$P.taskList = resp.taskList;

					var tabs = [];
					var contents = [];
					for(var i=0; i < $P.taskList.length; i++){
						var task = $P.taskList[i];
						var taskSeCd = task.TASK_SE_CD;
						var taskSeNm = task.TASK_SE_NM;

						var tabButtonTemplate = $P.findn("taskTabButtonTemplate").innerHTML;
						var tabContentsTemplate = $P.findn("taskTabContentsTemplate").innerHTML;

						tabButtonTemplate = tabButtonTemplate.replace(/{task}/gi, taskSeCd);
						tabButtonTemplate = tabButtonTemplate.replace(/{taskNm}/gi, taskSeNm);
						if(i==0){
							tabButtonTemplate = tabButtonTemplate.replace(/{active}/gi, "active");
						} else {
							tabButtonTemplate = tabButtonTemplate.replace(/{active}/gi, "");
						}

						tabContentsTemplate = tabContentsTemplate.replace(/{task}/gi, taskSeCd);
						if(i==0){
							tabContentsTemplate = tabContentsTemplate.replace(/{activeshow}/gi, "active show");
						} else {
							tabContentsTemplate = tabContentsTemplate.replace(/{activeshow}/gi, "");
						}

						tabs.push(tabButtonTemplate);
						contents.push(tabContentsTemplate);
					}

					$P.$findn("tabButtonContainer").html(tabs.join(""));
					$P.$findn("tabContentContainer").html(contents.join(""));

					if(MY_INFO.institute != "ADMIN00"){
						$(".superadmin").attr("hidden","hidden");
					}

					for(var i=0; i < $P.taskList.length; i++){
						var task = $P.taskList[i];
						var taskSeCd = task.TASK_SE_CD;
						var taskSeNm = task.TASK_SE_NM;
						let formName = taskSeCd+"Form";

						$P.$findn(formName).find("[name='taskSeNm']").val(taskSeNm);
						$P.$findn(formName).find("[name='advntceDayCnt']").val(task.ADVNTCE_DAY_CNT);
						$P.$findn(formName).find("[name='advntceRdcrt']").val(task.ADVNTCE_RDCRT);
						$P.$findn(formName).find("[name='wksnRdcrt']").val(task.WKSN_RDCRT);
						$P.$findn(formName).find("[name='ffnlgAdtnYmd']").val(task.FFNLG_ADTN_YMD);
						$P.$findn(formName).find("[name='ffnlgAdtnRt']").val(task.FFNLG_ADTN_RT);
						$P.$findn(formName).find("[name='ffnlgInadtnRt']").val(task.FFNLG_INADTN_RT);
						$P.$findn(formName).find("[name='ffnlgInadtnMaxCnt']").val(task.FFNLG_INADTN_MAX_CNT);

						$P.$findn(formName).find("[name='nxrpLinkSeCd']").val(task.NXRP_LINK_SE_CD);
						$P.$findn(formName).find("[name='nxrpLinkSeDtlSn']").val(task.NXRP_LINK_SE_DTL_SN);
					}

					resolve({resp, textStatus, jqXHR});
				},
				error: function(jqXHR, textStatus, error) {
				}
			});
		});
	};

	$P.getVltnInfo = async function(){
		return new Promise((resolve, reject) => {
			ajax.get({
				url: wctx.url("/ogdp/getVltns.do"),
				data: {
					useYN : "Y",
					sggCd : $P.curSggCd
				},
				success : function(resp, textStatus, jqXHR) {

					var datasetNames = Object.keys($P.taskDatasets);
					for(var i=0; i < datasetNames.length; i++){
						var filtered = resp.vltnList.filter(item => item.TASK_SE_CD == datasetNames[i].substr(0,3));
						$P.taskDatasets[datasetNames[i]].setData(filtered);
					}

					for(var i=0; i < datasetNames.length; i++){
						var taskSeCd = datasetNames[i].substr(0,3);
						var template = $P.findn("taskTbodyTemplate").innerHTML;
						var taskDataset = $P.taskDatasets[taskSeCd+"Dataset"];
						var trs = taskDataset.empty ? [""] : taskDataset.inStrings(template);
						$P.$findn(taskSeCd+"tbody").html(trs.join());
					}

					resolve({resp, textStatus, jqXHR});
				},
				error: function(jqXHR, textStatus, error) {
				}
			});
		});
	};

	//이미지 뷰어
	FimsComponentization.fnMakeSingleImageViewer($P.findn("offcsImage"), $P.findn("offcs"), "orgn-path", "orgn-name");
	FimsComponentization.fnMakeSingleImageViewer($P.findn("symbolImage"), $P.findn("symbol"), "orgn-path", "orgn-name");
	FimsComponentization.fnMakeSingleImageViewer($P.findn("logoImage"), $P.findn("logo"), "orgn-path", "orgn-name");

	//시군구 기본 설정 저장 버튼
	$P.$findn("btnSaveSgg").on("click", function(){

		var formData = new FormData($P.findn("mainForm"));

		ajax.post({
			url: wctx.url("/ogdp/updateSggStng.do"),
			data: formData,
			contentType : false, processData : false,
			success: (resp) => {
				dialog.alert({
					content : "저장됐습니다.",
					init : function(){
						AppSupport.setDialogZindex();
						AppSupport.focusClose();
					},
					onClose : () => {
						$P.getSggInfo();
					}
				});
			}
		});
	});

	//업무 추가 버튼
	$P.$findn("btnOpenSelectTaskDialog").on("click", function(){
		$("#selectTaskButtons").html("");

		var keys = Object.keys(ALL_TASK);
		var ableKeys = [];

		for(var i=0; i < keys.length; i++){
			if($P.$findn("tabContentContainer").find("[name='tab"+keys[i]+"']").length < 1){
				ableKeys.push(keys[i]);
			}
		}
		if(ableKeys.length < 1){
			alert("추가 가능한 과태료 업무가 없습니다.");
			return;
		}


		var pn = "${pageName}";
		for(var i=0; i < ableKeys.length; i++){

			var button = `<button type="button" class="btn btn-xl btn-primary" onclick="pageObject['`
				+pn
				+`'].fnCreateTaskStng('`
				+ableKeys[i]
				+`');">`
				+ALL_TASK[ableKeys[i]]
				+`</button>`;

			$("#selectTaskButtons").append(button);
		}

		$("#selectTaskModal").modal("show");
	});

	$P.fnCreateTaskStng = (taskSeCd) => {
		$("#selectTaskModal").modal("hide");

		ajax.post({
			url: wctx.url("/ogdp/createTaskStng.do"),
			data: {
				sggCd : $P.$findn("mainForm").find("[name='sggID']").val(),
				taskSeCd : taskSeCd
			},
			success: (resp) => {
				dialog.alert({
					content : "저장됐습니다.",
					init : function(){
						AppSupport.setDialogZindex();
						AppSupport.focusClose();
					},
					onClose : () => {
						$P.getSggTaskInfo().then(()=>{ $P.getVltnInfo(); });
					}
				});
			}
		});
	};

	$P.fnSaveForTask = (el) => {
		var taskSeCd = el.dataset.task;
		var sggCd = $P.$findn("mainForm").find("[name='sggID']").val();

		var formData = new FormData($P.findn(taskSeCd+"Form"));
		formData.append("taskSeCd",taskSeCd);
		formData.append("sggCd", sggCd);

		var rowArr = $P.getRowData(taskSeCd+"tbody", formData);

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

		ajax.post({
			url: wctx.url("/ogdp/updateTaskStng.do"),
			data: formData,
			contentType : false, processData : false,
			success: (resp) => {
				dialog.alert({
					content : "저장됐습니다.",
					init : function(){
						AppSupport.setDialogZindex();
						AppSupport.focusClose();
					},
					onClose : () => {
						$P.getSggTaskInfo().then(()=>{ $P.getVltnInfo(); });
					}
				});
			}
		});
	};


	$P.getRowData = (tbodyName, formData) => {
		var rowArr = [];
		$P.$findn(tbodyName).find("tr").each(function(){
			var row = {};

			row.vltnId = this.dataset.key;
			row.vltnArtcl = $($P.fnGetElement(this,"vltnArtcl")).val();
			row.vltnLawNm = $($P.fnGetElement(this,"vltnLawNm")).val();
			row.vltnLaw1 = $($P.fnGetElement(this,"vltnLaw1")).val();
			row.vltnLaw2 = $($P.fnGetElement(this,"vltnLaw2")).val();
			row.vltnLawEtc = $($P.fnGetElement(this,"vltnLawEtc")).val();
			row.acntgSeCd = $($P.fnGetElement(this,"acntgSeCd")).val();
			row.acntgSeNm = $($P.fnGetElement(this,"acntgSeNm")).val();
			row.txitmCd = $($P.fnGetElement(this,"txitmCd")).val();
			row.txitmNm = $($P.fnGetElement(this,"txitmNm")).val();
			row.operItemCd = $($P.fnGetElement(this,"operItemCd")).val();
			row.operItemNm = $($P.fnGetElement(this,"operItemNm")).val();
			row.spclBizCd = $($P.fnGetElement(this,"spclBizCd")).val();
			row.spclBizNm = $($P.fnGetElement(this,"spclBizNm")).val();

			row.sggCd = formData.get("sggID");
			row.taskSeCd = formData.get("taskSeCd");

			rowArr.push(row);
		});

		return rowArr;
	};


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

	/**************************************************************************
	 * 초기화
	 **************************************************************************/
	$P.getSggInfo()
    .then(() => {
    	return $P.getSggTaskInfo();
	})
	.then(() => {
		return $P.getVltnInfo();
	});


});


</script>