<!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  : MypageReturnFormWeb.html
 * @desc    : 마이페이지 > 반품신청 Page
 *============================================================================
 * STYLE24
 * Copyright(C) 2021 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2021.02.25   card007     최초 작성
 *******************************************************************************
 -->
<body>

<th:block layout:fragment="content">
	<div class="content myOrderList">
		<div class="cont_body">
			<!-- CONT-BODY -->
			<div class="lnb">
				<div class="lnb_tit">
					<h2>마이페이지</h2>
				</div>
				<div class="lnb_list">
					<ul id="mypageLnbList"></ul>
				</div>
			</div>
			<div class="my_cont">
				<div class="sec_head">
					<h3>반품 신청</h3>
					<div class="od_detail">
						(주문번호 : <span class="num" th:text="${ordNo}"></span>)
					</div>
				</div>
				<div class="sec_body mypage_body">
					<form class="form_wrap" role="form">
						<div class="order_list">
							<section class="order_row">
								<div class="part_deliver">
									<div class="tbl_tit">
										<!-- 주문일/선물일 설정 -->
										<span class="start_t" th:unless="${returnList.oneData.giftPackYn == 'Y'}">주문일</span>
										<span class="gift_t" th:if="${returnList.oneData.giftPackYn == 'Y'}">선물일</span>
										<!-- //주문일/선물일 설정 -->
		
										<span class="order_date" th:text="${returnList.oneData.ordDt}"></span>
		
										<!-- 배송구분 설정 -->
										<span class="order_label02" th:if="${returnList.shotDelv}">총알배송</span>
										<span class="order_label01" th:if="${returnList.selfMall}">STYLE24 일반배송</span>
										<span class="order_label01" th:if="${returnList.supplyMall}">업체직배송</span>
										<!-- //배송구분 설정 -->
										<a href="javascript:void(0)" class="detail_btn" th:attr="ordNo=${returnList.oneData.ordNo}" onclick="fnGoToOrderDetail(this)">주문상세보기</a>
									</div>
									<div class="tbl type2">
										<table id="returnList">
											<colgroup>
												<col width="1020">
												<col width="180">
											</colgroup>
											<tbody>
											<th:block th:if="${returnList.returnList}" th:each="return, status : ${returnList.returnList}" th:with="imageUrl=${@environment.getProperty('upload.goods.view')}">
												<tr>
													<td>
														<div class="info_item">
															<div class="thumb_box">
																<a href="">
																	<img th:src="${imageUrl + '/' + return.sysImgNm}" width="100%" alt="">
																</a>
															</div>
															<div class="info_box">
																<p class="od_name">
																	<a href="">
																		<span class="brand" th:text="${return.brandNm}"></span>
																		<span class="name" th:text="${return.goodsNm}"></span>
																	</a>
																</p>
																<p class="od_opt">
																	<span class="option"><em th:text="${return.optCd1}"></em><em th:text="${return.optCd2}"></em></span>
																	<span class="count">수량 <em th:text="${return.ordQty}"></em>개</span>
																</p>
															</div>
															<div class="info_calc">
																<p class="price">
																	<span class="selling_price" th:text="|${#numbers.formatInteger(return.ordAmt, 1, 'COMMA')}원|"></span>
																</p>
																<p class="point"><span th:text="${#numbers.formatInteger(return.savePntAmt, 1, 'COMMA')}"></span>p</p>
															</div>
														</div>
													</td>
													<td class="cnt_sel">
														<span class="cnt_t">수량</span>
														<div class="form_field">
															<div class="select_custom type1">
																<div class="combo">
																	<input type="hidden" name="chgQty" value="0" th:attr="ordDtlNo=${return.ordDtlNo}, ordCanChgQty=${return.ordCanChgQty}"/>
																	<div class="select">선택</div>
																	<ul class="list" style="width:100px; margin:0 auto">
																		<li class="selected" value="0">선택</li>
																		<li th:if="${return.ordCanChgQty > 0}" th:each="num : ${#numbers.sequence(1,return.ordCanChgQty)}" th:value="${num}" th:text="${num}" onclick="fnChangeQty(this);"></li>
																	</ul>
																</div>
															</div>
														</div>
		<!--												<select class="select_dress" name="chgQty" onchange="fnChangeQty();">-->
		<!--													<option value="">선택</option>-->
		<!--													<option th:if="${return.ordQty > 0}" th:each="num : ${#numbers.sequence(1,return.ordQty)}" th:value="${num}" th:text="${num}"></option>-->
		<!--												</select>-->
													</td>
												</tr>
											</th:block>
											</tbody>
										</table>
									</div>
									<div class="order_confirm">
										<p class="cf_txt cf_desc c_primary">반품하실 상품의 수량을 선택하신 후 반품 신청을 하실 수 있습니다.</p>
									</div>
								</div>
							</section>
							<section class="order_row">
								<div class="tbl_tit">
									<h3 class="subH3">반품 사유</h3>
								</div>
								<div class="tbl type1">
									<table>
										<colgroup>
											<col width="*">
										</colgroup>
										<tbody>
										<tr>
											<td>
												<div class="form_field">
													<div class="select_custom type1">
														<div class="combo">
															<input type="hidden" name="chgReason"/>
															<div class="select">반품 사유를 선택하세요</div>
															<ul class="list" style="width:400px">
																<li class="selected" value="">반품 사유를 선택하세요</li>
																<li th:if="${returnReason}" th:each="oneData, status : ${returnReason}" th:value="${oneData.cd}" th:text="${oneData.cdNm}" onclick="fnChangeReason(this);"></li>
															</ul>
														</div>
													</div>
												</div>
											</td>
										</tr>
										<tr>
											<td>
												<textarea class="doc_exchange" name="chgMemo" id="chgMemo" placeholder="자세한 사유를 입력해주세요." onkeyup="fnGetTextLength(this, 200);"></textarea>
												<p class="txt_cnt"><span id="return_cnt" class="c_primary">0</span>/200</p>
											</td>
										</tr>
										</tbody>
									</table>
								</div>
							</section>
							<section class="order_row" id="wdGb">
								<div class="order_tit">
									<h3 class="subH3">반품 방식 선택</h3>
								</div>
								<div class="tbl type1">
									<table>
										<colgroup>
											<col width="*">
										</colgroup>
										<tbody>
										<tr>
											<td>
												<div class="form_field radio_field">
													<div class="">
														<input type="radio" name="wdGb" id="withdraw" value="W" checked>
														<label for="withdraw"><span>방문회수 <b class="c_primary">택배사에서 방문하여 회수</b></span></label>
													</div>
													<div class="">
														<input type="radio" name="wdGb" id="direct" value="D">
														<label for="direct"><span>직접반송 <b class="c_primary">고객이 직접 반송처리</b></span></label>
													</div>
												</div>
											</td>
										</tr>
										</tbody>
									</table>
								</div>
							</section>
							<section class="order_row" id="chgerLocation">
								<div class="order_tit">
									<h3 class="subH3">상품 회수지</h3>
									<span class="del_t">택배사에서 반품 상품을 직접 회수할 장소 선택</span>
									<button type="button" class="btn_popup" onclick="fnChangeDeliveryAddr('chger');"><span>회수지 선택</span></button>
								</div>
								<div class="tbl type1">
									<table>
										<colgroup>
											<col width="200">
											<col width="*">
										</colgroup>
										<tbody>
										<tr>
											<th>성명</th>
											<td id="chgerNm" th:text="${deliveryAddrInfo.recipNm}"></td>
											<input type="hidden" name="chgerNm" th:value="${deliveryAddrInfo.recipNm}">
										</tr>
										<tr>
											<th>연락처</th>
											<td id="chgerPhnno" th:text="${deliveryAddrInfo.recipPhnno}"></td>
											<input type="hidden" name="chgerPhnno" th:value="${deliveryAddrInfo.recipPhnno}">
										</tr>
										<tr>
											<th>주소</th>
											<td id="chgerAddr" th:text="|${deliveryAddrInfo.recipBaseAddr} ${deliveryAddrInfo.recipDtlAddr}|"></td>
											<input type="hidden" name="chgerBaseAddr" th:value="${deliveryAddrInfo.recipBaseAddr}">
											<input type="hidden" name="chgerDtlAddr" th:value="${deliveryAddrInfo.recipDtlAddr}">
										</tr>
										</tbody>
									</table>
								</div>
							</section>
							<section class="order_row" id="returnLocation" style="display:none">
								<div class="order_tit">
									<h3 class="subH3">반품하실 배송지</h3>
								</div>
								<div class="tbl type1">
									<table>
										<colgroup>
											<col width="200">
											<col width="*">
										</colgroup>
										<tbody>
										<tr>
											<th>성명</th>
											<td th:text="${deliveryAddrInfo.rtnLocNm}"></td>
											<input type="hidden" name="rtnLocNm" th:value="${deliveryAddrInfo.rtnLocNm}">
										</tr>
										<tr>
											<th>연락처</th>
											<td th:text="${deliveryAddrInfo.rtnLocTelno}"></td>
											<input type="hidden" name="rtnLocTelno" th:value="${deliveryAddrInfo.rtnLocTelno}">
										</tr>
										<tr>
											<th>주소</th>
											<td th:text="|${deliveryAddrInfo.rtnLocBaseAddr} ${deliveryAddrInfo.rtnLocDtlAddr}|"></td>
											<input type="hidden" name="rtnLocBaseAddr" th:value="${deliveryAddrInfo.rtnLocBaseAddr}">
											<input type="hidden" name="rtnLocDtlAddr" th:value="${deliveryAddrInfo.rtnLocDtlAddr}">
										</tr>
										</tbody>
									</table>
								</div>
							</section>
							<section class="order_row">
								<div class="order_tit">
									<h3 class="subH3">환불 정보</h3>
									<button type="button" class="btn_popup"><span>취소 전표 보기</span></button>
								</div>
								<div class="tbl type1 re_info_tbl">
									<div class="r_left">
										<dl>
											<dt>환불(예정) 금액</dt>
											<dd>
												<span class="big_t"><strong id="returnAmt">0</strong>원</span>
											</dd>
										</dl>
										<dl>
											<dt>상품취소 금액</dt>
											<dd>
												<span id="goodsCancelAmt">0</span>원
											</dd>
										</dl>
										<dl>
											<dt>배송비</dt>
											<dd>
												<span id="deliveryFee">0</span>원
											</dd>
										</dl>
										<dl>
											<dt>할인금액 차감</dt>
											<dd>
												<span id="deductDcAmt">0</span>원
											</dd>
										</dl>
									</div>
									<div class="r_right">
										<dl>
											<dt>환불수단</dt>
											<dd>
												<span th:text="${paymentInfo.payMeansNm}"></span>
											</dd>
										</dl>
										<dl>
											<dt>결제금액 환불</dt>
											<dd>
												<span id="refundPayAmt">0</span>원
											</dd>
										</dl>
										<dl>
											<dt>포인트 환불</dt>
											<dd>
												<span id="refundPoint">0</span>P
											</dd>
										</dl>
										<dl>
											<dt>상품권 환불</dt>
											<dd>
												<span id="refundGiftCard">0</span>원
											</dd>
										</dl>
									</div>
								</div>
								<p class="alert_t">※ 카드사로 결제 취소 요청이 전달된 후 환불까지는 평일 기준 3 ~7일이 소요될 수 있습니다.</p>
							</section>
							<section class="order_row" id="addDeliveryFee" style="display:none">
								<div class="ship_fee">
									<p><span class="c_primary" id="addPayCost">2,500원</span> 배송비 추가 결제가 필요합니다.</p>
									<input type="hidden" name="addPayCost"/>
								</div>
							</section>
							<div class="btn_wrap">
								<button type="button" class="btn btn_default cancle_btn" onclick="cfnGoToPage(_PAGE_MYPAGE_CRE_LIST)"><span>반품 취소</span></button>
								<button tyep="submit" class="btn btn_primary submit_btn" onclick="fnReturn()"><span id="returnButton">반품 신청</span></button>
							</div>
						</div>
					</form>
				</div>
			</div>
			<!-- // CONT-BODY -->
		</div>
	</div>
