<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : CouponPopupForm.html
 * @desc    : 쿠폰 등록 팝업 화면
 *============================================================================
 * ISTYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.12.23   xyzp1539       최초 작성
 *******************************************************************************
 -->
 
<!-- 쿠폰적용대상-->
<div class="inner-panelContent">
	<div class="panelContent">
		<div class="panelBar">
			<h4>적용 대상 상품 등록</h4>
		</div>
		<table class="frmStyle">
			<colgroup>
				<col style="width:15%;">
				<col style="width:85%;">
			</colgroup>
			<tbody>
				<tr>
					<th>적용범위<em class="required" title="필수"></em></th>
					<td>
						<input type="hidden" name="applyScope" required="required" data-valid-name="적용범위">
						<label class="rdoBtn"> <input type="radio" name="rdoApplyScope" value="A"/>전체</label>
						<label class="rdoBtn"> <input type="radio" name="rdoApplyScope" value="I" checked/>개별</label>
					</td>
				</tr>
				<tr class="supplyTrArea">
					<th>공급처</th>
					<td>
						<div class="padding10 inner-tb-solid">
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnSupplyAdd">공급처 추가</button>
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnSupplyDel">선택삭제</button>
							<br/>
							<div id="supplyGridList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
						</div>
					</td>
				</tr>
				<tr class="brandTrArea">
					<th>브랜드</th>
					<td>
						<div class="padding10 inner-tb-solid">
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnBrandAdd">브랜드 추가</button>
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnBrandDel">선택삭제</button>
							<br/>
							<div id="brandGridList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
						</div>
					</td>
				</tr>
				<tr class="categoryTrArea">
					<th>카테고리</th>
					<td>
						<div class="padding10 inner-tb-solid">
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnCateAdd">카테고리 추가</button>
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnCateDel">선택삭제</button>
							<br/>
							<div id="cateGridList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
						</div>
					</td>
				</tr>
				<tr class="goodsTrArea">
					<th>적용상품</th>
					<td>
						<div class="padding10 inner-tb-solid">
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnGoodsAdd">상품 추가</button>
							<button type="button" class="btn btnRight btn-success btn-lg" id="btnGoodsDel">선택삭제</button>
							<br/>
							<div id="goodsGridList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
						</div>
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</div>

<div class="inner-panelContent exceptArea">
	<div class="panelContent">
		<div class="panelBar">
			<h4>제외 대상 상품 등록</h4>
		</div>
		<table class="frmStyle">
			<colgroup>
				<col style="width:15%;">
				<col style="width:85%;">
			</colgroup>
			<tbody>
			<tr>
				<th>제외상품</th>
				<td>
					<div class="padding10 inner-tb-solid">
						<button type="button" class="btn btnRight btn-success btn-lg" id="btnExcepGoodsAdd">제외상품 추가</button>
						<button type="button" class="btn btnRight btn-success btn-lg" id="btnExcepGoodsDel">선택삭제</button>
						<br/>
						<div id="excepGoodsGridList" style="width:100%; height:200px;" class="ag-theme-balham"></div>
					</div>
				</td>
			</tr>
			</tbody>
		</table>
	</div>
</div>

<script th:inline="javascript">
// 공통코드 리스트
var formalGbList 			= gagajf.convertToArray([[${formalGbList}]]);
var cateGbList 				= gagajf.convertToArray([[${cateGbList}]]);
var selfBrandList 			= gagajf.convertToArray([[${selfBrandList}]]);

var cpnDtlRefvalSupplyCompList 	= [[${cpnDtlRefvalSupplyCompList}]];
var cpnDtlRefvalApplyGoodsList 	= [[${cpnDtlRefvalApplyGoodsList}]];
var cpnDtlRefvalCateList 		= [[${cpnDtlRefvalCateList}]];
var cpnDtlRefvalBrandList 		= [[${cpnDtlRefvalBrandList}]];
var cpnDtlRefvalExceptGoodsList = [[${cpnDtlRefvalExceptGoodsList}]];

