<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : PlanCornerListForm.html
 * @desc    : 기획전 코너 관리 화면 Page
 *============================================================================
 * SISUN
 * Copyright(C) 2019 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.05.06   sowon   최초 작성
 *******************************************************************************
 -->

<div class="modalPopup" data-width="1200" data-height="800" id="popupPlanCorner">

	<div class="panelStyle" style="height: 750px;">
		<div class="panelTitle">
			<strong>기획전 관리</strong>
			<button type="button" class="close"	onclick="uifnPopupClose('popupPlanCorner')">
				<i class="fa fa-times"></i>
			</button>
		</div>

		<div class="panelContent">
			<form th:object="${planInfo}" id="planCornerListForm"
				name="planCornerListForm" action="#"
				th:action="@{'/marketing/planning/corner/list'}" th:method="post">
				<input type="hidden" th:field="*{planSq}" />
				<input type="hidden" th:field="*{planDtlSq}" />
				<table class="frmStyle" style="margin-bottom: 10px;">
					<colgroup>
						<col style="width: 10%;" />
						<col style="width: 10%;" />
						<col style="width: 10%;" />
						<col style="width: 20%;" />
						<col style="width: 10%;" />
						<col style="width: 15%;" />
						<col style="width: 10%;" />
						<col style="width: 15%;" />
					</colgroup>
					<tr>
						<th>기획전번호</th>
						<td><label th:text="*{planSq}" id="planSq"></label></td>
						<th>기획전명</th>
						<td><label th:text="*{planNm}" id="planNm"></label></td>
						<th>기획전시작일</th>
						<td><label th:text="*{dispStdt}" id="dispStdt"></label></td>
						<th>기획전종료일</th>
						<td><label th:text="*{dispEddt}" id="dispEddt"></label></td>
					</tr>
				</table>

				<div class="panelContent">
					<ul class="panelBar">
						<li class="boxContentBtnT" style="margin-left: -20px; margin-right: -23px;">
							<span class="btnLeft">
								<button type="button" class="btn btn-warning btn-sm" id="btnAddRow">행추가</button>
								<button type="button" class="btn btn-danger btn-sm" id="btnDeleteRow">행삭제</button>
							</span> 
						</li>
						<li class="right">
							<span class="btnRight"> 
								<!-- <button type="button" class="btn btn-default btn-lg" onclick="fnCornerCopyPopup();">코너복사</button> -->
								<button type="button" class="btn btn-success btn-lg" onclick="fnPlanCornerSave();">저장</button>
						   </span>
					   </li>
					</ul>
					<div id="gridListCorner" style="width: 100%; max-height: 230px; height: 230px;" 	class="ag-theme-balham"></div>
				</div>
			</form>
		</div>

		<div class="panelContent">
			<div>
				<h4>
					코너명 : <label id="cornerNm"></label>
				</h4>
				<div class="aR" style="float: right; margin-top: 10px;">
					<button type="button" class="btn btn-Right btn-default btn-lg"onclick="fnGoodsExcelUpload();">엑셀상품추가</button>
					<button type="button" class="btn btn-default btn-lg" onclick="cfnDownloadSampleFile('SF012');">엑셀상품추가 양식 다운로드</button>
					<button type="button" class="btn btn-default btn-lg" onclick="fnOpenGoodsPopup();">상품추가</button>
					<!-- <button type="button" class="btn btn-default btn-lg"onclick="fnDispOrdChange();">순서변경</button> -->
					<button type="button" class="btn btn-danger btn-lg"	onclick="fnDeleteGoods();">선택삭제</button>
				</div>
			</div>

			<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="planListPagination"></div>
				</li>
			</ul>
		</div>

	</div>
