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

<th:block layout:fragment="content">

<main class="container my">
	<section class="content my_return">
		<form id="returnForm" class="form_wrap">
			<input type="hidden" name="accountNo" 	th:value="${oneData.accountNo}"/>
			<input type="hidden" name="accountNm" 	th:value="${oneData.accountNm}"/>
			<input type="hidden" name="bankCd" 		th:value="${oneData.bankCd}"/>
			<input type="hidden" name="chgReason"/>
			<input type="hidden" name="shipCompCd"/>

			<div class="inner wide bg_beige">
				<div class="order_number">
					<dl class="clear">
						<dt>주문번호</dt>
						<dd th:text="${oneData.ordNo}"></dd>
					</dl>
				</div>
			</div>
			<div class="inner">
				<div class="part_goods">
					<div class="goods_top">
						<div class="goods_date">주문일<span class="date" th:text="${oneData.ordDt}"></span></div>
					</div>

					<!-- 반품상품목록 -->
					<th:block th:if="${returnList.returnList}" th:each="return, status : ${returnList.returnList}" th:with="imageUrl=${@environment.getProperty('upload.goods.view')}">
						<div class="goods_section">
							<div class="goods_detail">
								<a href="javascript:void(0)" th:attr="goodsCd=${return.goodsCd}, optCd1=${return.goodsType == 'G056_N' ? return.optCd1 : ''}, ithrCd='IN21_03'" onclick="fnGoToGoodsDetail(this)">
									<div class="thumb_box">
										<img th:src="${imageUrl + '/' + return.sysImgNm + '?RS=90'}" width="100%" alt="">
									</div>
									<div class="info_box">
										<div class="od_name">
											<div class="brand">
												<span th:text="${return.brandNm}"></span>
												<div class="badge_wrap">
													<em class="order_badge order_bullet_badge"	th:if="${return.shotDelvYn == 'Y'}">총알배송</em>
													<em class="order_badge"						th:if="${return.shotDelvYn == 'N' and return.selfGoodsYn == 'Y'}">STYLE24 일반배송</em>
													<em class="order_badge"						th:if="${return.selfGoodsYn == 'N'}">업체직배송</em>
												</div>
											</div>
											<div class="name" th:text="${return.goodsNm}"></div>
										</div>
										<div class="od_opt">
											<!-- 세트상품일때 -->
											<th:block th:if="${return.goodsType} == 'G056_S'">
												<th:block th:each="option , index2 : ${return.colorNmArr}">
													<div class="option">
														<em th:text="${return.itemNmArr[index2.index]}"></em>
														<em th:text="${option}"></em>
														<em th:text="${return.optCd2Arr[index2.index]}"></em>
													</div>
												</th:block>
											</th:block>
											<!-- //세트상품일때 -->
											<!-- 단품상품일때 -->
											<th:block th:unless="${return.goodsType} == 'G056_S'">
												<div class="option">
													<em th:text="${return.colorNm}"></em>
													<em th:text="${return.optCd2}"></em>
												</div>
											</th:block>
											<!-- //단품상품일때 -->
										</div>
										<div class="od_calc">
											<th:block th:if="${(return.ordAmt - return.cnclRtnAmt) > (return.realOrdAmt + return.pntDcAmt + return.gfcdUseAmt)}">
												<p class="sale_price">
													<del><em th:text="${#numbers.formatInteger(return.ordAmt - return.cnclRtnAmt, 1, 'COMMA')}"></em>원</del>
												</p>
											</th:block>
											<p class="price">
												<span class="selling_price">
													<em th:text="${#numbers.formatInteger(return.realOrdAmt + return.pntDcAmt + return.gfcdUseAmt, 1, 'COMMA')}"></em>원
												</span>
											</p>
										</div>
									</div>
								</a>
							</div>
							<div class="goods_select">
								<div class="select_custom select_count">
									<div class="combo">
										<input type="hidden" name="chgQty" value="0" th:attr="ordDtlNo=${return.ordDtlNo}, ordCanChgQty=${return.ordCanChgQty}"/>
										<div class="select">수량 0개</div>
									</div>
								</div>
							</div>
							<th:block th:if="${#lists.size(returnList.returnList) == status.count}">
								<div class="goods_txt">
									<p class="cf_txt cf_desc">반품하실 상품의 수량을 선택하신 후<br>반품 신청을 하실 수 있습니다.</p>
								</div>
							</th:block>
						</div>
					</th:block>
					<!-- //취소상품목록 -->
					
				</div>
			</div>
			<div class="inner">
				<div class="tbl_wrap">
					<div class="tbl_tit"> 
						<h3>반품 사유</h3>
					</div>
					<div class="tbl tbl_tarea">
						<table>
							<colgroup>
								<col width="*">
							</colgroup>   
							<tr>
								<th class="sr-only">반품 접수 일자</th>
								<td>
									<div class="select_custom select_return">
										<div class="combo">
											<div class="select">반품 사유를 선택하세요.</div>
										</div>
									</div>
								</td>
							</tr>
							<tr>
								<th class="sr-only">반품 완료 일자</th>
								<td>
									<div class="textarea_wrap">
										<textarea class="doc_return" name="chgMemo" id="chgMemo" maxlength="200" placeholder="자세한 사유를 입력해주세요."></textarea>
										<p class="txt_cnt"><span id="return_cnt" class="c_primary">0</span>/200</p>
									</div>
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>
			
			<div class="inner wdGb">
				<div class="tbl_wrap">
					<div class="tbl_tit"> 
						<h3>반품방식 선택</h3>
					</div>
					<div class="retrieve_method">
						<div class="tbl tbl_radio">
							<table>
								<colgroup>
									<col width="*">
								</colgroup>
								<tbody>
									<tr>
										<th class="sr-only">방문 회수</th>
										<td>
											<div class="form_field">
												<input type="radio" name="wdGb" id="withdraw" checked="checked" value="W">
												<label for="withdraw"><span>방문 회수 <b class="c_primary">택배사에서 고객에게 방문하여 회수</b></span></label>
											</div>
										</td>
									</tr>
									<tr>
										<th class="sr-only">직접 배송</th>
										<td>
											<div class="form_field">
												<input type="radio" name="wdGb" id="direct" value="D">
												<label for="direct"><span>직접 배송 <b class="c_primary">고객이 반품지로 직접 반송</b></span></label>
											</div>
										</td>
									</tr>
								</tbody>
								
							</table>
						</div>
					</div>
				</div>
			</div>
			<div class="inner">
				<div class="retrieve_box visit" style="display:block;" id="chgerLocation">
					<div class="tbl_wrap">
						<div class="tbl_tit"> 
							<h3>반품 회수지 주소</h3>
							<button type="button" id="btn_adrsChange_pop" class="btn_popup" onclick="fnChangeDeliveryAddr();"><span>회수지 변경</span></button>
						</div>
						<div class="tbl">
							<input type="hidden" name="chgerNm" 		th:value="${deliveryAddrInfo.recipNm}">
							<input type="hidden" name="chgerPhnno" 		th:value="${deliveryAddrInfo.recipPhnno}">
							<input type="hidden" name="chgerZipcode" 	th:value="${deliveryAddrInfo.recipZipcode}">
							<input type="hidden" name="chgerBaseAddr" 	th:value="${deliveryAddrInfo.recipBaseAddr}">
							<input type="hidden" name="chgerDtlAddr" 	th:value="${deliveryAddrInfo.recipDtlAddr}">
							<input type="hidden" name="chgerRtnMemo" 	th:value="${deliveryAddrInfo.delvMemo}">
							<div class="ship_info">
								<dl>
									<div class="name">
										<dt><span class="sr-only">배송지명</span></dt>
										<dd id="chgerNm" th:text="${deliveryAddrInfo.recipNm}"></dd>
									</div>
									<div class="addr">
										<dt><span class="sr-only">배송주소</span></dt>
										<dd id="chgerAddr" th:text="|${deliveryAddrInfo.recipBaseAddr}    ${deliveryAddrInfo.recipDtlAddr}|"></dd>
									</div>
									<div class="phone">
										<dt><span class="sr-only">휴대폰 번호</span></dt>
										<dd id="chgerPhnno" th:text="${deliveryAddrInfo.recipPhnno}"></dd>
									</div>
									<div class="desc_txt">택배사에서 반품 상품을 직접 회수할 장소 선택</div>
								</dl>
							</div>
						</div>
					</div>
				</div>
				<div class="retrieve_box direct" style="display:none;" id="returnLocation">
					<div class="tbl_wrap">
						<div class="tbl_tit"> 
							<h3>반송 정보</h3>
						</div>
						<div class="tbl">
							<div class="ship_info">
								<dl>
									<div class="addr">
										<dt><span>반송 주소</span></dt>
										<dd th:text="|${deliveryAddrInfo.rtnLocBaseAddr} ${deliveryAddrInfo.rtnLocDtlAddr}|"></dd>
									</div>
									<div class="">
										<dt><span>택배사 선택</span></dt> <!-- 210409_수정 : class sr-only 삭제 -->
										<dd>
											<div class="select_custom select_courier">
												<div class="combo">
													<div class="select">택배사를 선택하세요.</div>
												</div>
											</div>
										</dd>
									</div>
									<div class="phone">
										<dt><span>반송 송장번호</span></dt>
										<dd><input type="tel" class="form_control" name="wdInvoiceNo" data-valid-type="numeric" value="" oninput='handleOnInput(this, 20)' placeholder="송장번호를 입력해주세요."></dd>
