<!DOCTYPE html>
<html lang="ko"
	xmlns:th="http://www.thymeleaf.org">
<!--
 *******************************************************************************
 * @source  : RefundDetailForm.html
 * @desc    : 환불상세팝업
 *============================================================================
 * ISTYLE24
 * Copyright(C) 2020 TSIT, All rights reserved.
 *============================================================================
 * VER  DATE         AUTHOR      DESCRIPTION
 * ===  ===========  ==========  =============================================
 * 1.0  2020.11.16   moon        최초 작성
 *******************************************************************************
 -->
	<ul class="popup modal" data-width="1260" >
		<div class="panelStyle">
		<!-- TITLE -->
		<div class="panelTitle">
			<h2>회수 상세</h2>
			<button type="button" class="close" onclick="uifnPopupClose('popupWithdrawDetail')"><i class="fa fa-times"></i></button>
		</div>
		<!-- //TITLE -->

			<form id="withdrawDetailForm" name="withdrawDetailForm" action="#" th:method="post" onSubmit="return false">
				<input type="hidden" name="orgChgReason" readonly/>
				<input type="hidden" name="orgEncloseFee" readonly/>
				<table class="frmStyle">
					<colgroup>
						<col style="width:10%;" />
						<col style="width:15%;" />
						<col style="width:10%;" />
						<col style="width:15%;" />
						<col style="width:10%;" />
						<col style="width:15%;" />
						<col style="width:10%;" />
						<col />
					</colgroup>
					<tr>
						<th>회수구분</th>
						<td>
							<span id="returnType"></span>
							<input type="hidden" name="chgGb"/>
						</td>
						<th>도착일자</th>
						<td>
							<span id="arriValDt"></span>
						</td>
						
					</tr>
					<tr>
						<th>최종요청사유</th>
						<td>
							<select name="chgReason"></select>
						</td>
						<th>귀책사유<i class="star"></i></th>
						<td>
							<span id="chgReasonText">
							</span>
						</td>
					</tr>
					<tr id="refundArea0">
						<th>동봉비</th>
						<td>
							<input type="text" name="encloseFee" data-valid-type="integer" onchange="_encloseFee=$(this).val(); $('#withdrawDetailForm select[name=chgReason]').trigger('change');" class="w100 aR"/>원
						</td>
						<th>착불비</th>
						<td>
							<span id="codFee"></span>원
						</td>
					</tr>
					<tr>
						<th>회수메모</th>
						<td>
							<span id="shipMemo"></span>
						</td>
						<th>회수사유</th>
						<td><span id="changeReason"></span></td>
					</tr>
					<tr>
						<th>클레임메모</th>
						<td colspan="3">
							<span id="claimMemo"></span>
						</td>
					</tr>
				</table>
				
				<div id="divRefundInfo">
					<h4>환불 예정 정보</h4>
					<table class="frmStyle">
						<colgroup>
							<col style="width:10%;" />
							<col style="width:15%;" />
							<col style="width:10%;" />
							<col style="width:15%;" />
							<col style="width:10%;" />
							<col style="width:15%;" />
							<col style="width:10%;" />
							<col/>
						</colgroup>
						<tr id="refundArea1">
							<th>총 결제 금액</th>
							<td colspan="3"><span id="totPayAmt"></span>원 (상품 실결제 금액 : <span id="totRealAmt"></span>원, 배송비 : <span id="delvFee"></span>원)</td>
						</tr>
						<tr id="refundArea2">
							<th>취소 상품 금액</th>
							<td><span id="cnclGoodsAmt"></span>원</td>
							<th>취소 사용 포인트</th>
							<td><span id="cnclPointAmt"></span>원</td>
							<th>취소 사용 쿠폰금액</th>
							<td><span id="cnclCouponAmt"></span>원</td>
							<th>취소 상품 환불금액</th>
							<td><span id="cnclGoodsRefundAmt"></span>원</td>
						</tr>
						<tr>
							<th>추가 고객부담 배송비</th>
							<td>
								<span id="custShipAmt"></span>원
							</td>
							<td colspan="4">
								(원주문배송비 : <span id="orgDelvFee"></span>원 + 회수배송비 : <span id="returnDelvFee"></span>원)<span id="delvFeeAddText"></span>
							</td>
						</tr>
						<tr id="refundArea4">
							<th>환불예정금액</th>
							<td colspan="7"><span id="totRefundAmt"></span>원</td>
						</tr>
					</table>
				</div>
				
				<div class="cardArea" style="height: 350px;">
					<h4 style="width:98%;">
						회수대상 상품 정보
						<span class="btnRight"  id="pgBtn" >
							<label><input type="checkbox" name="pgStats" value="N" th:if="${sessionInfo.roleCd == '0000'}">PG 전문 미전송</label>
						</span>
					</h4>
		
					<div id="refundGridList" style="width: 100%; height: 260px; padding-top:10PX;" class="ag-theme-balham"></div>
				</div>
			</form>
		
		</div>
	</ul>

