<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : CouponIssuePopupForm.html
 * @desc    : 쿠폰발급 팝업 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.01.28   jsshin     최초 작성
 *******************************************************************************
 -->
<div class="modalPopup" data-width="960" data-height="900" >
	<div id="panel" class="panelStyle">
		<!-- TITLE -->
		<div class="panelTitle">
			<strong>쿠폰 발급</strong>
			<button type="button" class="close" onclick="uifnPopupClose('popupCouponIssue');"><em class="fa fa-times"></em></button>
		</div>
		<!-- //TITLE -->

		<!-- CONTENT -->
		<div class="panelContent">
			<form id="searchCouponForm" name="searchCouponForm" action="#" th:action="@{'/marketing/coupon/retrieve/list'}" th:method="post">
				<table class="frmStyle" aria-describedby="검색조건">
					<colgroup>
						<col style="width:10%;"/>
						<col style="width:40%;"/>
						<col style="width:10%;"/>
						<col style="width:40%;"/>
					</colgroup>
					<tbody>
						<tr>
							<th>사이트<em class="required" title="필수"></em></th>
							<td>
								<select name="siteCd" required="required">
									<option th:if="${siteList}" th:each="oneData, status : ${siteList}" th:value="${oneData.cd}" th:text="|[${oneData.cd}] ${oneData.cdNm}|"></option>
								</select>
							</td>
							<th>쿠폰유형</th>
							<td>
								<select name="cpnType">
									<option value="">[전체]</option>
									<option th:if="${cpnTypeList}" th:each="oneData, status : ${cpnTypeList}" th:value="${oneData.cd}" th:text="|[${oneData.cd}] ${oneData.cdNm}|"></option>
								</select>
							</td>
						</tr>
						<tr>
							<th>쿠폰ID</th>
							<td>
								<input type="text" name="cpnId" maxlength="20"/>
							</td>
							<th>쿠폰명</th>
							<td>
								<input type="text" name="cpnNm" maxlength="50"/>
							</td>
						</tr>
					</tbody>
				</table>
				<ul class="panelBar">
					<li class="center">
						<button type="button" class="btn btn-base btn-lg" id="btnSearchCouponRetrieve">조회</button>
					</li>
				</ul>
			</form>
			<!-- 리스트 영역 -->
			<div id="gridCouponList" style="width: 100%; height: 420px;" class="ag-theme-balham"></div>
			<!-- //리스트 영역 -->
			<form id="couponIssueForm" name="couponIssueForm">
				<input type="hidden" name="cpnId"/>
				<input type="hidden" name="pdGb"/>
				<input type="hidden" name="custNo"/>
				<table class="frmStyle" aria-describedby="발급내용">
					<colgroup>
						<col style="width: 10%"/>
						<col style="width: 40%"/>
						<col style="width: 10%"/>
						<col style="width: 40%"/>
					</colgroup>
					<tr id="availTermsTr">
						<th class="availTerm">유효기간시작일시<em class="required" title="필수"></em></th>
						<td class="availTerm">
							<input type="text" name="availStdt" class="schDate w100" data-valid-name="유효기간시작일시"/>
							<select name="availStHH" data-valid-name="유효기간시작(시)"required="required">
								<th:block th:each="num, index : ${#numbers.sequence(0, 23)}">
									<option th:value="${#numbers.formatInteger(num, 2)}" th:text="|${#numbers.formatInteger(num, 2)}시|">시간</option>
								</th:block>
							</select>
							<select name="availStMM" data-valid-name="유효기간시작(분)" required="required">
								<th:block th:each="num, index : ${#numbers.sequence(0, 59)}">
									<option th:value="${#numbers.formatInteger(num, 2)}" th:text="|${#numbers.formatInteger(num, 2)}분|">분</option>
								</th:block>
							</select>
						</td>

						<th class="availTerm">유효기간종료일시<em class="required" title="필수"></em></th>
						<td class="availTerm">
							<input type="text" name="availEddt" class="schDate w100" data-valid-name="유효기간종료일시"/>
							<select name="availEdHH" data-valid-name="유효기간종료(시)">
								<th:block th:each="num, index  : ${#numbers.sequence(0, 23)}">
									<option th:value="${#numbers.formatInteger(num, 2)}" th:text="|${#numbers.formatInteger(num, 2)}시|">시간</option>
								</th:block>
							</select>
							<select name="availEdMM" data-valid-name="유효기간종료(분)">
								<th:block th:each="num: ${#numbers.sequence(0, 59)}">
									<option th:value="${#numbers.formatInteger(num, 2)}" th:text="|${#numbers.formatInteger(num, 2)}분|">분</option>
								</th:block>
							</select>
						</td>
					</tr>
					<tr id="availDaysTr" style="display:none;">
						<th>유효기간(일)</th>
						<td><input type="text" name="availDays" data-valid-type="integer"></td>
					</tr>
					<tr>
						<th>발급사유</th>
						<td>
							<select name="pubReason" data-valid-name="발급사유" required>
								<option th:if="${cpnPubReasonList}" th:each="oneData, status : ${cpnPubReasonList}" th:value="${oneData.cd}"
										th:text="${'[' + oneData.cd + '] ' + oneData.cdNm}"></option>
							</select>
						</td>
						<th>만료알림발송여부<em class="required" title="필수"></em></th>
						<td>
							<select name="endAlimSendYn" id="endAlimSendYn" data-valid-name="만료알림발송여부" required="required">
								<option value="Y">Y</option>
								<option value="N" selected="selected">N</option>
							</select>
						</td>
					</tr>
					<tr>
						<th>상세사유</th>
						<td colspan="3">
							<textarea name="pubReasonDtl" class="textareaR3" style="resize: none;"  data-valid-name="상세사유" required="required"></textarea>
						</td>
					</tr>
				</table>
			</form>
			<!-- 버튼 배치 영역 -->
			<ul class="panelBar">
				<li class="right">
					<button type="button" class="btn btn-info btn-lg" id="btnIssueCoupon">발급</button>
				</li>
			</ul>
			<!-- //버튼 배치 영역 -->
		</div>
	</div>
