<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
	layout:decorator="mob/common/layout/MypageLayoutMob">
<!--
 *******************************************************************************
 * @source  : MypageGiftcardFormMob.html
 * @desc    : 마이페이지 > 상품권 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.04.12   sowon     최초 작성
 *******************************************************************************
 -->
<body>
<!-- 상단헤드 //? -->
<th:block layout:fragment="content">
		<main role="" id="" class="container my">
			<section class="content myVoucher">

				<div class="inner">
					<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>
						</div>
					</div>
					<div class="have_amount">
						<dl>
							<div>
								<dt>보유 상품권</dt>
								<dd><em th:text="${#numbers.formatInteger(giftcardInfo.totalCount,0,'COMMA')}"></em>장</dd>
							</div>
						</dl>
						<dl>
							<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="inner">
						
					<div class="ADwrap">
						<span class="adcopy">상품권 등록</span>
						<div class="tip_wrap tip1" >
							<div class="tip_tit">?</div>
							<div class="tip_contents">
								<p class="tip_txt">
									<ul>
										<li>상품권은 상품 구매 시 현금과 동일하게 사용됩니다.</li>
										<li>상품권은 등록한 해당 몰에서만  사용이 가능합니다.<br>(YES24와 중복 사용 불가)</li>
										<li>사용 후 남은 잔액은 상품권 잔액으로 환불되며, 유효 기간 내에 사용가능합니다.</li>
										<li>유효 기간이 지난 상품권의 잔액은 자동 소멸됩니다.</li>
										<li>상품권은 현금성 결제 수단에 포함되어 주문시 포인트 적립이 가능합니다.</li>
										<li>상품권으로 결제한 금액은 마이페이지 &gt; 주문 상세 페이지에서 현금영수증을 발급 받으실 수 있습니다.</li>
									</ul>
								</p>
							</div>
						</div>
					</div>
					<div class="form_field">
						<div class="input_wrap certi_wrap">
							<input type="text" class="form_control"  id="gift_input" placeholder="상품권 번호를 입력해주세요.">
							<button type="button" id="btn_gift_confirm" class="btn btn_dark" onclick="giftcardSave()"><span>등록</span></button> <!-- 210409_추가 : btn_gift_confirm id 추가 -->
						</div>
					</div>

				</div>

				<div class="inner wide">
					<div class="select_box">
						<div class="form_field">
							<div class="select_custom month sup">
								<!-- 210408_ 수정 : 스크립트없는 기본 셀렉터 사용으로 변경 -->
								<div class="select pure">
									<select name="month" id="month" onchange='fnChangeDate(this.value)' >
									</select>
								</div>
							</div>
						</div>
					</div>
					<div class="tabWrap">
						<ul class="tabIndex">
							<li id="SearchUseGiftcard"><a href="javascript:void(0);" >사용내역</a></li>
							<li id="SearchOwnGiftcard"><a href="javascript:void(0);" >보유상품권</a></li>
						</ul>
						<div class="tabContents">
							<div class="tab_cont" id="giftcardList"></div> 
						</div>
					</div>
				</div>

			</section>
		</main>
<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++) {
		$("#month").append(	"<option value='"+ date[i].year + "" + date[i].month + "'>" + date[i].year	+ "년" + date[i].month + "월 </option>")
	}
	//$(".month").append("<option class='selected' value='"+date[0].year+""+date[0].month+"'>"+ date[0].year + "년" + date[0].month + "월 </option>"); // 현재년도 선택 */ 
}
appendYear($("#month"));

