<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorator="web/common/layout/MypageLayoutWeb">
<!--
 *******************************************************************************
 * @source  : MypagePointForm.html
 * @desc    : 마이페이지 > 상품권 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2021 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.03.12   sowon     최초 작성
 *******************************************************************************
 -->
<body>

	<th:block layout:fragment="content">
		<!--  container -->
	<div class="content myVoucher">
		<div class="cont_body">
			<!-- 페이지특정 클래스 = myVoucher -->
			<div class="cont_body">
				<div class="lnb">
					<div class="lnb_tit">
						<h2>마이페이지</h2>
					</div>
					<div class="lnb_list">
						<ul id="mypageLnbList"></ul>
					</div>
				</div>	
				<div class="cont">
					<div class="sec_head">
						<h3 class="subH1">상품권</h3>
					</div>
					<div class="sec_body">
						<div class="highlight_area">
							<div class="have_amount">
								<div class="total_amount">
									나의 보유 금액&nbsp;<span><em
										th:text="${#numbers.formatInteger(giftcardInfo.useGift,0,'COMMA')}"></em>원</span>
								</div>
								<dl>
									<div>
										<dt>보유 상품권</dt>
										<dd>
											<em
												th:text="${#numbers.formatInteger(giftcardInfo.totalCount,0,'COMMA')}"></em>장
										</dd>
									</div>
									<div>
										<dt>
											<span class="tag primary_line">D-<em>30</em></span>한 달 이내 소멸
											예정
										</dt>
										<dd>
											<em
												th:text="${#numbers.formatInteger(giftcardInfo.expireCount,0,'COMMA')}"></em>원
										</dd>
									</div>
								</dl>
							</div>
						</div>
						<div class="input_area">
							<form class="form_wrap">
								<div class="form_field">
									<label class="input_label"><span>상품권 등록</span></label>
									<div class="input_wrap">
										<input type="text" class="form_control" id="gift_input"
											placeholder="상품권 번호를 입력해주세요">
									</div>
									<button type="button" class="btn btn_dark"
										onclick="giftcardSave()">
										<span>등록</span>
									</button>
								</div>
							</form>
						</div>
						<div class="com_info_txt">
							<p class="tit">상품권 등록 안내</p>
							<ul>
								<li>상품권은 상품 구매시 현금과 동일하게 사용됩니다.</li>
								<li>상품권은 등록한 해당 몰에서만 사용이 가능합니다.(YES24와 중복 사용불가)</li>
								<li>사용 후 남은 잔액은 상품권 잔액으로 환불되며, 유효기간 내에 사용 가능합니다.</li>
								<li>유효기간이 지난 상품권의 잔액은 자동 소멸됩니다.</li>
								<li>상품권은 현금성 결제 수단에 포함되어 주문시 포인트 적립이 가능합니다.</li>
								<li>상품권으로 결제한 금액은 마이페이지 > 주문상세페이지에서 현금영수증을 발급 받으실 수 있습니다.</li>
							</ul>
						</div>
						<div class="content_area">
							<div class="taps">
								<div>
									<ul>
										<li id="SearchUseGiftcard"><a href="javascript:void(0);" >사용내역</a></li>
										<li id="SearchOwnGiftcard"><a href="javascript:void(0);" >보유상품권</a></li>
									</ul>
								</div>
							</div>
							<div class="select_box" id="dateField">
								<div class="form_field">
									<div class="select_custom month">
										<div class="combo">
											<div class="select"></div>
											<ul class="list" id="searchDt">
											</ul>
										</div>
									</div>
								</div>
							</div>
							<!-- 데이터 있을 시 -->
							<div class="list_box" id="giftcardList"></div>
							<!-- //데이터 있을 시 -->
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- // CONT-BODY -->
		</div>

