<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : CardPromotionForm.html
 * @desc    : 카드프로모션관리
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.02.03   eskim       최초 작성
 *******************************************************************************
 -->
	<div id="main">
		<!-- 메인타이틀 영역 -->
		<div class="main-title">
		</div>
		<!-- //메인타이틀 영역 -->
		<!-- 메뉴 설명 -->
		<div class="infoBox menu-desc">
		</div>
		<form id="cardPromotionSearchForm" name="cardPromotionSearchForm" action="#" th:action="@{'/marketing/card/promotion/list'}">
		<input type="hidden" id="prmtGb" name="prmtGb" value="B" /> <!-- 무이자 -->
 		<!-- 패널 영역1 -->
		<div class="panelStyle" >
			<!-- <div class="panelTitle">
				<h3><i class="fa fa-info-circle"></i>아래 검색조건 중 하나를 꼭 입력해 주세요.</h3>
			</div> -->
			<div class="panelContent">
				<table class="frmStyle">
					<colgroup>
						<col width="10%"/>
						<col/>
					</colgroup>
					<tr>
						<th>구분</th>
						<td>
							<label class="rdoBtn"><input type="radio" name="search"  value="1"  checked/>프로모션ID</label>
							<label class="rdoBtn"><input type="radio" name="search"  value="2"/>프로모션명</label>
							<input type="text" class="w300" maxlength="30" name="condition"/>
						</td>
					</tr>
					<tr>
						<th>기간</th>
						<td id="sellTerms"></td>
					</tr>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-gray btn-lg" id="btnInit" >초기화</button>
						<button type="button" class="btn btn-info btn-lg" id="btnSearch" >조회</button>
					</li>
				</ul>	
			</div>
			<!-- //검색조건 영역 -->
		</div>
		<!-- 패널 영역1 -->
		<div class="panelStyle">
			<!-- 검색결과 영역 -->
			<!-- 상단버튼 영역  -->
			<ul class="panelBar">
				<li>
					<button type="button" class="btn btn-danger btn-lg" id="btnCardPromotionDispUpdate">선택비노출</button>
					<button type="button" class="btn btn-danger btn-lg" id="btnCardPromotionDelete">선택삭제</button>
				</li>
				<li class="right">
					<button type="button" class="btn btn-primary btn-lg" id="btnCardPromotionSave">등록</button>
					검색결과 : <strong><span id="gridRowTotalCount">0</span> 건</strong>&nbsp;
					
					쪽번호 <span id="pgNo">0</span>/ <strong id="endPgNo">0</strong>&nbsp;&nbsp;
					<select id="pageSize" name="pageSize">
						<option value="50" selected="selected">50개씩 보기</option>
						<option value="100">100개씩 보기</option>
						<option value="500">500개씩 보기</option>
						<option value="1000">1000개씩 보기</option>
					</select>
					<input type="hidden" name="pageNo" id="pageNo" value ="1"/>
				</li>
			</ul>
			<!-- //상단버튼 영역  -->
			<div id="gridList" style="width: 100%; height: 550px;" class="ag-theme-balham"></div>
			<ul class="panelBar">
				<li class="center">
					<div class="tablePaging" id="cardListPagination"></div>
				</li>
			</ul>
			<!-- 검색결과 영역 -->
		</div>
		</form>
		<!-- //패널 영역2 -->
	</div>