</div>
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
/*<![CDATA[*/

	var planInfo = [[${planInfo}]];
	var cornerDispTypeList = gagajf.convertToArray([[${cornerDispTypeList}]]);
	var planDtlStatList = gagajf.convertToArray([[${planDtlStatList}]]);
	var goodsStatList =gagajf.convertToArray([[${goodsStatList}]]);
	var uploadGoodsUrl = [[${@environment.getProperty('upload.goods.view')}]];

	var columnDefsCorner = [
		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{headerName: "코너번호"		, field:'planDtlSq'			, width:120, cellClass: 'text-center', editable: false },
		{headerName: "코너명"			, field:'cornerNm'			, width:400, cellClass: 'text-left',
			cellRenderer: function(params) {return '<a href="javascript:void(0);">' + params.value + '</a>'; },
			cellEditor: 'textCellEditor',
			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:'planSq'	, width:90, cellClass: 'text-left', hide: true},
		{headerName: "시작일"			, field:'startSearchDate'	, width:110, cellClass: 'text-center',
			cellEditor: 'datePicker',
			cellEditorParams: { maxlength: 10, required: true },
		},
		{headerName: "시작시간"		, field:'startSearchTime'	, width:150, cellClass: 'text-center',
			cellEditor: 'dateTimer',
			cellEditorParams: { maxlength: 8, required: true },
		},
		{headerName: "종료일"			, field:'endSearchDate'		, width:110, cellClass: 'text-center',
			cellEditor: 'datePicker',
			cellEditorParams: { maxlength: 10, required: true }
		},
		{headerName: "종료시간"		, field:'endSearchTime'		, width:150, cellClass: 'text-center',
			cellEditor: 'dateTimer',
			cellEditorParams: { maxlength: 8, required: true },
		},
		{headerName: "등록자"			, field:'regNm'				, width:120, cellClass: 'text-center', editable: false },
		{headerName: "수정자"			, field:'updNm'				, width:120, cellClass: 'text-center', editable: false }
	];

	var gridOptionsCorner = gagaAgGrid.getGridOptions(columnDefsCorner);
	gridOptionsCorner.suppressRowClickSelection = true;
	gridOptionsCorner.stopEditingWhenGridLosesFocus = true;
	gridOptionsCorner.defaultColDef.editable = true;
	gridOptionsCorner.rowSelection = 'multiple';

	
	// 코너 셀 클릭 이벤트
	gridOptionsCorner.onCellClicked = function(event) {
		var field = event.colDef.field;
		if (field != 'cornerNm') return;

		fnBindSearch(event.data);
	}

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

			$('#cornerNm').html(data.cornerNm);
			_planDtlSq = data.planDtlSq;

			fnConnerGoodsSearch();
		}
	}

	// 코너 상품 조회
	var fnConnerGoodsSearch = function() {
		uifnPopupClose('popupGoods');
		var actionUrl = '/marketing/planning/corner/goods/list';
		var data = {planDtlSq:_planDtlSq};
		var jsonData = JSON.stringify(data);

		gagajf.ajaxJsonSubmit(actionUrl, jsonData, function(data) {
			gridOptionsGoods.api.setRowData(data.planGoodsList);
		});
	}

	// 코너 조회
	var fnCornerSearch = function() {
		var formId = '#planCornerListForm';
		gagaAgGrid.fetch($(formId).prop('action'), gridOptionsCorner, formId
						, function() {
								$('#gridListGoods').html('');
								$('#cornerNm').html('');
								gagaAgGrid.createGrid('gridListGoods', gridOptionsGoods);
				});
		
		uifnPopupClose('fnCreateGoods');
	}
	// 행추가
	$('#btnAddRow').on('click', function() {
		var allData = gagaAgGrid.getAllRowData(gridOptionsCorner);
		var planSq = $('#planCornerListForm input[name=planSq]').val();
		var stdt = planInfo.dispStdt.split(" ");
		var eddt = planInfo.dispEddt.split(" ");

		if (allData.length > 0 && typeof allData[0].crud == 'undefined') {
			mcxDialog.alert('추가 된 코너를 저장 후 코너를 추가하세요.');
			return;
		} else {
	
			var data = { planDtlSq: '', planSq:planSq, cornerNm:'',cornerDispType: '', startSearchDate: _today, startSearchTime: stdt[1], endSearchDate: eddt[0], endSearchTime: eddt[1]};
			gagaAgGrid.addRowData(gridOptionsCorner, data);
		}

	});

	// 행삭제
	$('#btnDeleteRow').on('click', function() {
		var selectData = gagaAgGrid.selectedRowData(gridOptionsCorner);

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

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

				gagajf.ajaxJsonSubmit('/marketing/planning/corner/delete', jsonData, function() {
					gridOptionsCorner.api.updateRowData({remove:gagaAgGrid.selectedRowData(gridOptionsCorner)});
					fnCornerSearch();
				});
			}
		});
	});

	// 코너승인
	var fnCornerConfirm = function() {
		var selectData = gagaAgGrid.selectedRowData(gridOptionsCorner);
		if (selectData.length < 1) {
			mcxDialog.alert('승인 할 코너가 없습니다.');
			return;
		}

		if (selectData.length == 1) {
			if (gagajf.isNull(selectData[0].planDtlStat)) {
				mcxDialog.alert('승인할 코너가 없습니다.');
				return;
			}
		}

		var Msg = '';
		$(selectData).each(function(idx, data) {
			if (data.planDtlStat == '90') {
				Msg = '승인상태가 삭제인 코너가 존재합니다.<br/>선택한 코너를 승인 하시겠습니까?';
			}
			if (data.planDtlStat != '20') {
				data.planDtlStat = '20'; // 승인
			}
		});

		Msg = !gagajf.isNull(Msg) ? Msg : '선택 된 코너를 승인 하시겠습니까?';
		mcxDialog.confirm(Msg, {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(selectData);
				gagajf.ajaxJsonSubmit('/marketing/plan/corner/confirm', jsonData, fnCornerSearch);
			}
		});
	}

	// 코너 저장
	var fnPlanCornerSave = function() {
		var changeData = gagaAgGrid.getChangedData(gridOptionsCorner);

		if (changeData.length < 1) {
			mcxDialog.alert('변경 된 코너가 없습니다.');
			return;
		}

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

		var result = true;
		$(changeData).each(function(idx, data) {
			var stdt = planInfo.dispStdt.split(" ");
			var eddt = planInfo.dispEddt.split(" ");

			// 날짜 유효성 체크
			if (Number(stdt[0]) > Number(data.startSearchDate)) {
				mcxDialog.alert('코너의 시작일이 유효하지 않습니다.');
				result = false;
			}

			if (Number(eddt[0]) < Number(data.endSearchDate)) {
				mcxDialog.alert('코너의 종료일이 유효하지 않습니다.');
				result = false;
			}

			if (Number(data.startSearchDate.replaceAll("-", "")) > Number(data.endSearchDate.replaceAll("-", ""))) {
				mcxDialog.alert('진행기간 시작일자는 종료일자보다 클 수 없습니다.');
				result = false;
			}

			if (Number(data.startSearchDate.replaceAll("-", "")) < Number(_today.replaceAll("-", "")) && data.crud == 'C') {
				mcxDialog.alert('시작일자는 오늘포함 이후로 등록해주세요.');
				result = false;
			}

			if (Number(data.endSearchDate.replaceAll("-", "")) < Number(_today.replaceAll("-", "")) && data.crud == 'C') {
				mcxDialog.alert('종료일자는 오늘포함 이후로 등록해주세요.');
				result = false;
			}

			// 기획전 시작종료일과 코너 시작종료일 체크
			if (stdt[0].replaceAll("-", "") > data.startSearchDate.replaceAll("-", "")) {
				mcxDialog.alert("기획전 시작일보다 코너시작일이 작을 수 없습니다.");
				result = false;
			}

			if (eddt[0].replaceAll("-", "") < data.endSearchDate.replaceAll("-", "")) {
				mcxDialog.alert("기획전 종료일보다 코너종료일이 클 수 없습니다.");
				result = false;
			}

			if (result) {
				data.dispStdt = data.startSearchDate + ' ' + data.startSearchTime;
				data.dispEddt = data.endSearchDate + ' ' + data.endSearchTime;
			}
		});

		if (!result) return;

		mcxDialog.confirm('저장 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function() {
				var jsonData = JSON.stringify(changeData);
				gagajf.ajaxJsonSubmit('/marketing/planning/corner/save', jsonData, fnCornerSearch);
			}
		});
	}

	// 코너 복사
	var fnCornerCopyPopup = function() {
		var actionUrl = '/marketing/planning/corner/copy/list/form?planSq=' + planInfo.planSq;
		actionUrl += '&copyMode=CORNER';
		cfnOpenModalPopup(actionUrl,'popupCornerCopy');
	}
	
	var uploadGoodsUrl = [[${@environment.getProperty('upload.goods.view')}]];
	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:'imgPath6'		, width:100 , height:60, cellClass: 'text-right'
			, cellRenderer: function(params) {
				var imgPath = '';
				if (params.data.imgType == "A"){
					imgPath = uploadGoodsUrl;
				}
				if(typeof params.value!='undefined' && params.value!='' && params.value!=null){
					imgPath = imgPath + params.value;
				}else{
					imgPath = imgPath + params.data.imgPath1;
				}
				return '<img width="60" src="'+imgPath.replace('1000', '100')+'" onerror="this.src=\''+_uximgUrl+'/image/no.png\';">';
			}
		},
		/* {headerName: "전시순서"	, field:'dispOrd'		, width:80 , cellClass: 'text-center'
			, editable : true, cellEditor: 'numericCellEditor'
			, valueFormatter: function(params) { return params.value.addComma(); }
		}, */
		{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: "TAG가"		, field:'tagPrice'		, width:100, cellClass: 'text-right'
			,valueFormatter: function(params) {
				if(params.value && params.value > 0) {
					return params.value.addComma();
				} else {
					return '0';
				}
			}
		},
		{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 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);
		}

