package com.style24.admin.biz.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaDateUtil;

import com.style24.admin.biz.dao.TsaDeliveryDao;
//import com.style24.admin.biz.dao.TsaOrderDao;
import com.style24.admin.biz.dao.TsaWithdrawDao;
//import com.style24.admin.biz.dao.TsaWmsWithdrawDao;



//import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.Delivery;
//import com.style24.persistence.domain.Order;
//import com.style24.persistence.domain.PayGate;
//import com.style24.persistence.domain.Point;
import com.style24.persistence.domain.Withdraw;



import com.style24.admin.support.env.TsaConstants;
import com.style24.admin.support.env.TsaConstants.OrderDetailStat;
//import com.style24.admin.support.env.TsaConstants.OrderStat;
//import com.style24.admin.support.env.TsaConstants.PayMeans;
//import com.style24.admin.support.env.TsaConstants.PaymentStat;
//import com.style24.admin.support.env.TsaConstants.PurchaseReturnGb;
//import com.style24.admin.support.env.TsaConstants.UsacGb;

import com.style24.core.support.message.TscMessageByLocale;
import com.style24.admin.support.security.session.TsaSession;

/**
 * 회수관리 Service
 *
 * @author moon
 * @since 2020. 11. 16
 */
@Service
@Slf4j
public class TsaWithdrawService {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsaWithdrawDao withdrawDao;

	@Autowired
	private TsaDeliveryDao deliveryDao;

	//@Autowired
	//private TsaOrderDao orderDao;

	//@Autowired
	//private TsaOrderService orderService;

	//@Autowired
	//private TsaWmsWithdrawDao wmsWithdrawDao;

	@Autowired
	private TsaKakaoService kakaoService;

	/**
	 * 회수등록 - 조회(송장번호용)
	 *
	 * @param withdraw
	 * @return Collection<Withdraw>
	 * @author rladbwnd5
	 * @since 2020. 02. 11
	 */
//	public Collection<Withdraw> getWithdrawRegisterInvoiceList(Withdraw withdraw) {
//		Collection<Withdraw> dataList = withdrawDao.getWithdrawRegisterInvoiceList(withdraw);
//		return dataList;
//	}

	/**
	 * 회수등록 - 조회(상품코드용)
	 *
	 * @param withdraw
	 * @return Withdraw List
	 * @author rladbwnd5
	 * @since 2020. 02. 12
	 */
//	public Collection<Withdraw> getWithdrawRegisterGoodsList(Withdraw withdraw) {
//		return withdrawDao.getWithdrawRegisterGoodsList(withdraw);
//	}

	/**
	 * 회수등록 - 등록처리
	 *
	 * @param withdrawList
	 * @return Withdraw List
	 * @author rladbwnd5
	 * @since 2020. 02. 12
	 */
//	@Transactional("shopTxnManager")
//	public void createWithdrawInfo(Collection<Withdraw> withdrawList) {
//		String uesrId = TsaSession.getInfo().getUserId();
//
//		// 회수 마스터 등록 정보
//		Withdraw withdrawInfo = withdrawList.iterator().next();
//
//		// 주문변경번호
//		Long ordChgSq = withdrawInfo.getOrdChgSq();
//
//		// 기존 회수 수량
//		int wdQty = withdrawInfo.getSumWdQty();
//
//		// 1. 회수 상세 등록 (동일 여부 판단 위해 상세 먼저 등록)
//		for (Withdraw withdrawDetailInfo : withdrawList) {
//			if (ordChgSq > 0) {
//				wdQty += withdrawDetailInfo.getWdQty(); // 기존 회수 수량 + 회수 수량
//
//				// 회수 완료 확인
//				if (withdrawInfo.getSumChgQty() == wdQty) {
//					withdrawInfo.setSameYn("Y");
//				}
//			} else {
//				withdrawInfo.setSameYn("N");
//			}
//
//			withdrawDetailInfo.setRegId(uesrId);
//			withdrawDetailInfo.setUpdId(uesrId);
//			withdrawDao.createWithdrawDetailInfo(withdrawDetailInfo);
//		}
//
//		// 2. 회수 마스터 등록 처리
//		withdrawInfo.setRegId(uesrId);
//		withdrawInfo.setUpdId(uesrId);
//		withdrawDao.saveWithdrawInfo(withdrawInfo);
//	}

	/**
	 * 회수송장번호 변경
	 *
	 * @param
	 * @return
	 * @author rladbwnd5
	 * @since 2020. 02. 27
	 */
//	@Transactional("shopTxnManager")
//	public void updateRegisterWdInvoiceNo(Withdraw withdraw) {
//		withdraw.setUpdId(TsaSession.getInfo().getUserId());
//		withdrawDao.updateRegisterWdInvoiceNo(withdraw);
//	}

	/**
	 * 회수송장번호 조회
	 *
	 * @param
	 * @return
	 * @author yujung
	 * @since 2020. 05. 31
	 */
//	public Collection<Withdraw> getWdInvoiceNo(Withdraw withdraw) {
//		return withdrawDao.getWdInvoiceNo(withdraw);
//	}

	/**
	 * 환불관리 목록
	 *
	 * @param withdraw
	 * @return Collection<Withdraw>
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Collection<Withdraw> getRefundList(Withdraw withdraw) {
		return withdrawDao.getRefundList(withdraw);
	}

	/**
	 * 환불관리 회수데이터 삭제처리
	 *
	 * @param
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public void deleteWithdrawInfo(Withdraw withdraw) {
		Withdraw search = new Withdraw();
		search.setWdInvoiceNo(withdraw.getWdInvoiceNo());
		Collection<Withdraw> withdrawList = withdrawDao.getRefundList(search);
		// 마지막 회수 리스트 일 때 마스터 정보 삭제
		if (withdrawList.size() == 1) {
			withdrawDao.deleteWithdraw(withdraw);
		}

		withdrawDao.deleteWithdrawDetail(withdraw);
	}

	/**
	 * 회수마스터 삭제처리
	 *
	 * @param
	 * @return
	 * @author yujung
	 * @since 2020. 06. 01
	 */
//	@Transactional("shopTxnManager")
//	public void deleteWithdraw(Withdraw withdraw) {
//		withdrawDao.deleteWithdraw(withdraw);
//	}

	/**
	 * 회수상세 삭제처리
	 *
	 * @param
	 * @return
	 * @author yujung
	 * @since 2020. 06. 01
	 */
//	@Transactional("shopTxnManager")
//	public void deleteWithdrawDetail(Withdraw withdraw) {
//		withdrawDao.deleteWithdrawDetail(withdraw);
//	}

	/**
	 * 회수등록 팝업 목록
	 *
	 * @param
	 * @return
	 * @author rladbwnd5
	 * @since 2020. 03. 03
	 */
//	public Collection<Withdraw> getWithdrawRegisterPopupList(Withdraw withdraw) {
//		return withdrawDao.getWithdrawRegisterPopupList(withdraw);
//	}

	/**
	 * 회수등록팝업 주문매핑(송장번호 수정)
	 *
	 * @param
	 * @return
	 * @author yujung
	 * @since 2020. 03. 25
	 */
//	@Transactional("shopTxnManager")
//	public void updateOrderChangeWdInvoiceNo(Withdraw withdraw) {
//		String userId = TsaSession.getInfo().getUserId();
//
//		// 주문변경 회수송장번호 변경
//		Withdraw orderChangeParam = new Withdraw();
//		orderChangeParam.setOrdChgSq(withdraw.getOrdChgSq());
//		orderChangeParam.setWdInvoiceNo(withdraw.getWdInvoiceNo());
//		orderChangeParam.setUpdId(userId);
//		withdrawDao.updateRegisterWdInvoiceNo(orderChangeParam);
//
//		// 회수상세 변경
//		Withdraw withdrawDetailInfo = new Withdraw();
//		withdrawDetailInfo.setWdInvoiceNo(withdraw.getWdInvoiceNo());
//		withdrawDetailInfo.setGoodsCd(withdraw.getGoodsCd());
//		withdrawDetailInfo.setSizeCd(withdraw.getSizeCd());
//		withdrawDetailInfo.setOrdDtlNo(withdraw.getOrdDtlNo());
//		withdrawDetailInfo.setUpdId(userId);
//		withdrawDao.updateWithdrawDetailInfo(withdrawDetailInfo);
//
//		// 회수송장번호 등록
//		Withdraw wdInvoiceInfo = new Withdraw();
//		wdInvoiceInfo.setWdInvoiceNo(withdraw.getWdInvoiceNo());
//		wdInvoiceInfo.setOrdChgSq(withdraw.getOrdChgSq());
//		wdInvoiceInfo.setUpdId(userId);
//		withdrawDao.updateWithdrawOrderChange(wdInvoiceInfo);
//	}