<!--										<dd><input type="number" pattern="\d*" class="form_control" name="wdInvoiceNo" data-valid-type="numeric" value="" oninput='handleOnInput(this, 20)' placeholder="송장번호를 입력해주세요."></dd>-->
									</div>
								</dl>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="inner">
				<div class="tbl_wrap pay_wrap">
					<div class="tbl_tit"> 
						<h3>환불 정보</h3>
						<strong class="pay"><span id="returnAmt">0</span>원</strong>
					</div>
					<div class="tbl type1">
						<table>
							<colgroup>
								<col width="227">
								<col width="*">
							</colgroup>   
							<tr>
								<td>
									<dl class="refund_deduct">
										<div>
											<dt>상품 취소 금액</dt>
											<dd>
												<div>
													<span id="goodsCancelAmt">0</span>원
												</div>
											</dd>
										</div>
										<div>
											<dt>배송비</dt>
											<dd>
												<div>
													<span id="deliveryFee">0</span>원
												</div>
											</dd>
										</div>
										<div>
											<dt>할인 금액 차감</dt>
											<dd>
												<div>
													<span id="deductDcAmt">0</span>원
												</div>
											</dd>
										</div>
									</dl>
									<dl class="refund_detail">
										<div>
											<dt>환불 수단</dt>
											<dd>
												<div>
													<span th:if="${paymentInfo.pgGb == 'KCP'}" th:text="${paymentInfo.payMeansNm}"></span>
													<span th:if="${paymentInfo.pgGb == 'NAVER'}" th:text="|네이버페이|"></span>
													<span th:if="${paymentInfo.pgGb == 'KAKAO'}" th:text="|카카오페이|"></span>
													<span th:if="${paymentInfo.pgGb == 'PAYCO'}" th:text="|PAYCO|"></span>
												</div>
											</dd>
										</div>
										<div>
											<dt>결제금액 환불</dt>
											<dd>
												<div>
													<span id="refundPayAmt">0</span>원
												</div>
											</dd>
										</div>
										<div>
											<dt>포인트 환불</dt>
											<dd>
												<div>
													<span id="refundPoint">0</span>P
												</div>
											</dd>
										</div>
										<div>
											<dt>상품권 환불</dt>
											<dd>
												<div>
													<span id="refundGiftCard">0</span>원
												</div>
											</dd>
										</div>
									</dl>
								</td>
							</tr>
						</table>
					</div>
				</div>
				<div class="required_group" id="addDeliveryFee" style="display:none">
					<p>배송비 <span class="c_primary" id="addPayCost">0원</span> 추가 결제가 필요합니다.</p>
					<input type="hidden" name="addPayCost"/>
				</div>
				<div class="btn_group btn_group_flex">
					<div><button type="button" class="btn btn_default" onclick="cfnGoToPage(_PAGE_NOMEMBER_ORDER_LIST);"><span>취소</span></button></div>
					<div><button type="button" id="btn_order_return" class="btn btn_dark" onclick="fnReturn()"><span>반품 신청</span></button></div>
				</div>
			</div>
		</form>
	</section>
