<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : OrderSamplePopupForm.html
 * @desc    : 주문 샘플 데이터 생성 팝업 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.01.30   card007     최초 작성
 *******************************************************************************
 -->
<div class="modalPopup" data-width="1200" id="popupOrderSample">
	<div class="panelStyle">
		<!-- TITLE -->
		<div class="panelTitle">
			<strong th:text="${'주문 샘플 데이터 생성'}"></strong>
			<button type="button" class="close" onclick="uifnPopupClose('popupOrderSample');"><em class="fa fa-times"></em></button>
		</div>
		<!-- //TITLE -->
		
		<!-- CONTENT -->
		<div class="panelContent">
			<form id="orderSamplePopupForm" name="orderSamplePopupForm" action="#" th:action="@{'/order/sample/create'}" th:method="post">
				<table class="frmStyle" aria-describedby="등록폼">
					<colgroup>
						<col style="width:7%;"/>
						<col style="width:26%;"/>
						<col style="width:7%;"/>
						<col style="width:26%;"/>
						<col style="width:7%;"/>
						<col/>
					</colgroup>
					<tbody>
						<tr>
							<th>회원번호</th>
							<td>
								<input class="w200" type="text" name="custNo" id="custNo"/>
								<button type="button" class="btn btn-info btn-lg" id="btnOrderSearch" onclick="fnApplyCustomerInfo()">적용</button>
							</td>
							<th>주문자명</th>
							<td>
								<input type="text" name="ordNm" id="ordNm"/>
							</td>
							<th>핸드폰번호</th>
							<td>
								<input type="text" name="ordPhnno" id="ordPhnno"/>
							</td>
						</tr>
						<tr>
							<th>전화번호</th>
							<td>
								<input type="text" name="ordTelno" id="ordTelno"/>
							</td>
							<th>이메일</th>
							<td colspan="3">
								<input type="text" name="ordEmail" id="ordEmail"/>
							</td>
						</tr>
						<tr>
							<th>배송지</th>
							<td colspan="5">
								<input type="text" name ="recipZipcode" id="recipZipcode" class="w100" readonly="readonly"/>
								<button type="button" class="btn btn-info" onclick="fnOpenDaumAddr('delivery');">우편번호찾기</button>
								<input type="text" name ="recipBaseAddr" id="recipBaseAddr" class="w300"/>
								<input type="text" name ="recipDtlAddr" id="recipDtlAddr" class="w300"/>
							</td>
						</tr>
					</tbody>
				</table>
			</form>
		</div>
		<!-- //CONTENT -->

		<!-- Grid -->
		<ul class="panelBar">
			<li class="left">
				<button type="button" class="btn btn-danger btn-lg" onclick="fnGoodsDeleteRow();">행삭제</button>
			</li>
			<li class="right">
				<button type="button" class="btn btnRight btn-base btn-lg" onclick="fnOpenGoodsPopup();">주문상품추가</button>
			</li>
		</ul>
		<div id="gridGoodsList" style="height: 390px;" class="ag-theme-balham lh60"></div>
		<!-- //Grid -->

		<!-- 버튼 배치 영역 -->
		<ul class="panelBar">
			<li class="right">
				<button type="button" class="btn btn-info btn-lg" id="btnCreateOrderSample">저장</button>
			</li>
		</ul>
		<!-- //버튼 배치 영역 -->
	</div>
</div>

