<%@ 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">
		    <div class="container-page-btn"><%-- 조회조건 --%>
		        <button type="button" name="btnReset" class="btn btn-outline-dark w-px-120" title="초기화">초기화</button>
		        <span class="container-window-btn-right">
					<button type="button" name="btnSearch" class="btn btn-search w-px-120" title="검색">검색</button>
		        </span>
		    </div>
		    <form name="frmSearch">
		        <div class="container-search">
                    <div class="row g-1">
                        <div class="col-6">
                            <span class="form-label fw-bold form-search-title w-px-120 text-end">업무구분</span>
                            <span class="form-search-linebox">
								<c:forEach items="${FIM054List}" var="item">
									<c:if test="${'RVS,PVS,BPV'.contains(item.code)}">
										<label>
											<input name="taskSeCd" type="radio" value="${item.code}"
											class="form-check-input" alt="업무구분"
											onchange="pageObject['${pageName}'].fnResetAndChangeBiz(this.value);">
											${item.value}
										</label>
									</c:if>
								</c:forEach>
                            </span>
                        </div>
                    </div>
		        </div>
		    </form>

			<div><%-- 리스트 --%>
				<span class="container-page-btn">
					<div class="d-flex flex-row justify-content-between">
						<span is="paging-info" name="useTeamPagingInfo" class="dataTables_info"></span>
		                <ul name="useTeamPaging" class="pagination pagination-primary"></ul>
					</div>
			     </span>
			</div>
			<div class="card-datatable text-nowrap">
		        <div class="dataTables_wrapper dt-bootstrap5 no-footer">
					<div name="table-responsive_0" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="useTeamTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
							<thead class="sticky-thead">
								<tr name="useTeamTheadTr">
									<th style="width: 160px;">단속조</th>
									<th style="width: 160px;">단속구분</th>
									<th style="width: 160px;">단속원1</th>
									<th style="width: 160px;">단속원2</th>
									<th style="width: 160px;">단속원3</th>
									<th style="width: 160px;">단속원4</th>
									<th style="width: 400px;">특이사항</th>
									<th style="width: 180px;">등록일시</th>
									<th class="dummy-th"></th>
								</tr>
		                    </thead>
		                    <tbody name="useTeamTbody"></tbody>
							<template is="curly-brackets" name="useTeamRow">
	                    		<tr data-index="DATA-INDEX">
	                    			<td onclick ondblclick class="text-start">TEAM_NM</td>
	                    			<td onclick ondblclick class="text-start">CRDN_SE_NM</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_1</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_2</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_3</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_4</td>
		                    		<td onclick ondblclick class="text-start">ETC_CN</td>
		                    		<td onclick ondblclick class="text-center">REG_DT</td>
		                    		<td class="dummy-td"></td>
		                    	</tr>
	                    	</template>
	                    	<template name="useTeamNotFound">
	                    		<tr><td valign="top" colspan="9" class="dataTables_empty text-center">단속팀 정보를 찾지 못했습니다.</td>
	                    		</tr>
	                    	</template>
						</table>
					</div>
				</div>
		    </div>

		    <div class="card"><%-- 입력, 수정 --%>
				<form name="frmEdit">

					<div class="row g-1">
						<div class="col-md-3">
							<label is="name-label" for="teamNm" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end required">단속조명</label>
							<input type="text" is="id-input" name="teamNm" class="form-control" data-maxlengthb="20" required />
						</div>
						<div class="col-md-9">
							<label is="name-label" for="crdnSeCd" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end">단속구분</label>
							<select is="id-select" name="crdnSeCd" class="form-select">
								<option value=""></option>
								<c:forEach items="${FIM002List}" var="item">
									<option value="${item.code}">${item.value}</option>
				                </c:forEach>
							</select>
						</div>
						<div class="col-md-3">
							<label is="name-label" for="teamer1" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end">단속원1</label>
							<input type="text" is="id-input" name="teamer1" class="form-control" data-maxlengthb="20" />
						</div>
						<div class="col-md-3">
							<label is="name-label" for="teamer2" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end">단속원2</label>
							<input type="text" is="id-input" name="teamer2" class="form-control" data-maxlengthb="20" />
						</div>
						<div class="col-md-3">
							<label is="name-label" for="teamer3" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end">단속원3</label>
							<input type="text" is="id-input" name="teamer3" class="form-control" data-maxlengthb="20" />
						</div>
						<div class="col-md-3">
							<label is="name-label" for="teamer4" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end">단속원4</label>
							<input type="text" is="id-input" name="teamer4" class="form-control" data-maxlengthb="20" />
						</div>
						<div class="col-md-12">
							<label is="name-label" for="etcCn" class="w-px-130 bg-lighter pe-2 col-form-label text-sm-end">특이사항</label>
							<input type="text" is="id-input" name="etcCn" class="form-control w-px-700" data-maxlengthb="1000" />
						</div>
					</div>
					<div class="row mt-4 justify-content-end mb-3">
						<div class="col-md-6">
							<div class="row justify-content-end">
								<div class="col-sm-3">
									<button type="button" name="btnSave" class="btn btn-primary">저장</button>
									<button type="button" name="btnRemove" class="btn btn-primary">삭제</button>
								</div>
							</div>
						</div>
					</div>

				</form>
			</div>

		    <div class="container-search"><%-- 비사용 리스트 --%>
				<div class="row g-1">
					<div class="col-6">
						<label is="name-label" for="deletedTeamNm" class="form-label fw-bold form-search-title">선택된 단속조</label>
						<span class="form-search-linebox">
							<input type="text" is="id-input" name="deletedTeamNm" class="form-control" />
							<button type="button" name="btnShowDeleted" class="btn btn-search">비사용 단속조 조회</button>
						</span>
					</div>
				</div>
			</div>
		    <div class="card-datatable text-nowrap">
		        <div class="dataTables_wrapper dt-bootstrap5 no-footer">
					<div name="table-responsive_1" class="table-responsive ox-scroll oy-scroll h-px-300">
						<table name="delTeamTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
							<thead class="sticky-thead">
								<tr name="delTeamTheadTr">
									<th style="width: 200px;">단속조</th>
									<th style="width: 200px;">단속구분</th>
									<th style="width: 200px;">단속원1</th>
									<th style="width: 200px;">단속원2</th>
									<th style="width: 200px;">단속원3</th>
									<th style="width: 200px;">단속원4</th>
									<th style="width: 200px;">특이사항</th>
									<th style="width: 200px;">등록일</th>
									<th style="width: 200px;">해체일</th>
									<th class="dummy-th"></th>
								</tr>
		                    </thead>
		                    <tbody name="delTeamTbody"></tbody>
							<template is="curly-brackets" name="delTeamRow">
	                    		<tr data-index="DATA-INDEX">
	                    			<td onclick ondblclick class="text-start">TEAM_NM</td>
	                    			<td onclick ondblclick class="text-start">CRDN_SE_NM</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_1</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_2</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_3</td>
		                    		<td onclick ondblclick class="text-start">TEAMER_4</td>
		                    		<td onclick ondblclick class="text-start">ETC_CN</td>
		                    		<td onclick ondblclick class="text-center">REG_DT</td>
		                    		<td onclick ondblclick class="text-center">MDFCN_DT</td>
		                    		<td class="dummy-td"></td>
		                    	</tr>
	                    	</template>
	                    	<template name="delTeamNotFound">
	                    		<tr>
	                    			<td valign="top" colspan="10" class="dataTables_empty text-center">
	                    			조회된 정보가 없습니다.
	                    			</td>
	                    		</tr>
	                    	</template>
						</table>
					</div>
				</div>
		    </div>
		</div>
	</div>
  	<div class="content-backdrop fade"></div>