</main>

<!-- 210408_반품 수량 선택 팝업 -->
<th:block th:if="${returnList.returnList}" th:each="return, status : ${returnList.returnList}">
	<div class="popup_box returnCountPop">
		<div class="lap">
			<div class="popup_close">카테고리닫기</div>
			<div class="popup_head sr-only">
				<h2 class="">주문상태 선택 팝업</h2>
			</div>
			<div class="popup_con">
				<div class="button_list clear">
					<button type="button" class="on" qty=0 onclick="fnChangeReturnQty(this);"><span>수량 0개</span></button>
					<th:block th:each="num : ${#numbers.sequence(1, return.ordCanChgQty)}">
						<button type="button" th:qty="${num}" onclick="fnChangeReturnQty(this);"><span th:text="|수량 ${num}개|"></span></button>
					</th:block>
					<input type="hidden" name="ordDtlNo" th:value="${return.ordDtlNo}">
				</div> 
			</div>
		</div>
	</div>
</th:block>
<!-- //210408_반품 수량 선택 팝업 -->

<!-- 210408_반품 사유 선택 팝업 -->
<div id="returnReasonPop" class="popup_box returnReasonPop">
	<div class="lap">
		<div class="popup_close">카테고리닫기</div>
		<div class="popup_head sr-only">
			<h2 class="">주문상태 선택 팝업</h2>
		</div>
		<div class="popup_con">
			<div class="button_list">
				<th:block th:if="${returnReason}" th:each="oneData, status : ${returnReason}">
					<button type="button" th:attr="chgReason=${oneData.cd}" onclick="fnChangeReturnReason(this);">
						<span th:text="${oneData.cdNm}"></span>
					</button>
				</th:block>
			</div>
		</div>
	</div>
</div>
<!-- //210408_반품 사유 선택 팝업 -->