	/**
	 * 회수등록팝업 주문매핑(주문상세일련번호 수정)
	 *
	 * @param
	 * @return
	 * @author yujung
	 * @since 2020. 03. 25
	 */
//	@Transactional("shopTxnManager")
//	public void updateWithdrawOrdDtlNo(Withdraw withdraw) {
//		// 아웃바운드 정보 업데이트
//		Withdraw outboundInfo = new Withdraw();
//		outboundInfo.setWdInvoiceNo(withdraw.getWdInvoiceNo());
//		outboundInfo.setCsObYn("Y");
//		outboundInfo.setCsObId(TsaSession.getInfo().getUserId());
//		withdrawDao.updateWithdrawOutbound(outboundInfo);
//
//		// 회수상세 변경
//		Withdraw withdrawDetailInfo = new Withdraw();
//		withdrawDetailInfo.setWdInvoiceNo(withdraw.getWdInvoiceNo());
//		withdrawDetailInfo.setGoodsCd(withdraw.getGoodsCd());
//		withdrawDetailInfo.setSizeCd(withdraw.getSizeCd());
//		withdrawDetailInfo.setOrdDtlNo(withdraw.getOrdDtlNo());
//		withdrawDetailInfo.setUpdId(TsaSession.getInfo().getUserId());
//		withdrawDao.updateWithdrawDetailInfo(withdrawDetailInfo);
//
//		// 회수관리 주문상세번호 및 상품 정보 변경
//		Withdraw withdrawInfo = new Withdraw();
//		withdrawInfo.setOrgOrdDtlNo(withdraw.getOrgOrdDtlNo()); // 원주문상세번호
//		withdrawInfo.setGoodsCd(withdraw.getGoodsCd());
//		withdrawInfo.setSizeCd(withdraw.getSizeCd());
//		withdrawInfo.setOrdDtlNo(withdraw.getOrdDtlNo()); // 변경 될 주문번호
//		withdrawInfo.setWdInvoiceNo(withdraw.getWdInvoiceNo());
//		withdrawInfo.setUpdId(TsaSession.getInfo().getUserId());
//		withdrawDao.updateWithdrawDetailGoodsInfo(withdrawInfo);
//
//		// withdrawDao.updateWithdrawOrdDtlNo(withdraw);
//		// return super.ok(message.getMessage("SUCC_0002"));
//	}

	/**
	 * 환불관리 상세정보
	 *
	 * @param withdraw - 변경주문번호
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Collection<Withdraw> getRefundDetailList(Withdraw withdraw) {
		return withdrawDao.getRefundDetailList(withdraw);
	}

	/**
	 * 환불관리 남은상품정보
	 *
	 * @param withdraw - 변경주문번호, 주문번호
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Withdraw getRemainGoodsInfo(Withdraw withdraw) {
		return withdrawDao.getRemainGoodsInfo(withdraw);
	}

	/**
	 * 환불관리 남은상품리스트
	 *
	 * @param withdraw - 변경주문번호, 주문번호
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Collection<Withdraw> getWithdrawRemainOrderDetailList(Withdraw withdraw) {
		return withdrawDao.getWithdrawRemainOrderDetailList(withdraw);
	}

	/**
	 * 회수관리 쿠폰정보
	 *
	 * @param withdraw - 변경주문번호, 주문번호
	 * @return
	 * @author moon
	 * @since 2020. 11. 15
	 */
	public Withdraw getCouponInfo(Withdraw withdraw) {
		return withdrawDao.getCouponInfo(withdraw);
	}


