<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : NotiinfoForm.html
 * @desc    : 정보고시 목록
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.10.19   eskim       최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		<!-- 테이블 영역 -->
		<div class="panelStyle">
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/notiInfo/list'}" >
			<input type="hidden" id="niClsfCd" name="niClsfCd"/>
			<div class="boxTitle"></div>
			<ul class="boxContent">
				<li class="boxContentBtnT">
					<span style="padding:5.5px 15px; background:#e9ecfb; border-top:1px solid #dae0fd; border-bottom:0.5px solid #dae0fd;">업체</span>
					<select name="supplyCompCd" id="supplyCompCd">
						<!-- <option value="1003" selected="selected">한세드림</option>
						<option value="1004">(주)에프알제이</option>
						<option value="1005">(주)엠케이트렌드</option> -->
						<option value="3" selected="selected">한세드림</option>
						<option value="4">(주)에프알제이</option>
						<option value="5">(주)엠케이트렌드</option>
						<option value="E" >입점</option>
					</select>
				</li>
				<li class="boxContentTop">
					<table class="w100p">
						<colgroup>
							<col style="width:45%;"/>
							<col style="width:2%;"/>
							<col/>
							<col style="width:10%;"/>
						</colgroup>
						<tr>
							<td><h4>고시분류</h4></td>
							<td>&nbsp;</td>
							<td><h4>고시항목</h4></td>
							<td class="aR padB10"><button type="button" class="btn btn-success btn-lg" id="btnNotiItemlSave">저장</button></td>
						</tr>
						<tr>
							<td><div id="gridNotiList" style="width: 100%; height: 600px;" class="ag-theme-balham"></div></td>
							<td>&nbsp;</td>
							<td colspan="2"><div id="gridNotiItemlList" style="width: 100%; height: 600px;" class="ag-theme-balham"></div></td>
						</tr>
					</table>
				</li>
			</ul>
			</form>
		</div>
		<!-- //테이블 영역 -->
	</div>