<!-- 210408_ 추가 : 환불 계좌 등록 팝업 -->
<div id="refundAccountPop" class="popup_box refundAccountPop">
	<input type="hidden" name="confirmedAccountNo"/>
	<input type="hidden" name="confirmedAccountNm"/>
	<input type="hidden" name="confirmedBankCd"/>
	<div class="lap">
		<div class="popup_close">카테고리닫기</div>
		<div class="popup_head sr-only">
			<h2 class="">환불 계좌 등록 팝업</h2>
		</div>
		<div class="popup_con">
			<div class="tbl_wrap">
				<div class="tbl_tit"> 
					<h3>환불 계좌 등록</h3><!-- 210409_수정 : 텍스트 변경 -->
				</div>
				<div class="tbl type1">
					<table>
						<colgroup>
							<col width="*">
						</colgroup>   
						<tbody>
							<tr>
								<th>예금주</th>
								<td>
									<div class="form_field">
										<input type="text" name="accountNm" class="form_control" th:value="${ordNm}" placeholder="이름를 입력해 주세요" readonly="readonly">
									</div>
								</td>
							</tr>
							<tr>
								<th>은행명</th>
								<td>
									<div class="form_field">
										<div class="select_custom select_bank">
											<div class="combo">
												<div class="select">선택</div>
												<input type="hidden" name="bankCd" value=""/>
											</div>
										</div>
									</div>
								</td>
							</tr>
							<tr>
								<th>계좌번호</th>
								<td>
									<div class="input_wrap certi_wrap">
										<input type="tel" class="form_control" name="accountNo" value="" placeholder="">
										<button type="button" id="btn_bank_certi" class="btn btn_dark"><span>계좌인증</span></button>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
		<div class="pop_foot">
			<div class="btn_group_flex">
				<div class="">
					<button type="submit" id="btn_bank_return" class="btn btn_dark btn_block"><span>계좌 등록 후 환불 신청</span></button>
				</div>
			</div>
		</div>
	</div>
</div>
<!-- //210408_ 추가 : 환불 계좌 등록 토스트 팝업 -->

<!-- 210408_ 추가 : 은행 선택 팝업 -->
<div id="refundBankPop" class="popup_box refundBankPop">
	<div class="lap">
		<div class="popup_close">카테고리닫기</div>
		<div class="popup_head sr-only">
			<h2 class="">은행 선택 팝업</h2>
		</div>
		<div class="popup_con">
			<div class="button_list clear">
				<th:block th:if="${bankList}" th:each="oneData, status : ${bankList}">
					<button type="button" th:attr="bankCd=${oneData.cd}, bankNm=${oneData.cdNm}"><span th:text="${oneData.cdNm}"></span></button>
				</th:block>
			</div>
		</div>
	</div>
</div>
<!-- //210408_ 추가 : 은행 선택 팝업 -->

<!-- 210819_ 추가 : 택배사 선택 팝업 -->
<div id="returnCourierPop" class="popup_box returnCourierPop" style="display: none;">
	<div class="lap">
		<div class="popup_close">카테고리닫기</div>
		<div class="popup_head sr-only">
			<h2 class="">택배사 선택 팝업</h2>
		</div>
		<div class="popup_con">
			<div class="button_list">
				<th:block th:if="${shipCompanyList}" th:each="oneData, status : ${shipCompanyList}">
					<button type="button" th:attr="shipCompCd=${oneData.cd}" onclick="fnSelectShipComp(this);"><span th:text="${oneData.cdNm}"></span></button>
				</th:block>
			</div>
		</div>
	</div>
</div>
<!-- //210819_ 추가 : 택배사 선택 팝업 -->

<script src="/ux/plugins/gaga/gaga.paging.js"></script>
<script th:inline="javascript">
var isLogin 		= [[${isLogin}]];
let returnList 		= [[${returnList.returnList}]];
let returnOrderInfo = [[${returnList.returnOrderInfo}]];
let oneData 		= [[${oneData}]];
let paymentInfo 	= [[${paymentInfo}]];
let isCustomer 		= true;
let jsonObj 		= {};
let ordNo 			= [[${oneData.ordNo}]];

$(document).ready(function() {
	// 입점업체의 경우 회수방식 직접배송 처리
	if (oneData.selfGoodsYn != 'Y') {
		$('#withdraw').click();
		$('.wdGb').css('display','none');
	}

	// 타이틀명
	$('#htopTitle').text('반품 신청');
});

// 반품수량버튼기능
$(".select_custom.select_count").each(function(idx){
	$(this).on("click", function(){
		// 전체비활성화
		$(".returnCountPop").hide();
		
		// 수량팝업활성화
		$(".returnCountPop").eq(idx).show().addClass("active");
		
		$("body").css({"overflow":"hidden"});
	});

	// 팝업 닫기
	$(".popup_close").trigger("click");
});

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

	if (wdGb == 'W') {
		$('#chgerLocation').css('display', '');
		$('#returnLocation').css('display', 'none');
	} else {
		$('#chgerLocation').css('display', 'none');
		$('#returnLocation').css('display', '');
	}

	// 환불금액 계산
	fnChangeReturnQty();
});

// 은행목록 버튼 기능
//$("#refundBankPop .button_list button").each(function(){
//	$(this).on("click", function(){
//		$("#refundAccountPop input[name=bankCd]").val($(this).attr("id"));
//		$("#refundAccountPop .select_custom.select_bank .select").text($(this).find("span").text());
//	});
//
//	// 팝업 닫기
//	$(".popup_close").trigger("click");
//});