//ag-grid 공급처 컬럼
var supplyColumnDefs = [
	{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
	{ headerName : "공급업체코드" , field: "supplyCompCd" , width:150, cellClass: 'text-center'} ,
	{ headerName: "공급업체명" , field: "supplyCompNm" , width:150, cellClass: 'text-center'},
	{ headerName: "쿠폰대상일련번호"  , field: "cpnRefvalSq" , width: 120 , cellClass: 'text-center' , hide:true},
	{ headerName: "삭제여부"  , field: "delYn" , width: 120 , cellClass: 'text-center' , hide:true}
];

// ag-grid 브랜드 컬럼
var brandSelColumnDefs = [
	{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
	{ headerName : "브랜드ID" , field: "brandCd" , width: 120, cellClass : 'text-center'} ,
	{ headerName : "브랜드명" , field: "brandEnm" , width: 120, cellClass: 'text-center'} ,
	{ headerName: "쿠폰대상일련번호"  , field: "cpnRefvalSq" , width: 120 , cellClass: 'text-center' , hide:true},
	{ headerName: "삭제여부"  , field: "delYn" , width: 120 , cellClass: 'text-center' , hide:true}
];

// ag-grid 적용상품 컬럼
var goodsSelColumnDefs = [
	{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
	{ headerName: "상품구분" , field: "goodsGb" , width: 100, cellClass: 'text-center'} ,
	{ headerName: "Product ID" , field: "goodsCd" , width: 120, cellClass: 'text-center'},
	{ headerName: "상품명"  , field: "goodsNm" , width: 250 , cellClass: 'text-center'} ,
	{ headerName: "쿠폰대상일련번호"  , field: "cpnRefvalSq" , width: 120 , cellClass: 'text-center' , hide:true},
	{ headerName: "삭제여부"  , field: "delYn" , width: 120 , cellClass: 'text-center' , hide:true}
];

// ag-grid 카테고리 컬럼
var cateSelColumnDefs = [
	{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
	{ headerName: "사이트" , field: "siteCd" , width: 100 , cellClass: 'text-center' ,
		cellEditor: 'agRichSelectCellEditor',
		cellEditorParams: { values: gagaAgGrid.extractValues(siteCdList) },
		valueFormatter: function (params) { return gagaAgGrid.lookupValue(siteCdList, params.value); },
		valueParser: function (params) { return gagaAgGrid.lookupKey(siteCdList, params.newValue); }
	},
	{ headerName: "카테고리구분" , field: "cateGb" , width: 100 , cellClass: 'text-center' ,
		cellEditor: 'agRichSelectCellEditor',
		cellEditorParams: { values: gagaAgGrid.extractValues(cateGbList) },
		valueFormatter: function (params) { return gagaAgGrid.lookupValue(cateGbList, params.value); },
		valueParser: function (params) { return gagaAgGrid.lookupKey(cateGbList, params.newValue); }
	},
	{ headerName: "카테고리코드" , field: "cateNo" , width: 100 , cellClass: 'text-center'} ,
	{ headerName: "카테고리명" , field: "cateNm" , width: 120 , cellClass: 'text-center'},
	{ headerName: "이월/정상구분" , field: "formalGb" , width: 120 , cellClass: 'text-center',
		cellEditor: 'agRichSelectCellEditor',
		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:"brandCd" , width:150, cellClass: "text-center", required: true ,
		editable: true, cellEditor: 'agRichSelectCellEditor',
		cellEditorParams: { values: gagaAgGrid.extractValues(selfBrandList) },
		valueFormatter: function (params) { return gagaAgGrid.lookupValue(selfBrandList, params.value); },
		valueParser: function (params) { return gagaAgGrid.lookupKey(selfBrandList, params.newValue); }
	},
	{ headerName: "쿠폰대상일련번호"  , field: "cpnRefvalSq" , width: 120 , cellClass: 'text-center' , hide:true},
	{ headerName: "삭제여부"  , field: "delYn" , width: 120 , cellClass: 'text-center' , hide:true}
];

// ag-grid 제외상품 컬럼
var excepGoodsColumnDefs = [
	{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
	{ headerName: "상품구분" , field: "goodsGb" , width: 100, cellClass: 'text-center'} ,
	{ headerName: "Product ID" , field: "goodsCd" , width: 120, cellClass: 'text-center'},
	{ headerName: "상품명"  , field: "goodsNm" , width: 250 , cellClass: 'text-center'} ,
	{ headerName: "쿠폰대상일련번호"  , field: "cpnRefvalSq" , width: 120 , cellClass: 'text-center' , hide:true},
	{ headerName: "삭제여부"  , field: "delYn" , width: 120 , cellClass: 'text-center' , hide:true}
];

var supplyGridOptions 			= gagaAgGrid.getGridOptions(supplyColumnDefs);
var brandGridOptions 			= gagaAgGrid.getGridOptions(brandSelColumnDefs);
var cateGridOptions 			= gagaAgGrid.getGridOptions(cateSelColumnDefs);
var goodsGridOptions 			= gagaAgGrid.getGridOptions(goodsSelColumnDefs);
var excepGoodsGridOptions 		= gagaAgGrid.getGridOptions(excepGoodsColumnDefs);

cateGridOptions.rowSelection 		= "multiple";
goodsGridOptions.rowSelection 		= "multiple";
brandGridOptions.rowSelection 		= "multiple";
supplyGridOptions.rowSelection 		= "multiple";
excepGoodsGridOptions.rowSelection 	= "multiple";
	
var applyInfoInit = function() {	

	gagaAgGrid.createGrid('brandGridList'		, brandGridOptions);
	gagaAgGrid.createGrid('cateGridList'		, cateGridOptions);
	gagaAgGrid.createGrid('supplyGridList'		, supplyGridOptions);
	gagaAgGrid.createGrid('goodsGridList'		, goodsGridOptions);
	gagaAgGrid.createGrid('excepGoodsGridList'	, excepGoodsGridOptions);
	
	// 수정모드시 그리드 세팅
	if (cpnDtlRefvalSupplyCompList != null) {
		supplyGridOptions.api.setRowData(cpnDtlRefvalSupplyCompList);
		goodsGridOptions.api.setRowData(cpnDtlRefvalApplyGoodsList);
		excepGoodsGridOptions.api.setRowData(cpnDtlRefvalExceptGoodsList);
		brandGridOptions.api.setRowData(cpnDtlRefvalBrandList);
		cateGridOptions.api.setRowData(cpnDtlRefvalCateList);
		
		$("#CouponForm input:radio[name='rdoApplyScope']:radio[value=" + cpnDetail.applyScope + "]").prop('checked', true);
		
		if (cpnDetail.applyScope == 'A'){ 
			$("#CouponForm .supplyTrArea").hide();
			$("#CouponForm .brandTrArea").hide();
			$("#CouponForm .categoryTrArea").hide();
			$("#CouponForm .goodsTrArea").hide();
			$("#CouponForm .exceptArea").hide();
		}
	}
	
	// 적용범위 클릭 시
	$("#CouponForm input[name=rdoApplyScope]").bind('click', function () {
		//전체적용일때
		if ($('#CouponForm input:radio[name="rdoApplyScope"]:checked').val() == 'A'){ 
			supplyGridOptions.api.updateRowData({remove:gagaAgGrid.getAllRowData(supplyGridOptions)});
			brandGridOptions.api.updateRowData({remove:gagaAgGrid.getAllRowData(brandGridOptions)});
			cateGridOptions.api.updateRowData({remove:gagaAgGrid.getAllRowData(cateGridOptions)});
			goodsGridOptions.api.updateRowData({remove:gagaAgGrid.getAllRowData(goodsGridOptions)});
			excepGoodsGridOptions.api.updateRowData({remove:gagaAgGrid.getAllRowData(excepGoodsGridOptions)});
			
			$("#CouponForm .supplyTrArea").hide();
			$("#CouponForm .brandTrArea").hide();
			$("#CouponForm .categoryTrArea").hide();
			$("#CouponForm .goodsTrArea").hide();
			$("#CouponForm .exceptArea").hide();
		}
		//개별적용일때
		else{ 
			var radioValue = $("#CouponForm input[name=rdoCpnType]:checked").val();
			
			// 배송비 쿠폰일때
			if (radioValue == 'G230_30') {
				$("#CouponForm .supplyTrArea").show();
			} else {
				$("#CouponForm .supplyTrArea").show();
				$("#CouponForm .brandTrArea").show();
				$("#CouponForm .categoryTrArea").show();
				$("#CouponForm .goodsTrArea").show();
				$("#CouponForm .exceptArea").show();
			}
		}
	});
	
	//적용대상 - 공급처 추가 버튼시
	$('#btnSupplyAdd').on('click' , function (){
		cfnOpenCompanyListPopup("fnSetPopupComapnyInfo" , "M");
	});
	
	// 적용대상 - 브랜드 추가 버튼시
	$('#btnBrandAdd').on('click' , function(){
		cfnOpenBrandListPopup("fnSetPopupBrandInfo", "M");
	});
	
	// 적용대상 - 카테고리 추가시
	$('#btnCateAdd').on('click' , function () {
		cfnOpenCategoryPopup("fnSetPopupCategoryInfo");
	});
	
	// 적용대상 - 상품 추가시
	$('#btnGoodsAdd').on('click' , function () {
		cfnOpenGoodsPopup("fnSetPopupApplyGoodsInfo");
	});

	// 적용대상 - 제외상품 추가시
	$('#btnExcepGoodsAdd').on('click' , function(){
		cfnOpenGoodsPopup("fnSetPopupExceptGoodsInfo");
	});
	
	// 삭제버튼 클릭시
	// 1.공급업체
	$('#btnSupplyDel').on('click', function() {
		supplyGridOptions.api.updateRowData({remove:gagaAgGrid.selectedRowData(supplyGridOptions)});
	});
	// 2.브랜드
	$('#btnBrandDel').on('click', function() {
		brandGridOptions.api.updateRowData({remove:gagaAgGrid.selectedRowData(brandGridOptions)});
	});
	// 3.카테고리
	$('#btnCateDel').on('click', function() {
		cateGridOptions.api.updateRowData({remove:gagaAgGrid.selectedRowData(cateGridOptions)});
	});
	// 4.적용상품
	$('#btnGoodsDel').on('click', function() {
		goodsGridOptions.api.updateRowData({remove:gagaAgGrid.selectedRowData(goodsGridOptions)});
	});
	// 5.제외상품
	$('#btnExcepGoodsDel').on('click', function() {
		excepGoodsGridOptions.api.updateRowData({remove:gagaAgGrid.selectedRowData(excepGoodsGridOptions)});
	});
	
	// 비활성화처리 대기상태가아닐때 동작
	if (cpnDetail.cpnStat != 'G232_10' || issueCnt > 0) {
		$("#CouponForm input[name=rdoApplyScope]").attr("disabled", true);
		$('#btnSupplyDel').hide();
		$('#btnBrandDel').hide();
		$('#btnCateDel').hide();
		$('#btnGoodsDel').hide();
		$('#btnExcepGoodsDel').hide();
		
		$('#btnSupplyAdd').hide();
		$('#btnBrandAdd').hide();
		$('#btnCateAdd').hide();
		$('#btnGoodsAdd').hide();
		$('#btnExcepGoodsAdd').hide();
	}
}

//공급업체 설정 / 업체 추가 콜백함수
var fnSetPopupComapnyInfo = function(result) {
	// 기존 리스트 데이터 for
	for(let i = 0 ; i < result.length ; i++) {
		let addChk = true, gridListValue = gagaAgGrid.getAllRowData(supplyGridOptions);		// 받아온 모든 데이터

		// 받아온 data for
		for(let j = 0 ; j < gridListValue.length ; j++) {
			// 동일한 data는 추가하지 않음
			if(gridListValue[j].supplyCompCd == result[i].supplyCompCd) {	addChk = false;	}		// 중복체크
		}

		// 중복되지 않은 데이터 리스트에 추가
		if(addChk) {
			gagaAgGrid.addRowData(supplyGridOptions, {"supplyCompCd" : result[i].supplyCompCd, "supplyCompNm" : result[i].supplyCompNm});
		}
	}
};

//브랜드 설정 / 브랜드 추가 콜백함수 (단수로 가져오므로 복수일 경우에 수정 확인 필요)
var fnSetPopupBrandInfo = function(result) {
	for(let i = 0 ; i < result.length ; i++) {
		let addChk = true, gridListValue = gagaAgGrid.getAllRowData(brandGridOptions);		// 받아온 모든 데이터

		// 받아온 data for
		for(let j = 0 ; j < gridListValue.length ; j++) {
			if(gridListValue[j].brandCd == result[i].brandCd) {	addChk = false;	}					// 중복체크
		}

		// 중복되지 않은 데이터 리스트에 추가
		if(addChk) {
			gagaAgGrid.addRowData(brandGridOptions, {"brandCd" : result[i].brandCd, "brandEnm" : result[i].brandEnm, "supplyCompNm" : result[i].supplyCompNm});
		}
	}
};

//카테고리 추가 콜백 함수
var fnSetPopupCategoryInfo = function (result) {
	// 기존 리스트 데이터 for
	for(let i = 0 ; i < result.length ; i++) {
		let addChk = true, gridListValue = gagaAgGrid.getAllRowData(cateGridOptions);		// 받아온 모든 데이터

		// 받아온 data for
		for(let j = 0 ; j < gridListValue.length ; j++) {
			// 동일한 data는 추가하지 않음
			if(gridListValue[j].cateNo == result[i].cateNo) {	addChk = false;	}		// 중복체크
		}

		// 중복되지 않은 데이터 리스트에 추가
		if(addChk) {
			gagaAgGrid.addRowData(cateGridOptions, {"siteCd":result[i].siteCd , "cateGb":result[i].cateGb , "cateNo":result[i].cateNo, "cateNm":result[i].cateNm , "formalGb":result[i].formalGb , "brandEnm":null});
		}
	}
}

//적용 상품 리스트 콜백함수
var fnSetPopupApplyGoodsInfo = function(result) {
	gridAddGoodsList(goodsGridOptions, result , "apply");
};

//적용 상품 리스트 콜백함수
var fnSetPopupExceptGoodsInfo = function(result) {
	gridAddGoodsList(excepGoodsGridOptions, result , "except");
};

//ag-grid 상품관련 list 콜백함수
function gridAddGoodsList(OriginGridListOption, result, gubun) {
	var goodsGbVal = "G800_10";
	
	if (gubun == 'except') {
		goodsGbVal = "G800_30";
	}

	let addCnt 		= 0;
	let failCnt 	= 0;
	let dupliCnt 	= 0;
	let goodsDCnt 	= 0;

	for (let i = 0 ; i < result.length ; i++) {
		let addChk = true, gridListValue = gagaAgGrid.getAllRowData(OriginGridListOption);		// 받아온 모든 데이터

		if(result[i].goodsType == 'G056_D'){ //딜상품 제외
			addChk = false;
			goodsDCnt++;
		}

		// 받아온 data for
		for (let j = 0 ; j < gridListValue.length ; j++) {
			if(gridListValue[j].goodsCd == result[i].goodsCd) {	addChk = false;	dupliCnt++;}				// 중복체크
		}

		// 중복되지 않은 데이터 리스트에 추가
		if (addChk) {
			gagaAgGrid.addRowData(OriginGridListOption, {"goodsGb": goodsGbVal, "goodsCd" : result[i].goodsCd, "goodsNm" : result[i].goodsNm});
			addCnt++;
		}
	}
	uifnPopupClose('popupGoods');
	failCnt = result.length - addCnt - dupliCnt - goodsDCnt;
	mcxDialog.alert("데이터가 적용되었습니다.<br/>" + addCnt + "건 성공, "+ dupliCnt + "건 중복, "+ goodsDCnt + "건 딜상품 제외, " + failCnt + "건 실패");
}

//2021.08.17 초기화설정 변경
$(document).ready(function() {

});
</script>
</html>