<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ColorForm.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/color/list'}" th:method="post">
			<div class="panelStyle">
				<!-- 버튼 배치 영역 -->
				<ul class="panelBar">
					<li>
						<button type="button" class="btn btn-dark btn-sm" id="btnAddRow">행추가</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 groupColorCodeList = gagajf.convertToArray([[${groupColorCodeList}]]);
	var groupColorCodeNmList = gagajf.convertToArray([[${groupColorCodeNmList}]]);

	// 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: "colorCd", width: 100, cellClass: 'text-center',
			editable : function(params){return params.data.crud=='C' ? true : false;},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 2, required: true, onblur: '$(this).val($(this).val().toUpperCase())' }
		},
		{headerName: "색상영문명", field: "colorEnm", width: 200, cellClass: 'text-left',
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 50, required: true }
		},
		{headerName: "색상국문명", field: "colorKnm", width: 200, cellClass: 'text-left',
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 50, required: true }
		},
		{headerName: "RGB색상코드", field: "colorFile", width: 100, cellClass: 'text-center',
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 7, required: true, onblur: '$(this).val($(this).val().toUpperCase())' }
		},
		{headerName: "색상", width: 60, cellClass: 'text-center', editable: false,
			cellStyle : function(params){
				return { 'background-color': params.data.colorFile};
			}
		},
		{headerName: "그룹색상명", field: "colorGrpCd", width: 180, cellClass: 'text-left',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(groupColorCodeList), required: true },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(groupColorCodeNmList, params.value); }
		},
		{headerName: "그룹색상", width: 80, cellClass: 'text-center', editable: false,
			cellStyle : function(params){
				return { 'background-color': gagaAgGrid.lookupValue(groupColorCodeList, params.data.colorGrpCd)};
			}
		},
		{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); }
		},
		{headerName: "등록자", field: "regNm" , width: 100, cellClass: 'text-center', editable: false},
		{headerName: "등록일시", field: "regDt", width: 150, cellClass: 'text-center', editable: false,
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		},
		{headerName: "수정자", field: "updNm" , width: 100, cellClass: 'text-center', editable: false},
		{headerName: "수정일시", field: "updDt", width: 150, cellClass: 'text-center', editable: false,
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		}
		
	];

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

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

	//그리드 셀에디트 하는 화면에 옵션 추가해 주면 포커스 잃을 시 에디트 바로 중지(데이터 변경후 엔터 안쳐도 됩)
	gridOptions.stopEditingWhenGridLosesFocus = true;

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

	// 행추가
	$('#btnAddRow').on('click', function() {
		var data = { colorCd: null, colorEnm: null, colorKnm: null, colorFile: null, colorGrpCd: null, useYn: "Y" };
		gagaAgGrid.addRowData(gridOptions, data, "colorCd");
	});

	// 저장
	$('#btnSave').on('click', function() {
		// 변경된 데이터
		//var changedData = gridOptions.api.getSelectedRows();
		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 optCheck = false;
		var selIndex = 0;
		changedData.forEach(function(item, index) {
			
			if(optCheck) return false;
			
			if (item.crud == "C"){
				selIndex = index;
				loopRowData.forEach(function(loopItem, loopIndex) {
					if (selIndex != loopIndex){
						if(item.colorCd == loopItem.colorCd){
							optCheck = true;
							mcxDialog.alertC("색상코드가 중복됩니다. 확인해주세요.", {
								sureBtnText: "확인",
								sureBtnClick: function() {
									gridOptions.api.setFocusedCell(selIndex, "colorCd", null);
								}
							});
							return;
						}
					}
				});	
			}
			
			if(optCheck) return false;
				
			if (item.colorFile.indexOf("#") !=0 ) {
				optCheck = true;
				mcxDialog.alertC("RGB색상코드는 #으로 시작해주세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						gridOptions.api.setFocusedCell(index, "colorFile", null);
					}
				});
				return false;
			}
			
			if(optCheck) return false;
			
			if (item.colorFile.length != 7 ) {
				optCheck = true;
				mcxDialog.alertC("RGB색상코드는 #포함 7자리로 입력해주세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						gridOptions.api.setFocusedCell(index, "colorFile", null);
					}
				});
				return false;
			}
			if(optCheck) return false;
		});

		if(optCheck) {
			return false;
		}

		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(changedData);
				gagajf.ajaxJsonSubmit('/goods/color/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>