<script src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
	let returnList = [[${returnList.returnList}]];
	let oneData = [[${returnList.oneData}]];
	let usedGiftCardInfo = [[${usedGiftCardInfo}]];
	let usedPointInfo = [[${usedPointInfo}]];

	$(document).ready(function() {
		// 마이페이지 LNB 설정
		fnSetMypageLnbList(2);
		
		// 마이페이지 location 설정
		fnSetMypageLocation('취소/반품/교환 내역', '_PAGE_MYPAGE_CRE_LIST', '반품 신청');
		
		// 셀렉트박스 활성화
		$('.select_custom.type1').each(function(index) {
			var selecter01 = new sCombo($(this));
		});

		// 입점업체의 경우 회수방식 직접배송 처리
		if (oneData.selfGoodsYn == 'Y') {
			$('#direct').click();
			$('#wdGb').css('display','none');
		}
	});
	
	// 반품 처리
	var fnReturn = function() {
		// TODO
		// 반품신청 처리
	}
	
	// 반품 수량 변경 이벤트 처리
	var fnChangeQty = function(param) {
		let url = '/mypage/cancel/refund/amt/calculate';

		if (param != null) {
			$(param).parent().parent().find('input[name=chgQty]').val($(param).val());
		}

		let chgReason = $('input[name=chgReason]').val();

		console.log(chgReason);
		if (!gagajf.isNull(chgReason)) {
			let returnRequestList = [];

			// 반품 수량 설정
			let chgQtyArr = [];
			let ordDtlNoArr = [];
			let ordCanChgQtyArr = [];
			let chgQtyChk = 0;
			$.each($('input[name=chgQty]'), function(idx, item) {
				let chgQty = $(item).val();
				let ordDtlNo = $(item).attr('ordDtlNo');
				let ordCanChgQty = $(item).attr('ordCanChgQty');

				chgQtyArr.push(Number(chgQty));
				ordDtlNoArr.push(Number(ordDtlNo));
				ordCanChgQtyArr.push(Number(ordCanChgQty));
				
				chgQtyChk += Number(chgQty);
			});

			if (chgQtyChk > 0) {
				// 환불포인트, 환불상품권 금액 계산
				let refundPoint = fnCalculatePoint(chgQtyArr, ordDtlNoArr, ordCanChgQtyArr);
				let refundGiftCard = fnCalculateGiftCard(chgQtyArr, ordDtlNoArr, ordCanChgQtyArr);
				
				$.each(returnList, function (idx, item) {
					let index = ordDtlNoArr.indexOf(item.ordDtlNo);
					item.ordCanChgQty = chgQtyArr[index];
					
					returnRequestList.push(item);
				})
				
				let jsonData = JSON.stringify(returnRequestList);
				
				gagajf.ajaxJsonSubmit(url, jsonData, function (result) {
					let spanCnclRtnAmt = Number(result.spanCnclRtnAmt);
					let sumDeliveryFee = Number(result.sumDeliveryFee);
					let spanTotDeliveryFee = Number(result.spanTotDeliveryFee);
					let spanCpnDcAmt = Number(result.spanCpnDcAmt);
					let spanTmtbDcAmt = Number(result.spanTmtbDcAmt);
					let spanPrePntDcAmt = Number(result.spanPrePntDcAmt);
					let spanRefundAmt = Number(result.spanRefundAmt);
					
					let goodsCancelAmt = spanCnclRtnAmt;										// 상품취소금액
					let deliveryFee = sumDeliveryFee - spanTotDeliveryFee;						// 배송비
					let deductDcAmt = 0 - spanCpnDcAmt - spanTmtbDcAmt - spanPrePntDcAmt;		// 할인금액 차감(쿠폰+다다익선+선포인트)
					let refundPayAmt = spanRefundAmt;											// 결제금액 환불
					let returnAmt = refundPayAmt + refundPoint + refundGiftCard;				// 환불예정금액
					
					// 금액 설정
					$('#returnAmt').text(returnAmt.addComma());
					$('#goodsCancelAmt').text(goodsCancelAmt.addComma());
					$('#deliveryFee').text(deliveryFee.addComma());
					$('#deductDcAmt').text(deductDcAmt.addComma());
					$('#refundPayAmt').text(refundPayAmt.addComma());
					$('#refundPoint').text(refundPoint.addComma());
					$('#refundGiftCard').text(refundGiftCard.addComma());
					console.log(result);
				});
			}
		}
	}

	// 반품 방식 변경 이벤트
	$('input[name=wdGb]').on('change', function() {
		let wdGb = $('input[name=wdGb]:radio:checked').val();

		if (wdGb == 'W') {
			$('#chgerLocation').css('display', '');
			$('#returnLocation').css('display', 'none');
		} else {
			$('#chgerLocation').css('display', 'none');
			$('#returnLocation').css('display', '');
		}
	});
	
	// 반품 사유 변경 이벤트
	var fnChangeReason = function(param) {
		// TODO
		// 반품 사유 변경 처리
		$(param).parent().parent().find('input[name=chgReason]').val($(param).val());
		fnChangeQty();
	}

	// 환불 포인트 계산
	var fnCalculatePoint = function(chgQtyArr, ordDtlNoArr, ordCanChgQtyArr) {
		let refundPoint = 0;

		$.each(usedPointInfo, function(idx, item) {
			let index = ordDtlNoArr.indexOf(item.ordDtlNo);
			let chgQty = chgQtyArr[index];
			let ordCanChgQty = ordCanChgQtyArr[index];
			
			if (chgQty > 0) {
				if (chgQty == ordCanChgQty) {
					refundPoint += item.pntAmt;
				} else {
					refundPoint += item.pntAmt * (chgQty / ordCanChgQty);
				}
			}
		});
		
		return refundPoint;
	}
	
	// 환불 상품권 계산
	var fnCalculateGiftCard = function(chgQtyArr, ordDtlNoArr, ordCanChgQtyArr) {
		let refundGiftCard = 0;
		
		$.each(usedGiftCardInfo, function(idx, item) {
			let index = ordDtlNoArr.indexOf(item.ordDtlNo);
			let chgQty = chgQtyArr[index];
			let ordCanChgQty = ordCanChgQtyArr[index];
			
			if (chgQty > 0) {
				if (chgQty == ordCanChgQty) {
					refundGiftCard += item.gfcdAmt;
				} else {
					refundGiftCard += item.pntAmt * (chgQty / ordCanChgQty);
				}
			}
		});
		
		return refundGiftCard;
	}
</script>

</th:block>

</body>
</html>