<script th:inline="javascript">
/*<![CDATA[*/
	var useYnList = gagajf.convertToArray([[${useYnList}]]);
	var niItemCdList = gagajf.convertToArray([[${niItemCdList}]]);
	// specify the columns
	var columnNotiDefs = [
		/* {width: 40, minWidth: 40, cellClass: 'text-right', headerCheckboxSelection: true, checkboxSelection: true, filter: false}, */
		{headerName: "CRUD", field: "crud", width: 75, minWidth: 75, hide: true},
		//{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "고시분류코드", field: "niClsfCd", width: 150, cellClass: 'text-center',editable: true,
			editable : function(params){return params.data.crud=='C' ? true : false;},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 50, required: true },
			cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}	
		},
		{headerName: "상품 정보고시명", field: "niClsfNm", width: 440, cellClass: 'text-center',editable: true,
			editable : function(params){return params.data.crud=='C' ? true : false;}
		},
		{headerName: "등록일자", field: "regDt" , width: 150, cellClass: 'text-center', hide: true},
		{headerName: "수정일자", field: "udtDt", width: 150, cellClass: 'text-center', hide: true}
	];
	
	var columnNotiItemlDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-right', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "CRUD", field: "crud", width: 75, minWidth: 75, hide: true},
		{headerName: "항목명", field: "niItemCd" , width: 200, cellClass: 'text-left' ,editable: true,
			editable : function(params){return params.data.crud=='C' ? true : false;},
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(niItemCdList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(niItemCdList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(niItemCdList, params.newValue); }
		},
		{headerName: "내용", field: "niContent" , width: 350, cellClass: 'text-left' ,editable: true,
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 500, required: true }
		},
		{headerName: "노출순서", field: "dispOrd" , width: 110, cellClass: 'text-center',editable: true,
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 3, validType: 'integer', required: true }
		},
		{headerName: "등록일자", field: "regDt" , width: 150, cellClass: 'text-center', hide: true},
		{headerName: "수정일자", field: "udtDt", width: 150, cellClass: 'text-center', hide: true},
		{headerName: "niClsfCd", field: "niClsfCd", hide: true},
		{headerName: "supplyCompCd", field: "supplyCompCd", hide: true}
	];

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

	// Add on options
	gridNotiItemlOptions.rowSelection = 'multiple';
	gridNotiItemlOptions.suppressRowClickSelection = true;
	
	//Row Click
	gridNotiOptions.onCellClicked = function(event) {
		var niClsfCd = event.data.niClsfCd;
		if (event.colDef.field == "niClsfCd" && event.data.crud != "C"){
			fnNotiItemlSearch(niClsfCd);
		}
	}
	
	// 조회
	var fnSearch = function() {

		var formId = '#searchForm';
		$('#searchForm input[name=niClsfCd]').val('');
		
		if (gagajf.isNull($('#searchForm select[name=supplyCompCd]').val())){
			mcxDialog.alertC("업체를 선택해 주세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#searchForm select[name=supplyCompCd]').focus();
				}
			});
			return;
		}

		gagaAgGrid.fetch($(formId).prop('action'), gridNotiOptions, formId);
		fnNotiItemlSearch('01');	// 임의값을 넣어서 고시항목 초기화
		
	}

	// 상세 조회
	var fnNotiItemlSearch = function(niClsfCd){

		$('#searchForm input[name=niClsfCd]').val(niClsfCd);
		
		var actionUrl = "/goods/notiInfo/item/list";
		gagaAgGrid.fetch(actionUrl, gridNotiItemlOptions, '#searchForm');
	}

	// 고시항목 행추가
	$('#btnNotiItemlAddRow').on('click', function() {
		
		if ($('#searchForm input[name=niClsfCd]').val() == ""){
			mcxDialog.alert("고시분류 선택 후 추가해 주세요.");
			return;
		}
		var iRow = gridNotiItemlOptions.api.getDisplayedRowCount();
		
		var allRowData = gagaAgGrid.getAllRowData(gridNotiItemlOptions);
		var maxDispOrd = 0;
		allRowData.forEach(function(item, index) {
			if (item.dispOrd > maxDispOrd){
				maxDispOrd = item.dispOrd;
			}
		});
		
		var niClsfCd = $('#searchForm input[name=niClsfCd]').val();
		var supplyCompCd = $('#searchForm select[name=supplyCompCd]').val();
		
		var data = { crud: "C", niItemCd: "", niContent: "", dispOrd: Number(maxDispOrd)+1, niClsfCd: niClsfCd, supplyCompCd: supplyCompCd};
		
		//그리드 마지막에 추가해야함
		gridNotiItemlOptions.api.updateRowData({add: [data], addIndex: 0});

	});
	
	// 고시항목 행삭제
	$('#btnNotiItemlDeleteRow').on('click', function() {
		
		var selectedData = gagaAgGrid.selectedRowData(gridNotiItemlOptions);
		var iTotalCnt = 0;
		var iCnt = 0;
		selectedData.forEach(function(item, index) {
			iTotalCnt ++;
			if (item.crud == "C"){
				gridNotiItemlOptions.api.updateRowData({remove: [item]});	
				iCnt ++;
			}
		});
		
		if (iTotalCnt > 0 && iTotalCnt == iCnt){
			return;
		}
		
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		mcxDialog.confirm('삭제하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				//화면에서 삭제
				var removedData = gagaAgGrid.removeRowData(gridNotiItemlOptions, false);
				
				var jsonData = JSON.stringify(removedData);
				gagajf.ajaxJsonSubmit('/goods/notiInfo/item/delete', jsonData, fnNotiItemlCollBack);
			}
		});
	});
	
	// 고시항목 저장
	$('#btnNotiItemlSave').on('click', function() {
		
		var checkFlag = false;
		
		var selectedData = gagaAgGrid.selectedRowData(gridNotiItemlOptions);
		
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		// Validation
		if (!gagaAgGrid.validation(gridNotiItemlOptions, selectedData))
			return;
		
		//항목 중복 여부 확인
		var allRowData = gagaAgGrid.getAllRowData(gridNotiItemlOptions);
		var loopRowData = gagaAgGrid.getAllRowData(gridNotiItemlOptions);
		var selIndex = 0;
		
		selectedData.forEach(function(item, index) {
		
			if(checkFlag) return false;
			
			if (item.crud == "C"){
				selIndex = index;
				loopRowData.forEach(function(loopItem, loopIndex) {
					if (selIndex != loopIndex){
						if(item.niItemCd == loopItem.niItemCd){
							checkFlag = true;
							mcxDialog.alertC("항목명이 중복됩니다. 확인해주세요.", {
								sureBtnText: "확인",
								sureBtnClick: function() {
									gridNotiItemlOptions.api.setFocusedCell(selIndex, "niItemCd", null);
								}
							});
							return;
						}
					}
				});	
			}
		});
		
		if(checkFlag) return false;
		
		
		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var jsonData = JSON.stringify(selectedData);
				gagajf.ajaxJsonSubmit('/goods/notiInfo/item/save', jsonData, fnNotiItemlCollBack);
			}
		});
	});
	
	var fnNotiItemlCollBack = function(){

		fnNotiItemlSearch($('#searchForm input[name=niClsfCd]').val());
	}
	
	$("#supplyCompCd").on("change", function(){
		fnSearch();
	});
	
	$(document).ready(function() {

		// Create a agGrid
		gagaAgGrid.createGrid('gridNotiList', gridNotiOptions);
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridNotiItemlList', gridNotiItemlOptions);
		
		fnSearch();

	});
/*]]>*/
</script>
</html>