<%@ 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">
	<div class="container-xxl flex-grow-1 px-0">
		<div name="statWrapper" class="card wrapper-list">
			<span class="mb-1">
				<!-- 상단 버튼 -->
				<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 my-2">
							<!-- 업무구분 -->
							<div class="col-8">
								<span class="form-label fw-bold form-search-title text-end">업무구분</span>
								<span class="form-search-linebox">
									<label>
										<input type="radio" class="form-check-input" name="taskSeCd" alt="업무구분"
											value="" onchange="" checked="checked">
										전체
									</label>
									<c:forEach items="${TaskListForSgg}" var="item">
										<label>
											<input type="radio" class="form-check-input" name="taskSeCd" alt="업무구분"
												value="${item.code}" onchange="">
											${item.value}
										</label>
									</c:forEach>
								</span>
							</div>
							<div class="col-4">
								<label is="name-label" for="sggCd" class="form-label fw-bold form-search-title text-end">시군구</label>
								<span class="form-search-linebox">
									<select is="id-select" name="sggCd" class="form-select">
										<option value="">전체</option>
										<option value="${sggCd}" selected>${sggNm}</option>
									</select>
								</span>
							</div>
						</div>
						<div class="row g-1 my-2">
							<div class="col-12">
								<select name="dayColumn" class="form-select">

	                            </select>
	                            <span class="form-search-linebox">
	                                <input type="text" name="firstDay"
	                                class="form-control form-date"
	                                	data-fmt-type="day"   title="시작 날짜 선택" />
	                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
	                                ~
	                                <input type="text" name="lastDay"
	                                class="form-control form-date"
	                                	data-fmt-type="day" title="종료 날짜 선택">
	                                <button type="button" class="bx bx-lg bx-calendar bg-white"></button>
	                            </span>

							</div>
						</div>
						<div class="row g-1 my-2" name="searchForMenu">

						</div>
						<div class="row g-1 my-2 bg-lighter">
							<div class="col-3">
								<label is="name-label" for="groupLevel1" class="form-label fw-bold form-search-title text-end">그룹단위1</label>
								<select is="id-select" name="groupLevel1" class="form-select">

								</select>
							</div>
							<div class="col-3">
								<label is="name-label" for="groupLevel2" class="form-label fw-bold form-search-title text-end">그룹단위2</label>
								<select is="id-select" name="groupLevel2" class="form-select">
									<option value="">미선택</option>
								</select>
							</div>
							<div class="col-3">
								<label is="name-label" for="groupLevel3" class="form-label fw-bold form-search-title text-end">그룹단위3</label>
								<select is="id-select" name="groupLevel3" class="form-select">
									<option value="">미선택</option>
								</select>
							</div>
							<div class="col-3">
								<label is="name-label" for="groupLevel4" class="form-label fw-bold form-search-title text-end">그룹단위4</label>
								<select is="id-select" name="groupLevel4" class="form-select">
									<option value="">미선택</option>
								</select>
							</div>
						</div>

						<div class="row g-1 my-2">
							<div class="col-12 d-flex">
								<label is="name-label" for="preset" class="form-label fw-bold form-search-title text-end">집계항목</label>
								<select is="id-select" name="preset"
								class="form-select w-100 mw-100">
									<option value="totCnt" selected>전체건수</option>
								</select>
							</div>
						</div>

						<div class="row g-1 my-2 bg-lighter">
							<div class="col-3">
								<label is="name-label" for="refListYn" class="form-label fw-bold form-search-title text-end">상세목록</label>
								<select is="id-select" name="refListYn" class="form-select">
									<option value="N">미조회</option>
									<option value="Y">조회</option>
								</select>
							</div>
						</div>

					</div> <!-- / 메인 조건 -->
				</form>
			</span>

			<span name="masterArea">
				<div class="card-datatable text-nowrap">
			        <div class="dataTables_wrapper dt-bootstrap5 no-footer">
						<div class="table-responsive ox-scroll oy-scroll h-px-350">
							<table name="masterTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
								<thead class="sticky-thead">
									<tr name="masterThead">
									</tr>
								</thead>
			                    <tbody name="masterTbody">
			                    </tbody>
			                </table>
			            </div>
			        </div>
			    </div>
			</span>

			<span name="detailArea" hidden>
				<h2 class="mt-4">상세목록</h2>
				<div class="card-datatable text-nowrap">
			        <div class="dataTables_wrapper dt-bootstrap5 no-footer">
						<div class="table-responsive ox-scroll oy-scroll h-px-350">
							<table name="detailTable" class="table-layout-fixed datatables-ajax table table-bordered dataTable no-footer">
								<thead class="sticky-thead">
									<tr name="detailThead">
									</tr>
								</thead>
			                    <tbody name="detailTbody">
			                    </tbody>
			                </table>
			            </div>
			        </div>
			    </div>
			</span>

		</div>
	</div>

	<div class="content-backdrop fade"></div>

