<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : GoodsPriceReservePopupForm.html
 * @desc    : 상품 가격 예약등록 화면
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.13   eskim       최초 작성
 *******************************************************************************
 -->	
	<div class="modalPopup" data-width="850" >
		<div class="panelStyle">
			<div class="panelTitle">
				<h2>상품가격예약</h2>
				<button type="button" class="close" onclick="uifnPopupClose('popupGoodsPriceReserve')"><i class="fa fa-times"></i></button>
			</div>
			<form id="goodsPriceRsvtForm" name="goodsPriceRsvtForm" >
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:20%;"/>
						<col style="width:10%;"/>
						<col/>
					</colgroup>
					<tr>
						<th>상품예약가격<em class="required" title="필수"></em></th>
						<td><input type="text" class="w100p aR" id="resGoodsPrice" name="resGoodsPrice" maxlength="10" data-valid-type="numeric" /></td>
						<th>예약일시<em class="required" title="필수"></em></th>
						<td>
							<input name="applyStYMD" id="applyStYMD" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="예약시작일" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
							<select name="applyStHH" id="applyStHH" required="required" data-valid-name="예약 시작시간">
								<th:block th:each="num, index  : ${#numbers.sequence(0,23)}">
								<option  th:value="${#numbers.formatInteger(num,2)}" th:text="|${#numbers.formatInteger(num,2)}시|" >시간</option>
								</th:block>
							</select>
							<input name="applyStdt" id="applyStdt" type="hidden" />
							~
							<input name="applyEdYMD" id="applyEdYMD" type="text" class="w80 schDate" maxlength="10" required="required" data-valid-name="예약 종료일" th:value="${#calendars.format(#calendars.createNow(), 'yyyy-MM-dd')}"/>
							<select name="applyEdHH" id="applyEdHH" required="required" data-valid-name="예약 종료시간">
								<th:block th:each="num: ${#numbers.sequence(0,23)}">
								<option  th:value="${#numbers.formatInteger(num,2)}"  th:text="|${#numbers.formatInteger(num,2)}시|" th:selected="${#numbers.formatInteger(num,2)}==23 ? 'true'">시간</option>
								</th:block>
							</select>
							<input name="applyEddt" id="applyEddt" type="hidden" />
						</td>
					</tr>
				</table>
			</div>
			<ul class="panelBar">
				<li class="left">
					<button type="button" class="btn btn-danger btn-lg" id="btnDeleteGoodsPriceRsvt">상품삭제</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>
			<div id="gridGoodsPriceRsvtList" style="width: 100%; height: 400px;" class="ag-theme-balham"></div>
			<ul class="panelBar">
				<li class="right">
					<button type="button" class="btnRight btn btn-base btn-lg" id="btnSaveGoodsPriceRsvt">적용</button>
				</li>
			</ul>
			</form>	
		</div>
	</div>