	/**
	 * 회수관리 - 회수처리
	 *
	 * @param params
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public void refundDetailConfirm(Withdraw params) {
//		// 기본값 설정
//		String userId = TsaSession.getInfo().getUserId();
//		int custNo = params.getCustNo();		// 회원번호
//		Long ordNo = params.getOrdNo();		// 주문번호
//		Long ordDtlNo = params.getOrdDtlNo();	// 주문상세번호
//		Long ordChgSq = params.getOrdChgSq();	// 주문변경번호
//		int cnclRtnQty = params.getCnclRtnQty();	// 취소반품 수량
//		int custShipAmt = params.getCustShipAmt();	// 고객부담배송비
//		String chgGb = params.getChgGb();	// 변경요청구분
//		String supplyCompCd = params.getSupplyCompCd();
//		String pgStat = params.getPgStats();
//		String mallGb = params.getMallGb();
//		String chgReason = params.getChgReason();
//		String orgChgReason = params.getOrgChgReason();
//		int orgEncloseFee = params.getOrgEncloseFee();
//		int encloseFee = params.getEncloseFee();
//		String delvLocCd = params.getDelvLocCd();	// 반품처코드
//
//		if (!chgReason.equals(orgChgReason)) {
//			Withdraw chgParams = new Withdraw();
//			chgParams.setUpdId(userId);
//			chgParams.setChgReason(chgReason);
//			chgParams.setOrdChgSq(ordChgSq);
//			withdrawDao.updateWithdrawOrderChange(chgParams);
//		}
//
//		if (encloseFee != orgEncloseFee) {
//			Withdraw withdrawParams = new Withdraw();
//			withdrawParams.setEncloseFee(encloseFee);
//			withdrawParams.setUpdId(userId);
//			withdrawParams.setWdInvoiceNo(params.getWdInvoiceNo());
//			withdrawDao.updateWithdrawEncloseFee(withdrawParams);
//		}
//
//		Withdraw ordChgDtlParams = new Withdraw();
//		ordChgDtlParams.setOrdChgSq(ordChgSq);
//		ordChgDtlParams.setOrdDtlNo(ordDtlNo);
//		if (TsaConstants.OrderChangeGb.EXCHANGE.value().equals(params.getChgGb())) {	// 교환인 경우
//			ordChgDtlParams.setChgStat(TsaConstants.OrderChangeStat.EXCHANGE_COMPLETE.value());
//		} else {
//			ordChgDtlParams.setChgStat(TsaConstants.OrderChangeStat.RETURN_COMPLETE.value());
//		}
//		ordChgDtlParams.setUpdId(userId);
//		withdrawDao.updateWithdrawOrderChangeDetailInfo(ordChgDtlParams);
//
//		int remainCount = withdrawDao.getRemainWithdrawCount(ordChgSq);	// 회수컨펌 남은 개수
//
//		if (remainCount == 0) {
//			// 주문 변경 회수 종료 일시 업데이트
//			Withdraw orderChangeInfo = new Withdraw();
//			orderChangeInfo.setOrdChgSq(ordChgSq);
//			orderChangeInfo.setUpdId(userId);
//			withdrawDao.updateOrderChangeInfo(orderChangeInfo);
//
//			int orgDelvFee = 0;	// 원주문배송비
//			int refundAmt = 0;	// 환불금액
//			int refundPntAmt = 0;
//			int refundPrePntAmt = 0;
//			int refundGoodsCpnAmt = 0;
//			int refundCartCpnAmt = 0;
//			int refundCancelCartCpnAmt = 0;
//			int refundPlusCpnAmt = 0;
//			int refundSavePntAmt = 0;
//			Long usedCartCpnSq = null;
//
//			Collection<TsaPoint> pointList = new ArrayList<TsaPoint>();
//			Collection<TsaPoint> prePointList = new ArrayList<TsaPoint>();
//			Collection<TsaPoint> savePointList = new ArrayList<TsaPoint>();
//
//			// ORD_CHG_SQ 별 ITEM_CD 단위의 리스트
//			Collection<Withdraw> withdrawList = withdrawDao.getWithdrawDetailList(params);
//
//			// 쿠폰정보
//			String couponCartCpnSq = withdrawList.iterator().next().getCartCpnSq();
//			Withdraw couponInfo = null;
//			if (StringUtils.isNotBlank(couponCartCpnSq)) {
//				Withdraw searchCoupon = new Withdraw();
//				searchCoupon.setCartCpnSq(couponCartCpnSq);
//				searchCoupon.setCustNo(custNo);
//				couponInfo = withdrawDao.getCouponInfo(searchCoupon);
//			}
//
//			List<Withdraw> ifOnilneSales = new ArrayList();
//			GagaMap setOrdDtlNos = new GagaMap();
//			int cancelRequestAmt = 0;                            // 취소요청금액 cancelRequestAmt
//
//			for (Withdraw withdraw : withdrawList) {
//				// 세트상품인 경우 회수컨펌 처리건이 있으면 스킵
//				if ("S".equals(withdraw.getGoodsType()) && setOrdDtlNos.getInt(withdraw.getOrdDtlNo()) > 1) {
//					continue;
//				}
//				orgDelvFee = withdraw.getOrgDelvFee();
//				String goodsCpnSq = withdraw.getGoodsCpnSq();
//				String cartCpnSq = withdraw.getCartCpnSq();
//				int cnclReturnRealOrdAmt = 0;
//				int orgOrdAmt = withdraw.getOrdAmt();
//				int orgCurrPrice = withdraw.getCurrPrice();
//				int orgRealOrdAmt = withdraw.getRealOrdAmt();
//				int ordQty = withdraw.getOrdQty();
//				int orgCnclRtnQty = withdraw.getCnclRtnQty();
//				int wdQty = withdraw.getWdQty();
//				int realOrdQty = ordQty - orgCnclRtnQty;
//				int orgCnclRtnAmt = withdraw.getCnclRtnAmt();
//				int orgGoodsCpnDcAmt = withdraw.getGoodsCpnDcAmt();
//				int orgCartCpnDcAmt = withdraw.getCartCpnDcAmt();
//				int orgPntDcAmt = withdraw.getPntDcAmt();
//				int orgPrePntDcAmt = withdraw.getPrePntDcAmt();
//				int orgSavePntAmt = withdraw.getSavePntAmt();
//				String plusCpnSq = withdraw.getPlusCpnSq();
//				int orgPlusCpnDcAmt = withdraw.getPlusCpnDcAmt();
//
//				/* 정산,환불 처리용 */
//				int rfPntAmt = (int)((double)orgPntDcAmt / realOrdQty * wdQty);				// 환원 포인트
//				int rfPrePntAmt = (int)((double)orgPrePntDcAmt / realOrdQty * wdQty);		// 취소 선포인트
//				int rfGoodsCpnAmt = (int)((double)orgGoodsCpnDcAmt / realOrdQty * wdQty);	// 취소 상품쿠폰금액
//				int rfCartCpnAmt = (int)((double)orgCartCpnDcAmt / realOrdQty * wdQty);		// 취소 장바구니쿠폰금액
//				int rfPlusCpnAmt = (int)((double)orgPlusCpnDcAmt / realOrdQty * wdQty);		// 취소 플러스쿠폰금액
//				int rfSavePntAmt = (int)((double)orgSavePntAmt / realOrdQty * wdQty);
//
//				refundPntAmt += rfPntAmt;
//				refundPrePntAmt += rfPrePntAmt;
//				refundGoodsCpnAmt += rfGoodsCpnAmt;
//				refundCartCpnAmt += rfCartCpnAmt;
//				refundPlusCpnAmt += rfPlusCpnAmt;
//				refundSavePntAmt += rfSavePntAmt;
//
//				int cnclRtnAmt = 0;
//				int erpCnclRtnAmt = 0;
//				int goodsCpnDcAmt = orgGoodsCpnDcAmt - rfGoodsCpnAmt;
//				int cartCpnDcAmt = orgCartCpnDcAmt - rfCartCpnAmt;
//				int plusCpnDcAmt = orgPlusCpnDcAmt - rfPlusCpnAmt;
//				int pntDcAmt = orgPntDcAmt - rfPntAmt;
//				int prePntDcAmt = orgPrePntDcAmt - rfPrePntAmt;
//				int savePntAmt = orgSavePntAmt - (orgSavePntAmt / realOrdQty * wdQty);
//				cnclRtnQty = orgCnclRtnQty + wdQty;
//
//				log.info("orgRealOrdAmt = " + orgRealOrdAmt);
//				log.info("wdQty = " + wdQty);
//				log.info("cnclRtnAmt = " + cnclRtnAmt);
//
//				cnclRtnAmt += orgCnclRtnAmt + (orgCurrPrice * wdQty);
//				erpCnclRtnAmt = (orgCurrPrice * wdQty);
//				cnclReturnRealOrdAmt = (orgCurrPrice * wdQty) - rfPntAmt - rfPrePntAmt - rfGoodsCpnAmt - rfCartCpnAmt - rfPlusCpnAmt;
//
//				log.info("orgCnclRtnAmt = " + orgCnclRtnAmt);
//				log.info("orgRealOrdAmt = " + orgRealOrdAmt);
//				log.info("orgOrdAmt = " + orgOrdAmt);
//				log.info("ordQty = " + ordQty);
//				log.info("orgCnclRtnQty = " + orgCnclRtnQty);
//				log.info("(orgOrdAmt / (ordQty - orgCnclRtnQty)) = " + (orgOrdAmt / (ordQty - orgCnclRtnQty)));
//				log.info("refundPntAmt = " + refundPntAmt);
//				log.info("refundPrePntAmt = " + refundPrePntAmt);
//				log.info("refundGoodsCpnAmt = " + refundGoodsCpnAmt);
//				log.info("refundCartCpnAmt = " + refundCartCpnAmt);
//				log.info("refundPlusCpnAmt = " + refundPlusCpnAmt);
//				log.info("cnclReturnRealOrdAmt = " + cnclReturnRealOrdAmt);
//
//				int realOrdAmt = orgRealOrdAmt - cnclReturnRealOrdAmt;
//				refundAmt += cnclReturnRealOrdAmt;
//
//				log.info("realOrdAmt = " + realOrdAmt);
//				log.info("cnclRtnQty = " + cnclRtnQty);
//				log.info("cnclRtnAmt = " + cnclRtnAmt);
//				log.info("goodsCpnDcAmt = " + goodsCpnDcAmt);
//				log.info("goodsCpnSq = " + goodsCpnSq);
//				log.info("cartCpnDcAmt = " + cartCpnDcAmt);
//				log.info("cartCpnSq = " + cartCpnSq);
//				log.info("pntDcAmt = " + pntDcAmt);
//				log.info("prePntDcAmt = " + prePntDcAmt);
//				log.info("savePntAmt = " + savePntAmt);
//				log.info("plusCpnDcAmt = " + plusCpnDcAmt);
//				log.info("plusCpnSq = " + plusCpnSq);
//
//				// 주문상세 업데이트
//				log.info("============== 주문상세 업데이트 ==============");
//
//				Withdraw updParams = new Withdraw();
//				updParams.setUpdId(userId);
//				updParams.setOrdDtlNo(withdraw.getOrdDtlNo());
//				if (cnclRtnQty == ordQty) {
//					updParams.setOrdDtlStat(OrderDetailStat.PAYMENT_AFTER_CANCEL.value());
//				}
//				updParams.setRealOrdAmt(realOrdAmt);
//				updParams.setCnclRtnQty(cnclRtnQty);
//				updParams.setCnclRtnAmt(cnclRtnAmt);
//				updParams.setGoodsCpnDcAmt(goodsCpnDcAmt);
//				updParams.setGoodsCpnSq(goodsCpnSq);
//				updParams.setCartCpnDcAmt(cartCpnDcAmt);
//				updParams.setCartCpnSq(cartCpnSq);
//				updParams.setPlusCpnDcAmt(plusCpnDcAmt);
//				updParams.setPlusCpnSq(plusCpnSq);
//				updParams.setPntDcAmt(pntDcAmt);
//				updParams.setPrePntDcAmt(prePntDcAmt);
//				updParams.setSavePntAmt(savePntAmt);
//				updParams.setRegId(userId);
//				withdrawDao.updateWithdrawOrderDetailInfo(updParams);
//				withdrawDao.createWithdrawOrderDetailHstInfo(updParams);
//
//				// 주문상세 업데이트
//				log.info("============== 매출반영 ==============");
//
//				Withdraw ifData = new Withdraw();
//				ifData.setOrdDtlNo(withdraw.getOrdDtlNo());
//				ifData.setOrdNo(ordNo);
//				ifData.setWdQty(wdQty);
//				ifData.setCnclRtnAmt(cnclRtnAmt);
//				ifData.setGoodsCd(withdraw.getGoodsCd());
//				ifData.setRealOrdAmt(cnclReturnRealOrdAmt);
//				ifData.setRealOrdQty(realOrdQty);
//				ifData.setRfGoodsCpnAmt(rfGoodsCpnAmt);
//				ifData.setRfCartCpnAmt(rfCartCpnAmt);
//				ifData.setRfPlusCpnAmt(rfPlusCpnAmt);
//				ifData.setRfPntAmt(rfPntAmt);
//				ifData.setRfPrePntAmt(rfPrePntAmt);
//				ifData.setRfSavePntAmt(rfSavePntAmt);
//				ifData.setGoodsType(withdraw.getGoodsType());
//				ifData.setOrdAmt(erpCnclRtnAmt);
//				ifData.setCartCpnSq(cartCpnSq);
//				ifData.setGoodsCpnSq(goodsCpnSq);
//				ifData.setPlusCpnSq(plusCpnSq);
//				ifData.setOrderNm(withdraw.getOrderNm());
//				ifData.setOrderPhnno(withdraw.getOrderPhnno());
//				ifOnilneSales.add(ifData);
//
//				// 자사몰이면서 반품이면 포인트,쿠폰 반환
//				if (TsaConstants.MallGb.SELFMALL.value().equals(mallGb) && TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {
//
//					if (rfPntAmt > 0) {
//						TsaPoint point = new TsaPoint();
//						point.setPntAmt(rfPntAmt);
//						point.setOrdNo((int)(long)ordNo);
//						point.setOrdDtlNo((int)(long)ordDtlNo);
//						pointList.add(point);
//					}
//
//					if (rfPrePntAmt > 0) {
//						TsaPoint point = new TsaPoint();
//						point.setPntAmt(rfPrePntAmt);
//						point.setOrdNo((int)(long)ordNo);
//						point.setOrdDtlNo((int)(long)ordDtlNo);
//						prePointList.add(point);
//					}
//
//					if (savePntAmt > 0) {
//						TsaPoint point = new TsaPoint();
//						point.setPntAmt(-rfSavePntAmt);
//						point.setOrdNo((int)(long)ordNo);
//						point.setOrdDtlNo((int)(long)ordDtlNo);
//						savePointList.add(point);
//					}
//
//					if (StringUtils.isNotBlank(withdraw.getGoodsCpnSq())) {
//						TsaOrder goodsCpnParam = new TsaOrder();
//						goodsCpnParam.setCustCpnSq(Long.parseLong(withdraw.getGoodsCpnSq()));
//						goodsCpnParam.setUpdId(userId);
//
//						TsaCoupon goodsCpnInfo = orderDao.getCustCouponInfo(goodsCpnParam.getCustCpnSq());
//						if (goodsCpnInfo != null) {
//							goodsCpnInfo = orderDao.getCouponInfo(goodsCpnInfo.getCpnId());
//
//							if (goodsCpnInfo != null && ("10".equals(goodsCpnInfo.getReissuance()) || "30".equals(goodsCpnInfo.getReissuance()))) {
//								orderDao.updateCustCouponCancel(goodsCpnParam);
//							}
//						}
//					}
//
//					if (StringUtils.isNotBlank(withdraw.getPlusCpnSq())) {
//						TsaOrder plusCpnParam = new TsaOrder();
//						plusCpnParam.setCustCpnSq(Long.parseLong(withdraw.getPlusCpnSq()));
//						plusCpnParam.setUpdId(userId);
//
//						TsaCoupon plusCpnInfo = orderDao.getCustCouponInfo(plusCpnParam.getCustCpnSq());
//						if (plusCpnInfo != null) {
//							plusCpnInfo = orderDao.getCouponInfo(plusCpnInfo.getCpnId());
//
//							if (plusCpnInfo != null && ("10".equals(plusCpnInfo.getReissuance()) || "30".equals(plusCpnInfo.getReissuance()))) {
//								orderDao.updateCustCouponCancel(plusCpnParam);
//							}
//						}
//					}
//
//					if (StringUtils.isNotBlank(withdraw.getCartCpnSq())) {
//						usedCartCpnSq = Long.parseLong(withdraw.getCartCpnSq());
//					}
//				}
//
//				// 반품요청에 대한 컨펌시 환입 정산정보 생성
//				if (TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {
//					Withdraw paramUsac = new Withdraw();
//					paramUsac.setUsacGb(UsacGb.PURCHASE_RETURN.value());
//					paramUsac.setPrtnGb(PurchaseReturnGb.RETURN.value());
//					paramUsac.setOrdDtlNo(withdraw.getOrdDtlNo());
//					paramUsac.setOrgUsacGb(UsacGb.SELL.value());
//					paramUsac.setUsacQty(wdQty);
//					paramUsac.setGoodsCpnDcAmt(rfGoodsCpnAmt);
//					paramUsac.setCartCpnDcAmt(rfCartCpnAmt);
//					paramUsac.setPlusCpnDcAmt(rfPlusCpnAmt);
//					paramUsac.setPntDcAmt(rfPntAmt);
//					paramUsac.setPrePntDcAmt(rfPrePntAmt);
//					paramUsac.setRegId(userId);
//					withdrawDao.createWithdrawUsac(paramUsac);
//				}
//
//				// 세트상품인 경우 상세번호를 저장
//				if ("S".equals(withdraw.getGoodsType())) {
//					setOrdDtlNos.setInt(withdraw.getOrdDtlNo(), setOrdDtlNos.getInt(withdraw.getOrdDtlNo()) < 1 ? 1 : setOrdDtlNos.getInt(withdraw.getOrdDtlNo()) + 1);
//				}
//			}
//
//			// 쿠폰 처리
//			String chgReasonCds = "10,11,12,13,15,21,30";	// 고객 귀책
//			if (chgReasonCds.contains(chgReason) && TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {
//				if (couponInfo != null) {
//					if (StringUtils.isNotBlank(couponCartCpnSq) && couponInfo.getBuyLimitAmt() > 0) {
//						refundCancelCartCpnAmt += orderDetailCouponCancel(ordNo, ordChgSq, couponInfo.getBuyLimitAmt());
//					}
//				}
//			}
//
//			Withdraw orderDetailSumAmtInfo = withdrawDao.getOrderDetailSumAmt(ordNo.toString());
//
//			// 마지막에 처리 할 것. 장바구니 쿠폰 사용 여부 처리( 추후 구매제한에 대한 것도 처리 필요)
//			if (StringUtils.isNotBlank(couponCartCpnSq) && orderDetailSumAmtInfo.getTotCartCpnDcAmt() == 0 && TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {
//				TsaCoupon cartCpnInfo = new TsaCoupon();
//				if (usedCartCpnSq != null) {
//					cartCpnInfo = orderDao.getCustCouponInfo(usedCartCpnSq);
//				}
//				if (cartCpnInfo != null) {
//					cartCpnInfo = orderDao.getCouponInfo(cartCpnInfo.getCpnId());
//
//					if (cartCpnInfo != null && ("10".equals(cartCpnInfo.getReissuance()) || "30".equals(cartCpnInfo.getReissuance()))) {
//						TsaOrder paramCpn = new TsaOrder();
//						paramCpn.setUpdId(userId);
//						paramCpn.setCustCpnSq(Long.parseLong(couponCartCpnSq));
//						orderDao.updateCustCouponCancel(paramCpn);
//					}
//				}
//			}
//
//			int remainOrdCnt = withdrawDao.getOrderNotCancelCnt(ordNo);
//
//			TsaDelivery paramOrder = new TsaDelivery();
//			paramOrder.setOrdNo(ordNo);
//
//			if (remainOrdCnt == 0 && TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {
//				paramOrder.setUpdId(userId);
//				paramOrder.setOrdStat(OrderStat.PAYMENT_AFTER_CANCEL.value());
//				deliveryDao.updateOrder(paramOrder);
//			}
//
//			/* 포인트 처리 */
//			TsaOrder ordPnt = new TsaOrder();
//			ordPnt.setOrdNo(Long.toString(ordNo));
//			ordPnt.setCustNo(Integer.toString(custNo));
//			ordPnt.setOccurGb(TsaConstants.PointOccurGb.USE_POINT.value());
//			int ordUsedCustPointHstSq = orderDao.getOrderCustPointHstSq(ordPnt);	// 사용한 포인트 정보
//
//			if (ordUsedCustPointHstSq > 0 && TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {
//
//				// 환불 포인트 만료일
//				String expireDt = orderDao.getOrderAccountExpireDt(ordUsedCustPointHstSq);
//				String toDay = GagaDateUtil.getToday();
//
//				if (StringUtils.isNotBlank(expireDt)) {
//
//					// 만료일이 지났으면 오늘 + 7일로 셋팅
//					long longSwitchDueDt = Long.parseLong(expireDt);
//					long longToDay = Long.parseLong(toDay);
//
//					if (longSwitchDueDt < longToDay) {
//						expireDt = GagaDateUtil.getOffsetDate(toDay, 7, "yyyyMMdd");
//					}
//
//					// 사용 포인트 반환
//					if (refundPntAmt > 0) {
//						TsaPoint point = new TsaPoint();
//						point.setCustNo(Integer.toString(custNo));
//						point.setOccurGb(TsaConstants.PointOccurGb.USE_POINT_CANCEL.value());
//						point.setGivenPntAmt(refundPntAmt);
//						point.setAvailPntAmt(refundPntAmt);
//						point.setUsePntAmt(0);
//						point.setExpireDt(expireDt);
//						point.setOrdNo(Integer.parseInt(Long.toString(ordNo)));
//						point.setSwitchDueDt(GagaDateUtil.getTodayDateTime());
//						point.setPntUploadStat(TsaConstants.PointOccurStat.APPLY_COMPLETE.value());
//						point.setPntUploadDt(point.getSwitchDueDt());
//						point.setRegId(userId);
//						point.setUpdId(userId);
//						orderDao.createPointAccount(point);
//
//						point.setPntAmt(point.getGivenPntAmt());
//						orderDao.createCustPointHst(point);
//
//						orderDao.createPointDetail(point);
//
//						for (TsaPoint paramPnt : pointList) {
//							paramPnt.setCustPointHstSq(point.getCustPointHstSq());
//							paramPnt.setRegId(userId);
//							orderDao.createOrderPoint(paramPnt);
//						}
//					}
//
//					// 적립 예정 포인트 취소
//					if (refundSavePntAmt > 0) {
//						TsaPoint point = new TsaPoint();
//
//						point.setOrdNo(Integer.parseInt(Long.toString(ordNo)));
//						point.setOccurGb(TsaConstants.PointOccurGb.EXPECT_POINT.value());
//						String switchDueDt = orderDao.getPointAccountSwitchDueDt(point);
//						expireDt = orderDao.getPointAccountExpireDt(point);
//						String pntUploadStat = orderDao.getPointAccountPntUploadStat(point);
//						
//						int availPntAmt = 0;
//						String uploadDt = "";
//						String uploadStat = TsaConstants.PointOccurStat.APPLY_EXPECT.value();
//						String toDayTime = GagaDateUtil.getTodayDateTime();
//
//						// 예정일이 지났으면 오늘로 셋팅
//						if (TsaConstants.PointOccurStat.APPLY_COMPLETE.value().equals(pntUploadStat)) {
//							availPntAmt = -refundSavePntAmt;
//							switchDueDt = toDayTime;
//							uploadDt = switchDueDt;
//							uploadStat = TsaConstants.PointOccurStat.APPLY_COMPLETE.value();
//						}
//
//						point.setCustNo(Integer.toString(custNo));
//						point.setOccurGb(TsaConstants.PointOccurGb.EXPECT_POINT_CANCEL.value());
//						point.setGivenPntAmt(-refundSavePntAmt);
//						point.setAvailPntAmt(availPntAmt);
//						point.setUsePntAmt(0);
//						point.setExpireDt(expireDt);
//						point.setSwitchDueDt(GagaDateUtil.getTodayDateTime());
//						point.setPntUploadStat(uploadStat);
//						point.setPntUploadDt(uploadDt);
//						point.setRegId(userId);
//						point.setUpdId(userId);
//						orderDao.createPointAccount(point);
//
//						point.setPntAmt(point.getGivenPntAmt());
//						orderDao.createCustPointHst(point);
//
//						orderDao.createPointDetail(point);
//
//						for (TsaPoint paramPnt : savePointList) {
//							paramPnt.setCustPointHstSq(point.getCustPointHstSq());
//							paramPnt.setRegId(userId);
//							orderDao.createOrderPoint(paramPnt);
//						}
//					}
//				}
//			}
//
//			if (TsaConstants.OrderChangeGb.RETURN.value().equals(chgGb)) {	// 반품인경우
//				// 결제 정보
//				TsaOrder paramPay = new TsaOrder();
//				paramPay.setOrdNo(ordNo.toString());
//				paramPay.setPayStat(PaymentStat.PAYMENT_COMPLETE.value());
//				paramPay.setDelvPayGb("O");
//				TsaOrder pay = orderDao.getPayment(paramPay);
//
//				pay.setOrgPayStat(PaymentStat.PAYMENT_COMPLETE.value());
//
//				int orgPaySq = pay.getPaySq();
//				int paySq = orgPaySq + 1;
//				int orgPayAmt = pay.getPayAmt();
//				int devlFeePaySq = orgPaySq;
//
//				// 원 결제 정보 업데이트
//				pay.setOrdNo(ordNo.toString());
//				pay.setPayStat(PaymentStat.PAYMENT_CANCEL.value());
//				pay.setUpdId(userId);
//
//				/* 9.배송비 등록 */
//				GagaMap delvMap = deliveryFeeProcess(params, orgPaySq, chgReasonCds);
//				int totRfDelvFee = delvMap.getInt("totDelvFee");	// 총환불배송비
//				int rfDelvCpnAmt = delvMap.getInt("rfDelvCpnAmt");
//
//				// 환불금액
//				log.info("============== 환불 금액 ==============");
//
//				if (TsaConstants.MallGb.SELFMALL.value().equals(mallGb)) {	// 자사몰인경우
//					refundAmt = refundAmt + totRfDelvFee - refundCancelCartCpnAmt;
//				}
//
//				log.info("refundAmt = " + refundAmt);
//				log.info("custShipAmt = " + custShipAmt);
//				log.info("orgDelvFee = " + orgDelvFee);
//				log.info("refundGoodsCpnAmt = " + refundGoodsCpnAmt);
//				log.info("refundCartCpnAmt = " + (refundCartCpnAmt + refundCancelCartCpnAmt));
//				log.info("refundPntAmt = " + refundPntAmt);
//				log.info("refundPrePntAmt = " + refundPrePntAmt);
//				log.info("refundCancelCartCpnAmt = " + refundCancelCartCpnAmt);
//				log.info("refundPlusCpnAmt = " + refundPlusCpnAmt);
//				log.info("totRfDelvFee = " + totRfDelvFee);
//				log.info("rfDelvCpnAmt = " + rfDelvCpnAmt);
//
//				// 환불정보
//				if (TsaConstants.MallGb.SELFMALL.value().equals(mallGb)) {	// 자사몰만 환불정보 등록
//					if (PayMeans.ACCOUNT_DEPOSIT.value().equals(pay.getPayMeans())) {
//						pay.setOrdChgSq(ordChgSq);
//						TsaOrder paramRefund = orderDao.getRefundAccount(pay);
//
//						if (paramRefund != null) {
//							pay.setRaBnk(paramRefund.getRaBnk());
//							pay.setRaNm(paramRefund.getRaNm());
//							pay.setRaNo(paramRefund.getRaNo());
//						} else {
//							paramRefund = orderDao.getCustomerDefaultAccount(Integer.toString(custNo));
//							if (paramRefund != null) {
//								pay.setRaNo(paramRefund.getRaNo());
//								pay.setRaNm(paramRefund.getRaNm());
//								pay.setRaBnk(paramRefund.getRaBnk());
//							}
//						}
//						if (paramRefund == null) {
//							throw new IllegalStateException("환불계좌정보가 없습니다.");
//						}
//						paramRefund.setOrdNo(Long.toString(ordNo));
//						paramRefund.setPaySq(pay.getPaySq());
//						paramRefund.setOrdChgSq(ordChgSq);
//						paramRefund.setRefundAmt(refundAmt);
//						paramRefund.setRfGoodsCpnAmt(refundGoodsCpnAmt + refundPlusCpnAmt + rfDelvCpnAmt);
//						paramRefund.setRfCartCpnAmt(refundCartCpnAmt + refundCancelCartCpnAmt);
//						paramRefund.setRfPntAmt(refundPntAmt);
//						paramRefund.setRfPrePntAmt(refundPrePntAmt);
//						paramRefund.setRegId(userId);
//						orderDao.createRefund(paramRefund);
//					} else {
//						TsaOrder paramRefund = new TsaOrder();
//						paramRefund.setOrdNo(Long.toString(ordNo));
//						paramRefund.setPaySq(pay.getPaySq());
//						paramRefund.setOrdChgSq(ordChgSq);
//						paramRefund.setRefundAmt(refundAmt);
//						paramRefund.setRfGoodsCpnAmt(refundGoodsCpnAmt + refundPlusCpnAmt + rfDelvCpnAmt);
//						paramRefund.setRfCartCpnAmt(refundCartCpnAmt + refundCancelCartCpnAmt);
//						paramRefund.setRfPntAmt(refundPntAmt);
//						paramRefund.setRfPrePntAmt(refundPrePntAmt);
//						paramRefund.setRegId(userId);
//						orderDao.createRefund(paramRefund);
//					}
//				}
//
//				int payAmt = orgPayAmt - refundAmt;
//
//				String partCancelYn = "N";
//
//				if (orgPaySq > 1) {
//					partCancelYn = "Y";
//				}
//
//				if (payAmt > 0) {
//					paramPay.setPaySq(paySq);
//					paramPay.setPayAmt(payAmt);
//					paramPay.setPayStat(PaymentStat.PAYMENT_COMPLETE.value());
//					paramPay.setRegId(userId);
//					paramPay.setUpdId(userId);
//					paramPay.setOrgPaySq(pay.getPaySq());
//					orderDao.createPayment(paramPay);
//
//					partCancelYn = "Y";
//					devlFeePaySq = paySq;
//				}
//
//				// 매출반영
//				// ERP 판매반영 생성
//				for (Withdraw withdraw : ifOnilneSales) {
//					withdraw.setPayAmt(payAmt);
//					withdraw.setRefundAmt(refundAmt);
//					withdraw.setRegId(userId);
//					createIfEcpTbSalesReturn(withdraw);
//				}
//
//				boolean checkPay = orgPayAmt - payAmt < 0 ? true : false;
//				if (checkPay) {
//					throw new IllegalStateException("결제금액과 환불정보가 맞지 않습니다.");
//				}
//
//				/* PG결제취소 */
//
//				TsaPayGate paramPg = new TsaPayGate();
//				paramPg.setPgShopId(pay.getPgShopId());	// 상점아이디
//				paramPg.setPgGb(pay.getPgGb());    // pg구분
//				paramPg.setTid(pay.getPgTid());    // 거래번호
//				paramPg.setCancelAmt(refundAmt);    // 취소금액
//				paramPg.setPartCancelYn(partCancelYn);    // 부분취소여부
//
//				if (TsaConstants.PayMeans.ACCOUNT_DEPOSIT.value().equals(pay.getPayMeans())) {        // 무통입금일때
//					paramPg.setRefundYn("Y");
//					paramPg.setRefundBankCd(pay.getRaBnk());    // 환불은행코드
//					paramPg.setRefundAcctNo(pay.getRaNo());    // 환불계좌번호
//					paramPg.setRefundAcctNm(pay.getRaNm());    // 환불계좌주명
//				}
//
//				// 자사몰이고 결제완료이고 PG점프가 아닌경우 PG와 통신한다.
//				if (TsaConstants.MallGb.SELFMALL.value().equals(mallGb)
//					&& TsaConstants.PaymentStat.PAYMENT_COMPLETE.value().equals(pay.getOrgPayStat()) && "N".equals(pgStat)) {
//
//					GagaMap result = orderService.cancelPgPayment(paramPg);
//
//					if (result.getBoolean("success")) {        // 00:취소성공
//						result.put("resultCd", "00");
//						result.put("resultMsg", "결제취소가 완료되었습니다.");
//						pay.setPgCnclTid(result.getString("TID"));
//					} else {
//						throw new IllegalStateException(result.getString("ResultMsg"));        // PG처리 실패시 전체 ROLLBACK 처리함.
//					}
//
//				}
//
//				if (payAmt == 0) {
//					paySq = orgPaySq;
//					pay.setPayStat(TsaConstants.PaymentStat.PAYMENT_CANCEL.value());
//				}
//
//				orderDao.updatePayment(pay);
//
//				// 카카오 알림톡 전송
//				try {
//					if (TsaConstants.MallGb.SELFMALL.value().equals(mallGb)) {
//						kakaoService.sendReturnComplete(params, withdrawList);
//					}
//				} catch (Exception e) {
//					e.fillInStackTrace();
//				}
//
//			} else {// 교환인 경우
//
//				// 교환출고처 지정대기(26) 상태인 놈을 출고처 예정(34) 으로 업데이트
//				for (Withdraw withdraw : ifOnilneSales) {
//					withdrawDao.updateExchangeLocAssignStatus(withdraw);
//					withdraw.setUpdId(userId);
//					withdraw.setRegId(userId);
//					withdrawDao.createWithdrawOrderDetailHstInfo(withdraw); // 원주문상세번호에 대한 이력
//					withdrawDao.createWithdrawOrderDetailHstInfo2(withdraw); // 교환 주문상세번호에 대한 이력
//				}
//
//				// 매출반영 환입 ERP 판매반영 생성
//				for (Withdraw withdraw : ifOnilneSales) {
//					withdraw.setRegId(userId);
//					createIfEcpTbSalesReturn(withdraw);
//				}
//				// 카카오 알림톡 전송
//				try {
//					if (TsaConstants.MallGb.SELFMALL.value().equals(mallGb)) {
//						kakaoService.sendWithdrawConfirm(params, withdrawList);
//					}
//				} catch (Exception e) {
//					e.fillInStackTrace();
//				}
//			}
//
//		}
//
	}

	/**
	 * ERP 환입반영처리
	 *
	 * @param withdraw - 주문 정보
	 * @return
	 * @author yh98kim
	 * @since 2020. 05. 13
	 */