</div>

<script>
LoadScript("statMainScript",wctx.url("/resources/js/fims/stat/statMain.js?ver=${ver}"));

/**************************************************************************
 * Global Variable
 **************************************************************************/
pageObject["${pageName}"] = newDoctxFinder("${pageName}");

$(document).ready(function(){

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

	$P.statQuery = {};
	$P.refListMap = {};

	/**************************************************************************
	* DatasetControl, Dataset, FormFields
	**************************************************************************/
	var alt = newStatMainAlt($P);

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

		var DS = alt.dataset;
		var empty = DS.empty;
		var notFound = [""];
		var found = $P.findn("detailGridTbodyTemplate").innerHTML;
		var replacer = (str, dataItem) => str
			.replace(/{onclick}/gi, "pageObject['${pageName}'].clickDetailGrid('{DATA-INDEX}');")
			.replace(/{ondblclick}/gi, "pageObject['${pageName}'].dblClickDetailGrid('{DATA_ID}');");
		var trs = empty ? notFound : DS.inStrings(found, replacer);
		$P.$findn("detailTbody").html(trs.join());

		//보안모드
	    fn_securityModeToggle($("#securityMode--top").is(":checked"));
	};

	/**************************************************************************
	 * pageObject.function
	 **************************************************************************/
	$P.fnReset = () => {

		var searchForm = $P.$findn("frmSearch");
		searchForm.find("input[type='radio'][name='taskSeCd'][value='']").prop("checked", true);
		$P.$findn("sggCd").find("option:eq(1)").prop("selected", true);
		$P.$findn("dayColumn").find("option:eq(0)").prop("selected", true);

		$P.$findn("firstDay").datepicker('setDate', TODAY());
		$P.$findn("lastDay").datepicker('setDate', TODAY());

		var searchForMenu = $P.$findn("searchForMenu");
		searchForMenu.find("select").each(function(){ $(this).find("option:eq(0)").prop("selected", true); });
		searchForMenu.find("input[type='checkbox']").prop("checked", false);
		searchForMenu.find("input[type='text']").val("");

		$P.$findn("groupLevel1").find("option:eq(0)").prop("selected", true);
		$P.$findn("groupLevel2").val("");
		$P.$findn("groupLevel3").val("");
		$P.$findn("groupLevel4").val("");
		$P.$findn("preset").find("option:eq(0)").prop("selected", true);
		$P.$findn("refListYn").find("option:eq(0)").prop("selected", true);

		$P.changeGrid();
		$P.showDetailGrid();
	}

	//그룹핑 요청 정보 추출
	$P.getGroupInfoList = () => {
		var groupInfoLiost = [];

		var selected = $P.$findn("groupLevel1").find(":selected");
		groupInfoLiost.push({
			refCol : selected[0].dataset.refCol,
			ctgrType : selected[0].dataset.ctgrType,
			dtlCtgr : selected[0].dataset.dtlCtgr
		})

		selected = $P.$findn("groupLevel2").find(":selected");
		if(selected.val() == ""){
			return groupInfoLiost;
		}

		groupInfoLiost.push({
			refCol : selected[0].dataset.refCol,
			ctgrType : selected[0].dataset.ctgrType,
			dtlCtgr : selected[0].dataset.dtlCtgr
		})

		selected = $P.$findn("groupLevel3").find(":selected");
		if(selected.val() == ""){
			return groupInfoLiost;
		}

		groupInfoLiost.push({
			refCol : selected[0].dataset.refCol,
			ctgrType : selected[0].dataset.ctgrType,
			dtlCtgr : selected[0].dataset.dtlCtgr
		})

		selected = $P.$findn("groupLevel4").find(":selected");
		if(selected.val() == ""){
			return groupInfoLiost;
		}

		groupInfoLiost.push({
			refCol : selected[0].dataset.refCol,
			ctgrType : selected[0].dataset.ctgrType,
			dtlCtgr : selected[0].dataset.dtlCtgr
		})

		return groupInfoLiost;
	}

	//수치값 요청 정보 추출
	$P.getNumberValueInfoList = () => {
		var numberValuefoLiost = [];

		var preset = $P.$findn("preset").find(":selected");

		if(preset.val() == "totCnt"){
			numberValuefoLiost = [{ aggregateType : "count" }];
			return numberValuefoLiost;
		}

		numberValuefoLiost = window[preset.val()];

		return numberValuefoLiost;
	}

	//코드서브셋 요청 정보 추출
	$P.getCodeSubsetInfoList = () => {
		var codeSubsetInfoList = [];

		var groupLevel1subset = $P.getCodeSubsetInfo("groupLevel1");
		var groupLevel2subset = $P.getCodeSubsetInfo("groupLevel2");
		var groupLevel3subset = $P.getCodeSubsetInfo("groupLevel3");
		var groupLevel4subset = $P.getCodeSubsetInfo("groupLevel4");
		var subsetForGroup = [];
		subsetForGroup = subsetForGroup.concat(groupLevel1subset);
		if($P.$findn("groupLevel2").val() != ""){
			subsetForGroup = subsetForGroup.concat(groupLevel2subset);
			if($P.$findn("groupLevel3").val() != ""){
				subsetForGroup = subsetForGroup.concat(groupLevel3subset);
				if($P.$findn("groupLevel4").val() != ""){
					subsetForGroup = subsetForGroup.concat(groupLevel4subset);
				}
			}
		}

		var subsetForPreset = $P.getCodeSubsetInfo("preset");

		codeSubsetInfoList = subsetForGroup.concat(subsetForPreset);

		if(codeSubsetInfoList.length > 1){
			codeSubsetInfoList = $P.subsetDeduplication(codeSubsetInfoList);
		}

		return codeSubsetInfoList;
	}

	//특정 요소의 코드서브셋 정보 추출
	$P.getCodeSubsetInfo = (elementName) => {
		var result = [];

		var selected = $P.$findn(elementName).find(":selected");
		if(window[selected.val()+"_codeSubsetInfoList"] != undefined){
			result = window[selected.val()+"_codeSubsetInfoList"];
		}
		return result;
	}

	//중복 서브셋정보 제거
	$P.subsetDeduplication = (arr) => {

		var resultArr = [];

		var iterator = arr.values();

		for(var element of iterator) {
			var testFunc = function(resultElement){
				return (resultElement.sourceGroup == element.sourceGroup && resultElement.targetCode == element.targetCode);
			};
			var testResult = resultArr.findIndex(testFunc);

			if(testResult == -1){
				resultArr.push(element);
			}
		}

		return resultArr;
	}

	//그리드 모양 변경
	$P.changeGrid = () => {

		//그룹단위 초기화
		if($P.$findn("groupLevel2").val() == ""){
			$P.$findn("groupLevel3").val("");
			$P.$findn("groupLevel3").attr("disabled","disabled");
		} else {
			$P.$findn("groupLevel3").removeAttr("disabled");
		}

		if($P.$findn("groupLevel3").val() == ""){
			$P.$findn("groupLevel4").val("");
			$P.$findn("groupLevel4").attr("disabled","disabled");
		} else {
			$P.$findn("groupLevel4").removeAttr("disabled");
		}

		//그리드 초기화
		$P.$findn("masterThead").html("");
		$P.$findn("masterTbody").html("");
		$P.$findn("detailThead").html("");
		$P.$findn("detailTbody").html("");

		//상단 그리드
		var level1Text = $P.$findn("groupLevel1").find(":selected").text();
		$P.$findn("masterThead").append("<th class='text-orange' style='width:160px'>"+level1Text+"</th>");

		if($P.$findn("groupLevel2").val() != ""){
			var level2Text = $P.$findn("groupLevel2").find(":selected").text();
			$P.$findn("masterThead").append("<th class='text-orange' style='width:160px'>"+level2Text+"</th>");

			if($P.$findn("groupLevel3").val() != ""){
				var level3Text = $P.$findn("groupLevel3").find(":selected").text();
				$P.$findn("masterThead").append("<th class='text-orange' style='width:160px'>"+level3Text+"</th>");

				if($P.$findn("groupLevel4").val() != ""){
					var level4Text = $P.$findn("groupLevel4").find(":selected").text();
					$P.$findn("masterThead").append("<th class='text-orange' style='width:160px'>"+level4Text+"</th>");
				}
			}
		}

		var preset = $P.$findn("preset").find(":selected");
		var cols = preset.text().split(",");
		for(var i=0; i < cols.length; i++){
			$P.$findn("masterThead").append("<th style='width: 160px;'>"+cols[i]+"</th>");
		}

		$P.$findn("masterThead").append("<th class='cmn dummy-th'></th>");

		//하단 그리드
		var detailTheadTemplate = $P.findn("detailGridTheadTemplate");
		$P.$findn("detailThead").append(detailTheadTemplate.innerHTML);
	}

	//상세 그리드 표시
	$P.showDetailGrid = () => {
		if($P.$findn("refListYn").val() == "Y"){
			$P.$findn("detailArea").removeAttr("hidden");
		} else {
			$P.$findn("detailArea").attr("hidden","hidden");
		}
	}

	//통계 검색
	$P.searchStat = () => {


		var formFields = new FimsFormFields($P.selectorn("frmSearch"));
		var formFieldsData = formFields.get();

		if(formFieldsData.firstDay == "" || formFieldsData.lastDay == ""){
			dialog.alert("시작일자와 종료일자를 입력하세요.");
			return;
		}

		var statQuery = {
			structureType 	: "aggregate",
			decimalPoint : 1
		};

		//업무구분
		if(formFieldsData.taskSeCd != ""){
			statQuery.taskSeCd = formFieldsData.taskSeCd;
		}

		//날짜 조회조건
		statQuery.dayColumn = formFieldsData.dayColumn;
		statQuery.firstDay = formFieldsData.firstDay;
		statQuery.lastDay = formFieldsData.lastDay;

		statQuery.carGb = formFieldsData.carGb;
		statQuery.schExclEnd = formFieldsData.schExclEnd;
		statQuery.schOnlyRent = formFieldsData.schOnlyRent;

		//통계 유형
		var preset = $P.$findn("preset").find(":selected");
		if(preset.val() == "totCnt"){
			statQuery.statDomain = $P.$findn("defaultStatDomain").val();
		} else {
			statQuery.statDomain = preset[0].dataset.statDomain;
		}

		//집계 그룹 정보
		statQuery.groupInfoList = $P.getGroupInfoList();

		//수치값 정보
		statQuery.numberValueInfoList = $P.getNumberValueInfoList();

		//코드서브셋 정보
		statQuery.codeSubsetInfoList = $P.getCodeSubsetInfoList();

		//상세목록 조회 여부
		statQuery.refListYn = formFieldsData.refListYn;

		$P.statQuery = JSON.parse(JSON.stringify(statQuery));

		statQuery = FimsSupport.fnJsonToFormData(statQuery, "groupInfoList");
		statQuery = FimsSupport.fnJsonToFormData(statQuery, "numberValueInfoList");
		statQuery = FimsSupport.fnJsonToFormData(statQuery, "codeSubsetInfoList");

		ajax.get({
			url : wctx.url("/stat/stat01/010/info.do"),
			data : statQuery,
			success : (resp) => {
				var stat = resp.stat;
				$P.renderStat(stat);
			}
		});

	}

	//통계 그리드 렌더링
	$P.renderStat = (stat) => {
		$P.$findn("masterTbody").html("");
		$P.$findn("detailTbody").html("");
		refListMap = {};

		var statItems = stat.statItems;

		if(statItems == null || statItems.length == 0){
			dialog.alert("조회된 자료가 없습니다.");
			return;
		}

		//비율 소수점
		var decimalPoint = 0;
		if($P.statQuery.decimalPoint != null){
			decimalPoint = $P.statQuery.decimalPoint;
		}
		var pointMove = Number.parseFloat(0.1 ** decimalPoint).toFixed(decimalPoint);

		for(var i=0; i < statItems.length; i++){

			var statItem = statItems[i];

			var itemIds = statItem.itemId;
			var itemNames = statItem.itemName;
			var numberValues = statItem.numberValue;

			var itemKey = itemIds.join("_");

			refListMap[itemKey] = statItem.refList == null ? [] : statItem.refList;

			var tr = "<tr data-key='"+itemKey+"' >";

			for(var j=0; j < itemNames.length; j++){

				if($P.statQuery.groupInfoList[j].ctgrType == "date"){
					tr += "<td class='text-center' >";
				} else {
					tr += "<td>";
				}
				tr += itemNames[j];
				tr += "</td>";
			}
			for(var k=0; k < numberValues.length; k++){
				tr += "<td class='text-end' >";

				if($P.statQuery.numberValueInfoList[k].aggregateType == "ratio"){
					tr += Number.parseFloat(numberValues[k] * pointMove).toFixed(decimalPoint);
					tr += " %";
				} else {
					tr += numberFormat.format(numberValues[k]);
				}
				tr += "</td>";
			}

			tr += "</tr>";

			$P.$findn("masterTbody").append(tr);
		}
		$P.$findn("masterTbody").find("tr").attr("onclick","pageObject['${pageName}'].clickMasterGrid(this);");
		$P.$findn("masterTbody").find("tr").attr("ondblclick","pageObject['${pageName}'].dblClickMasterGrid(this);");
	}

	$P.clickMasterGrid = (obj) => {
		var dataKey = obj.dataset.key;
		$P.$findn("masterTbody").setCurrentRow(dataKey);
	}

	$P.dblClickMasterGrid = (obj) => {
		var dataKey = obj.dataset.key;
		alt.dataset.setData(refListMap[dataKey]);

		var offset = $P.$findn("masterArea").offset();
		$P.$findn("statWrapper").animate({scrollTop : offset.top}, 400);
	}

	$P.clickDetailGrid = (dataIndex) => {
		$P.$findn("detailTbody").setCurrentRow(dataIndex);
	}

	$P.dblClickDetailGrid = (key) => {

	}

	AppSupport.initDatepicker($P.findn("frmSearch")); //달력 초기화

	$P.$findn("dayColumn").append($P.findn("dayColumnDatalist").innerHTML);

	$P.$findn("searchForMenu").append($P.findn("searchForMenuTemplate").innerHTML);

	$P.$findn("groupLevel1").append($P.findn("groupLevelDatalist").innerHTML);
	$P.$findn("groupLevel2").append($P.findn("groupLevelDatalist").innerHTML);
	$P.$findn("groupLevel3").append($P.findn("groupLevelDatalist").innerHTML);
	$P.$findn("groupLevel4").append($P.findn("groupLevelDatalist").innerHTML);

	$P.$findn("preset").append($P.findn("presetDatalist").innerHTML);

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

	$P.$findn("groupLevel1").on('change', () => $P.changeGrid());
	$P.$findn("groupLevel2").on('change', () => $P.changeGrid());
	$P.$findn("groupLevel3").on('change', () => $P.changeGrid());
	$P.$findn("groupLevel4").on('change', () => $P.changeGrid());
    $P.$findn("preset").on('change', () => $P.changeGrid());

    $P.$findn("refListYn").on('change', () => $P.showDetailGrid());

    $P.fnReset();
});


</script>