<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsAdkeywordForm.html
 * @desc    : 광고키워드 관리
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.12.14   eskim     최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<!-- //메뉴 설명 -->
		
		<!-- 검색조건 영역 -->
		<div class="panelStyle">
			<!-- TITLE -->
			<div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 하나를 꼭 입력해 주세요.</h3>
			</div>
			<!-- //TITLE -->
			<form id="searchForm" name="searchForm" action="#" th:action="@{'/goods/ad/keyword/list'}" >
				<input type="hidden" id="searchGb" name="searchGb" />
			<div class="panelContent">	
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col width="10%"/>
						<col width="30%"/>
						<col width="10%"/>
						<col width="20%"/>
						<col width="10%"/>
						<col/>
					</colgroup>
					<tr>
						<th>광고키워드</th>
						<td>
							<input type="text" class="w200" name="adKeyword" id="adKeyword" maxlength="20"/>
						</td>
						<th>상품코드</th>
						<td>
							<input type="text" class="w200" name="goodsCd" id="goodsCd" maxlength="20"/>
						</td>
						<th>사용여부</th>
						<td>
							<select name="useYn">
								<option value="">[전체]</option>
								<option value="Y">[Y] Yes</option>
								<option value="N">[N] No</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>기간</th>
						<td colspan="5" id="sellTerms">
						</td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-gray btn-lg" onclick="$('#searchForm')[0].reset();">초기화</button>
						<button type="button" class="btn btn-base btn-lg" id="btnSearch">조회</button>
					</li>
				</ul>
			</div>	
			</form>
		</div>
		<!-- 검색조건 영역 -->
		<!-- 리스트 영역 -->
		<div class="panelStyle">
			<div id="gridKeywordList" style="width: 100%; height: 400px" class="ag-theme-balham"></div>
		</div>
		<!-- //리스트 영역 -->
		<form id="goodsAdkeywordForm" name="goodsAdkeywordForm" action="#" th:action="@{'/goods/ad/keyword/save'}">
		<input type="hidden" name="goodsList" />
		<!-- 등록/수정 -->
		<div class="panelStyle" >
			<ul>
				<li>
					<table class="w100p">
						<colgroup>
							<col style="width:49%;"/>
							<col style="width:1%;"/>
							<col/>
						</colgroup>
						<tr>
							<td class="vaT">
								<table class="frmStyle" aria-describedby="등록/수정 폼">
									<colgroup>
										<col style="width:15%;"/>
										<col style="width:35%;"/>
										<col style="width:15%;"/>
										<col/>
									</colgroup>
									<tr>
										<th>일련번호</th>
										<td>
											<input type="text" class="w100" name="adKeywordSq" placeholder="자동부여" readonly="readonly"/>
										</td>
										<th>사용여부</th>
										<td>
											<input type="hidden" name="useYn"/>
											<label class="chkBox checked"><input type="checkbox" name="chkUseYn" checked="checked" value="Y"/>사용</label>
										</td>
									</tr>
									<tr>
										<th>광고키워드<i class="required" title="필수"></i></th>
										<td colspan="3">
											<input type="text"  class="w50p"  name="adKeyword" required="required" data-valid-name="광고키워드"  maxlength="20"/>
										</td>
									</tr>
									
									<tr>	
										<th>기간<i class="required" title="필수"></i></th>
										<td colspan="3">
											<input type="text" class="schDate w100" name="adKeywordStdt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
											~
											<input type="text" class="schDate w100" name="adKeywordEddt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
										</td>
									</tr>
								</table>
							</td>
							<td>&nbsp;</td>
							<td>
							<ul class="panelBar">
								<li class="left">
									<button type="button" class="btn btn-danger btn-lg" id="btnDeleteadKeywordGoods">삭제</button>
								</li>
								<li class="right">
									<button type="button" class="btn btn-base btn-lg" id="btnSearchExcel">엑셀조회</button>
									<button type="button" class="btn btn-info btn-lg" id="btnSearchGoods">상품조회</button>
								</li>
							</ul>
							<ul>
								<li id="gridKeywordGoodsList" style="width: 100%; height: 450px;" class="ag-theme-balham"></li>
							</ul>
							</td>
						</tr>
					</table>
				</li>
			</ul>
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="right">
					<button type="button" class="btn btn-info btn-lg" id="btnNew">신규</button>
					<button type="button" class="btn btn-success btn-lg" id="btnSave">저장</button>
				</li>
			</ul>
			<!-- //버튼 배치 영역 -->
		</div>
		<!-- 등록/수정 -->
		</form>
	</div>