// 반품 처리
var fnReturn = function() {
	let url = '/noMember/return';

	// 반품 사유 체크
	let chgReason = $('#returnForm input[name=chgReason]').val();
	if (gagajf.isNull(chgReason)) {
		mcxDialog.alert('반품사유를 선택해주세요.');
		return false;
	}

	// 주문상세번호 및 반품 수량 설정
	let ordDtlNoArr 		= [];
	let cnclRtnReqQtyArr 	= [];
	let chkQty 				= 0;
	$.each($('#returnForm input[name=chgQty]'), function(idx, item) {
		let chgQty 		= $(item).val();
		let ordDtlNo 	= $(item).attr('ordDtlNo');

		if (chgQty > 0) {
			ordDtlNoArr.push(Number(ordDtlNo));
			cnclRtnReqQtyArr.push(Number(chgQty));
			chkQty += chgQty;
		}
	});

	// 반품 수량 체크
	if (chkQty == 0) {
		mcxDialog.alert('반품하실 상품의 수량을 선택해주세요.');
		return false;
	}

	// 환불계좌 체크
	let accountNo 	= $('#returnForm input[name=accountNo]').val();
	let accountNm	= $('#returnForm input[name=accountNm]').val();
	let bankCd 		= $('#returnForm input[name=bankCd]').val();
	
	// 임시
	//paymentInfo.payMeans 	= "G014_20";
	//paymentInfo.payStat 	= "G016_30";
	
	// 무통장입금, 결제완료 일때 환불계좌정보 체크
	if (paymentInfo.payMeans == 'G014_20' && paymentInfo.payStat == 'G016_30' && (gagajf.isNull(accountNo) || gagajf.isNull(accountNm) || gagajf.isNull(bankCd))) {
		let data = {};
		data.ordNo 			= oneData.ordNo;
		data.accountNm 		= oneData.accountNm;
		
		$('#refundAccountPop').show().addClass("active");
		$("body").css({"overflow":"hidden"});
		
		return false;
	}

	// 추가배송비 PG 처리
	let addPayCost 			= $('#returnForm input[name=addPayCost]').val();
	let wdGb				= $('#returnForm input[name=wdGb]:radio:checked').val();

	let data 				= {};
	data.ordNo 				= oneData.ordNo;
	data.ordChgSq 			= 0;
	data.chgReason 			= chgReason;
	data.chgMemo 			= $('#returnForm textarea[name=chgMemo]').val();
	data.accountNo 			= $('#returnForm input[name=accountNo]').val();
	data.accountNm 			= $('#returnForm input[name=accountNm]').val();
	data.bankCd 			= $('#returnForm input[name=bankCd]').val();
	data.isCustomer 		= isCustomer;
	data.wdGb 				= wdGb;
	data.chgerNm 			= wdGb == 'W' ? $('#returnForm input[name=chgerNm]').val() : '';
	data.chgerZipcode 		= wdGb == 'W' ? $('#returnForm input[name=chgerZipcode]').val() : '';
	data.chgerBaseAddr 		= wdGb == 'W' ? $('#returnForm input[name=chgerBaseAddr]').val() : '';
	data.chgerDtlAddr 		= wdGb == 'W' ? $('#returnForm input[name=chgerDtlAddr]').val() : '';
	data.chgerPhnno 		= wdGb == 'W' ? $('#returnForm input[name=chgerPhnno]').val() : '';
	data.chgerRtnMemo 		= wdGb == 'W' ? $('#returnForm input[name=chgerRtnMemo]').val() : '';
	data.ordDtlNoArr 		= ordDtlNoArr;
	data.wdInvoiceNo 		= $('#returnForm input[name=wdInvoiceNo]').val();
	data.addPayCost 		= addPayCost;
	data.cnclRtnReqQtyArr 	= cnclRtnReqQtyArr;
	data.delvFeeCdGrp 		= oneData.delvFeeCdGrp;
	data.shipCompCd			= $('#returnForm input[name=shipCompCd]').val();

	let jsonData = JSON.stringify(data);

	gagajf.ajaxJsonSubmit(url, jsonData, function(result) {
		if (addPayCost > 0) {
			let ordChgSq = result.ordChgSq;
			let ordNo = result.ordNo;

			$('#addPaymentForm input[name=ordChgSq]').val(ordChgSq);
			$('#addPaymentForm input[name=ordNo]').val(ordNo);

			document.addPaymentForm.submit();
		} else {
			cfnGoToPage(_PAGE_NOMEMBER_CRE_LIST);
		}
	}, true);
}