<script type="text/javascript" src="/ux/plugins/gaga/gaga.paging.js?v=2019072202"></script>
<script th:inline="javascript">
/*<![CDATA[*/
	var dcGbList = { "1":"즉시할인", "2":"청구할인", "3":"제휴카드" };
	var 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('cardPromotionSearchForm',params.node.rowIndex, 'A');}
		},
		{headerName: "프로모션ID", field: "cardPrmtSq", width: 130, cellClass: 'text-center'},
		{headerName: "프로모션명", field: "prmtNm", width: 200, cellClass: 'text-center'
			,cellRenderer: function(params) {
				return '<a href="javascript:void(0);">' + params.value + '</a>';
			}
		},
		{headerName: "행사구분", field: "dcGb", width: 120, cellClass: 'text-center',
			cellEditorParams: { values: gagaAgGrid.extractValues(dcGbList) },
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(dcGbList, params.value); }
		},
		{headerName: "할인조건", field: "minPayAmt", width: 150, cellClass: 'text-center'},
		{headerName: "할인(원, %)", field: "dcValNm", width: 150, cellClass: 'text-center'},
		{headerName: "노출여부", field: "dispYn", width: 100, cellClass: 'text-center'},
		{headerName: "시작일", field: "prmtStd", width: 120, cellClass: 'text-center'},
		{headerName: "종료일", field: "prmtEdd", width: 120, cellClass: 'text-center'},
		{headerName: "수정자", field: "updNm" , width: 150, 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: "regNm", width: 150, 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") : '';
			}
		}
	];
	
	// Get GridOptions
	var gridOptions = gagaAgGrid.getGridOptions(columnDefs);

	// 중복 선택 가능
	gridOptions.rowSelection = 'multiple';
	gridOptions.suppressRowClickSelection = true;

	// Row Click
	gridOptions.onCellClicked = function(event) {
		if (event.colDef.field == "prmtNm"){
			cardPromotionPopup(event.data.cardPrmtSq);
		}
	}

	// 초기화 클릭시
	$('#btnInit').on('click', function() {
		fnInit();
	});
	
	var fnInit = function(){
		$('#cardPromotionSearchForm')[0].reset();
	}
	
	// 조회클릭시
	$('#btnSearch').on('click', function() {
		$("#cardPromotionSearchForm input[name=pageNo]").val('1');
		fnCardPromotionListSearch();
	});

	// 조회
	var fnCardPromotionListSearch = function() {
		
		if(!fnConditionCheck()) return;
		
		gagaPaging.init('cardPromotionSearchForm', fnSearchCallBack, 'cardListPagination', $('#cardPromotionSearchForm').find('#pageSize').val());
		gagaPaging.load($("#cardPromotionSearchForm input[name=pageNo]").val());
	}

	//검색 조건 확인
	var fnConditionCheck = function(){
		var formId = '#cardPromotionSearchForm';
		var form = document.cardPromotionSearchForm;

		var searchFlag = false;
		var cnt = 0;
		
		/* for (i = 0; i < form.elements.length; i++ ) {
			var el = form.elements[i];
			if ($(el).prop("type") == "text" || $(el).prop("type") == "textarea" || ($(el).prop("type") == "select-one" && 
					el.name != "search" && el.name != "pageSize" && el.name != "beforSkipFlag")) {
				if (!(el.value == null || el.value == "")) {
					cnt++;
				}
			}
		}
		
		if(cnt > 0) searchFlag = true;
		
		if(searchFlag == false){
			mcxDialog.alert("검색조건을 입력하세요.");
			return false;
		}
		 */
		var fromDate = $('#cardPromotionSearchForm input[name=stDate]').val();
		var toDate = $('#cardPromotionSearchForm input[name=edDate]').val();
		
		if (!gagajf.isNull(fromDate) || !gagajf.isNull(toDate)) {
			
			if (gagajf.isNull(fromDate) || gagajf.isNull(toDate)) {
				mcxDialog.alertC("등록일 조회시 시작일자와 종료일자를 입력하세요.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#cardPromotionSearchForm input[name=stDate]').focus();
					}
				});
				return false;
			}

			if (fromDate > toDate) {
				mcxDialog.alert("노출기간 시작일자는 종료일자 보다 클 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						$('#cardPromotionSearchForm input[name=stDate]').focus();
					}
				});
				return false;
			} 
		}

		return true;
	}
	
	var fnSearchCallBack = function(result){

		$('#cardPromotionSearchForm').find('#gridRowTotalCount').html(result.pageing.pageable.totalCount.addComma());
		$('#cardPromotionSearchForm').find('#pageNo').val(result.pageing.pageable.pageNo.addComma());
		$('#cardPromotionSearchForm').find('#pgNo').html(result.pageing.pageable.pageNo.addComma());
		$('#cardPromotionSearchForm').find('#endPgNo').html(result.pageing.pageable.totalPage.addComma());
		gridOptions.api.setRowData(result.cardPromotionList);
		gagaPaging.createPagination(result.pageing.pageable);
	}
	
	//페이징 
	$('#cardPromotionSearchForm select[name=pageSize]').on('change', function() {
		$("#cardPromotionSearchForm input[name=pageNo]").val('1');
		fnCardPromotionListSearch($("#cardPromotionSearchForm input[name=searchGb]").val());
	});
	
	//카드 무이자 팝업
	$('#btnCardPromotionSave').click(function(e) {
		cardPromotionPopup();
	});
	
	var cardPromotionPopup = function(cardPrmtSq){
		var actionUrl = "/marketing/card/promotion/popup/form/";
		if (typeof(cardPrmtSq) != 'undefined' && cardPrmtSq != null ){
			actionUrl += cardPrmtSq;
		}else{
			actionUrl += 0;
		}
		
		cfnOpenModalPopup(actionUrl, 'popupCardPromotion'); 
	}

	//카드 프로모션 비노출
	$('#btnCardPromotionDispUpdate').click(function(e) {
		//상품선택여부 확인처리 추가
		var selectedData = gridOptions.api.getSelectedRows();

		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return false;
		}
		
		var arrCardPrmtSq = [];
		var chkFlag = false;
		$.each(selectedData, function(idx, item) {
			
			var toDateStr = new Date().format("YYYYMMDD");
			if (toDateStr > item.prmtEdd.replace(/-/gi,'') ){
				chkFlag = true;
				mcxDialog.alertC("종료된 무이자할부정보는 삭제할 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						gridOptions.api.setFocusedCell(idx, "prmtEdd", null);
					}
				});
				return false;
			}
		
			arrCardPrmtSq.push(item.cardPrmtSq);
		});

		if (chkFlag){
			return;
		}
		
		mcxDialog.confirm('비노출 처리 하시겠습니까? ',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var data = {arrCardPrmtSq : arrCardPrmtSq};
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/marketing/card/promotion/dispYn/update', jsonData, fnCardPromotionDeleteCollBack);
			}
		});
		
	});
	
	//카드 프로모션 삭제
	$('#btnCardPromotionDelete').click(function(e) {
		//상품선택여부 확인처리 추가
		var selectedData = gridOptions.api.getSelectedRows();

		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 행이 없습니다.');
			return false;
		}
		
		var arrCardPrmtSq = [];
		var chkFlag = false;
		$.each(selectedData, function(idx, item) {
			
			var toDateStr = new Date().format("YYYYMMDD");
			if (toDateStr > item.prmtEdd.replace(/-/gi,'') ){
				chkFlag = true;
				mcxDialog.alertC("종료된 무이자할부정보는 삭제할 수 없습니다.", {
					sureBtnText: "확인",
					sureBtnClick: function() {
						gridOptions.api.setFocusedCell(idx, "prmtEdd", null);
					}
				});
				return false;
			}
		
			arrCardPrmtSq.push(item.cardPrmtSq);
		});

		if (chkFlag){
			return;
		}
		
		mcxDialog.confirm('삭제하시겠습니까? <br/> 삭제한 프로모션은 복구할수 없습니다.',  {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				var data = {arrCardPrmtSq : arrCardPrmtSq};
				var jsonData = JSON.stringify(data);
				gagajf.ajaxJsonSubmit('/marketing/card/promotion/delete', jsonData, fnCardPromotionDeleteCollBack);
			}
		});
	});
	
	var fnCardPromotionDeleteCollBack = function(){
		fnCardPromotionListSearch();
	}
	
	$(document).ready(function() {

		cfnCreateCalendar('#sellTerms', 'stDate', 'edDate', true, '기간', 'X');
		var chkBeforSkipFlag = '&nbsp;&nbsp;<label class="chkBox"><input type="checkbox" name="beforSkipFlag" value="Y" >이전데이터 제외</label>';
		$("#cardPromotionSearchForm").find('#sellTerms').append(chkBeforSkipFlag);
		//gagajf.setDate('#sellTerms','stDate', 'edDate', '7d');
		
		// Create a agGrid
		gagaAgGrid.createGrid('gridList', gridOptions);

	});

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