// 사용내역 조회
$("#SearchUseGiftcard").click(function() {
	// class제거 추가
	$("#SearchOwnGiftcard").removeClass("active");
	$("#SearchUseGiftcard").addClass("active");
	$("#giftcardList").attr("class", "tab_cont active");
	
	// 2021.08.13 날짜 선택박스 활성화 처리
	$(".select_box select").removeAttr("disabled");

	// 날짜 필드 
	$("#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 = '';
	
	if (giftcardUseList.length == 0) {
		tmtbHtml += '<div class="nodata">';
		tmtbHtml += '<div class="txt_box">';
		tmtbHtml += '<p>상품권 사용내역이 없습니다.<br></p>';
		tmtbHtml += '</div>';
		tmtbHtml += '</div>';
	}else{
		tmtbHtml += '<ul>                                                                   ';
		for (let i = 0; i < giftcardUseList.length; i++) {
			let useGiftcard = giftcardUseList[i];
			tmtbHtml += '	<li>                                                               ';
			tmtbHtml += '		<div>                                                          ';
			if (useGiftcard.gfcdAmt<0) {
				tmtbHtml += '			<span class="tag deepgray">차감</span>                       ';
			}else{
				tmtbHtml += '		    <span class="tag primary">적립</span>';
			}
			
			tmtbHtml += '			<span class="tag_name">'+useGiftcard.occurDtlDesc+'</span>                         ';
			tmtbHtml += '			<span class="txt_content">'	+ useGiftcard.goodsNm + '</span>   ';
			tmtbHtml += '			<span class="txt_time">'+useGiftcard.regDt+'</span>          ';
			tmtbHtml += '		</div>                                                         ';
			tmtbHtml += '		<div>                                                          ';
			if (useGiftcard.gfcdAmt<0) {
				tmtbHtml += '			<span class="amount_minus">                                ';
				tmtbHtml += '				<em>'+useGiftcard.gfcdAmt.addComma()+'</em>원                                      ';
				tmtbHtml += '			</span>                                                    ';
			}else{
				tmtbHtml += '			<span class="amount_plus" style="color:#fd4802">                                ';
				tmtbHtml += '				<em>+'+useGiftcard.gfcdAmt.addComma()+'</em>원                                      ';
				tmtbHtml += '			</span>                                                    ';
			}
			
			tmtbHtml += '		</div>                                                         ';
			tmtbHtml += '	</li>                                                              ';
		}
		
		tmtbHtml += '</ul>                                                                  ';
	}

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

// 보유상품권 조회
$("#SearchOwnGiftcard").click(function() {
	$("#SearchUseGiftcard").removeClass("active");
	$("#SearchOwnGiftcard").addClass("active");
	$("#giftcardList").attr("class", "tab_cont active");
	
	// 2021.08.13 날짜 선택박스 disabled 처리
	$(".select_box select").attr("disabled","disabled");

	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">';
		tmtbHtml2 += '<div class="txt_box">';
		tmtbHtml2 += '<p>보유한 상품권이 없습니다.<br></p>';
		tmtbHtml2 += '</div>';
		tmtbHtml2 += '</div>';
	} else {
		
		for (let i = 0; i < giftcardOwnList.length; i++) {
			let ownGiftcard = giftcardOwnList[i];
			if (ownGiftcard.rmGfcdAmt == 0 || ownGiftcard.useYn == 'N') {
				tmtbHtml2 += '<div class="voucher disable">';
			} else {
				tmtbHtml2 += '<div class="voucher">';
			}
			tmtbHtml2 += '	<div>';
			tmtbHtml2 += '		<p class="vch_name">'+ ownGiftcard.gfcdNm +'</p>';
			tmtbHtml2 += '		<p class="vch_price">';
			tmtbHtml2 += '			<span class="tag primary_line"><em>'+ ownGiftcard.chgGfcdAmt.addComma()	+ '</em>원권</span>';
			tmtbHtml2 += '		</p>';
			if (ownGiftcard.rmGfcdAmt > 0) {
				tmtbHtml2 += '<p class="vch_remain">잔액<span><em>'+ ownGiftcard.rmGfcdAmt.addComma()+ '</em>원</span></p>';
			} else {
				tmtbHtml2 += '<p class="vch_remain">전액소진</p>';
			}
			tmtbHtml2 += '		<p class="vch_code">'	+ ownGiftcard.gfcdNo + '</p>';
			tmtbHtml2 += '	</div>';
			tmtbHtml2 += '	<div class="vch_date">';
			tmtbHtml2 += '		~&nbsp;<span>'	+ ownGiftcard.useExpDate + '</span>';
			tmtbHtml2 += '	</div>';
			tmtbHtml2 += '</div>';
		}
	}
	$("#giftcardList").html(tmtbHtml2);

}

function fnChangeDate(obj) {
	console.log(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);
					});
		}
	});

}



/*<![CDATA[*/
$(document).ready(function() {
	$('#htopTitle').text('상품권');
	// 전체내역 표시
	$("#SearchUseGiftcard").trigger('click');
	// 셀렉트박스 활성화
	$('.select').each(function(index) {
		var selecter01 = new sCombo($(this));
	});
});
/*]]>*/
</script>
	</th:block>

</body>
</html>