<script th:inline="javascript">
	let date = [[${date}]];
	let year = date[0].year;
	let month = date[0].month;

	//동적으로 날짜 년도 append
	function appendYear() {
		for (var i = 0; i < date.length; i++) {
			$("#searchDt").append(	"<li onclick='fnChangeDate(this.value)' value='"+ date[i].year + "" + date[i].month + "'>" + date[i].year	+ "년" +  "  " + date[i].month + "월 </li>")
		}
		$(".select").html(date[0].year + "년"  +  "  " + date[0].month + "월"); // 현재년도 선택 */ 
	}
	appendYear($("#searchDt"));

	// 사용내역 조회
	$("#SearchUseGiftcard").click(function() {
		// class제거 추가
		$("#SearchOwnGiftcard").removeClass("active");
		$("#SearchUseGiftcard").addClass("active");
		$("#giftcardList").attr("class", "order_list");

		// 날짜 필드 
		$("#dateField").css("display", "block");

		let data = {
			searchDt : year + "" + month,
			month : month
		};

		var jsonData = JSON.stringify(data);

		$.ajax({
			type : "POST",
			data : jsonData,
			url : '/mypage/gift/use/list',
			contentType : 'application/json',
			dataType : 'json',
			success : function(result) {
				useGiftcard(result);
			}
		})
	});

	function useGiftcard(result) {

		let giftcardUseList = result.giftcardUseList;

		let tmtbHtml = "";
		tmtbHtml += '<div class="tbl type5">\n';
		tmtbHtml += '<table>\n';
		tmtbHtml += '<colgroup>\n';
		tmtbHtml += '<col width="10%">\n';
		tmtbHtml += '<col width="*">\n';
		tmtbHtml += '<col width="18%">\n';
		tmtbHtml += '<col width="18%">\n';
		tmtbHtml += '</colgroup>\n';
		tmtbHtml += '<thead>\n';
		tmtbHtml += '<tr>\n';
		tmtbHtml += '<th scope="col"><span class="sr-only">차감</span></th>\n';
		tmtbHtml += '<th scope="col">내용</th>\n';
		tmtbHtml += '<th scope="col">사용금액</th>\n';
		tmtbHtml += '<th scope="col">일자</th>\n';
		tmtbHtml += '</tr>\n';
		tmtbHtml += '</thead>\n';

		if (giftcardUseList.length <= 0) {
			tmtbHtml += '<tbody>\n';
			tmtbHtml += '</tbody>\n';
			tmtbHtml += '</table>\n';
			tmtbHtml += '</div>\n';
			tmtbHtml += '<div class="nodata">\n';
			tmtbHtml += '<div class="txt_box">\n';
			tmtbHtml += '<p>상품권 사용내역이 없습니다.<br></p>\n';
			tmtbHtml += '</div>\n';
			tmtbHtml += '</div>\n';

		} else {
			tmtbHtml += '<tbody>\n';

			for (let i = 0; i < giftcardUseList.length; i++) {
				let useGiftcard = giftcardUseList[i];
				tmtbHtml += '<tr>\n';
				if(useGiftcard.gfcdAmt > 0){
					tmtbHtml += '		<td><span class="tag primary">적립</span></td>\n';
				}else{
					tmtbHtml += '		<td><span class="tag deepgray">차감</span></td>\n';
				}
				tmtbHtml += '<td>\n';
				tmtbHtml += '<div class="txt_content" style="padding-left:40px; text-align:left;">'	+ useGiftcard.goodsNm + '</div>\n';
				tmtbHtml += '</td>\n';
				if(useGiftcard.gfcdAmt<0){
					tmtbHtml += '<td><span class="amount_minus"> <em>\n'
						+ ' '
						+ useGiftcard.gfcdAmt.addComma()
						+ '</em>원\n';
				}else{
					tmtbHtml += '<td><span class="amount_plus" style="color:#fd4802"> <em>\n'
						+ '+'
						+ useGiftcard.gfcdAmt.addComma()
						+ '</em>원\n';
				}
				
				tmtbHtml += '</span></td>\n';
				tmtbHtml += '<td>' + useGiftcard.regDt
						+ '</td>\n';
				tmtbHtml += '</tr>\n';
			}
			tmtbHtml += '</tbody>\n';
			tmtbHtml += '</table>\n';
			tmtbHtml += '</div>\n';

		}

		$("#giftcardList").html(tmtbHtml);
	}

	// 보유상품권 조회
	$("#SearchOwnGiftcard").click(function() {
		$("#SearchUseGiftcard").removeClass("active");
		$("#SearchOwnGiftcard").addClass("active");
		$("#giftcardList").attr("class", "gift_list");

		// 날짜 필드 
		$("#dateField").css("display", "none");
		let data = {};

		var jsonData = JSON.stringify(data);

		$.ajax({
			type : "POST",
			data : jsonData,
			url : '/mypage/gift/own/list',
			contentType : 'application/json',
			dataType : 'json',
			success : function(result) {
				ownGiftcard(result);
			}
		})
	});

	function ownGiftcard(result) {

		let giftcardOwnList = result.giftcardOwnList;

		let tmtbHtml2 = "";
		if (giftcardOwnList.length <=0) {
			tmtbHtml2 += '<div class="nodata">\n';
			tmtbHtml2 += '<div class="txt_box">\n';
			tmtbHtml2 += '<p>보유한 상품권이 없습니다.<br></p>\n';
			tmtbHtml2 += '</div>\n';
			tmtbHtml2 += '</div>\n';
		} else {

			tmtbHtml2 += '<div class="voucher_list">\n';
			tmtbHtml2 += '<ul>\n';
				for (let i = 0; i < giftcardOwnList.length; i++) {
				let ownGiftcard = giftcardOwnList[i];

				tmtbHtml2 += '<li>';
				if (ownGiftcard.rmGfcdAmt == 0 || ownGiftcard.useYn == 'N') {
					tmtbHtml2 += '<div class="voucher disable">\n';
				} else {
					tmtbHtml2 += '<div class="voucher">\n';
				}

				tmtbHtml2 += '<div>\n';
				tmtbHtml2 += '<p class="vch_name">'	+ ownGiftcard.gfcdNm + '</p>\n';
				tmtbHtml2 += '<p class="vch_price"><span class="tag primary_line"><em>'	+ ownGiftcard.chgGfcdAmt.addComma()	+ '</em>원권</span></p>\n';
				if (ownGiftcard.rmGfcdAmt > 0) {
					tmtbHtml2 += '<p class="vch_remain">잔액<span><em>'+ ownGiftcard.rmGfcdAmt.addComma()+ '</em>원</span></p>\n';
				} else {
					tmtbHtml2 += '<p class="vch_remain">전액소진</p>\n';
				}

				tmtbHtml2 += '<p class="vch_code">'	+ ownGiftcard.gfcdNo + '</p>\n';
				tmtbHtml2 += '</div>';
				tmtbHtml2 += '<div class="vch_date">~&nbsp;<span>'	+ ownGiftcard.useExpDate	+ '</span></div>\n';
				tmtbHtml2 += '</div>\n';
				tmtbHtml2 += '</li>\n';
			}
			tmtbHtml2 += '</ul>\n';
			tmtbHtml2 += '</div>\n';

		}

		$("#giftcardList").html(tmtbHtml2);

	}

	function fnChangeDate(obj) {
		
		var seletedDate = obj.toString();
		var splitMonth = seletedDate.substr(4);

		data = {
			month : splitMonth,
			searchDt : seletedDate
		};

		var jsonData = JSON.stringify(data);

		$.ajax({
			type : "POST",
			data : jsonData,
			url : '/mypage/gift/use/list',
			contentType : 'application/json',
			dataType : 'json',
			success : function(result) {
				useGiftcard(result);
			}
		})
	}

	// 상품권 등록 버튼 누를 시 
	function giftcardSave() {
		if ($("#gift_input").val() == ""
				|| $("#gift_input").val() == null) {
			mcxDialog.alert("상품권 번호를 입력해주세요.");
			return;
		}

		data = {
			gfcdNo : $("#gift_input").val()
		};

		var jsonData = JSON.stringify(data);

		mcxDialog.confirm("상품권을 등록 하시겠습니까?", {
			cancelBtnText : "취소",
			sureBtnText : "확인",
			sureBtnClick : function() {

				gagajf.ajaxJsonSubmit(
						'/mypage/gift/use/confirm', jsonData,
						function() {
							//$("#gift_input").val('');
							cfnGoToPage(_PAGE_MYPAGE_GIFTCARD);
						});
			}
		});

	}

	$(document).ready(function() {

		// 마이페이지 LNB 설정
		fnSetMypageLnbList(6);

		// 마이페이지 location 설정
		fnSetMypageLocation('상품권', '_PAGE_MYPAGE_GIFTCARD');

		// 전체내역 표시
		$("#SearchUseGiftcard").trigger('click');

		// 셀렉트박스 활성화
		$('.select_custom.month').each(function(index) {
			var selecter01 = new sCombo($(this));
		});
	});
</script>
</th:block>

</body>
</html>