<script th:inline="javascript">
/*<![CDATA[*/

	var ordChgSq = [[${ordChgSq}]];	// 주문변경번호
	var remainGoodsInfo = [[${remainGoodsInfo}]]; // 주문 남은 상품 정보
	var remainGoodsList = [[${remainGoodsList}]]; // 주문 남은 상품 목록
	var couponInfo = [[${couponInfo}]]; // 쿠폰 정보
	var orderDetailSumAmt = [[${orderDetailSumAmt}]];
	var sumQty = [[${sumQty}]];
	var ordChgCnt = [[${ordChgCnt}]];	//회수신청건수
	var chgGb = "반품";
	
	var columnDefsDetail = [
		{headerName: "주문번호", 		field: "ordNo", 	width: 150, minWidth: 100, cellClass: 'text-center',
			cellRenderer: function(params) {
				return "<a href=\"javascript:void(0);\" onclick=\"cfnOpenOrderDetailPopup('" + params.value + "');\">" + params.value + "</a>";
			}
		},
		{headerName: "상품코드", 		field: "goodsCd", 	width: 150, minWidth: 100, cellClass: 'text-center',
			cellRenderer: function(params) {
				return "<a href=\"javascript:void(0);\" onclick=\"cfnOpenGoodsDetailPopup('U','" + params.value + "','');\">" + params.value + "</a>";
			}
		},
		{headerName: "사이즈", 		field: "sizeCd", 	width: 70, minWidth: 100, cellClass: 'text-center'},
		{headerName: "신청수량", 		field: "chgQty", 	width: 100, minWidth: 100, cellClass: 'text-center'},
		{headerName: "회수수량", 		field: "wdQty", 	width: 100, minWidth: 100, cellClass: 'text-center'},
		{headerName: "상품명", 		field: "goodsNm",	width: 150, minWidth: 100},
		{headerName: "회수처리상태", 	field: "wdStat",	width: 120, minWidth: 100, cellClass: 'text-center'},
		{headerName: "회수처리", 		field: "ordDtlNo",	width: 120, minWidth: 100, cellClass: 'text-center'
			, cellRenderer : function(params) {
				if (params.data.wdStat == 'N') {
					if (params.data.wdQty > 0) {
						return "<a href=\"javascript:void(0);\" class=\"btn btn-base btn-sm\">회수컨펌</a>";
					} else {
						return "";
					}
				} else if (params.data.wdStat == 'Y') {
					return "회수완료";
				}
			}
		},
		{headerName: "등록일", 		field: "regDt", 	width: 100, minWidth: 100, cellClass: 'text-center'},
		{headerName: "등록자", 		field: "udtId", 	width: 100, minWidth: 100, cellClass: 'text-center'}
	];
	
	// Get withDrawDetailGridOptions
	var withdrawDetailGridOptions = gagaAgGrid.getGridOptions(columnDefsDetail);
	withdrawDetailGridOptions.rowSelection = 'multiple';
	
	withdrawDetailGridOptions.getRowStyle = function(params) {
		if (params.data.wdStat == 'N') {
			if (params.data.wdQty < 1) {
				return { 'background-color': '#FF0000'};
			}
		} 
	}
	
	$(document).ready(function() {
		// Create a agGrid
		gagaAgGrid.createGrid('refundGridList', withdrawDetailGridOptions);
		
		fnDetailSearch(true);
	});
	
	var initFlag = '';
	//회수 상세내역 조회
	var fnDetailSearch = function(Init) {
		initFlag = Init;
		var data = { 'ordChgSq' : ordChgSq };
		var jsonData = JSON.stringify(data);
		
		gagajf.ajaxJsonSubmit('/withdraw/detail/list', jsonData, fnWithdrawDetailCallback);
	}
	
	// 상세 정보 콜백 함수
	var fnWithdrawDetailCallback = function(result) {
		if (result.length < 1) {
			mcxDialog.alert('회수데이터 오류입니다. 운영팀에 문의 해주세요! ');
			return;
		}
		
		var confirmCnt = 0;
		$(result).each(function(idx) {
			if (result[idx].wdStat == 'Y') {
				confirmCnt++;
			}
			
			// 전체 회수 완료 일 때.
			if (result.length == confirmCnt || result[idx].mallGb == '20') {
				fnSearch();
				setReadOnly(true);
				$('#pgBtn').hide();
				$('#divRefundInfo').hide();
			}
		});
		
		// 회수리스트 설정
		withdrawDetailGridOptions.api.setRowData(result); 
		
		if (!initFlag) return;
		
		fnSetWithdrawInfo(result[0]);	// 회수정보 설정
		fnSetCnclInfo(result);			// 취소 관련 설정

		if(chgGb == "40") {
			$('#divRefundInfo').hide();
		}
	}
	
	var _orgDelvFee = 0;	// 최초 배송비
	var _delvFee = 0;		// 배송비
	var _totRealOrdAmt = 0;	// 상품 실결제금액
	var _payAmt = 0;		// 총결제금액
	var _encloseFee = 0;	// 동봉비
	
	var _totCnclGoodsAmt = 0;		// 총 취소 상품 금액
	var _totCnclPointAmt = 0;		// 총 취소 사용 포입트
	var _totCnclCouponAmt = 0;		// 총 취소 사용 쿠폰
	var _totCnclGoodsRefundAmt = 0;	// 총 취소 상품 환불금액
	
	// 회수정보 설정
	var fnSetWithdrawInfo = function(data) {
		// 전역변수 설정
		_orgDelvFee = gagajf.convNull(data.orgDelvFee, 0); // 최초배송비
		_delvFee = data.delvFee; // 부과배송비
		if(_orgDelvFee > 0) _delvFee = _orgDelvFee;
		
		_totRealOrdAmt = data.totRealOrdAmt;
		_payAmt = data.payAmt == null ? 0 : data.payAmt;
		_encloseFee = data.encloseFee;
		
		// 회수 상세
		$('#withdrawDetailForm input[name=chgGb]').val(data.chgGb);
		chgGb = data.chgGb;
		$("#returnType").text(data.returnType); 		//회수구분
		$('#arriValDt').text(data.regDt);				//회수일시
		$('#shipMemo').text(data.wdMemo);				//회수메모
		$('#codFee').text(data.codFee);					//착불비
		$('#withdrawDetailForm input[name=chgReason]').val(data.wdReqReason);
		$('#withdrawDetailForm input[name=orgChgReason]').val(data.wdReqReason);
		$('#withdrawDetailForm input[name=encloseFee]').val(_encloseFee);			//동봉비
		$('#withdrawDetailForm input[name=orgEncloseFee]').val(_encloseFee);			//동봉비
		
		$('#delvFee').text(_orgDelvFee.addComma());	//배송비
		$('#totRealAmt').text(_totRealOrdAmt.addComma());	//상품 실결제 금액
		$('#totPayAmt').text(_payAmt.addComma());	//총 결제금액
		$('#claimMemo').text(data.chgMemo);
		cfnCreateCombo('/renderer/avail/commonCode/list/G688', $('#withdrawDetailForm select[name=chgReason]'), '', data.chgReason);
	}
	
	// 취소 금액 설정
	var fnSetCnclInfo = function(data) {
		$(data).each(function(idx, item) {
			var sumCpn = item.goodsCpnDcAmt + item.cartCpnDcAmt + item.plusCpnDcAmt;
			var sumPoint = item.pntDcAmt + item.prePntDcAmt;
			
			_totCnclCouponAmt += Number((sumCpn / (item.ordQty - item.cnclRtnQty)) * item.wdQty);
			_totCnclPointAmt  += Number((sumPoint / (item.ordQty - item.cnclRtnQty)) * item.wdQty);
			_totCnclGoodsAmt  += item.currPrice * Number(item.wdQty);
			
			if (item.ordQty != (item.wdQty + item.cnclRtnQty)) {
				var tempCouponAmt = Number((sumCpn / (item.ordQty - item.cnclRtnQty)) * (item.ordQty - item.cnclRtnQty - item.wdQty));
				var tempPointAmt = Number((sumPoint / (item.ordQty - item.cnclRtnQty)) * (item.ordQty - item.cnclRtnQty - item.wdQty));
				var tempGoodsAmt = item.currPrice * (item.ordQty - item.cnclRtnQty - item.wdQty);
				
				var tempOrdAmt = Number(tempGoodsAmt - tempPointAmt - tempCouponAmt);
				remainGoodsInfo.realOrdAmt += tempOrdAmt;
			}
		});
		
		_totCnclGoodsRefundAmt = Math.floor(_totCnclGoodsAmt) - Math.floor(_totCnclPointAmt) - Math.floor(_totCnclCouponAmt);

		$('#cnclGoodsAmt').text(Math.floor(_totCnclGoodsAmt).addComma());
		$('#cnclPointAmt').text(Math.floor(_totCnclPointAmt).addComma());
		$('#cnclCouponAmt').text(Math.floor(_totCnclCouponAmt).addComma());
		$('#cnclGoodsRefundAmt').text(Math.floor(_totCnclGoodsRefundAmt).addComma());

		fnSetChgReason(data[0].chgReason);
	}
	
	// 귀책사유 설정
	$('#withdrawDetailForm select[name=chgReason]').on('change', function() {
		fnSetChgReason($(this).val());
	});
	
	// 변경요청설정
	var fnSetChgReason = function(value) {
		var checkData = ['10', '11', '12', '13', '15', '21', '30']; //귀책이 고객
		var orgDelvFee = 0;
		var custShipAmt = 0;
		if (gagajf.isNull(value)) return;

		if(ordChgCnt == 1) {	//1회 회수비 0원
			_delvFee = 0;
			$('#delvFeeAddText').text(" 1회 회수비용은 회사가 부담합니다.");
		} else if (checkData.indexOf(value) != -1) {	// 고객 귀책사유인 경우
			$('#chgReasonText').text('고객');
			if(_orgDelvFee == 0) {	// 원주문 배송비가 0 이면
				// 남은상품의 실주문금액이 최소주문금액보다 작거나 0인 경우 부과배송비(TB_GOODS 의 DELV_FEE)를 원주문 배송비로 저장
				if (remainGoodsInfo.minOrdAmt > remainGoodsInfo.realOrdAmt || remainGoodsInfo.realOrdAmt == 0) {
					orgDelvFee = _delvFee;
				}
			}
			
			//_orgDelvFee = orgDelvFee;
			
			if (couponInfo != null && couponInfo.buyLimitAmt > 0) {
				if (couponInfo.buyLimitAmt > remainGoodsInfo.realOrdAmt) {	//남은상품의 실주문금액이 쿠폰사용금액기준액보다 작은경우 장바구니 쿠폰 취소
					
					$(remainGoodsList).each(function(idx, goods) {
						_totCnclCouponAmt += Number(goods.cartCpnDcAmt);
					});
					
					_totCnclGoodsRefundAmt = _totCnclGoodsAmt - _totCnclPointAmt - _totCnclCouponAmt;
					$('#cnclCouponAmt').text(_totCnclCouponAmt.addComma());
					$('#cnclGoodsRefundAmt').text(_totCnclGoodsRefundAmt.addComma());
				}
			}
			
			$('#orgDelvFee').text(orgDelvFee.addComma());
			$('#returnDelvFee').text(_delvFee.addComma());
			
			// 고객부담 배송비 = 원주문배송비 + 회수배송비 + 착불비
			custShipAmt = Number(orgDelvFee) + Number(_delvFee) + Number($('#codFee').text().replace(/,/gi, ""));
		} else {
			if (couponInfo != null && couponInfo.buyLimitAmt > 0) {
				if (couponInfo.buyLimitAmt > remainGoodsInfo.realOrdAmt) {
					
					$(remainGoodsList).each(function(idx, goods) {
						_totCnclCouponAmt -= Number(goods.cartCpnDcAmt);
					});
					
					_totCnclGoodsRefundAmt = _totCnclGoodsAmt - _totCnclPointAmt - _totCnclCouponAmt;
					$('#cnclCouponAmt').text(_totCnclCouponAmt.addComma());
					$('#cnclGoodsRefundAmt').text(_totCnclGoodsRefundAmt.addComma());
				}
			}
			
			$('#chgReasonText').text('회사');
			$('#orgDelvFee').text('0');
			$('#returnDelvFee').text('0');
		}
		
		
		// 고객부담배송비 -= 동봉비
		$('#custShipAmt').text((custShipAmt - $('#withdrawDetailForm input[name=encloseFee]').val().replace(/,/gi, "")).addComma());
		
		fnSetTotRefundData(custShipAmt);
	}
	
	// 환불 금액 계산
	var fnSetTotRefundData = function(custShipAmt) {
		custShipAmt = (custShipAmt - $('#withdrawDetailForm input[name=encloseFee]').val().replace(/,/gi, ""));	// 배송비(고객부담배송비 - 동봉비)

		if (_totCnclGoodsRefundAmt < 1)
			return;
		
		if ($('#chgReasonText').text() == '고객') {
			if (remainGoodsInfo.realOrdAmt == 0) {
				var tempDelvFee = 0;
			}
		} else {	// 귀책사유가 회사에 있고 남은상품의 실주문금액이 0이거나 총취소환불금액과 같을 경우
			var tempDelvFee = 0;
			if (remainGoodsInfo.realOrdAmt == 0 || remainGoodsInfo.realOrdAmt == _totCnclGoodsRefundAmt) {
				//tempDelvFee = _orgDelvFee;
			}
		}

		var delvFee = tempDelvFee == 0 ? tempDelvFee : _orgDelvFee;
		var totRefundAmt = Number(_totCnclGoodsRefundAmt) + Number(delvFee) - Number(custShipAmt);//- Number(custShipAmt);//+ Number(_orgDelvFee) - Number(custShipAmt);
		$('#totRefundAmt').text(Math.floor(totRefundAmt).addComma());
	}
	
	// 회수컨펌 클릭 시
	withdrawDetailGridOptions.onCellClicked = function(event) {
		if (event.colDef.field != "ordDtlNo" || event.data.wdQty < 1 || event.data.wdStat == "Y") return;
		
		if (sumQty.chgQty != sumQty.wdQty) {
			mcxDialog.alert('반품신청 수량과 회수등록수량이 맞지 않습니다.<br/>반품신청수량 : ' + sumQty.chgQty + '<br/>회수등록수량 : ' + sumQty.wdQty);
			return;
		}
		
		fnWithdrawDetailConfirm(event.data);
	}
	
	// 회수 컨펌
	var confirmFlag = true;
	var fnWithdrawDetailConfirm = function(data) {
		var totPayAmt = $('#totPayAmt').text().replace(/,/gi,"");
		var totRefundAmt = $('#totRefundAmt').text().replace(/,/gi,"");
		
		if ( data.mallGb == '10' && chgGb == '30') {
			if (totRefundAmt <= 0) { // 아웃바운드 필요. (동동 및 계좌이체로 받아야함)
				mcxDialog.alert('환불금액 부족합니다.');
				return;
			}
			
			if(Number(totRefundAmt) > Number(totPayAmt)) {
				mcxDialog.alert('환불금액이 총 결제금액보다 큽니다.<br/>환불금액 : ' + totRefundAmt + '<br/>(남은)결제금액 : ' + totPayAmt);
				return;
			}
		}
		
		var allData = gagaAgGrid.getAllRowData(withdrawDetailGridOptions);
		var remainCnt = 0;
		
		$(allData).each(function(idx) {
			remainCnt++;
		});
		
		data.chgGb = $('#withdrawDetailForm input[name=chgGb]').val();
		data.chgReason = $('#withdrawDetailForm select[name=chgReason]').val();	// 최종요청사유
		data.orgChgReason = $('#withdrawDetailForm input[name=orgChgReason]').val();
		data.encloseFee = $('#withdrawDetailForm input[name=encloseFee]').val().replace(/,/gi, "");		// 동봉비
		data.orgEncloseFee = $('#withdrawDetailForm input[name=orgEncloseFee]').val().replace(/,/gi, "");		// 동봉비
		data.custShipAmt = $('#custShipAmt').text().replace(/,/gi, "");	// 고객부담 배송비
		data.pgStats = $('#withdrawDetailForm input:checkbox[name=pgStats]').is(":checked") ? "Y" : "N"; 
		data.totRefundAmt = totRefundAmt;
		data.mode = allData.length;
		
// 		data.searchType = '1'; // 테스트 에러

		var jsonData = JSON.stringify(data);
		
		if (!confirmFlag) {
			mcxDialog.alert('데이터 처리 중입니다.');
			return;
		}

		mcxDialog.confirm('회수컨펌 하시겠습니까?', {
			cancelBtnText: "취소",
			sureBtnText: "확인",
			sureBtnClick: function(){
				gagajf.ajaxJsonSubmit('/withdraw/detail/confirm', jsonData, function(result) {
					confirmFlag = true;
					fnDetailSearch(false);
				});
			}
		});
	}
	
	// readonly 설정
	var setReadOnly = function(flag) {
		if (flag) {
			$('#withdrawDetailForm input[name=encloseFee]').attr('readonly', 'readonly');
			$('#withdrawDetailForm input[name=encloseFee]').addClass('formControl');
			
			$('#withdrawDetailForm select[name=chgReason]').attr('disabled', 'disabled');
			$('#withdrawDetailForm select[name=chgReason]').addClass('formControl');	
		} else {
			$('#withdrawDetailForm input[name=encloseFee]').remove('readonly');
			$('#withdrawDetailForm input[name=encloseFee]').removeClass('formControl');
			
			$('#withdrawDetailForm select[name=chgReason]').remove('disabled');
			$('#withdrawDetailForm select[name=chgReason]').removeClass('formControl');
		}
		
	}

/*]]>*/
</script>
</html>