// 반품 수량 변경 이벤트 처리
var fnChangeReturnQty = function(param) {
	let url = '/noMember/cancel/refund/amt/calculate';
	
	// 반품수량설정
	if (param != null) {
		$("#returnForm input[name=chgQty]").each(function(idx){
			var ordDtlNo = $(this).attr("ordDtlNo");
			if (ordDtlNo == $(param).parent().find("input[name=ordDtlNo]").val()) {
				$(this).val($(param).attr("qty"));
				$(this).parent().find(".select").text($(param).find("span").text());
			}
		});
	}

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

	if (!gagajf.isNull(chgReason)) {
		// 반품 수량 설정
		let cnclRtnReqQtyArr 	= [];
		let ordDtlNoArr 		= [];
		let ordCanChgQtyArr 	= [];
		let allDelvCanYn 		= '';
		
		$.each($('#returnForm input[name=chgQty]'), function(idx, item) {
			let chgQty 			= $(item).val();
			let ordDtlNo 		= $(item).attr('ordDtlNo');
			let ordCanChgQty 	= $(item).attr('ordCanChgQty');
			
			cnclRtnReqQtyArr.push(Number(chgQty));
			ordDtlNoArr.push(Number(ordDtlNo));
			ordCanChgQtyArr.push(Number(ordCanChgQty));
		});
		
		// 2021.09.07 card007 전체반품 원배송비 무료 해택 차감 처리
		let delvGfcdUseAmt;
		let realDelvAmt;
		let orgDelvFee;
		
		if (returnOrderInfo != null && returnOrderInfo.length > 0) {
			allDelvCanYn 	= 'Y';
			delvGfcdUseAmt 	= returnOrderInfo[0].delvGfcdUseAmt;
			realDelvAmt 	= returnOrderInfo[0].realDelvAmt;
			orgDelvFee 		= returnOrderInfo[0].orgDelvFee;
			
			$.each(returnOrderInfo, function (index, orderInfo) {
				let cnt = -1;
				$.each(ordDtlNoArr, function (idx, ordDtlNo) {
					if (orderInfo.ordDtlNo == ordDtlNo) {
						cnt = idx;
					}
				});
				
				if (cnt == -1) {
					allDelvCanYn = 'N';
				} else {
					if (orderInfo.ordQty != cnclRtnReqQtyArr[cnt]) {
						allDelvCanYn = 'N';
					}
				}
			});
		}

		let data 				= {};
		data.ordNo 				= oneData.ordNo;
		data.chgGb 				= 'G680_30';
		data.ordDtlNoArr 		= ordDtlNoArr;
		data.cnclRtnReqQtyArr 	= cnclRtnReqQtyArr;
		data.delvFeeCdGrp 		= oneData.delvFeeCdGrp;
		
		let jsonData = JSON.stringify(data);
		
		gagajf.ajaxJsonSubmit(url, jsonData, function (result) {
			let refundPoint 		= Number(result.spanPntDcAmt);				// 환불 포인트 금액
			let spanGfcdUseAmt 		= Number(result.spanGfcdUseAmt);			// 환불 상품권 금액
			let spanDelvGfcdUseAmt 	= Number(result.spanDelvGfcdUseAmt);		// 환불 배송비 상품권 금액
			let spanCnclRtnAmt 		= Number(result.spanCnclRtnAmt);			// 환불 상품 금액
			let spanCpnDcAmt 		= Number(result.spanCpnDcAmt);				// 쿠폰 할인 차감 금액
			let spanCpn1DcAmt 		= Number(result.spanCpn1DcAmt);				// 즉시할인 쿠폰 차감 금액
			let spanTmtbDcAmt 		= Number(result.spanTmtbDcAmt);				// 다다익선 할인 차감 금액
			let spanPrePntDcAmt 	= Number(result.spanPrePntDcAmt);			// 선포인트 할인 차감 금액
			let sumDeliveryFee 		= Number(result.sumDeliveryFee);			// 원주문배송비 (반품에서는 안돌려줘서 항상 0일듯)
			//let spanTotDeliveryFee = Number(result.spanTotDeliveryFee);		// 추가배송비 (무료배송비 허들 깨져서 발생한 배송비) - 추가배송비는 환불컨펌에서 처리
			let spanTotDeliveryFee 	= 0;
			let spanTotRtnDelvFee 	= Number(result.spanTotRtnDelvFee);			// 반품배송비 (회수요청으로 인한 반품 배송비)
			let spanRealCnclRtnAmt 	= Number(result.spanRealCnclRtnAmt);		// 환불 상품 실결제 금액 (환불상품금액 - 할인차감금액)
			let refundGiftCard 		= spanGfcdUseAmt + spanDelvGfcdUseAmt;		// 환불 상품권 금액 합계
			let spanRefundAmt 		= spanRealCnclRtnAmt + sumDeliveryFee;		// 환불예정금액 (환불상품실결제금액 - 원주문배송비)

			// 반품 사유 및 반품 방식 배송비 계산
			if (result.spanRealCnclRtnAmt > 0) {
				let wdGb = $('#returnForm input[name=wdGb]:radio:checked').val();
				// 회사사유 : 추가배송비 0, 반품배송비 0
				if (!isCustomer) {
					spanTotRtnDelvFee = 0;
					//spanTotDeliveryFee = 0;									// 추가배송비는 환불컨펌에서 처리
				}
				// 고객사유(직접발송) : 반품배송비 0
				else if (wdGb == 'D') {
					spanTotRtnDelvFee = 0;
				}
			} else {
				spanTotRtnDelvFee = 0;
				//spanTotDeliveryFee = 0;										// 추가배송비는 환불컨펌에서 처리
			}
			
			// 2021.09.07 card007 전체반품 원배송비 무료 해택 차감 처리
			// 배송비정책 기준 전체 반품이고 귀책사유일때
			if (allDelvCanYn == 'Y' && isCustomer) {
				
				// 기 결제한 배송비 금액이 없을때
				if (delvGfcdUseAmt + realDelvAmt == 0) {
					// 원주문배송비 추가
					spanTotRtnDelvFee += orgDelvFee;
				}
			}

			let goodsCancelAmt = spanCnclRtnAmt + spanCpn1DcAmt;				// 상품취소금액
			let addDelvFee = spanTotRtnDelvFee + spanTotDeliveryFee;			// 추가배송비
			let deductDcAmt = spanCpnDcAmt + spanTmtbDcAmt + spanPrePntDcAmt;	// 할인금액 차감(쿠폰+다다익선+선포인트)
			let refundPayAmt = spanRefundAmt - addDelvFee;						// 결제금액 환불

			// 추가배송비 영역 설정
			if (refundPayAmt < 0) {
				refundPayAmt += addDelvFee;
				$('#addDeliveryFee').css('display', '');
				$('#addPayCost').text(addDelvFee.addComma() + '원');
				$('#returnForm input[name=addPayCost]').val(addDelvFee);
			} else {
				$('#addDeliveryFee').css('display', 'none');
				$('#returnForm input[name=addPayCost]').val(0);
			}

			let returnAmt = refundPayAmt + refundPoint + refundGiftCard;				// 환불예정금액

			// 금액 설정
			$('#returnAmt').text(returnAmt.addComma());
			$('#goodsCancelAmt').text(goodsCancelAmt.addComma());
			$('#deliveryFee').text((0 - addDelvFee).addComma());
			$('#deductDcAmt').text((0 - deductDcAmt).addComma());
			$('#refundPayAmt').text(refundPayAmt.addComma());
			$('#refundPoint').text(refundPoint.addComma());
			$('#refundGiftCard').text(refundGiftCard.addComma());
		});
	}

	// 팝업 닫기
	$(".popup_close").trigger("click");
}

