<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsDetailNoticeForm.html
 * @desc    : 상품상세공지관리 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.05   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/notice/list'}" >
				<input type="hidden" name="noticeType" value="G047_30"/>
				<input type="hidden" id="searchGb" name="searchGb" />
			<div class="panelContent">	
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col width="10%"/>
						<col width="40%"/>
						<col width="10%"/>
						<col/>
					</colgroup>
					<tr>
						<th>업체/브랜드</th>
						<td>
							<select name="supplyCompCd" id="supplyCompCd">
								<option value="" th:if="${sessionInfo.roleCd} != 'B000'">[전체]</option>
								<option th:if="${supplyCompList}" th:each="oneData, status : ${supplyCompList}" th:value="${oneData.cd}" th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
							<select name="brandCd" id="brandCd">
								<option value="">[전체]</option>
							</select>
						</td>
						<th>키워드</th>
						<td>
							<select name="search" id="search">
								<option value="searchGoodsCd">상품코드</option>
								<option value="searchGoodsNm">상품명</option>
								<option value="searchGoodsNum">품번</option>
								<option value="searchSupplyGoodsCd">업체상품코드</option>
							</select>
							<input type="text" class="w50p" name="condition" id="condition" maxlength="50"/>
						</td>
					</tr>
					<tr>
						<th>공지제목</th>
						<td>
							<input name="noticeTitle" type="text" maxlength="200"/>
						</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="3" 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="gridNoticeList" style="width: 100%; height: 400px" class="ag-theme-balham"></div>
		</div>
		<!-- //리스트 영역 -->
		<form id="goodsNoticeForm" name="goodsNoticeForm" action="#" th:action="@{'/goods/notice/save'}">
		<input type="hidden" name="urgentYn" value="N"/> <!-- 긴급공지여부 -->
		<input type="hidden" name="noticeType" value="G047_30"/>
		<input type="hidden" name="goodsList" />
		<!-- 등록/수정 -->
		<div class="panelStyle" >
			<ul>
				<li>
					<table class="w100p">
						<colgroup>
							<col style="width:65%;"/>
							<col style="width:1%;"/>
							<col/>
						</colgroup>
						<tr>
							<td>
								<table class="frmStyle" aria-describedby="등록/수정 폼">
									<colgroup>
										<col style="width:10%;"/>
										<col style="width:15%;"/>
										<col style="width:10%;"/>
										<col style="width:15%;"/>
										<col style="width:10%;"/>
										<col/>
									</colgroup>
									<tr>
										<th>공지번호</th>
										<td>
											<input type="text" class="w100" name="noticeSq" placeholder="자동부여" readonly="readonly"/>
										</td>
										<th>사용여부</th>
										<td>
											<input type="hidden" name="useYn"/>
											<label class="chkBox"><input type="checkbox" name="chkUseYn" checked="checked" value="Y"/>사용</label>
										</td>
										<th>공지기간<i class="required" title="필수"></i></th>
										<td>
											<input type="text" class="schDate w100" name="noticeStdt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
											~
											<input type="text" class="schDate w100" name="noticeEddt" maxlength="10" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
										</td>
									</tr>
									<tr>
										<th>제목<i class="required" title="필수"></i></th>
										<td colspan="5">
											<input type="text" name="noticeTitle" required="required" data-valid-name="제목"/>
										</td>
									</tr>
									<tr>
										<th>공지내용<i class="required" title="필수"></i></th>
										<td colspan="5">
											<textarea class="textareaR4" name="noticeContent" id="noticeContent"></textarea>
										</td>
									</tr>
								</table>
							</td>
							<td>&nbsp;</td>
							<td>
							<ul class="panelBar">
								<li class="left">
									<button type="button" class="btn btn-danger btn-lg" id="btnDeleteNoticeGoods">삭제</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="gridNoticeGoodsList" 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 type="text/javascript" src="/ux/plugins/summernote/summernote.js?v=2020103001"></script>
