<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : ShotDeliveryForm.html
 * @desc    : 총알배송 Page
 *============================================================================
 * SISUN
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.06.29   sowon        최초 작성
 *******************************************************************************
 -->
 
 <div id="main">
	<!-- 메인타이틀 영역 -->
	<div class="main-title">
	</div>
	<!-- //메인타이틀 영역 -->
	
	<!-- 메뉴 설명 -->
	<div class="infoBox menu-desc">
	</div>
	<!-- //메뉴 설명 -->
	
	<div class="panelStyle" style="height: 750px;">
		<div class="panelContent">
			<ul class="panelBar">
				<li>
					<h4>브랜드 목록</h4> 
				</li>
				<li class="right">
					<button type="button" class="btn btn-success btn-lg" onclick="fnShotBrandSave();">브랜드 저장</button>
				</li>
			</ul>
			<form id="shotBrandListForm" name="shotBrandListForm" action="#" th:action="@{'/marketing/shot/delivery/brand/list'}" th:method="post">
				<div class="panelContent">
					<div id="gridListBrand" style="width: 100%; max-height: 230px; height: 230px;" class="ag-theme-balham"></div>
				</div>
			</form>
		</div>

		<div class="panelContent">
			<ul class="panelBar">
				<li>
					<h4>브랜드명 : <label id="brandNm"></label></h4> 
				</li>
				<li class="right">
					<button type="button" class="btn btn-default btn-lg" onclick="fnOpenGoodsPopup();">상품추가</button>
					<button type="button" class="btn btn-danger btn-lg"	onclick="fnDeleteGoods();">선택삭제</button>
				</li>
			</ul>
			
			<div id="gridListGoods"	style="width: 100%; max-height: 350px; height: 350px;" class="ag-theme-balham lh60"></div>
<!-- 			<ul class="panelBar"> -->
<!-- 				<li class="center"> -->
<!-- 					<div class="tablePaging" id="brandGoodsPagination"></div> -->
<!-- 				</li> -->
<!-- 			</ul> -->
		</div>
	</div>