//	@Transactional("shopTxnManager")
//	public void createIfEcpTbSalesReturn(Withdraw withdraw) {
//		if ("S".equals(withdraw.getGoodsType())) {
//			// 세트의 단품별 비중을 구한다.
//			Collection<Withdraw> withdrawList = withdrawDao.getWithdrawDetailList2(withdraw);
//			int totCnt = withdrawList.size();
//			int cnt = 0;
//
//			int sumDivRfPntAmt = 0;
//			int sumDivRfPrePntAmt = 0;
//			int sumDivRfGoodsCpnAmt = 0;
//			int sumDivRfCartCpnAmt = 0;
//			int sumDivRfPlusCpnAmt = 0;
//			int sumDivRfSavePntAmt = 0;
//
//			int rfPntAmt = withdraw.getRfPntAmt();
//			int rfPrePntAmt = withdraw.getRfPrePntAmt();
//			int rfGoodsCpnAmt = withdraw.getRfGoodsCpnAmt();
//			int rfCartCpnAmt = withdraw.getRfCartCpnAmt();
//			int rfPlusCpnAmt = withdraw.getRfPlusCpnAmt();
//			int rfSavePntAmt = withdraw.getSavePntAmt();
//
//			int wdQty = withdraw.getWdQty();	// 회수수량
//			int realOrdAmt = withdraw.getRealOrdAmt();	// 실주문금액
//
//			GagaMap gMap = new GagaMap();
//
//			for (Withdraw wd : withdrawList) {
//				int divRfPntAmt = 0;
//				int divRfPrePntAmt = 0;
//				int divRfGoodsCpnAmt = 0;
//				int divRfCartCpnAmt = 0;
//				int divRfPlusCpnAmt = 0;
//				int divRfSavePntAmt = 0;
//
//				// item 별 비중: 회수수량 * itemQty * itemPrice / realOrdAmt
//				// 소수점 2째짜리까지 비중을 구한다.
//				Double rate = Math.round(wdQty * wd.getItemQty() * wd.getItemPrice() / realOrdAmt * 100) / 100.0;
//
//				if (totCnt > 1 && cnt == totCnt - 1) {	// 마지막 건인 경우 쿠폰 포인트는 총계에서 나머지 합계를 빼서 구한다.
//					divRfPntAmt = rfPntAmt - sumDivRfPntAmt;
//					divRfPrePntAmt = rfPrePntAmt - sumDivRfPrePntAmt;
//					divRfGoodsCpnAmt = rfGoodsCpnAmt - sumDivRfPrePntAmt;
//					divRfCartCpnAmt = rfCartCpnAmt - sumDivRfGoodsCpnAmt;
//					divRfPlusCpnAmt = rfPlusCpnAmt - sumDivRfPlusCpnAmt;
//					divRfSavePntAmt = rfSavePntAmt - sumDivRfSavePntAmt;
//				} else {
//					divRfPntAmt = (int)Math.round(rfPntAmt * rate);
//					divRfPrePntAmt = (int)Math.round(rfPrePntAmt * rate);
//					divRfGoodsCpnAmt = (int)Math.round(rfGoodsCpnAmt * rate);
//					divRfCartCpnAmt = (int)Math.round(rfCartCpnAmt * rate);
//					divRfPlusCpnAmt = (int)Math.round(rfPlusCpnAmt * rate);
//					divRfSavePntAmt = (int)Math.round(rfSavePntAmt * rate);
//
//					sumDivRfPntAmt += divRfPntAmt;
//					sumDivRfPrePntAmt += divRfPrePntAmt;
//					sumDivRfGoodsCpnAmt += divRfGoodsCpnAmt;
//					sumDivRfCartCpnAmt += divRfCartCpnAmt;
//					sumDivRfPlusCpnAmt += divRfPlusCpnAmt;
//					sumDivRfSavePntAmt += divRfSavePntAmt;
//				}
//				wd.setRfPntAmt(divRfPntAmt);
//				wd.setRfPrePntAmt(divRfPrePntAmt);
//				wd.setRfGoodsCpnAmt(divRfGoodsCpnAmt);
//				wd.setRfCartCpnAmt(divRfCartCpnAmt);
//				wd.setRfPlusCpnAmt(divRfPlusCpnAmt);
//				wd.setRfSavePntAmt(divRfSavePntAmt);
//				wd.setOrdAmt(wdQty * wd.getItemQty() * wd.getItemPrice());
//				int tmpRealOrdAmt = wdQty * wd.getItemQty() * wd.getItemPrice() - (divRfPntAmt - divRfPrePntAmt - divRfGoodsCpnAmt - divRfCartCpnAmt - divRfPlusCpnAmt);
//				wd.setRealOrdAmt(tmpRealOrdAmt);
//
//				withdrawDao.createIfEcpTbSalesReturn(withdraw);
//
//				cnt++;
//			}
//		} else {
//			withdrawDao.createIfEcpTbSalesReturn(withdraw);
//		}
//	}

	/**
	 * 배송비 처리
	 *
	 * @param params - 주문 정보
	 * @return
	 * @author yh98kim
	 * @since 2020. 05. 13
	 */