<script th:inline="javascript">
/*<![CDATA[*/
	
	var rsvtGoodsPriceColumnDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: 'No', width: 50, cellClass: 'text-center',valueGetter: function(params) { return params.node.rowIndex+1}},
		{headerName: "상품코드", field: "goodsCd", width: 140, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 330, cellClass: 'text-left'},
		{headerName: "정상가", field: "listPrice" , width: 120, cellClass: 'text-right'
			,valueFormatter: function(params) {return params.value.addComma();}
		},
		{headerName: "현재판매가", field: "currPrice", width: 120, cellClass: 'text-right'
			,valueFormatter: function(params) {return params.value.addComma();},
		},
		{headerName: "상품타입", field: "goodsType", width: 120, hide:true}
		
	];
	
	// Get GridOptions
	var rsvtGoodsPriceGridOptions = gagaAgGrid.getGridOptions(rsvtGoodsPriceColumnDefs);
	rsvtGoodsPriceGridOptions.enableBrowserTooltips = true;
	
	// 중복 선택 가능
	rsvtGoodsPriceGridOptions.rowSelection = 'multiple';
	rsvtGoodsPriceGridOptions.suppressRowClickSelection = true;
	//rsvtGoodsPriceGridOptions.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.

	// 상품 조회 클릭 시
	$('#btnSearchGoods').on('click', function() {
		cfnOpenGoodsPopup('fnSearchGoods');
	});

	// 상품 조회 콜백함수
	var fnSearchGoods = function(result) {
		if (result.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(rsvtGoodsPriceGridOptions);
		$.each(result, function(idx, item) {
			var isInvalid = false;
			if(item.goodsType != 'G056_N'){
				return true;
			}
			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(rsvtGoodsPriceGridOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "listPrice" : item.listPrice, "currPrice" : item.currPrice, "goodsType" : item.goodsType});
		});
		uifnPopupClose('popupGoods');
		return false;
	};

	// 저장 클릭 시
	$('#btnSaveGoodsPriceRsvt').on('click', function() {

		var allRowData = gagaAgGrid.getAllRowData(rsvtGoodsPriceGridOptions);

		if(allRowData.length == 0){
			mcxDialog.alertC("상품을 조회한 후 추가해주세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
				}
			});
			return;
		}

		if(gagajf.isNull($("#goodsPriceRsvtForm input[name=resGoodsPrice]").val())) {
			mcxDialog.alertC("상품 예약가격을 입력하세요.",{
				sureBtnText: "확인",
				sureBtnClick: function() {
					$("#goodsPriceRsvtForm input[name=resGoodsPrice]").focus();
				}
			});
			return false;
		}

		var fromDate = $('#goodsPriceRsvtForm input[name=applyStYMD]').val();
		var toDate = $('#goodsPriceRsvtForm input[name=applyEdYMD]').val();

		if (gagajf.isNull(fromDate)) {
			mcxDialog.alertC("예약 시작일자를 입력하세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsPriceRsvtForm input[name=applyStYMD]').focus();
				}
			});
			return false;
		}

		if (gagajf.isNull(toDate)) {
			mcxDialog.alertC("예약  종료일자를 입력하세요.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsPriceRsvtForm input[name=applyEdYMD]').focus();
				}
			});
			return false;
		}

		if (fromDate > toDate) {
			mcxDialog.alertC("예약 시작일자는 종료일자 보다 클 수 없습니다.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsPriceRsvtForm input[name=applyEdYMD]').focus();
				}
			});
			return false;
		}
		
		var optCheck = false;
		$.each(allRowData, function(index, item) {
			if (item.listPrice < $("#goodsPriceRsvtForm input[name=resGoodsPrice]").val()){
				optCheck = true;
				mcxDialog.alertC("가격예약 상품중 정상가가 예약가 보다 낮은 상품이 상품이 존재합니다.<br/>확인해 주세요", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						rsvtGoodsPriceGridOptions.api.setFocusedCell(index, "goodsCd", null);
					}
				});	
				return false;
			}
			
			if ("G056_N"  != item.goodsType ){
				optCheck = true;
				mcxDialog.alertC("일반상품이 아닌 상품은 가격예약을 할 수 없습니다.<br/>확인해 주세요", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						rsvtGoodsPriceGridOptions.api.setFocusedCell(index, "goodsCd", null);
					}
				});	
				return false;
			}
		});

		if (optCheck) return false;
		
		var applyStdt = $('#goodsPriceRsvtForm input[name=applyStYMD]').val().replaceAll("-","") +
		$('#goodsPriceRsvtForm select[name=applyStHH]').val() + "0000";

		var applyEddt = $('#goodsPriceRsvtForm input[name=applyEdYMD]').val().replaceAll("-","") +
		$('#goodsPriceRsvtForm select[name=applyEdHH]').val() +"5959";

		$('#goodsPriceRsvtForm input[name=applyStdt]').val(applyStdt);
		$('#goodsPriceRsvtForm input[name=applyEddt]').val(applyEddt);

		if ($('#goodsPriceRsvtForm input[name=applyStdt]').val() > $('#goodsPriceRsvtForm input[name=applyEddt]').val()) {
			mcxDialog.alertC("예약 시작일시는 종료일시 보다 클 수 없습니다.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsPriceRsvtForm input[name=applyEdYMD]').focus();
				}
			});
			return false;
		}

		var toDateStr = new Date().format("YYYYMMDDHHmmss");

		if (toDateStr >= applyStdt){
			mcxDialog.alertC("예약 시작일시는 현재일시 보다 작거나 같을 수 없습니다.",  {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsPriceRsvtForm input[name=applyStYMD]').focus();
				}
			});
			return false;
		}

		if (toDateStr >= applyEddt){
			mcxDialog.alertC("예약 종료일시는 현재일시 보다 작거나 같을 수 없습니다.", {
				sureBtnText: "확인",
				sureBtnClick: function() {
					$('#goodsPriceRsvtForm input[name=applyEdYMD]').focus();
				}
			});
			return false;
		}

		mcxDialog.confirm('저장하시겠습니까?',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var arrGoodsCd = [];
				var arrEndGoodsPrice = [];
				allRowData.forEach(function(item, index) {
					arrGoodsCd.push(item.goodsCd);
					arrEndGoodsPrice.push(item.currPrice);
				});
				
				var data = {resGoodsPrice : $('#goodsPriceRsvtForm input[name=resGoodsPrice]').val()
							, applyStdt : $('#goodsPriceRsvtForm input[name=applyStdt]').val()
							, applyEddt : $('#goodsPriceRsvtForm input[name=applyEddt]').val()
							, arrGoodsCd : arrGoodsCd
							, arrEndGoodsPrice : arrEndGoodsPrice
				};

				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/goods/price/reserve/save', jsonData, fnGoodsPriceRsvtListFormClose);

			}
		});
	});

	// 조회상품 삭제
	$('#btnDeleteGoodsPriceRsvt').on('click', function() {
		var selectedData = rsvtGoodsPriceGridOptions.api.getSelectedRows();
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}

		//화면에서 삭제
		var removedData = gagaAgGrid.removeRowData(rsvtGoodsPriceGridOptions, false);
	});
	
	//엑셀 상품 조회
	$('#btnSearchExcel').on('click', function() {
		cfnExcelUploadPopup('goodsPriceRsvtExcelUpload', 'goodsPriceRsvtExcelUpload');
	});

	var goodsPriceRsvtExcelUpload = function(result){
		var data = {procJob : result.procJob
			,excelFileNm : result.excelFileNm
		};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/goods/search/excelupload/save', jsonData, fnRsvtGoodsPriceExcelUploadCallBack);
	}

	var fnRsvtGoodsPriceExcelUploadCallBack = function(result){
		gagajf.ajaxJsonSubmit('/goods/excel/upload/goods/list', '', fnExcelSearchCallBack);
	}

	var fnExcelSearchCallBack = function(result){
		if (result.goodsExcelList.length < 1) return;
		var oldData = gagaAgGrid.getAllRowData(rsvtGoodsPriceGridOptions);
		$.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;
				}
			}
			if("G056_N" == item.goodsType){
				gagaAgGrid.addRowData(rsvtGoodsPriceGridOptions, {"goodsCd" : item.goodsCd, "goodsNm" : item.goodsNm, "listPrice" : item.listPrice, "currPrice" : item.currPrice, "goodsType" : item.goodsType});	
			}
			
		});
		return;
	}

	//창종료
	var fnGoodsPriceRsvtListFormClose = function(){
		uifnPopupClose('popupGoodsPriceReserve');
		fnGoodsPriceResDeleteCollBack();
	}

	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('gridGoodsPriceRsvtList', rsvtGoodsPriceGridOptions);
	});

/*]]>*/
</script>
</html>