// 		if (event.colDef.field == 'imgPath1') {
// 			// 이미지 팝업
// 			cfnOpenImagePreViewPopup('planGoodsDetail', event.data.imgPath1);
// 		}
	}

	// 상품 선택삭제
	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/planning/corner/goods/delete', jsonData, function() {
					fnConnerGoodsSearch();
				});
			}
		});
	}

	// 기획전 상세일련번호 전역 변수
	var _planDtlSq = '';

	// 엑셀상품추가
	var fnGoodsExcelUpload = function() {
		cfnExcelUploadPopup('createGoods', 'fnCreatePlanGoodsExcel');
	}

	var fnCreatePlanGoodsExcel = function(result) {
		var data = {planSq : planInfo.planSq
					,excelFileNm : result.excelFileNm
					};
		var jsonData = JSON.stringify(data);
		gagajf.ajaxJsonSubmit('/marketing/planning/corner/goods/excelupload', jsonData, fnConnerGoodsSearch);
	}

	var fnOpenGoodsPopup = function() {
		var allData = gagaAgGrid.getAllRowData(gridOptionsCorner);
		if (allData.length < 1 ) {
			mcxDialog.alert('기획전 코너가 존재 하지 않습니다.');
			return;
		}
		if (allData[0].regNm == '' || allData[0].regNm == null) {
			mcxDialog.alert('추가 된 코너를 저장 후 코너를 추가하세요.');
			return;
		}

		if ($("#cornerNm").text() == null || $("#cornerNm").text()=='') {
			mcxDialog.alert('코너를 선택해주세요.');
			return;
		}
		cfnOpenGoodsPopup('fnCreateGoods');
	}

	// 상품추가
	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 = { planDtlSq : _planDtlSq ,
						      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/planning/corner/goods/save', jsonData, fnConnerGoodsSearch);
			}
		});
	}

	// 순셔 변경 팝업
	var fnDispOrdChange = function(result) {
		var selectData = gagaAgGrid.selectedRowData(gridOptionsCorner);
		var params = 'planDtlSq='+ _planDtlSq;

		cfnOpenGoodsDispOrdChangePopup('fnConnerGoodsSearch', params);
	}
	
	$(document).ready(function() {
		gagaAgGrid.createGrid('gridListCorner', gridOptionsCorner);
		gagaAgGrid.createGrid('gridListGoods', gridOptionsGoods);

		fnCornerSearch();
	});


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