//	@Transactional("shopTxnManager")
//	public GagaMap deliveryFeeProcess(Withdraw params, int paySq, String chgReasonCds) {
//		GagaMap resultMap = new GagaMap();
//		TsaOrder order = new TsaOrder();
//		order.setOrdNo(Long.toString(params.getOrdNo()));
//		Collection<TsaOrder> delvFeeList = orderDao.getSupplyCompDelvFeeList(order);
//		String regId = TsaSession.getInfo().getUserId();
//		String ordNo = order.getOrdNo();
//		String chgReasonDesc = order.getChgReasonDesc();
//		int totDelvFee = 0;                    // 환불할 총배송비
//		int selfYCnt = 0;                    // 자사상품 카운트
//		String selfYSupplyCompCd = "";        // 자사상품 대표업체코드
//		int selfYDelvFee = 0;                // 자사상품 결제한배송비
//		int selfYAddDelvFee = 0;
//		int selfYMinOrdAmt = 9999999;        // 자사상품 무료배송 최소주문금액
//		int selfYSumRealOrdAmt = 0;            // 자사상품 총결제금액
//		Long selfYdelvCpnSq = null;			// 배송비쿠폰
//		int selfYDelvCpnAmt = 0;
//		int rfDelvCpnAmt = 0;
//
//		TsaOrder setParams = new TsaOrder();
//		setParams.setOrdNo(ordNo);
//		setParams.setPaySq(paySq);
//		setParams.setOrdChgSq(params.getOrdChgSq());
//
//		// 교환배송비 부과여부
//		boolean bExchDelvFee = false; // true: 교환배송비 부과, false: 교환배송비 부과안함
//
//		String delvFeeGb = TsaConstants.DeliveryFeeGb.RETURN_DELIVERY_FEE.value();
//		if (TsaConstants.OrderChangeGb.EXCHANGE.value().equals(params.getChgGb())) {
//			delvFeeGb = TsaConstants.DeliveryFeeGb.EXCHANGE_DELIVERY_FEE.value();	// 교환
//			if (chgReasonCds.contains(params.getChgReason())) {	// 고객귀책인 경우
//				bExchDelvFee = true;
//			}
//		}
//		setParams.setDelvFeeGb(delvFeeGb);
//		setParams.setDelvUsacYn("N");
//		setParams.setRegId(regId);
//		setParams.setUpdId(regId);
//
//		// 회수비(반품배송비) 부과여부
//		boolean bRtnDelvFee = true;	// true: 회수비 부과, false: 회수비 부과안함
//		// 주문당 변경건수
//		int chgCnt = deliveryDao.getOrdReturnChgCnt(params.getOrdNo());
//		// 회원이고 고객귀책인 경우에 주문당 1회만 회수비 무료
//		if (params.getCustNo() != 0 && chgReasonCds.contains(params.getChgReason())) {	// 고객귀책
//			if (chgCnt == 1) {
//				bRtnDelvFee = false;
//			}
//		}
//
//		for (TsaOrder oneData : delvFeeList) {
//
//			String selfYn = oneData.getSelfYn();
//			String supplyCompCd = oneData.getSupplyCompCd();
//
//			int payDelvFee = oneData.getPayDelvFee();
//			int delvFee = oneData.getDelvFee();
//			int sumRealOrdAmt = oneData.getSumRealOrdAmt();
//			int sumCnclRtnAmt = oneData.getSumCnclRtnAmt();
//			int minOrdAmt = oneData.getMinOrdAmt();
//			int delvCpnAmt = oneData.getDelvCpnAmt();
//			Long delvCpnSq = oneData.getDelvCpnSq();
//
//			log.debug("################# sumRealOrdAmt : {}", sumRealOrdAmt);
//			log.debug("################# sumCnclRtnAmt : {}", sumCnclRtnAmt);
//
//			if (selfYn.equals("Y")) {    // 자사
//				if (selfYCnt == 0) {    // 자사 대표업체코드 : 업체코드로 DESC 해서 가져옴 - 파스텔(W), 플라인타이거(F)
//					selfYSupplyCompCd = supplyCompCd;
//					selfYDelvFee = payDelvFee;
//					selfYAddDelvFee = delvFee;
//				}
//				if (minOrdAmt < selfYMinOrdAmt) {
//					selfYMinOrdAmt = minOrdAmt;
//				}
//
//				if (selfYDelvCpnAmt == 0) {
//					selfYDelvCpnAmt = delvCpnAmt;
//					selfYdelvCpnSq = delvCpnSq;
//				}
//
//				selfYSumRealOrdAmt += sumRealOrdAmt;
//				selfYCnt++;
//			} else {    // 입점업체
//
//				if (TsaConstants.OrderChangeGb.EXCHANGE.value().equals(params.getChgGb())) {	// 교환인 경우
//					if (bExchDelvFee) {	// 교환배송비 부과
//						setParams.setDelvFee(delvFee * 2 - params.getEncloseFee());
//						totDelvFee += delvFee * 2 - params.getEncloseFee();
//						// TB_DELIVERY_FEE 에서 ORD_NO, ORD_CHG_SQ 조건으로 Update
//						setParams.setSupplyCompCd(supplyCompCd);
//						withdrawDao.mergeDeliveryFee(setParams);
//					}
//				} else {	// 반품인 경우
//					if (payDelvFee > 0) {    // 결제한배송비가 있을경우
//
//						if (sumRealOrdAmt == 0) {    // 전체취소한경우 배송비 환불
//
//							// 귀책사유에 따라 배송비 환불
//							if (!chgReasonCds.contains(params.getChgReason())) {	// 회사귀책
//								setParams.setDelvFee(-payDelvFee - params.getEncloseFee());
//								totDelvFee += payDelvFee - delvCpnAmt + params.getEncloseFee();
//							} else {	// 고객귀책
//								if (bRtnDelvFee) {	// 회수비 부과
//									setParams.setDelvFee(delvFee - params.getEncloseFee());	// 회수배송비(delvFee) - 동봉비
//									// 총환불배송비 = 동봉비 - 배송쿠폰금액 - 고객부담배송비
//									totDelvFee += params.getEncloseFee() - delvCpnAmt - delvFee;
//								} else {
//									setParams.setDelvFee(0 - params.getEncloseFee());	// 회수배송비(delvFee) - 동봉비
//									// 총환불배송비 = 동봉비 - 배송쿠폰금액 - 고객부담배송비(0)
//									totDelvFee += params.getEncloseFee() - delvCpnAmt;
//								}
//							}
//
//							setParams.setSupplyCompCd(supplyCompCd);
//							orderDao.createDeliveryFee(setParams);
//
//							if (delvCpnSq != null && delvCpnSq > 0L) {
//								TsaCoupon delvCpnInfo = orderDao.getCustCouponInfo(delvCpnSq);
//								delvCpnInfo = orderDao.getCouponInfo(delvCpnInfo.getCpnId());
//
//								if ("10".equals(delvCpnInfo.getReissuance()) || "30".equals(delvCpnInfo.getReissuance())) {
//									TsaOrder delvCpnParam = new TsaOrder();
//									delvCpnParam.setUpdId(regId);
//									delvCpnParam.setCustCpnSq(delvCpnSq);
//									orderDao.updateCustCouponCancel(delvCpnParam);
//								}
//								rfDelvCpnAmt += delvCpnAmt;
//							}
//						}
//					} else {
//						if (delvCpnAmt == 0) {    // 결제한배송비가 없었을경우(배송비 쿠폰 사용시 계산 필요없음)
//							if (chgReasonCds.contains(params.getChgReason())) {	// 고객귀책
//								if (sumRealOrdAmt < minOrdAmt) {    // 무료배송최소주문금액보다 작을경우 배송비 발생
//									if (bRtnDelvFee) {	// 회수비 부과
//										setParams.setDelvFee(delvFee * 2);	// 회수배송비+원주문배송비
//										totDelvFee -= delvFee * 2;
//									} else {
//										setParams.setDelvFee(0);
//									}
//								} else {
//									if (bRtnDelvFee) {	// 회수비 부과
//										setParams.setDelvFee(delvFee);	// 회수배송비
//										totDelvFee -= delvFee;
//									} else {
//										setParams.setDelvFee(0);	// 회수배송비
//									}
//								}
//								setParams.setSupplyCompCd(supplyCompCd);
//								orderDao.createDeliveryFee(setParams);
//							}
//						}
//					}
//				}
//			}
//
//		} /* ~for */
//
//		/* 자사상품 배송비 등록 */
//		if (selfYCnt > 0) {
//
//			if (TsaConstants.OrderChangeGb.EXCHANGE.value().equals(params.getChgGb())) {	// 교환인 경우
//				if (bExchDelvFee) {	// 교환배송비 부과
//					setParams.setDelvFee(selfYAddDelvFee * 2 - params.getEncloseFee());
//					totDelvFee += selfYAddDelvFee * 2 - params.getEncloseFee();
//					// TB_DELIVERY_FEE 에서 ORD_NO, ORD_CHG_SQ 조건으로 Update
//					setParams.setSupplyCompCd(selfYSupplyCompCd);
//					withdrawDao.mergeDeliveryFee(setParams);
//				}
//
//			} else {
//
//				if (selfYDelvFee > 0) {    // 결제한배송비가 있을경우
//
//					if (selfYSumRealOrdAmt == 0) {    // 전체취소한경우 배송비 환불
//						// 귀책사유에 따라 배송비 환불
//						if (!chgReasonCds.contains(params.getChgReason())) {	// 회사귀책
//							setParams.setDelvFee(selfYDelvFee * -1 - params.getEncloseFee());
//							totDelvFee += selfYDelvFee - selfYDelvCpnAmt + params.getEncloseFee();
//						} else {
//							if (bRtnDelvFee) {	// 회수비 부과
//								setParams.setDelvFee(selfYDelvFee * -1 - params.getEncloseFee());
//								totDelvFee += params.getEncloseFee() - selfYDelvCpnAmt - selfYDelvFee;
//							} else {
//								setParams.setDelvFee(-params.getEncloseFee());
//								totDelvFee += params.getEncloseFee() - selfYDelvCpnAmt;
//							}
//						}
//						setParams.setSupplyCompCd(selfYSupplyCompCd);
//						orderDao.createDeliveryFee(setParams);
//
//						if (selfYdelvCpnSq != null && selfYdelvCpnSq > 0L) {
//							TsaCoupon delvCpnInfo = orderDao.getCustCouponInfo(selfYdelvCpnSq);
//							delvCpnInfo = orderDao.getCouponInfo(delvCpnInfo.getCpnId());
//
//							if ("10".equals(delvCpnInfo.getReissuance()) || "30".equals(delvCpnInfo.getReissuance())) {
//								TsaOrder delvCpnParam = new TsaOrder();
//								delvCpnParam.setUpdId(regId);
//								delvCpnParam.setCustCpnSq(selfYdelvCpnSq);
//								orderDao.updateCustCouponCancel(delvCpnParam);
//							}
//
//							rfDelvCpnAmt += selfYDelvCpnAmt;
//						}
//
//					} else {
//						if (bRtnDelvFee) {	// 회수비 부과
//							setParams.setDelvFee(-selfYDelvFee);
//						} else {
//							setParams.setDelvFee(0);
//						}
//						setParams.setSupplyCompCd(selfYSupplyCompCd);
//						orderDao.createDeliveryFee(setParams);
//						totDelvFee -= selfYDelvCpnAmt;
//					}
//
//				} else {
//					if (selfYDelvCpnAmt == 0) {							// 결제한배송비가 없었을경우(배송비 쿠폰 사용시 계산 필요없음)
//						if (chgReasonCds.contains(params.getChgReason())) {	// 고객귀책
//							if (selfYSumRealOrdAmt < selfYMinOrdAmt) {		// 무료배송최소주문금액보다 작을경우 배송비 발생
//								if (bRtnDelvFee) {	// 회수비 부과
//									setParams.setDelvFee(selfYAddDelvFee * 2);
//									totDelvFee -= selfYAddDelvFee * 2;
//								} else {
//									setParams.setDelvFee(0);
//									totDelvFee -= 0;
//								}
//								setParams.setSupplyCompCd(selfYSupplyCompCd);
//								orderDao.createDeliveryFee(setParams);
//							} else {									// 무료배송금액보다 큰 경우에는 회수비만 부과
//								if (bRtnDelvFee) {	// 회수비 부과
//									setParams.setDelvFee(selfYAddDelvFee);
//									totDelvFee -= selfYAddDelvFee;
//									setParams.setSupplyCompCd(selfYSupplyCompCd);
//									orderDao.createDeliveryFee(setParams);
//								}
//							}
//						}
//					}
//				}
//			}
//		}
//
//		resultMap.setInt("totDelvFee", totDelvFee);
//		resultMap.setInt("rfDelvCpnAmt", rfDelvCpnAmt);
//
//		return resultMap;
//	}

	/**
	 * 회수관리 - 주문상세 남은상품에 대한 장바구니쿠폰 처리
	 *
	 * @param ordNo
	 * @param ordChgSq
	 * @param buyLimitAmt
	 * @return int
	 * @author rladbwnd5
	 * @since 2020. 02. 17
	 */