// 반품 사유 변경 이벤트
var fnChangeReturnReason = function(param) {
	var customerReasonArr 	= ['G688_10'];
	let chgReason 			= $(param).attr('chgReason');

	// 귀책사유체크(취소, 반품, 교환)
	isCustomer = customerReasonArr.includes(chgReason);
	
	// 반품 사유 설정
	$('#returnForm input[name=chgReason]').val(chgReason);
	$("#returnForm .select_custom.select_return .select").text($(param).find("span").text());

	// 환불금액 계산
	fnChangeReturnQty();
}

// 회수지 정보 설정
var delvAddrSet = function(delvObj) {
	let chgerNm 			= delvObj.recipNm;
	let chgerPhnno 			= delvObj.recipPhnno;
	let chgerZipcode 		= delvObj.recipZipcode;
	let chgerBaseAddr 		= delvObj.recipBaseAddr;
	let chgerDtlAddr 		= delvObj.recipDtlAddr;
	let delvMemo 			= delvObj.delvMemo;
	let chgerAddr 			= chgerBaseAddr + '    ' + chgerDtlAddr;

	$('#returnForm input[name=chgerNm]').val(chgerNm);
	$('#returnForm input[name=chgerPhnno]').val(chgerPhnno);
	$('#returnForm input[name=chgerZipcode]').val(chgerZipcode);
	$('#returnForm input[name=chgerBaseAddr]').val(chgerBaseAddr);
	$('#returnForm input[name=chgerDtlAddr]').val(chgerDtlAddr);
	$('#returnForm input[name=chgerRtnMemo]').val(delvMemo);
	
	$('#chgerNm').text(chgerNm);
	$('#chgerPhnno').text(chgerPhnno);
	$('#chgerAddr').text(chgerAddr);
}

let isValid = false;

// 계좌인증
$('#btn_bank_certi').on('click', function () {
	
	if (gagajf.isNull($('#refundAccountPop input[name=bankCd]').val())) {
		mcxDialog.alert('은행을 선택해주세요.');
		return false;
	}
	
	if (gagajf.isNull($('#refundAccountPop input[name=accountNo]').val())) {
		mcxDialog.alert('계좌번호를 입력해주세요.');
		return false;
	}
	
	// 승인된 계좌 정보
	let confirmedAccountNm 	= $('#refundAccountPop input[name=confirmedAccountNm]').val();
	let confirmedAccountNo 	= $('#refundAccountPop input[name=confirmedAccountNo]').val();
	let confirmedBankCd 	= $('#refundAccountPop input[name=confirmedBankCd]').val();
	
	// 계좌정보
	let accountNm 			= $('#refundAccountPop input[name=accountNm]').val();
	let accountNo 			= $('#refundAccountPop input[name=accountNo]').val();
	let bankCd 				= $('#refundAccountPop input[name=bankCd]').val();
	
	if (accountNm != confirmedAccountNm || accountNo != confirmedAccountNo || bankCd != confirmedBankCd) {
		isValid = false;
	}
	
	if (!isValid) {
		let url 		= '/noMember/account/check';
		
		let data = {};
		data.accountNm 	= accountNm;
		data.accountNo 	= accountNo;
		data.bankCd 	= bankCd;
		data.ordNo 		= ordNo;
		
		let jsonData = JSON.stringify(data);
		
		gagajf.ajaxJsonSubmit(url, jsonData, function (result) {
			isValid = result.isValid;
			
			if (isValid) {
				mcxDialog.alert('계좌인증에 성공했습니다.');
				// 계좌인증 성공 시 Disabled 처리
				//$('#refundAccountPop .select_custom.select_bank').attr('disabled', true);
				//$('#refundAccountPop input[name=accountNo]').attr('disabled', true);
				
				$('#refundAccountPop input[name=confirmedAccountNm]').val(accountNm);
				$('#refundAccountPop input[name=confirmedAccountNo]').val(accountNo);
				$('#refundAccountPop input[name=confirmedBankCd]').val(bankCd);
				
				return false;
			} else {
				mcxDialog.alert('계좌정보를 다시 확인해주세요.');
				return false;
			}
		});
	}
});

