<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ItemkindBaseForm.html
 * @desc    : 품목관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.10.16   eskim     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/itemkind/base/list'}" >
			<div class="panelStyle">
				<!-- 버튼 배치 영역 -->
				<ul class="panelBar">
					<li>
						<button type="button" class="btn btn-dark btn-sm" id="btnAddRow">행추가</button>
						<button type="button" class="btn btn-danger btn-sm" id="btnDeleteRow">행삭제</button>
					</li>
					<li  class="right">
						<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
					</li>
				</ul>
				<!-- //버튼 배치 영역 -->
				
				<div id="gridList" style="width: 100%; height: 650px" class="ag-theme-balham"></div>
			</div>
		</form>
	</div>

<script th:inline="javascript">
/*<![CDATA[*/
	var useYnList = { "Y":"Yes", "N":"No" };
	var niClsfCdList = gagajf.convertToArray([[${niClsfCdList}]]);
	var sizeGbList = { "":"" ,"T":"상의", "B":"하의", "S":"신발"};
	// specify the columns
	var columnDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "품목코드", field: "itemkindCd", width: 150, cellClass: 'text-center', 
			editable : function(params){return params.data.crud=='C' ? true : false;},
			cellEditor: 'textCellEditor',
			cellEditorParams: { required: true, maxlength: 10, onblur: '$(this).val($(this).val().toUpperCase())' }
		},
		{headerName: "품목명", field: "itemkindNm", width: 350, cellClass: 'text-left',
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 50, required: true },
			cellRenderer: function (params) {
				if (gagajf.isNull( params.value)){
					return  params.value;
				}else{
					return  params.value.replaceAll("&gt;", ">");
				}
			}	
		},
		/* {headerName: "품목영문명", field: "itemkindEnm", width: 350, cellClass: 'text-center',
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 50, required: true }
		}, */
		{headerName: "정보고시분류", field: "niClsfCd"	, width: 350, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(niClsfCdList), required: true },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(niClsfCdList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(niClsfCdList, params.newValue); }
		},
		{headerName: "사이즈구분", field: "sizeGb", width: 150, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(sizeGbList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(sizeGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(sizeGbList, params.newValue); }
		},
		{
			headerName: "사용여부", field: "useYn", width: 100, minWidth: 75, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(useYnList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(useYnList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(useYnList, params.newValue); }
		}
	];

	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	// Grid editable
	gridOptions.defaultColDef.editable = true;

	// Add on options
	gridOptions.suppressRowClickSelection = true;
	gridOptions.rowSelection = 'multiple';

	gridOptions.stopEditingWhenGridLosesFocus = true;

	// 행추가
	$('#btnAddRow').on('click', function() {
		var data = { itemkindCd: null, itemkindNm: null, niClsfCd: null, sizeGb: null, useYn: "Y" };
		gagaAgGrid.addRowData(gridOptions, data, "itemkindCd");
	});

	// 행삭제
	$('#btnDeleteRow').on('click', function() {
		var selectedData = gridOptions.api.getSelectedRows();
		var removedData = gagaAgGrid.removeRowData(gridOptions);

		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}

		if (removedData.length > 0) {

			mcxDialog.confirm('삭제하시겠습니까?', {
				cancelBtnText: "취소",
				sureBtnText: "확인",
				sureBtnClick: function(){
					var deleteData = [];

					$.each(removedData, function(idx, item) {
						deleteData.push(item);
					});

					var jsonData = JSON.stringify(deleteData);
					gagajf.ajaxJsonSubmit('/goods/itemkind/delete', jsonData, fnSearch);
				}
			});
		}
	});

	// 저장
	$('#btnSave').on('click', function() {
		// 변경된 데이터
		var changedData = gagaAgGrid.getChangedData(gridOptions);
		var loopRowData = gagaAgGrid.getAllRowData(gridOptions);

		if (changedData.length == 0) {
			mcxDialog.alert('변경된 데이터가 없습니다.');
			return;
		}

		// Validation
		if (!gagaAgGrid.validation(gridOptions, changedData))
			return;
	
		var checkFlag = false;
		var selIndex = 0;
		changedData.forEach(function(item, index) {
			
			if(checkFlag) return false;
			
			if (item.crud == "C"){
				selIndex = index;
				loopRowData.forEach(function(loopItem, loopIndex) {
					if (selIndex != loopIndex){
						if(item.itemkindCd == loopItem.itemkindCd){
							checkFlag = true;
							mcxDialog.alertC("품목코드가 중복됩니다. 확인해주세요.", {
								sureBtnText: "확인",
								sureBtnClick: function() {
									gridOptions.api.setFocusedCell(selIndex, "itemkindCd", null);
								}
							});
							return;
						}
					}
				});	
			}
		});
		
		if(checkFlag) return false;
		
		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(changedData);
				gagajf.ajaxJsonSubmit('/goods/itemkind/save', jsonData, fnSearch);
			}
		});

	});

	// 조회
	var fnSearch = function() {
		var formId = "#searchForm";
		gagaAgGrid.fetch($(formId).prop('action'), gridOptions, formId);
	}
	
	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);
		
		fnSearch();
	});
	
/*]]>*/
</script>

</html>