//	@Transactional("shopTxnManager")
//	private int orderDetailCouponCancel(Long ordNo, Long ordChgSq, int buyLimitAmt) {
//		int refundCancelCartCpnAmt = 0;
//		String userId = TsaSession.getInfo().getUserId();
//
//		Withdraw searchParam = new Withdraw();
//		searchParam.setOrdNo(ordNo);
//		searchParam.setOrdChgSq(ordChgSq);
//		Withdraw remianGoodsInfo = withdrawDao.getRemainGoodsInfo(searchParam);
//
//		if (remianGoodsInfo.getRealOrdAmt() < buyLimitAmt) {
//			Collection<Withdraw> remainOrderDetailList = withdrawDao.getWithdrawRemainOrderDetailList(searchParam);
//
//			for (Withdraw orderDetail : remainOrderDetailList) {
//				// 기존 정산 취소
//				Withdraw paramCancelUsac = new Withdraw();
//				paramCancelUsac.setUsacGb(UsacGb.PURCHASE_RETURN.value());
//				paramCancelUsac.setPrtnGb("40"); // 해택할인취소 PurchaseReturnGb.CANCEL.value() 명칭 필요할 듯
//				paramCancelUsac.setOrdDtlNo(orderDetail.getOrdDtlNo());
//				paramCancelUsac.setOrgUsacGb(UsacGb.SELL.value());
//				paramCancelUsac.setUsacQty(orderDetail.getOrdQty());
//				paramCancelUsac.setGoodsCpnDcAmt(orderDetail.getGoodsCpnDcAmt());
//				paramCancelUsac.setCartCpnDcAmt(orderDetail.getCartCpnDcAmt());
//				paramCancelUsac.setPlusCpnDcAmt(orderDetail.getPlusCpnDcAmt());
//				paramCancelUsac.setPntDcAmt(orderDetail.getPntDcAmt());
//				paramCancelUsac.setPrePntDcAmt(orderDetail.getPrePntDcAmt());
//				paramCancelUsac.setRegId(userId);
//				paramCancelUsac.setPlusCpnDcAmt(orderDetail.getPlusCpnDcAmt());
//				withdrawDao.createWithdrawUsac(paramCancelUsac);
//
//				refundCancelCartCpnAmt += orderDetail.getCartCpnDcAmt();
//				orderDetail.setRealOrdAmt(orderDetail.getRealOrdAmt() + orderDetail.getCartCpnDcAmt());
//				orderDetail.setCartCpnDcAmt(0);
//				orderDetail.setCartCpnSq(null);
//				orderDetail.setUpdId(userId);
//				orderDetail.setRegId(userId);
//				withdrawDao.updateWithdrawOrderDetailInfo(orderDetail);
//				withdrawDao.createWithdrawOrderDetailHstInfo(orderDetail);
//
//				// 재정산
//				Withdraw paramUsac = new Withdraw();
//				paramUsac.setUsacGb(UsacGb.SELL.value());
//				paramUsac.setPrtnGb(null);
//				paramUsac.setOrdDtlNo(orderDetail.getOrdDtlNo());
//				paramUsac.setOrgUsacGb(UsacGb.SELL.value());
//				paramUsac.setUsacQty(orderDetail.getOrdQty());
//				paramUsac.setGoodsCpnDcAmt(orderDetail.getGoodsCpnDcAmt());
//				paramUsac.setCartCpnDcAmt(orderDetail.getCartCpnDcAmt());
//				paramUsac.setPlusCpnDcAmt(orderDetail.getPlusCpnDcAmt());
//				paramUsac.setPntDcAmt(orderDetail.getPntDcAmt());
//				paramUsac.setPrePntDcAmt(orderDetail.getPrePntDcAmt());
//				paramUsac.setPlusCpnDcAmt(orderDetail.getPlusCpnDcAmt());
//				paramUsac.setRegId(userId);
//				withdrawDao.createWithdrawUsac(paramUsac);
//			}
//		}
//
//		return refundCancelCartCpnAmt;
//	}

	/**
	 * 환불관리 - 주문번호 전체 금액
	 *
	 * @param ordNo
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Withdraw getOrderDetailSumAmt(String ordNo) {
		return withdrawDao.getOrderDetailSumAmt(ordNo);
	}

	/**
	 * 환불목록
	 *
	 * @param withdraw
	 * @return Withdraw List
	 * @author yujung
	 * @since 2020. 05. 29
	 */