// 계좌등록 후 환불신청 버튼 클릭 이벤트
$('#btn_bank_return').click(function() {
	if (isValid) {
		// 승인된 계좌 정보
		let confirmedAccountNm 	= $('#refundAccountPop input[name=confirmedAccountNm]').val();
		let confirmedAccountNo 	= $('#refundAccountPop input[name=confirmedAccountNo]').val();
		let confirmedBankCd 	= $('#refundAccountPop input[name=confirmedBankCd]').val();
		
		// 계좌정보
		let accountNm 	= $('#refundAccountPop input[name=accountNm]').val();
		let accountNo 	= $('#refundAccountPop input[name=accountNo]').val();
		let bankCd 		= $('#refundAccountPop input[name=bankCd]').val();
		
		if (accountNm == confirmedAccountNm && accountNo == confirmedAccountNo && bankCd == confirmedBankCd) {
			// 부모창의 input 값으로 환불계좌정보 설정
			$('#returnForm input[name=accountNo]').val(accountNo);
			$('#returnForm input[name=accountNm]').val(accountNm);
			$('#returnForm input[name=bankCd]').val(bankCd);
			
			// 팝업 닫기
			$("#refundAccountPop .popup_close").trigger("click");
			
			// 반품신청
			fnReturn();
		} else {
			mcxDialog.alert('인증받은 계좌정보와 다릅니다.');
		}
	} else {
		mcxDialog.alert('계좌인증이 필요합니다.');
	}
});

// 택배사 버튼 클릭 이벤트
var fnSelectShipComp = function(param) {
	let shipCompCd = $(param).attr('shipCompCd');
	$('#returnForm input[name=shipCompCd]').val(shipCompCd);
	$("#returnForm .select_custom.select_courier .select").text($(param).find("span").text());
	
	// 팝업 닫기
	$("#returnCourierPop .popup_close").trigger("click");
}
</script>

<script>
// 세부 사유 글자 수 제한
$('.doc_return').keyup(function(e){
	var content = $(this).val();
	$('#return_cnt').html(content.length);
	//if (content.length > 200){
	//	mcxDialog.alert("최대 200자까지 입력 가능합니다."); //210420_수정 : 시스템 alert -> dialog 변경.
	//	$(this).val(content.substring(0, 200));
	//	$('#return_cnt').html("200");
	//}
});

// 반품 사유 선택 팝업
$(document).on("click",".select_custom.select_return",function(e){
	$('#returnReasonPop').show().addClass("active");
	$("body").css({"overflow":"hidden"});
});

// 팝업_닫기
$('.popup_close').on("click",function(){
	let id = $(this).parent().parent().attr('id');
	$(this).parent().parent().hide().removeClass('active');
	
	if (id != 'refundBankPop') {
		$("body").css({"overflow": "visible"});
	}
});

// 버튼 색
$(document).on('click','.popup_box .button_list button',function(){
	//$('.popup_box .button_list button').removeClass('on');
	$.each($(this).parent().find('button'), function(idx, item) {
		$(item).removeClass('on');
	});
	$(this).addClass('on');
});

function handleOnInput(el, maxlength) {
	if(el.value.length > maxlength)  {
		el.value = el.value.substr(0, maxlength);
	}
}

//210408_ 추가 : 환불계좌등록 팝업 스크립트
$(document).on("click","#btn_refund_pop",function(e){
	$('#refundAccountPop').show().addClass("active");
	$("body").css({"overflow":"hidden"});
});

//210408_ 추가 : 은행선택 팝업 스크립트
$(document).on("click","#refundAccountPop .select_bank",function(e){
	$('#refundBankPop').show().addClass("active");
	$('#refundBankPop').css({"z-index":"1000"});
	$("body").css({"overflow":"hidden"});
});

//210510_추가 : 토스트 팝업 button 클릭 시 팝업 닫기.
$(document).on('click','.popup_box.refundBankPop .button_list button',function(){
	let bankCd = $(this).attr('bankCd');
	let bankNm = $(this).attr('bankNm');
	
	$('#refundAccountPop input[name=bankCd]').val(bankCd);
	$('#refundAccountPop .select_custom.select_bank .combo .select').text(bankNm);
	
	$(this).parents('.popup_box.refundBankPop').hide().removeClass('active');
	$("body").css({"overflow":"visible"});
});

// 210819_ 추가 : 택배사 선택 팝업
$(document).on("click",".select_custom.select_courier",function(e){
	$('#returnCourierPop').show().addClass("active");
	$("body").css({"overflow":"hidden"});
});
</script>

</th:block>

</body>
</html>