<script type="text/javascript" src="/ux/plugins/gaga/gaga.summernote.js?v=2021053101"></script>
<script th:inline="javascript">
/*<![CDATA[*/

	var columnNoticeDefs = [
		{headerName: 'No', width: 60, cellClass: 'text-center', valueGetter: function(params) { return params.node.rowIndex + 1 }},
		{headerName: "공지번호", field: "noticeSq", width: 90, cellClass: 'text-center'},
		{headerName: "공지제목", field: "noticeTitle", width: 500,
			cellRenderer: function(params) { return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "공지시작일", field: "noticeStdt", width:150, cellClass: 'text-center',
			cellRenderer: function(params) { return gagaAgGrid.toDateFormat(params.value); }
		},
		{headerName: "공지종료일", field: "noticeEddt", 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); }
		}
	];
	
	var columnNoticeGoodsDefs = [
		{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: 260, cellClass: 'text-left'}
	];

	var gridNoticeOptions = gagaAgGrid.getGridOptions(columnNoticeDefs);
	var gridNoticeGoodsOptions = gagaAgGrid.getGridOptions(columnNoticeGoodsDefs);

	gridNoticeGoodsOptions.rowSelection = 'multiple';
	gridNoticeGoodsOptions.suppressRowClickSelection = true;
	
	// Cell click
	gridNoticeOptions.onCellClicked = function(event) {
		if (event.colDef.field != 'noticeTitle')
			return;
		
		$('#goodsNoticeForm input[name=noticeSq]').val(event.data.noticeSq);
		if (event.data.useYn == 'Y') {
			$('#goodsNoticeForm input:checkbox[name=chkUseYn]').prop('checked', true);
			$('#goodsNoticeForm input:checkbox[name=chkUseYn]').parent("label").addClass("checked");
		} else {
			$('#goodsNoticeForm input:checkbox[name=chkUseYn]').prop('checked', false);
			$('#goodsNoticeForm input:checkbox[name=chkUseYn]').parent("label").removeClass("checked");
		}
		
		$('#goodsNoticeForm input[name=noticeStdt]').val(event.data.noticeStdt);
		$('#goodsNoticeForm input[name=noticeEddt]').val(event.data.noticeEddt);
		$('#goodsNoticeForm input[name=noticeTitle]').val(event.data.noticeTitle);

		// 공지내용. Summernote에 값 세팅
		gagaSn.setContents('#noticeContent', event.data.noticeContent);

		// 상품 목록
		fnGetNoticeGoodsList(event.data.noticeSq);
	}

	// 검색
	$('#btnSearch').on('click', function() {
		if(!fnConditionCheck()) return;
		gagaAgGrid.fetch($('#searchForm').prop('action'), gridNoticeOptions, '#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(){
						$('#goodsNoticeForm input[name=stDate]').focus();
					}
				});
				return false;
			} 
		}

		return true;
	}
	
	// 상품 목록 조회
	var fnGetNoticeGoodsList = function(noticeSq) {
		var actionUrl = '/goods/notice/goods/list/' + noticeSq;
		gagaAgGrid.fetch(actionUrl, gridNoticeGoodsOptions);
	}
	
	//업체변경시
	$('#searchForm select[name=supplyCompCd]').on('change', function() {
		var actionUrl = '/renderer/supplyCompany/brand/list/' + $(this).val();

		if(sessRoleCd == "G001_B000"){
			actionUrl = '/renderer/brand/AuthBrandlist';
		}
		$("#searchForm select[name=brandCd] option:gt(0)").remove();

		cfnCreateCombo(actionUrl, $('#searchForm select[name=brandCd]'), "[전체]", "");
	});	
	
	//엑셀 상품 조회
	$('#btnSearchExcel').on('click', function() {
		cfnExcelUploadPopup('goodsNoticeExcelUpload', 'goodsNoticeExcelUpload');
	});

	var goodsNoticeExcelUpload = function(result){
		var data = {procJob : result.procJob
			,excelFileNm : result.excelFileNm
		};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/goods/search/excelupload/save', jsonData, fnGoodsNoticeExcelUploadCallBack);
	}
	
	var fnGoodsNoticeExcelUploadCallBack = function(result){
		gagajf.ajaxJsonSubmit('/goods/excel/upload/goods/list', '', fnExcelSearchCallBack);
	}
	
	// 상품 엑셀 조회 콜백함수
	var fnExcelSearchCallBack = function(result) {
		if (result.goodsExcelList.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(gridNoticeGoodsOptions);
		$.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(gridNoticeGoodsOptions, {"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(gridNoticeGoodsOptions);
		$.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(gridNoticeGoodsOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "crud" : "C"});
		});
		uifnPopupClose('popupGoods');
		return;
	};
	
	// 상품 삭제
	$('#btnDeleteNoticeGoods').on('click', function() {
		
		var selectedData = gridNoticeGoodsOptions.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		// 신규 상세 공지일경우 화면에서만 삭제
		if (gagajf.isNull($('#goodsNoticeForm input[name=noticeSq]').val())){
			var removedData = gagaAgGrid.removeRowData(gridNoticeGoodsOptions, false);
			return;
		}
		
		mcxDialog.confirm('삭제하시겠습니까?',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var removedData = gagaAgGrid.removeRowData(gridNoticeGoodsOptions, false);
				var arrGoodsCd = [];
				$.each(selectedData, function(idx, item) {
					arrGoodsCd.push(item.goodsCd);
				});
				
				var data = {arrGoodsCd : arrGoodsCd
							,noticeSq : $('#goodsNoticeForm input[name=noticeSq]').val()
			};
			
			var jsonData = JSON.stringify(data);
			gagajf.ajaxJsonSubmit('/goods/notice/goods/delete', jsonData);
			}
		});
	});
	
	// 신규 버튼 클릭
	$("#btnNew").on("click", function(){
		$('#goodsNoticeForm')[0].reset();
		
		// 공지내용. Summernote에 값 세팅
		gagaSn.setContents('#noticeContent', "");

		// 그리드 초기화
		gridNoticeGoodsOptions.api.setRowData(null);
		 
		$('#goodsNoticeForm input[name=noticeSq]').val('');
		$('#goodsNoticeForm input[name=noticeStdt]').val(_today);
		$('#goodsNoticeForm input[name=noticeEddt]').val(_today);
	});
	
	// 저장
	$("#btnSave").on("click", function() {
		// 날짜 체크
		if (gagajf.isNull($('#goodsNoticeForm input[name=noticeStdt]').val())) {
			mcxDialog.alertC('공지시작일자를 입력해 주세요.', {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsNoticeForm input[name=noticeStdt]').focus();
				}
			});
			return;
		}

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

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

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

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

		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				
				//var goodsAllData = gagaAgGrid.getAllRowData(gridNoticeGoodsOptions);
				var goodsAllData = gagaAgGrid.getChangedData(gridNoticeGoodsOptions);
				
				var jsonGoodsData = JSON.stringify(goodsAllData);
				$('#goodsNoticeForm input[name=goodsList]').val(jsonGoodsData);
				
				var jsonData = JSON.stringify($('#goodsNoticeForm').serializeObject());
				gagajf.ajaxJsonSubmit($('#goodsNoticeForm').prop('action'), jsonData, function() {
					$('#btnSearch').trigger('click');
					$("#btnNew").trigger('click');
					//fnGetNoticeGoodsList($('#goodsNoticeForm input[name=noticeSq]').val());
					
				});
			}
		});
	});
	
	$(document).ready(function() {
		
		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '공지일', 'X');
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridNoticeList', gridNoticeOptions);
		gagaAgGrid.createGrid('gridNoticeGoodsList', gridNoticeGoodsOptions);
		
		// Create a summernote
		var snOptions = gagaSn.getToolbarOptions('media');
		gagaSn.createSummernote(snOptions, '#noticeContent');
		
	});
	
/*]]>*/
</script>

</html>