//	public Collection<Withdraw> getRefundCompleteList(Withdraw withdraw) {
//		return withdrawDao.getRefundCompleteList(withdraw);
//	}

	/**
	 * 반품신청, 회수수량 비교 데이터
	 *
	 * @param withdraw
	 * @return Withdraw
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Withdraw getSumChgQtyWdQty(Withdraw withdraw) {
		return withdrawDao.getSumChgQtyWdQty(withdraw);
	}

	/**
	 * wms 회수요청
	 *
	 * @param
	 * @return
	 * @author cjs
	 * @since 2020. 07. 14
	 */
//	@Transactional("wmsTxnManager")
//	public void saveWmsWithdrawRequest(TsaOrder order) {
//
//		String userId = TsaSession.getInfo().getUserId();
//
//		String reqSn = wmsWithdrawDao.getRequestSn();
//		order.setSeq(reqSn);
//
//		order.setInvoiceNo("123412341");
//		order.setOrdChgSq(3);
//		order.setRecipNm("반품자");
//		order.setRecipTelno("010-111-1111");
//		order.setRecipPhnno("010-2222-2222");
//		order.setRecipPostNo("12345");
//		order.setRecipBaseAddr("서울시 강남구 논현로 323");
//		order.setRecipDtlAddr("MTU 빌딩 6층 전산실");
//		order.setChgMemo("사이즈가 작아요");
//		order.setChgerRtnMemo("물류메모");
//		order.setChgGb("40");
//		order.setChgReason("13");
//		order.setRegDt("20200505121212");
//		order.setChgQty(1);
//		order.setChgRegDt("20200505121212");
//		order.setChgerNm("변경자");
//		if (order.getSellStoreCd() == null || order.getSellStoreCd().isEmpty()) {
//			order.setSellStoreCd("PASTEL");
//		}
//		order.setOrdDtlNos(order.getOrdDtlNo());
//		order.setChgQtys(Integer.toString(order.getChgQty()));
//
//		/* 1.회수요청 Header 등록 */
//		wmsWithdrawDao.createWithdrawHeader(order);
//
//		/* 2.회수요청 Detail 등록 */
//		int cnt = 0;
//		order.setChgStat(TsaConstants.OrderChangeStat.RETURN.value());
//		String[] ordDtlNoArr = order.getOrdDtlNos().split(",");
//		String[] chgQtyArr = order.getChgQtys().split(",");
//
//		for (String ordDtlNo : ordDtlNoArr) {
//			if (!StringUtils.isBlank(ordDtlNo)) {
//				order.setOrdDtlNo(ordDtlNo);
//				order.setChgQty(Integer.parseInt(chgQtyArr[cnt]));
//				wmsWithdrawDao.createWithdrawDetail(order);
//			}
//			cnt++;
//		}
//	}
}