<script th:inline="javascript">
/*<![CDATA[*/

	var columnKeywordDefs = [
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "광고키워드일련번호", field: "adKeywordSq", width: 150, cellClass: 'text-center'},
		{headerName: "광고키워드", field: "adKeyword", width: 300, cellClass: 'text-center', 
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "시작일", field: "adKeywordStdt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "종료일", field: "adKeywordEddt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "사용여부", field: "useYn", width:90, cellClass: 'text-center'},
		{headerName: "등록자", field: "regNm", width:90, cellClass: 'text-center'},
		{headerName: "등록일자", field: "regDt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "수정자", field: "updNm", width:90, cellClass: 'text-center'},
		{headerName: "수정일자", field: "updDt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		}
	];
	
	var columnKeywordeGoodsDefs = [
		{width: 40, cellClass: 'text-center', filter: false, rowDrag: true},
		{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: "CRUD", field: "crud", width: 75, minWidth: 75, hide: true},
		{headerName: "상품코드", field: "goodsCd", width: 140, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 350, cellClass: 'text-left'}
	];

	var gridKeywordOptions = gagaAgGrid.getGridOptions(columnKeywordDefs);
	var gridKeywordGoodsOptions = gagaAgGrid.getGridOptions(columnKeywordeGoodsDefs);

	gridKeywordGoodsOptions.rowSelection = 'multiple';
	gridKeywordGoodsOptions.suppressRowClickSelection = true;
	
	// 드래그
	gridKeywordGoodsOptions.rowDragManaged = true;
	gridKeywordGoodsOptions.stopEditingWhenGridLosesFocus = true;
	
	// Cell click
	gridKeywordOptions.onCellClicked = function(event) {
		if (event.colDef.field != 'adKeyword')
			return;
		
		$('#goodsAdkeywordForm input[name=adKeywordSq]').val(event.data.adKeywordSq);
		if (event.data.useYn == 'Y') {
			$('#goodsAdkeywordForm input:checkbox[name=chkUseYn]').prop('checked', true);
			$('#goodsAdkeywordForm input:checkbox[name=chkUseYn]').parent("label").addClass("checked");
		} else {
			$('#goodsAdkeywordForm input:checkbox[name=chkUseYn]').prop('checked', false);
			$('#goodsAdkeywordForm input:checkbox[name=chkUseYn]').parent("label").removeClass("checked");
		}
		
		$('#goodsAdkeywordForm input[name=adKeywordStdt]').val(event.data.adKeywordStdt);
		$('#goodsAdkeywordForm input[name=adKeywordEddt]').val(event.data.adKeywordEddt);
		$('#goodsAdkeywordForm input[name=adKeyword]').val(event.data.adKeyword);

		// 상품 목록
		fnGetadKeywordGoodsList(event.data.adKeywordSq);
	}

	// 검색
	$('#btnSearch').on('click', function() {
		if(!fnConditionCheck()) return;
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridKeywordOptions, '#searchForm');
	});
	
	//검색 조건 확인
	var fnConditionCheck = function(){
		var formId = '#searchForm';
		var form = document.searchForm;

		var searchFlag = false;
		var cnt = 0;

		for (i = 0; i < form.elements.length; i++ ) {
			var el = form.elements[i];

			if ($(el).prop("type") == "text" || ($(el).prop("type") == "select-one" && el.name != "search" && el.name != "pageSize")) {
				if (!(el.value == null || el.value == "")) {
					cnt++;
				}
			}
		}
			
		if(cnt > 0) searchFlag = true;

		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		
		var fromDate = $('#searchForm input[name=stDate]').val();
		var toDate = $('#searchForm input[name=edDate]').val();
		
		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {
			
			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				mcxDialog.alertC("기간 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function(){
						$('#searchForm input[name=stDate]').focus();
					}
				});
				return false;
			}

			if (fromDate > toDate) {
				mcxDialog.alertC("기간 시작일자는 종료일자 보다 클 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function(){
						$('#goodsAdkeywordForm input[name=stDate]').focus();
					}
				});
				return false;
			} 
		}

		return true;
	}
	
	// 상품 목록 조회
	var fnGetadKeywordGoodsList = function(adKeywordSq) {
		var actionUrl = '/goods/ad/keyword/goods/list/' + adKeywordSq;
		gagaAgGrid.fetch(actionUrl, gridKeywordGoodsOptions);
	}
	
	//엑셀 상품 조회
	$('#btnSearchExcel').on('click', function() {
		cfnExcelUploadPopup('goodsAdKeywordExcelUpload', 'goodsAdKeywordExcelUpload');
	});

	var goodsAdKeywordExcelUpload = function(result){
		var data = {procJob : result.procJob
			,excelFileNm : result.excelFileNm
		};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/goods/search/excelupload/save', jsonData, fnGoodsAdKeywordExcelUploadCallBack);
	}
	
	var fnGoodsAdKeywordExcelUploadCallBack = function(result){
		gagajf.ajaxJsonSubmit('/goods/excel/upload/goods/list', '', fnExcelSearchCallBack);
	}
	
	// 상품 엑셀 조회 콜백함수
	var fnExcelSearchCallBack = function(result) {
		if (result.goodsExcelList.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(gridKeywordGoodsOptions);
		$.each(result.goodsExcelList, function(idx, item) {
			var isInvalid = false;
			if (oldData != null && oldData.length != 0){
				oldData.forEach(function(oneData){
					if(oneData.goodsCd == item.goodsCd){
						isInvalid = true;
						return true;
					}
				});
				if(isInvalid){
					return isInvalid;
				}
			}
			gagaAgGrid.addRowData(gridKeywordGoodsOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "crud" : "C"});
		});
		return;
	};
	
	// 상품 조회 클릭 시
	$('#btnSearchGoods').on('click', function() {
		cfnOpenGoodsPopup('fnSearchCallBack');
	});

	// 상품 조회 콜백함수
	var fnSearchCallBack = function(result) {
		if (result.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(gridKeywordGoodsOptions);
		$.each(result, function(idx, item) {
			var isInvalid = false;
			if (oldData != null && oldData.length != 0){
				oldData.forEach(function(oneData){
					if(oneData.goodsCd == item.goodsCd){
						isInvalid = true;
						return true;
					}
				});
				if(isInvalid){
					return isInvalid;
				}
			}
			gagaAgGrid.addRowData(gridKeywordGoodsOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "crud" : "C"});
		});
		return;
	};
	
	// 상품 삭제
	$('#btnDeleteadKeywordGoods').on('click', function() {
		
		var selectedData = gridKeywordGoodsOptions.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		var removedData = gagaAgGrid.removeRowData(gridKeywordGoodsOptions, false);
		
		// 신규일 경우 화면에서만 삭제
		if (gagajf.isNull($('#goodsAdkeywordForm input[name=adKeywordSq]').val())){
			return;
		}
		
		var arrGoodsCd = [];
		$.each(selectedData, function(idx, item) {
			arrGoodsCd.push(item.goodsCd);
		});
		
		mcxDialog.confirm('삭제하시겠습니까?',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var data = {arrGoodsCd : arrGoodsCd
							,adKeywordSq : $('#goodsAdkeywordForm input[name=adKeywordSq]').val()
			};
			
			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/goods/ad/keyword/goods/delete', jsonData);
			}
		});
	});
	
	// 신규 버튼 클릭
	$("#btnNew").on("click", function(){
		$('#goodsAdkeywordForm')[0].reset();

		// 그리드 초기화
		gridKeywordGoodsOptions.api.setRowData(null);
		 
		$('#goodsAdkeywordForm input[name=adKeywordSq]').val('');
		$('#goodsAdkeywordForm input[name=adKeywordStdt]').val(_today);
		$('#goodsAdkeywordForm input[name=adKeywordEddt]').val(_today);
		
		$('#goodsAdkeywordForm input[name=chkUseYn]').prop("checked", true);
		$('#goodsAdkeywordForm input[name=chkUseYn]').parent("label").addClass("checked");
		
	});
	
	// 저장
	$("#btnSave").on("click", function() {
		// 날짜 체크
		if (gagajf.isNull($('#goodsAdkeywordForm input[name=adKeywordStdt]').val())) {
			mcxDialog.alertC('시작일자를 입력해 주세요.', {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsAdkeywordForm input[name=adKeywordStdt]').focus();
				}
			});
			return;
		}

		if (gagajf.isNull($('#goodsAdkeywordForm input[name=adKeywordEddt]').val())) {
			mcxDialog.alertC('종료일자를 입력해 주세요.', {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsAdkeywordForm input[name=adKeywordEddt]').focus();
				}
			});
			return;
		}
		var stDate = $('#goodsAdkeywordForm input[name=adKeywordStdt]').val().toDate('YYYY-MM-DD');
		var edDate = $('#goodsAdkeywordForm input[name=adKeywordEddt]').val().toDate('YYYY-MM-DD');

		if (stDate > edDate) {
			mcxDialog.alert("기간 종료일자는 시작일자 보다 클 수 없습니다.");
			return;
		}

		// validation
		if (!gagajf.validation('#goodsAdkeywordForm'))
			return false;

		$('#goodsAdkeywordForm input[name=useYn]').val($('#goodsAdkeywordForm input:checkbox[name=chkUseYn]').is(":checked") ? 'Y' : 'N');

		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var idx = 0;
				var goodsAllData = gagaAgGrid.getAllRowData(gridKeywordGoodsOptions);
				$.each(goodsAllData, function(idx, item) {
					item.dispOrd = idx+1;
				});
				
				var jsonGoodsData = JSON.stringify(goodsAllData);
				$('#goodsAdkeywordForm input[name=goodsList]').val(jsonGoodsData);
				
				var jsonData = JSON.stringify($('#goodsAdkeywordForm').serializeObject());
				gagajf.ajaxJsonSubmit($('#goodsAdkeywordForm').prop('action'), jsonData, function() {
					$('#btnSearch').trigger('click');
					$('#btnNew').trigger('click');
					
				});
			}
		});
	});
	
	$(document).ready(function() {
		
		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '기간', 'X');
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridKeywordList', gridKeywordOptions);
		gagaAgGrid.createGrid('gridKeywordGoodsList', gridKeywordGoodsOptions);
		
	});
	
/*]]>*/
</script>

</html>