</div>
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
	var cornerDispTypeList = gagajf.convertToArray([[${cornerDispTypeList}]]);
	var goodsStatList =gagajf.convertToArray([[${goodsStatList}]]);
	// 브랜드 그룹번호 전역변수
	var _brandGroupNo = '';
	
	var columnDefsBrand = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "브랜드번호"		, field:'brandGroupNo'			, width:150, cellClass: 'text-center', editable: false },
		{headerName: "브랜드그룹명"			, field:'brandNm'			, width:400, cellClass: 'text-center',
			cellRenderer: function(params) {return '<a href="javascript:void(0);">' + params.value + '</a>'; },
			cellEditorParams: { maxlength: 50, required: true }
		},
		{headerName: "코너유형"		, field:'cornerDispType'		, width:180, cellClass: 'text-center',
			cellEditor: 'agRichSelectCellEditor',
			cellEditorParams: { values: gagaAgGrid.extractValues(cornerDispTypeList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(cornerDispTypeList, params.value); },
			valueParser: function (params) { return gagaAgGrid.lookupKey(cornerDispTypeList, params.newValue); }
		},
		{headerName: "전시순서"		, field:'dispOrd'				, width:100, cellClass: 'text-right',
			cellEditor: 'textCellEditor',
			cellEditorParams: { maxlength: 3, required: true }
		},
		{headerName: "등록일"			, field:'regDt'				, width:200, cellClass: 'text-center', editable: false }
	];
	
	var columnDefsGoods = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "상품코드"	, field:'goodsCd'		, width:150, cellClass: 'text-left'
			, cellRenderer: function(params) {return '<a href="javascript:void(0);">' + params.value + '</a>'; }
		},
		{headerName: "상품명"		, field:'goodsNm'		, width:300, cellClass: 'text-left'},
		{headerName: "이미지"		, field:'sysImgNm'		, width:100 , height:60, cellClass: 'text-right'
			,cellRenderer: function(params) {
				return '<img width="60" src="'+ _goodsUrl+ "/" + params.value + '?RS=60" alt="" onclick="cfnOpenImagePreViewPopup(\'goodsImgView\', \''+ _goodsUrl+ "/" + params.value +'\')" onerror="this.src=\'/image/no.png\';"/>';
			}
		},
		{headerName: "재고"		, field:'stockQtySum'			, width:80 , cellClass: 'text-center'
			, cellRenderer: function(params) {return !gagajf.isNull(params.value) ? params.value : '0'; }
		},
		{headerName: "할인율(%)"		, field:'dcRate'		, width:80 , cellClass: 'text-center'},
		{headerName: "정상가"		, field:'listPrice'		, width:100, cellClass: 'text-right' , hide : true
			, valueFormatter: function(params) { return params.value.addComma(); }
		},
		{headerName: "판매가"		, field:'currPrice'		, width:100, cellClass: 'text-right'
			, valueFormatter: function(params) { return params.value.addComma(); }
		},
		{headerName: "정상/이월여부", field:'formalGb'		, width:120, cellClass: 'text-center'},
		{headerName: "상품상태"	, field:'goodsStat'		, width:100, cellClass: 'text-center'
			, valueFormatter: function(params) { return gagaAgGrid.lookupValue(goodsStatList, params.value); }
		},
		{headerName: "업체"		, field:'supplyCompNm'	, width:150, cellClass: 'text-left'},
		{headerName: "기획전상세"	, field:'planDtlSq'		, width:200, cellClass: 'text-left', hide: true},
		{headerName: "등록일"		, field:'regDt'			, width:100,  cellClass: 'text-left'
			, cellRenderer: function(params) { return !gagajf.isNull(params.value) ? params.value.toDate("YYYY-MM-DD HH:MM:SS").format("YYYY-MM-DD") : ''; }
		},
	];
	
	var gridOptionsBrand = gagaAgGrid.getGridOptions(columnDefsBrand);
	gridOptionsBrand.suppressRowClickSelection = true;
	gridOptionsBrand.stopEditingWhenGridLosesFocus = true;
	gridOptionsBrand.defaultColDef.editable = true;
	//gridOptionsBrand.rowSelection = 'multiple';
	
	var gridOptionsGoods = gagaAgGrid.getGridOptions(columnDefsGoods);
	gridOptionsGoods.rowSelection = 'multiple';
	gridOptionsGoods.rowHeight = 60; //이미지가 있을경우 높이 지정해야함.
	gridOptionsGoods.suppressRowClickSelection = true;

	gridOptionsGoods.onCellClicked = function(event) {
		if (event.colDef.field == 'goodsCd') {
			// 상품 상세 팝업
			cfnOpenGoodsDetailPopup('U',event.data.goodsCd);
		}
	}

	// 브랜드 셀 클릭 이벤트
	gridOptionsBrand.onCellClicked = function(event) {
		var field = event.colDef.field;
		if (field != 'brandNm') return;

		fnBindSearch(event.data);
	}

	// 코너 상품 조회 바인딩
	var fnBindSearch = function(data) {
		if (!gagajf.isNull(data.brandNm)) {

			$('#brandNm').html(data.brandNm);
			_brandGroupNo = data.brandGroupNo;

			fnShotGoodsSearch();
		}
	}
	// 상품 추가 버튼 클릭시 
	var fnOpenGoodsPopup = function() {
		var allData = gagaAgGrid.getAllRowData(gridOptionsBrand);
		if (allData.length < 1 ) {
			mcxDialog.alert('브랜드가 존재 하지 않습니다.');
			return;
		}

		if ($("#brandNm").text() == null || $("#brandNm").text()=='') {
			mcxDialog.alert('브랜드를 선택해주세요.');
			return;
		}
		cfnOpenGoodsPopup('fnCreateGoods');
	}

	// 브랜드 조회
	var fnBrandSearch = function() {
		var formId = '#shotBrandListForm';
		gagaAgGrid.fetch($(formId).prop('action'), gridOptionsBrand, formId
						, function() {
								$('#gridListGoods').html('');
								$('#brandNm').html('');
								gagaAgGrid.createGrid('gridListGoods', gridOptionsGoods);
				});
		
		uifnPopupClose('fnCreateGoods');
	}
	
	// 코너 저장
	var fnShotBrandSave = function() {
		var changeData = gagaAgGrid.getChangedData(gridOptionsBrand);

		if (changeData.length < 1) {
			mcxDialog.alert('변경된 브랜드 목록이 없습니다.');
			return;
		}

		// Validation
		if (!gagaAgGrid.validation(gridOptionsBrand, changeData))
			return;

		mcxDialog.confirm('저장하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(changeData);
				gagajf.ajaxJsonSubmit('/marketing/shot/delivery/brand/update', jsonData, fnBrandSearch);
			}
		});
	}
	
	// 상품추가
	var fnCreateGoods = function(result) {
		if (result.length < 1) return;
	
		var oldGoodsList = gagaAgGrid.getAllRowData(gridOptionsGoods);
		for (var disp = 0; disp < result.length; disp++) {
			let addChk = true;
			
			// 받아온 data for
			for(let j = 0 ; j < oldGoodsList.length ; j++) {
				if(oldGoodsList[j].goodsCd == result[disp].goodsCd) {	addChk = false;	}					// 중복체크
			}
			
			if(addChk) {
				var goods = { brandGroupNo : _brandGroupNo ,
						      goodsCd : result[disp].goodsCd ,
						      dispOrd : oldGoodsList.length+1
						    };
				oldGoodsList.unshift(goods);
			}
		}
		
		mcxDialog.confirm('선택하신 상품을 추가 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(oldGoodsList);
				gagajf.ajaxJsonSubmit('/marketing/shot/delivery/goods/save', jsonData, fnShotGoodsSearch);
			}
		});
	}


	// 브랜드 상품 조회
	var fnShotGoodsSearch = function() {
		uifnPopupClose('popupGoods');
		var actionUrl = '/marketing/shot/delivery/goods/list';
		var data = {brandGroupNo:_brandGroupNo};
		var jsonData = JSON.stringify(data);

		gagajf.ajaxJsonSubmit(actionUrl, jsonData, function(data) {
			gridOptionsGoods.api.setRowData(data.brandGoodsList);
		});
	}
	
	//선택삭제
	var fnDeleteGoods = function() {
		var removedData = gagaAgGrid.removeRowData(gridOptionsGoods);

		if (removedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return;
		}

		mcxDialog.confirm('선택된 상품을 삭제하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(removedData);

				gagajf.ajaxJsonSubmit('/marketing/shot/delivery/goods/delete', jsonData, function() {
					fnShotGoodsSearch();
				});
			}
		});
	}
	
	// 엑셀상품추가
	//var fnGoodsExcelUpload = function() {
	//	cfnExcelUploadPopup('createGoods', 'fnCreatePlanGoodsExcel');
	//}


	$(document).ready(function() {
		gagaAgGrid.createGrid('gridListBrand', gridOptionsBrand);
		gagaAgGrid.createGrid('gridListGoods', gridOptionsGoods);
		fnBrandSearch();
	});
</script>