</div>

<script>
LoadScript("crdn07010Script",wctx.url("/resources/js/fims/crdn/crdn07010.js?ver=${ver}"));
/**************************************************************************
* Global Variable
**************************************************************************/

pageObject["${pageName}"] = newDoctxFinder("${pageName}");
var FIM071 = new CommonCodes(${FIM071});
var FIM002 = new CommonCodes(${FIM002});

$(document).ready(function(){

	var $P = pageObject["${pageName}"];

	/**************************************************************************
	* DatasetControl, DatasetSupport, FormFields
	**************************************************************************/
	//사용중인 팀
	var ctrl = newCrdn07010Control($P);

	ctrl.dataset.onDatasetChange = (obj, option) => {

		var t = $P.getGridTemplate("useTeam");
		var trs = Apply.fromDataset.getTbody(ctrl.dataset, t.found, t.notFound, t.replacer);
		$P.renderUseTeamList(obj?.Paging?.totalSize, ctrl.dataset.length, trs);

		$P.pagingSupport.setPagingInfo(obj);
	};

	ctrl.dataset.onCurrentChange = (dataItem) => {
		if (!dataItem){
			$P.$findn("teamNm").val("");
			$P.$findn("crdnSeCd").val("");
			$P.$findn("teamer1").val("");
			$P.$findn("teamer2").val("");
			$P.$findn("teamer3").val("");
			$P.$findn("teamer4").val("");
			$P.$findn("etcCn").val("");
			return;
		}

		Apply.fromDataset.currentRow(ctrl.dataset, dataItem, $P.findn("useTeamTbody"));

		$P.$findn("teamNm").val(dataItem.data.TEAM_NM);
		$P.$findn("crdnSeCd").val(dataItem.data.CRDN_SE_CD);
		$P.$findn("teamer1").val(dataItem.data.TEAMER_1);
		$P.$findn("teamer2").val(dataItem.data.TEAMER_2);
		$P.$findn("teamer3").val(dataItem.data.TEAMER_3);
		$P.$findn("teamer4").val(dataItem.data.TEAMER_4);
		$P.$findn("etcCn").val(dataItem.data.ETC_CN);

		$P.$findn("deletedTeamNm").val(dataItem.data.TEAM_NM);

	}

	$P.pagingSupport = new FimsPagingSupport({
		doq: $P,
        linkContainer: "[name='useTeamPaging']"
	});

	//삭제된 팀
	var alt = newCrdn07010Alt($P);
	alt.dataset.onDatasetChange = (obj, option) => {

		var t = $P.getGridTemplate("delTeam");
		var trs = Apply.fromDataset.getTbody(alt.dataset, t.found, t.notFound, t.replacer);
		$P.renderDelTeamList(obj?.Paging?.totalSize, alt.dataset.length, trs);

	};

	/**************************************************************************
	* pageObject.function
	**************************************************************************/
	$P.fnReset = () => {
		var searchForm = $P.$findn("frmSearch");
		searchForm.find("input[type='text']").val("");
		searchForm.find("input[type='hidden']").val("");

		ctrl.dataset.setData([]);

		var editForm = $P.$findn("frmEdit");
		editForm.find("input[type='text']").val("");
		editForm.find("input[type='hidden']").val("");

		alt.dataset.setData([]);
	}

	$P.fnResetAndChangeBiz = (taskSeCd) => {
		$P.fnReset();

		ctrl.urls.load = wctx.url("/crdn/crdn07/010/list.do");
		ctrl.urls.remove = wctx.url("/crdn/crdn07/010/remove.do");
		ctrl.urls.save = wctx.url("/crdn/crdn07/010/save.do");
	}

	$P.getParams = () => {
		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		return formFields.get();
	}


	$P.searchUseTeamList = () => {
		ctrl.query = $P.getParams();
	    ctrl.load(1);
	}

	$P.refreshUseTeamList = () => {
    	if (ctrl.query.pageNum == null){
    		ctrl.query.pageNum = 1;
    	}

        ctrl.load(1);
    }

	$P.getGridTemplate = (gridType) => {
		var found;
		var notFound;
		var replacer;

		if (gridType == "useTeam"){
			notFound = [$P.findn("useTeamNotFound").innerHTML];
			found = $P.findn("useTeamRow").innerHTML;
			replacer = (str, dataItem) => str
				.replace(/{onclick}/gi, "pageObject['${pageName}'].clickUseTeamList('{DATA-INDEX}');")
	        	.replace(/{ondblclick}/gi, "");
		} else {
			notFound = [$P.findn("delTeamNotFound").innerHTML];
			found = $P.findn("delTeamRow").innerHTML;
			replacer = (str, dataItem) => str
				.replace(/{onclick}/gi, "")
	        	.replace(/{ondblclick}/gi, "");
		}

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

	$P.renderUseTeamList = (total, listLength, trs) => {
		$P.$findn("useTeamTbody").html(trs);
	}

	$P.renderDelTeamList = (total, listLength, trs) => {
		$P.$findn("delTeamTbody").html(trs);
	}

	$P.clickUseTeamList = (dataIndex) => {
		ctrl.dataset.setCurrent(dataIndex);
	}

	$P.fnSave = () => {
		var formFields = new FimsFormFields($P.selectorn("frmEdit"));
		var data = formFields.get();

		data.taskSeCd = $P.$findn("frmSearch").find("input[name='taskSeCd']:checked").val();

		ajax.get({
			url : ctrl.urls.save,
			data : data,
			success : (resp) => {
				if (resp.saved){
					$P.refreshUseTeamList();
				}
			}
		});
	}

	$P.fnRemove = () => {
		var dataKey = ctrl.dataset.getCurrent()["TEAM_ID"];
		ajax.get({
			url : ctrl.urls.remove,
			data : {
				"teamId" : dataKey
			},
			success : (resp) => {
				if (resp.saved){
					$P.refreshUseTeamList();
				}
			}
		});
	};

	$P.fnShowDeleted = () => {

		var teamNm = $P.$findn("deletedTeamNm").val();

		var taskSeCd = $P.$findn("frmSearch").find("input[name='taskSeCd']:checked").val();

		ajax.get({
			url : wctx.url("/crdn/crdn07/010/removedTeamList.do"),
			data: {
				"teamNm" : teamNm,
				"taskSeCd" : taskSeCd
			},
			success:(resp) => {

				alt.dataset.setData(resp);
			}
		});

	}


	/**************************************************************************
	* element.on
	**************************************************************************/
	$P.$findn("btnReset").on('click', () => $P.fnReset());
	$P.$findn("btnSearch").on("click", () => $P.searchUseTeamList());

	$P.$findn("btnSave").on('click', () => { $P.fnSave(); });
	$P.$findn("btnRemove").on('click', () => { $P.fnRemove(); });
	$P.$findn("btnShowDeleted").on('click', () => { $P.fnShowDeleted(); });

	Componentization.fnMakeResizableTable($P.findn("table-responsive_0"));
	Componentization.fnMakeResizableTable($P.findn("table-responsive_1"));

    /**************************************************************************
	 * 초기화
	 **************************************************************************/
	var defaultBizValue = $("#layout-navbar input[name='taskSeCd']:checked").val();
    if ("PVS,BPV".includes(defaultBizValue)) {
    	$P.$findn("frmSearch").find("input[name='taskSeCd'][value='" + defaultBizValue + "']").prop("checked",true);
    } else {
    	var taskForUser = MY_INFO.info.taskForUser;
    	var hasPVS = taskForUser.includes("PVS");
    	var hasBPV = taskForUser.includes("BPV");
    	if (hasPVS && !hasBPV){
    		$P.$findn("frmSearch").find("input[name='taskSeCd'][value='PVS']").prop("checked",true);
    	} else if (!hasPVS && hasBPV){
    		$P.$findn("frmSearch").find("input[name='taskSeCd'][value='BPV']").prop("checked",true);
    	} else {
    		$P.$findn("frmSearch").find("input[name='taskSeCd']").eq(0).prop("checked",true);
    	}
    }

	$P.fnResetAndChangeBiz($P.$findn("frmSearch").find("input[name='taskSeCd']:checked").val());

	$P.$findn("frmSearch").find("input[name='taskSeCd']").each(function(i) {
		$(this).prop("disabled", "true");
	});
});
</script>