</div>

<script th:inline="javascript">
/*<![CDATA[*/
	const START_END_TIME = '00';
	const END_TIME = '59';

	let elementCustNo = [[${elementCustNo}]];

	let siteList = gagajf.convertToArray([[${siteList}]]);
	let usableCustGbList = gagajf.convertToArray([[${usableCustGbList}]]);
	let cpnTypeList = gagajf.convertToArray([[${cpnTypeList}]]);
	let dcWayList = gagajf.convertToArray([[${dcWayList}]]);
	
	let columnDefsCouponList = [
// 		{width: 40, minWidth: 40, cellClass: 'text-center', headerCheckboxSelection: true, checkboxSelection: true, filter: false},
		{
			headerName: "사이트", field: "siteCd", width: 80, cellClass: "text-center", pinned: 'left',
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(siteList, params.value); }
		},
		{headerName: "쿠폰ID", field: "cpnId", width: 90, cellClass: 'text-center', pinned: 'left'},
		{headerName: "쿠폰명", field: "cpnNm", width: 150, pinned: 'left'},
		{
			headerName: "사용가능고객", field: "usableCustGb", width: 120, cellClass: "text-center",
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(usableCustGbList, params.value); }
		},
		{
			headerName: "쿠폰유형", field: "cpnType", width: 100, cellClass: "text-center",
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(cpnTypeList, params.value); }
		},
		{
			headerName: "할인방식", field: "dcWay", width: 100, cellClass: "text-center",
			valueFormatter: function (params) { return gagaAgGrid.lookupValue(dcWayList, params.value); }
		},
		{
			headerName: "할인값(PC)", field: "dcPval", width: 100, cellClass: "text-center",
			cellRenderer: function(params) { return (!gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) : '') + (params.data.dcWay == 'G240_10' ? '원' : '%'); }
		},
		{
			headerName: "할인값(모바일)", field: "dcMval", width: 100, cellClass: "text-center",
			cellRenderer: function(params) { return (!gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) : '') + (params.data.dcWay == 'G240_10' ? '원' : '%'); }
		},
		{
			headerName: "최고할인값", field: "maxDcAmt", width: 100, cellClass: "text-center",
			cellRenderer: function(params) { return (!gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) + '원' : '');}
		},
		{
			headerName: "유효기간", field: "availPeriod", width: 300, cellClass: "text-center",
			cellRenderer: function(params) {
				return params.data.pdGb == 'P' ? gagaAgGrid.toDateTimeFormat(params.data.availStdt)
					+ '~' + gagaAgGrid.toDateTimeFormat(params.data.availEddt) : gagaAgGrid.toAddComma(params.data.availDays) + '일';
			}
		},
		{headerName: "발행제한여부", field: "pubLimitYn", width: 100, cellClass: "text-center"},
		{
			headerName: "고객당발행제한수량", field: "custPubLimitQty", width: 100, cellClass: "text-center",
			cellRenderer: function(params) { return !gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) : ''; }
		},
		{
			headerName: "총발행제한수량", field: "totPubLimitQty", width: 100, cellClass: "text-center",
			cellRenderer: function(params) { return !gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) : ''; }
		},
		{
			headerName: "1회발행수량", field: "onePubQty", width: 100, cellClass: "text-center",
			cellRenderer: function(params) { return !gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) : ''; }
		},
		{headerName: "다운로드구분", field: "dnGb", width: 100, cellClass: "text-center"},
		{
			headerName: "구매제한금액", field: "buyLimitAmt", width: 100, cellClass: "text-right",
			cellRenderer: function(params) { return !gagajf.isNull(params.value) ? gagaAgGrid.toAddComma(params.value) : ''; }
		}
	];

	let gridOptionsCouponList = gagaAgGrid.getGridOptions(columnDefsCouponList);
	
	gridOptionsCouponList.rowSelection = 'single';
	gridOptionsCouponList.rowMultiSelectWithClick = true; // 클릭으로 선택 가능

	// 셀 클릭 이벤트
	gridOptionsCouponList.onCellClicked = function (event) {
		fnBindCouponInfo(event.data);
	};

	// 조회
	$('#btnSearchCouponRetrieve').on('click', function() {
		// Fetch data
		gagaAgGrid.fetch($('#searchCouponForm').prop('action'), gridOptionsCouponList, '#searchCouponForm');
	});
	

	// 발생
	$('#btnIssueCoupon').on('click', function() {
		let selectedData = gagaAgGrid.selectedRowData(gridOptionsCouponList);
		if (selectedData.length == 0) {
			mcxDialog.alert('선택된 쿠폰이 없습니다.');
			return false;
		}

		if (!gagajf.validation('#couponIssueForm'))
			return ;

		let availStHH = $("#couponIssueForm select[name=availStHH]").val();
		let availStMM = $("#couponIssueForm select[name=availStMM]").val();
		let availEdHH = $("#couponIssueForm select[name=availEdHH]").val();
		let availEdMM = $("#couponIssueForm select[name=availEdMM]").val();

		let custCoupon = $("#couponIssueForm").serializeObject();
		if (custCoupon.pdGb === 'P') {
			if (gagajf.isNull(custCoupon.availStdt) && gagajf.isNull(custCoupon.availEddt)) {
				mcxDialog.alert("유효 시작일시 / 유효 종료일시를 입력해주세요");
				return;
			}
			custCoupon.availStdt = custCoupon.availStdt+' '+availStHH +':'+ availStMM + ':' +START_END_TIME;
			custCoupon.availEddt = custCoupon.availEddt+' '+availEdHH +':'+ availEdMM + ':' +END_TIME;
			let today = new Date().format('YYYY-MM-DD');
			if (custCoupon.availStdt < today || custCoupon.availEddt < today) {
				mcxDialog.alert("유효 시작일시 / 유효 종료일시는 오늘일자 보다 크거나 같아야 합니다.");
				return;
			}
		}

		if (custCoupon.pdGb === 'D') {
			if (gagajf.isNull(custCoupon.availDays)) {
				mcxDialog.alert("유효기간(일)을 입력해주세요");
				return;
			}
		}

		mcxDialog.confirm("저장하시겠습니까?", {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function () {
				let jsonData = JSON.stringify(custCoupon);
				//console.log(jsonData);
				gagajf.ajaxJsonSubmit('/marketing/coupon/issue/save', jsonData, fnIssueCouponCallBack);
			}
		});

	});

	var fnIssueCouponCallBack = function () {
		uifnPopupClose('popupCouponIssue');
		fnSearchCoupon();
	}



	// 선택 쿠폰정보 셋팅
	var fnBindCouponInfo = function(params) {
		$('#couponIssueForm input[name=cpnId]').val(params.cpnId);
		$('#couponIssueForm input[name=pdGb]').val(params.pdGb);

		if (params.pdGb === 'P') {
			let stdt = params.availStdt.split(' ')[1].replaceAll(':','');
			let eddt = params.availEddt.split(' ')[1].replaceAll(':','');
			$('#couponIssueForm input[name=availStdt]').val(gagaAgGrid.toDateFormat(params.availStdt));
			$("#couponIssueForm select[name=availStHH]").val(stdt.substring(0, 2));
			$("#couponIssueForm select[name=availStMM]").val(stdt.substring(2, 4));
			$('#couponIssueForm input[name=availEddt]').val(gagaAgGrid.toDateFormat(params.availEddt));
			$("#couponIssueForm select[name=availEdHH]").val(eddt.substring(0, 2));
			$("#couponIssueForm select[name=availEdMM]").val(eddt.substring(2, 4));
		} else {
			$('#couponIssueForm input[name=availDays]').val(params.availDays);
		}

		//유효기간 숨김처리
		if (params.pdGb === 'P') {
			$("#availTermsTr").show();
			$("#availDaysTr").hide();
		} else if (params.pdGb === 'D') {
			$("#availTermsTr").hide();
			$("#availDaysTr").show();
		}

	}

	var fnInitDataSet = function () {
		let custNo = $(elementCustNo).val();
		if(!gagajf.isNull(custNo)) {
			$('#couponIssueForm input[name=custNo]').val(custNo);
		}
	};

	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('gridCouponList', gridOptionsCouponList);

		fnInitDataSet();


	});
/*]]>*/
</script>

</html>
