<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ItemkindCategoryForm.html
 * @desc    : 품목카테고리관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.01.06   gagamel     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<div class="panelStyle">
			<!-- 다중 TABLE 배치 -->
			<ul class="division">
				<li style="width: 40%">
					<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/itemkind/base/list'}" onsubmit="$('#btnSearch').trigger('click'); return false;">
						<ul class="panelBar">
							<li>
								<h4 class="marR10">품목 목록</h4>
								<input type="text" class="w300" name="itemkindNm" placeholder="품목명" maxlength="50"/>
								<button type="button" class="btn btn-base btn-lg" id="btnSearch">조회</button>
							</li>
						</ul>
					</form>
					<div id="gridList1" style="width: 100%; height: 670px" class="ag-theme-balham"></div>
				</li>
				<li style="width: 60%">
					<form id="searchForm2" name="searchForm2" action="#" th:action="@{'/display/category/gb/list'}">
						<ul class="panelBar">
							<li>
								<h4 class="marR10">카테고리 목록</h4>
								<select name="cateGb">
									<option value="">[카테고리구분]</option>
									<option th:if="${cateGbList}" th:each="oneData, status : ${cateGbList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
								</select>
								<button type="button" class="btn btn-info btn-lg" id="btnApply">품목카테고리매핑 목록에 추가</button>
							</li>
						</ul>
					</form>
					<div id="gridList2" style="width: 100%; height: 340px" class="ag-theme-balham"></div>
					
					<ul class="panelBar">
						<li>
							<h4><span id="itemkindCd" class="cBlue"></span><span id="itemkindNm" class="cBlue"></span> 품목의 자동전시카테고리매핑 목록</h4>
						</li>
						<li class="right">
							<button type="button" class="btn btn-danger btn-lg" id="btnDelete">삭제</button>
							<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
						</li>
					</ul>
					<div id="gridList3" style="width: 100%; height: 270px" class="ag-theme-balham"></div>
				</li>
			</ul>
		</div>
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	let cateGbList = gagajf.convertToArray([[${cateGbList}]]);

	let columnDefs1 = [
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{
			headerName: "품목코드", field: "itemkindCd", width: 150, cellClass: 'text-center',
			cellRenderer: function (params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "품목명", field: "itemkindNm", width: 300,
			cellRenderer: function (params) {
				if (gagajf.isNull( params.value)){
					return  params.value;
				}else{
					return  params.value.replaceAll("&gt;", ">");
				}
			}	
		}
	];
	
	let columnDefs2 = [
		{headerName: "FULL카테고리번호", field: "fullCateNo", width: 200, hide: true},
		{
			headerName: "카테고리구분", field: "cateGb", width: 120, cellClass: 'text-center',
			cellRenderer: function (params) { return gagaAgGrid.lookupValue(cateGbList, params.value); }
		},
		{headerName: "FULL카테고리명", field: "fullCateNm", width: 400,
			cellRenderer: function (params) {
				if (gagajf.isNull( params.value)){
					return  params.value;
				}else{
					return  params.value.replaceAll("&gt;", ">");
				}
			}	
		},
		{headerName: "카데고리명", field: "cateNm", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "분류레벨", field: "clsLvl", width: 100, hide: true}
	];
	
	let columnDefs3 = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "CRUD", field: "crud", width: 75, cellClass: 'text-center', hide: true},
		{headerName: "품목코드", field: "itemkindCd", cellClass: 'text-center', hide: true},
		{
			headerName: "카테고리구분", field: "cateGb", width: 120, cellClass: 'text-center',
			cellRenderer: function (params) { return gagaAgGrid.lookupValue(cateGbList, params.value); }
		},
		{headerName: "카테고리번호", field: "cateNo", width: 150, cellClass: 'text-center'},
		{headerName: "FULL카테고리번호", field: "fullCateNo", width: 200,
			cellRenderer: function (params) {
				if (gagajf.isNull( params.value)){
					return  params.value;
				}else{
					return  params.value.replaceAll("&gt;", ">");
				}
			}	
		},
		{headerName: "FULL카테고리명", field: "fullCateNm", width: 400,
			cellRenderer: function (params) {
				if (gagajf.isNull( params.value)){
					return  params.value;
				}else{
					return  params.value.replaceAll("&gt;", ">");
				}
			}	
		}
	];
	
	let gridOptions1 = gagaAgGrid.getGridOptions(columnDefs1);
	let gridOptions2 = gagaAgGrid.getGridOptions(columnDefs2);
	let gridOptions3 = gagaAgGrid.getGridOptions(columnDefs3);
	
	// Add on options
	gridOptions2.suppressRowClickSelection = true;
	gridOptions2.rowSelection = 'multiple';
	gridOptions2.treeData = true; // enable Tree Data mode
	gridOptions2.groupDefaultExpanded = -1; // expand all groups by default
	gridOptions2.getDataPath = function(data) { // just return the hierarchy, no conversion required
		return data.treePath.split("/");
	};
	gridOptions2.autoGroupColumnDef = {
		headerName: "카데고리번호", field: "cateNo", width: 200,
		cellRendererParams: {
			suppressCount: true, // 하위의 항목 건수 표시 안 함
			checkbox: function (params) {
				if (!gagajf.isNull(params.data)) {
					return true;
				}
			}
		}
	};
	
	gridOptions3.rowSelection = 'multiple';
	
	// Cell click
	gridOptions1.onCellClicked = function(event) {
		if (event.colDef.field != 'itemkindCd') {
			return;
		}
		
		// 품목카테고리매핑 조회
		fnSearchItemkindCategoryMapping(event.data.itemkindCd, event.data.itemkindNm);
	}

	// 검색 버튼 클릭 시
	$('#btnSearch').on('click', function() {
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridOptions1, '#searchForm');
	});
	
	// 카테고리구분 변경 시
	$('select[name=cateGb]').on('change', function() {
		if (gagajf.isNull($(this).val())) {
			mcxDialog.alert("카테고리구분을 선택해 주세요.");
			$(this).focus();
			return false;
		}
		
		let actionUrl = $('#searchForm2').prop('action') + '/' + $(this).val();
		gagaAgGrid.fetch(actionUrl, gridOptions2);
	});
	
	// 적용 버튼 클릭 시
	$('#btnApply').on('click', function() {
		if (gagajf.isNull($('#itemkindCd').html())) {
			mcxDialog.alert("선택된 품목이 없습니다. 먼저 품목 목록을 조회하고 [품목코드]를 선택 후 진행해 주세요.");
			return false;
		}
		
		let selectedData = gridOptions2.api.getSelectedRows();
		
		if (selectedData.length == 0) {
			mcxDialog.alert("선택된 데이터가 없습니다.");
			return false;
		}
		
		var applyData = [];
		
		selectedData.forEach(function(item) {
			if (item.clsLvl >= 3) {
				applyData.push(item);
			}
		});
		//2021-06-28 체크박스 해제 로직 추가
		let actionUrl = $('#searchForm2').prop('action') + '/' + $('select[name=cateGb]').val();
		gagaAgGrid.fetch(actionUrl, gridOptions2);

		fnAddCategory(applyData);
	});
	
	// 선택된 카테고리를 품목카테고리매핑 그리드에 추가
	var fnAddCategory = function(cateData) {
		var isExist = false;
		
		cateData.forEach(function(item) {
			isExist = false;
			console.log(item);
			gridOptions3.api.forEachNode(function(rowNode, index) {
				if (item.cateNo == rowNode.data.cateNo) {
					isExist = true;
				}
			});
			
			if (!isExist) {
				var data = {
						cateGb : item.cateGb,
						cateNo : item.cateNo,
						fullCateNo : item.fullCateNo,
						fullCateNm : item.fullCateNm,
						itemkindCd : $('#itemkindCd').html()
				};
				
				gagaAgGrid.addRowData(gridOptions3, data, "cateNo");
			}

		});
	}
	
	// 품목카테고리매핑 조회
	var fnSearchItemkindCategoryMapping = function(itemkindCd, itemkindNm) {
		$('#itemkindCd').html(itemkindCd);
		if (typeof(itemkindNm) != 'undefined') $('#itemkindNm').html(':' + itemkindNm);
		
		let actionUrl = "/display/itemkind/category/mapping/list/" + itemkindCd;
		gagaAgGrid.fetch(actionUrl, gridOptions3);
	}
	
	// 품목카테고리매핑 삭제
	$('#btnDelete').on('click', function() {
		// 추가된 ROW만 삭제하는 경우 DB 처리를 하지 않도록
		let selectedData = gagaAgGrid.selectedRowData(gridOptions3);
		let iTotCnt = 0;
		let iCnt = 0;
		selectedData.forEach(function(item, idx) {
			iTotCnt++;
			if (item.crud == "C") {
				gridOptions3.api.updateRowData({remove: [item]});
				iCnt ++;
			}
		});
		if (iTotCnt > 0 && iTotCnt == iCnt) { return; }
		// 추가된 ROW만 삭제하는 경우 DB 처리를 하지 않도록
		
		var removedData = gagaAgGrid.removeRowData(gridOptions3);
		
		if (removedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		mcxDialog.confirm('삭제하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(removedData);
				gagajf.ajaxJsonSubmit('/display/itemkind/category/mapping/delete', jsonData, function() {
					// 품목카테고리매핑 조회
					fnSearchItemkindCategoryMapping($('#itemkindCd').html());
				});
			}
		});
	});
	
	// 품목카테고리매핑 저장
	$('#btnSave').on('click', function() {
		// 변경된 데이터
		var changedData = gagaAgGrid.getChangedData(gridOptions3);
		
		if (changedData.length == 0) {
			mcxDialog.alert('변경된 데이터가 없습니다.');
			return;
		}
		
		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(changedData);
				gagajf.ajaxJsonSubmit('/display/itemkind/category/mapping/save', jsonData, function() {
					// 품목카테고리매핑 조회
					fnSearchItemkindCategoryMapping($('#itemkindCd').html());
				});
			}
		});
	});
	
	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('gridList1', gridOptions1);
		gagaAgGrid.createGrid('gridList2', gridOptions2);
		gagaAgGrid.createGrid('gridList3', gridOptions3);
	});
/*]]>*/
</script>

</html>