<script th:inline="javascript">
/*<![CDATA[*/
	var sessRoleCd = [[${sessionInfo.roleCd}]];
	var goodsStatList = gagajf.convertToArray([[${goodsStatList}]]);
	var formalGbList = gagajf.convertToArray([[${formalGbList}]]);
	var seasonList = gagajf.convertToArray([[${seasonList}]]);
	var columnDefs = [];
	columnDefs = [
		{width: 40, minWidth: 40, cellClass: 'text-right', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: 'No', width: 60, cellClass: 'text-center',
			valueGetter: function(params) { return cfnGridNumner('searchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "이미지", field: "sysImgNm", width: 100, height: 60, cellClass: 'text-center'
			,cellRenderer: function(params) {
				return '<img width="60" src="'+ _goodsUrl+ "/" + params.value + '" alt="" onclick="cfnOpenImagePreViewPopup(\'goodsImgView\', \''+ _goodsUrl+ "/" + params.value +'\')" onerror="this.src=\'/image/no.gif\';"/>';
			}
		},
		{headerName: "상품코드", field: "goodsCd", width: 140, cellClass: 'text-center'},
		{headerName: "상품명", field: "goodsNm", width: 200, cellClass: 'text-left'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "구성상품코드", field: "compsGoodsCd", width: 140, cellClass: 'text-center'},
		{headerName: "판매가능재고", field: "stockQtySum", width: 120, cellClass: 'text-right',
			valueFormatter: function(params) {	return params.value.addComma();},
			cellStyle : function(params){
				if ("00" == params.data.goodsStat  || "10" == params.data.goodsStat || "20" == params.data.goodsStat || "30" == params.data.goodsStat) {
					return;
				}
				var color = "";
				if (params.value <= 0){
					color = '#ff96689c';
				}
				return { 'background-color': color};
			}
		},
		{
			headerName		: "주문옵션"
			, field			: "optCd"
			, width			: 100
			, cellClass		: "text-center"
			, cellRenderer	: function (params) {
				var strVal			= '';
				if (!gagajf.isNull(params.data.optCd2)) {
					var optArr = params.data.optCd2.split(',');
					strVal += '<select class="optCd2" name="optCd2" goodsCd="' + params.data.goodsCd + '" onchange="fnChangeOption(this)">';
					if (gagajf.isNull(params.data.optCd)) {
						strVal += '<option value="" selected>선택</option>';	
					} else {
						strVal += '<option value="">선택</option>'
					}
					
					
					$.each(optArr, function (idx, item) {
						if (params.data.optCd == item) {
							strVal += '<option value="' + item + '" selected>' + item + '</option>';
						} else {
							strVal += '<option value="' + item + '">' + item + '</option>';
						}
					});
				}
				
				return strVal;
			}
		},
		{headerName: "주문수량", field: "ordQty", width: 100, cellClass: 'text-center', editable : true},
		{headerName: "상품상태", field: "goodsStat" , width: 100, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(goodsStatList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(goodsStatList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(goodsStatList, params.newValue); }
		},
		{headerName: "년도", field: "styleYear" , width: 80, cellClass: 'text-center'},
		{headerName: "시즌", field: "seasonCd" , width: 80, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(seasonList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(seasonList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(seasonList, params.newValue); }
		},
		{headerName: "정상가", field: "listPrice" , width: 100, cellClass: 'text-right'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		{headerName: "판매가", field: "currPrice" , width: 100, cellClass: 'text-right'
			,valueFormatter: function(params) {return params.value.addComma();},
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 14, validType: 'numeric'}
		},
		/*{headerName: "할인율", field: "dcRate" , width: 90, cellClass: 'text-right'},*/
		{headerName: "가격변경일", field: "priceUpdDt", width: 150, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		},
		{headerName: "ERP재고연동여부", field: "erpStockLinkYn", width: 120, cellClass: 'text-center'},
		{headerName: "이월구분", field: "formalGb", width: 100, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(formalGbList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(formalGbList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(formalGbList, params.newValue); }
		},
		{headerName: "반품가능", field: "returnableYn" , width: 90, cellClass: 'text-center'},
		{headerName: "등록일시", field: "regDt", width: 150, cellClass: 'text-center',
			cellRenderer: function(params) {
				return !gagajf.isNull(params.value) ? params.value.toDate("YYYYMMDDHHmmss").format("YYYY-MM-DD HH:mm:ss") : '';
			}
		},
		{headerName: "등록자", field: "regNm" , width: 100, cellClass: 'text-center'},
		{headerName: "수정일시", field: "updDt", width: 150, cellClass: 'text-center',
			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'}
	];
	
	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);
	
	// 중복 선택 가능
	gridOptions.rowSelection = 'multiple';
	gridOptions.suppressRowClickSelection = true;
	gridOptions.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.
	
	gridOptions.getRowStyle = function(params) {
		if ("G008_00" == params.data.goodsStat  || "G008_10" == params.data.goodsStat || "G008_20" == params.data.goodsStat || "G008_30" == params.data.goodsStat) {
			return { background: '#23c6c8' };
		}
	}

	// 주문수량 변경 이벤트
	gridOptions.onCellValueChanged = function(event) {
		let ordQty = event.data.ordQty;
		if (event.colDef.field == "ordQty" && event.data.ordQty > event.data.stockQtySum) {
			ordQty = event.data.stockQtySum;
			mcxDialog.alert('주문수량이 판매가능재고보다 클 수 없습니다.');
		}
		
		gridOptions.api.forEachNode(function(rowNode, index) {
			if (event.data.goodsCd == rowNode.data.goodsCd){
				rowNode.data.ordQty = ordQty;
				
				gridOptions.api.updateRowData({update: [rowNode.data]});
			}
		});
	}

	//상품조회 팝업
	var fnOpenGoodsPopup = function() {
		cfnOpenGoodsPopup('fnFetchGoods');
	}
	
	// 상품추가
	var fnFetchGoods = function(goodsData) {
		if (goodsData.length < 1) return;
		
		// 기존상품
		var oldGoodsSetList = gagaAgGrid.getAllRowData(gridOptions);
		var index = oldGoodsSetList.length+1;
		
		var arrGoodsCd = [];
		$.each(goodsData, function(idx, item) {
			arrGoodsCd.push(item.goodsCd);
		})
		
		var isExist = false;
		var jsonData = JSON.stringify(arrGoodsCd);
		gagajf.ajaxJsonSubmit('/order/sample/goods/info', jsonData, function(result) {
			$.each(result, function(idx, item) {
				isExist = false;
				gridOptions.api.forEachNode(function(rowNode, index) {
					//중복상품 여부 확인
					if (item.goodsCd == rowNode.data.goodsCd){
						isExist = true;
					}
				});
				
				if(!isExist){
					var data = {
						no: index
						, sysImgNm : item.sysImgNm
						, goodsCd : item.goodsCd
						, compsGoodsCd : item.repGoodsCd
						, goodsNm : item.goodsNm
						, ordQty : 1
						, optCd2 : item.siteCd
						, stockQtySum : item.stockQtySum
						, goodsStat : item.goodsStat
						, styleYear : item.styleYear
						, seasonCd : item.seasonCd
						, listPrice : item.listPrice
						, currPrice : item.currPrice
						, priceUpdDt : item.priceUpdDt
						, erpStockLinkYn : item.erpStockLinkYn
						, formalGb : item.formalGb
						, returnableYn : item.returnableYn
						, regDt : item.regDt
						, regNm : item.regNm
						, updDt : item.updDt
						, updNm : item.updNm
					};
					
					//그리드 마지막에 추가해야함
					gridOptions.api.updateRowData({add: [data], addIndex: idx});
					gridOptions.api.refreshCells();
					index++;
				}
			});
		});
	}

	//상품삭제
	var fnGoodsDeleteRow = function() {
		var selectedData = gagaAgGrid.selectedRowData(gridOptions);
		
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		//화면에서 삭제
		gagaAgGrid.removeRowData(gridOptions, false);
	}

	// 저장
	$('#btnCreateOrderSample').on('click', function() {
		// 입력 값 체크
		let selectedData = gagaAgGrid.selectedRowData(gridOptions);
		
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}
		
		let optChk = true;
		let qtyChk = true;
		$.each(selectedData, function(idx, item) {
			if (gagajf.isNull(item.optCd)) {
				optChk = false;
			} else if (item.ordQty <= 0) {
				qtyChk = false;
			}
		});
		
		if (!optChk) {
			mcxDialog.alert('주문옵션이 없습니다.');
			return false;
		}
		
		if (!qtyChk) {
			mcxDialog.alert('주문수량은 0보다 커야 됩니다.');
			return false;
		}
		
		mcxDialog.confirm("저장하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				let params = {};
				params.custNo = $('#custNo').val();
				params.ordNm = $('#ordNm').val();
				params.ordPhnno = $('#ordPhnno').val();
				params.ordEmail = $('#ordEmail').val();
				params.recipZipcode = $('#recipZipcode').val();
				params.recipBaseAddr = $('#recipBaseAddr').val();
				params.recipDtlAddr = $('#recipDtlAddr').val();
				params.goods = selectedData;
				
				let jsonData = JSON.stringify(params);
				
				gagajf.ajaxJsonSubmit($('#orderSamplePopupForm').prop('action'), jsonData, function(result) {
					uifnPopupClose('popupOrderSample');
				});
			}
		});
	});

	// 회원정보 적용
	var fnApplyCustomerInfo = function() {
		var params = {};
		params.searchGb = 'custNo';
		params.searchTxt = $('#orderSamplePopupForm input[name=custNo]').val();
		
		var jsonData = JSON.stringify(params);
		
		gagajf.ajaxJsonSubmit('/customer/active/list', jsonData, function(result) {
			let param = result[0];
			
			$('#ordNm').val(param.custNm);
			$('#ordPhnno').val(param.cellPhnno);
			$('#ordEmail').val(param.email);
			$('#recipZipcode').val(param.homeZipcode);
			$('#recipBaseAddr').val(param.homeBaseAddr);
			$('#recipDtlAddr').val(param.homeDtlAddr);
		});
	}

	var fnOpenDaumAddr = function() {
		let daumZip = new daum.Postcode({
			oncomplete: function(data) {
				// 우편번호와 주소 정보를 해당 필드에 넣는다.
				$('#orderSamplePopupForm input[name=recipZipcode]').val(data.zonecode);
				$('#orderSamplePopupForm input[name=recipBaseAddr]').val(cfnGetDaumRoadAddr(data));
				$('#orderSamplePopupForm input[name=recipDtlAddr]').focus();
				
				cfnCloseDaumAddr();
			},
			width: '100%'
		});
		
		cfnOpenDaumAddr(daumZip);
	}
	
	var fnChangeOption = function(param) {
		var params = {};
		params.goodsCd = $(param).attr('goodsCd');
		params.siteCd = $(param).val();
		
		var jsonData = JSON.stringify(params);
		gagajf.ajaxJsonSubmit('/order/sample/goods/stock', jsonData, function(result) {
			gridOptions.api.forEachNode(function(rowNode, index) {
				if (result.goodsCd == rowNode.data.compsGoodsCd){
					rowNode.data.stockQtySum = result.minOrdQty;
					console.log(result);
					rowNode.data.optCd = result.siteCd;
					gridOptions.api.updateRowData({update: [rowNode.data]});
				}
			});
		});
	}

	$(document).ready(function() {
		gagaAgGrid.createGrid('gridGoodsList', gridOptions);
	});
/*]]>*/
</script>

</html>
