package com.style24.admin.biz.service;

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

import com.style24.core.biz.service.TscNaverPayService;
import com.style24.core.support.env.TscConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gagaframework.web.parameter.GagaMap;
import com.style24.admin.biz.dao.TsaDeliveryDao;
import com.style24.admin.biz.dao.TsaWithdrawDao;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.admin.biz.service.TsaWmsWithdrawService;
import com.style24.core.biz.dao.TscOrderChangeDao;
import com.style24.core.biz.service.TscOrderChangeService;
import com.style24.core.biz.service.TscOrderRefundService;
import com.style24.core.support.env.TscConstants.OrderChangeGb;
import com.style24.core.support.env.TscConstants.OrderChangeStat;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.core.support.util.CryptoUtils;
import com.style24.core.biz.service.TscKakaotalkService;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.OrderChange;
import com.style24.persistence.domain.Withdraw;
import com.style24.persistence.domain.WithdrawExc;
import com.style24.persistence.domain.WmsWithdraw;

import lombok.extern.slf4j.Slf4j;

/**
 * 회수관리 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 TscOrderChangeDao orderChangeDao;
	
	@Autowired
	private TscOrderChangeService coreOrderChangeService;
	
	@Autowired
	private TscOrderRefundService coreOrderRefundService;
	
	@Autowired
	private TscOrderChangeService orderChangeService;
	
	@Autowired
	private TsaWmsWithdrawService wmsWithdrawService;

	@Autowired
	private TscNaverPayService coreNaverPayService;

	@Autowired
	private TscKakaotalkService kakaotalkService;

	
	

	/**
	 * 환불관리 목록 건수
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 05. 03
	 */
	public int getRefundListCount(Withdraw withdraw) {
		return withdrawDao.getRefundListCount(withdraw);
	}
	
	
	
	/**
	 * 환불관리 목록
	 *
	 * @param withdraw
	 * @return Collection<Withdraw>
	 * @author moon
	 * @since 2020. 11. 16
	 */
	public Collection<Withdraw> getRefundList(Withdraw withdraw) {
		return withdrawDao.getRefundList(withdraw);
	}
	
	
	
	/**
	 * 회수예외 목록 건수
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 03. 04
	 */
	public int getWithdrawExceptionListCount(WithdrawExc withdrawExc) {
		return withdrawDao.getWithdrawExceptionListCount(withdrawExc);
	}
	
	/**
	 * 회수예외 목록 
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 03. 04
	 */
	public Collection<WithdrawExc> getWithdrawExceptionList(WithdrawExc withdrawExc) {
		return withdrawDao.getWithdrawExceptionList(withdrawExc);
	}
	
	/**
	 * 회수예외 완료처리 
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 03. 04
	 */	
	@Transactional("shopTxnManager")
	public void createWithdrawInfo(WithdrawExc withdrawExc) {
		withdrawExc.setRecallStat("S");
		withdrawDao.updateWithdrawException(withdrawExc);
		
	}
	
	/**
	 * 회수예외 사유변경 목록 
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 05. 20
	 */
	public Collection<WithdrawExc> getWithdrawExceptionChangeList(WithdrawExc withdrawExc) {
		return withdrawDao.getWithdrawExceptionChangeList(withdrawExc);
	}
	
	/**
	 * 환불비 조회
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 05. 21
	 */
	public GagaMap getRefundAmt(Collection<WithdrawExc> list) {
		
		OrderChange  orderChange = new OrderChange();
		
		
		int[] ordDtlNoArr		= new int[list.size()];
		int[] cnclRtnReqQtyArr	= new int[list.size()];
		
		int i=0;
		for(WithdrawExc data : list) {
			ordDtlNoArr[i] = data.getOrdDtlNo();
			cnclRtnReqQtyArr[i] = data.getChgQty();
			i++;
		}
		
		WithdrawExc item = list.iterator().next();
		
		orderChange.setOrdDtlNoArr(ordDtlNoArr);
		orderChange.setCnclRtnReqQtyArr(cnclRtnReqQtyArr);
		orderChange.setCustNo(item.getCustNo());
		orderChange.setOrdNo(item.getOrdNo());
		orderChange.setDelvFeeCd(item.getDelvFeeCd());
		orderChange.setChgGb(item.getChgGb());
		
		GagaMap refundPreInfo = coreOrderChangeService.getRefundPreInfo(orderChange);
		List<Order> returnReqList = (List<Order>)refundPreInfo.get("cnclReqList"); 
		GagaMap result = coreOrderRefundService.cnclRtnRefundAmt(returnReqList);
		return result;
	}
	
	/**
	 * WMS회수목록 - 옵션정보 
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 03. 04
	 */
	public Collection<WmsWithdraw> getOptionInfo(Collection<WmsWithdraw> wmsWithdrawList) {
		
		for(WmsWithdraw data : wmsWithdrawList) {
			
			WmsWithdraw optionInfo = withdrawDao.getOptionInfo(data);
			data.setGoodsCd(optionInfo.getGoodsCd());
		}
		return wmsWithdrawList; 
	}	
	
	
	/**
	 * 회수지시목록 건수
	 *
	 * @param Withdraw
	 * @return
	 * @author moon
	 * @since 2021. 05. 10
	 */
	public int getWithdrawDirectiveListCount(Withdraw withdraw) {
		return withdrawDao.getWithdrawDirectiveListCount(withdraw);
	}
	
	/**
	 * 회수지시 목록 
	 *
	 * @param Withdraw
	 * @return
	 * @author moon 
	 * @since 2021. 05. 10
	 */
	public Collection<Withdraw> getWithdrawDirectiveList(Withdraw withdraw) {
		return withdrawDao.getWithdrawDirectiveList(withdraw);
	}
	
	/**
	 * 재회수지시
	 *
	 * @param Withdraw
	 * @return void
	 * @author moon
	 * @since 2021. 05. 11
	 */
	@Transactional("shopTxnManager")
	public void reRecallOrder(Withdraw withdraw) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		withdraw.setUpdNo(userNo);
		
		withdrawDao.updateReRecallOrderChange(withdraw);
		
		
		if(OrderChangeGb.RETURN.value().equals(withdraw.getChgGb())) { // 반품요청
			withdraw.setChgStat(OrderChangeStat.RETURN.value()); // 반품접수
		} else { //교환요청
			withdraw.setChgStat(OrderChangeStat.EXCHANGE.value()); // 교환접수 
		}
		withdrawDao.updateReRecallOrder(withdraw);
		
		// 상세목록 조회 
		Collection<Withdraw> list = withdrawDao.getOrdChgDtlList(withdraw);
		
		for(Withdraw data : list) {
			// 주문상세변경 이력 
			OrderChange ordChg = new OrderChange();
			ordChg.setRegNo(userNo);
			ordChg.setUpdNo(userNo);
			ordChg.setOrdChgSq(data.getOrdChgSq()); 
			ordChg.setOrdDtlNo(data.getOrdDtlNo()); 
			ordChg.setChgStat(data.getChgStat());
			orderChangeDao.createOrderChangeDetailHst(ordChg);
		}
		
		// WMS 재회수지시 
		wmsWithdrawService.updateReRecallOrder(withdraw);
		
	}
	
	/**
	 * 주문변경사유 변경
	 *
	 * @param Withdraw
	 * @return void
	 * @author moon
	 * @since 2021. 05. 21
	 */
	@Transactional("shopTxnManager")
	public void saveChangeReason(WithdrawExc withdrawExc) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		if("Y".equals(withdrawExc.getChangeYn())) {
			// TB_ORDER_CHANGE_DETAIL 변경 
			String[] listDtlNo = withdrawExc.getOrdDtlNoList().split(",");
			for(int i=0; i<listDtlNo.length; i++) {
				WithdrawExc item = new WithdrawExc();
				if("G680_30".equals(withdrawExc.getWdGb())) { // 반품요청
					item.setChgStat(OrderChangeStat.RETURN_WAIT.value());   // 반품대기 (추가배송비 결제 전)
				} else { // 교환요청 
					item.setChgStat(OrderChangeStat.EXCHANGE_WAIT.value()); // 교환대기 (추가배송비 결제 전)
				}
				item.setOrdChgSq(withdrawExc.getOrdChgSq());
				item.setOrdDtlNo(Integer.parseInt(listDtlNo[i]));
				item.setUpdNo(userNo);
				withdrawDao.updateChangeStat(item);
				
				// 주문상세변경 이력 
				OrderChange ordChg = new OrderChange();
				ordChg.setRegNo(userNo);
				ordChg.setUpdNo(userNo);
				ordChg.setOrdChgSq(item.getOrdChgSq()); 
				ordChg.setOrdDtlNo(item.getOrdDtlNo()); 
				ordChg.setChgStat(item.getChgStat());
				orderChangeDao.createOrderChangeDetailHst(ordChg);
				
			}
		}  else if("S".equals(withdrawExc.getChangeYn())) {
			String[] listDtlNo = withdrawExc.getOrdDtlNoList().split(",");
			for(int i=0; i<listDtlNo.length; i++) {
				WithdrawExc item = new WithdrawExc();
				item.setChgStat(OrderChangeStat.WITHDRAW_GOODS_CHECK.value());   // G685_31 상품검수중
				item.setOrdChgSq(withdrawExc.getOrdChgSq());
				item.setOrdDtlNo(Integer.parseInt(listDtlNo[i]));
				item.setUpdNo(userNo);
				withdrawDao.updateChangeStat(item);
				
				// 주문상세변경 이력 
				OrderChange ordChg = new OrderChange();
				ordChg.setRegNo(userNo);
				ordChg.setUpdNo(userNo);
				ordChg.setOrdChgSq(item.getOrdChgSq()); 
				ordChg.setOrdDtlNo(item.getOrdDtlNo()); 
				ordChg.setChgStat(item.getChgStat());
				orderChangeDao.createOrderChangeDetailHst(ordChg);
				
			}
		}
		
		// TB_ORDER_CHANGE 변경 
		withdrawExc.setUpdNo(userNo);
		withdrawDao.updateChangeReason(withdrawExc);
	}





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






	/**
	 * 회수관리 > 환불컨펌 > 환불처리 
	 *
	 * @param params
	 * @return
	 * @author moon
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public void refundDetailConfirm(GagaMap params) {
		
		Integer userNo = TsaSession.getInfo().getUserNo();
		OrderChange change = new OrderChange();
		
		change.setOrdNo(params.getInt("ordNo"));
		change.setCustNo(params.getInt("custNo"));
		change.setOrderNm(params.getString("ordNm"));
		change.setPgGb(params.getString("pgGb"));
		change.setPayMeans(params.getString("payMeans"));
		change.setBankCd(params.getString("bankCd"));
		change.setAccountNm(params.getString("accountNm"));
		change.setAccountNo(CryptoUtils.decryptAES(params.getString("accountNo")));
		//change.getOrdDtlNoList().add(params.getOrdDtlNo());
		//change.getCnclRtnReqQtyList().add(params.getCnclRtnQty());
		change.setChgReason(params.getString("chgReason"));
		change.setChgReasonNm(params.getString("chgReasonNm"));
		change.setBatchYn("N");
		change.setDelvAddrSq(params.getInt("delvAddrSq"));
		change.setAddDeliveryFeeYn(params.getString("addDeliveryFeeYn"));
		change.setAddDeliveryFee(params.getInt("addDeliveryFee"));
		change.setRegNo(userNo);
		change.setUpdNo(userNo);
		change.setUserNo(userNo);
		change.setOrdChgSq(params.getInt("ordChgSq"));
		change.setMallGb(params.getString("mallGb"));
		change.setSpanRefundAmt(params.getInt("spanRefundAmt"));
		change.setPgStat(params.getString("pgStat"));
		change.setCodFeeYn(params.getString("codFeeYn"));
		change.setCodFee(params.getInt("codFee"));
		change.setEnCloseFeeYn(params.getString("enCloseFeeYn"));
		change.setEncloseFee(params.getInt("enCloseFee"));
		change.setWdInvoiceNo(params.getString("wdInvoiceNo"));

		String allCanYn = params.getString("allCanYn");
		
		try {
			if ("Y".equals(allCanYn)) {
				orderChangeService.allRefund(change);
			} else {
				OrderChange orderChange= new OrderChange();
				orderChange.setOrdChgSq(params.getInt("ordChgSq"));
				orderChange.setUserNo(params.getInt("custNo"));

				GagaMap info = orderChangeService.refundConfirmPreInfo(orderChange);

				info.set("chgReasonNm"		, params.getString("chgReasonNm"));							// 변경사유
				info.set("chgReason"		, params.getString("chgReason"));							// 변경사유코드
				info.set("accountNm"		, params.getString("accountNm"));							// 환불계좌이름
				info.set("accountNo"		, CryptoUtils.decryptAES(params.getString("accountNo")));	// 환불계좌번호
				info.set("bankCd"			, params.getString("bankCd"));								// 환불계좌은행코드
				info.set("custNo"			, params.getInt("custNo"));									// 고객번호
				info.set("ordNm"			, params.getString("ordNm"));								// 주문자명
				info.set("delvAddrSq"		, params.getInt("delvAddrSq"));								// 배송지번호
				info.set("delvExpnYn"		, params.getString("delvExpnYn"));							// 확정후반품,불량여부
				info.set("addDeliveryFee"	, params.getInt("addDeliveryFee"));							// 추가배송비
				info.set("addDeliveryFeeYn"	, params.getString("addDeliveryFeeYn"));					// 추가배송비여부
				info.set("mallGb"			, params.getString("mallGb"));								// 몰구분
				info.set("ordNo"			, params.getInt("ordNo"));									// 주문번호
				info.set("ordChgSq"			, params.getInt("ordChgSq"));								// 변경요청번호
				info.set("pgStat"			, params.getString("pgStat"));								// PG 상태
				info.set("codFee"			, params.getInt("codFee"));									// 착불비
				info.set("codFeeYn"			, params.getString("codFeeYn"));							// 착불비여부
				info.set("enCloseFeeYn"		, params.getString("enCloseFeeYn"));						// 동봉비여부
				info.set("enCloseFee"		, params.getInt("enCloseFee"));								// 동봉비
				info.set("wdInvoiceNo"		, params.getInt("wdInvoiceNo"));							// 회수송장번호
				info.set("wdGb"				, params.getString("wdGb"));								// 회수구분
				info.set("addPayCost"		, params.getInt("addPayCost"));								// 추가배송비

				orderChangeService.partialRefund(info, userNo);
			}

			// 반품완료 알림톡
			
			Withdraw refundOrdchgSq = new Withdraw();
			refundOrdchgSq.setOrdChgSq(params.getInt("ordChgSq"));
			Withdraw info = withdrawDao.getRefundInfo(refundOrdchgSq);
			
			Order order = new Order();
			order.setOrdNo(info.getOrdNo());
			order.setCustNo(info.getCustNo());
			order.setOrdNm(info.getOrdNm());
			order.setOrdPhnno(info.getOrdPhnno());
			order.setRefundAmt(info.getRefundAmt());
			order.setGoodsCnt(info.getGoodsCnt()+"");
			order.setGoodsNm(info.getGoodsNm());
			
			kakaotalkService.sendRefundComplete(order, userNo);
			
			
			// 네이버페이 환불컨펌
			if(TscConstants.PgGb.NAVER_ORDER.value().equals(change.getPgGb())) {
				// PG 미전송이 아닐 경우 (Y면 미전송, N이면 전송)
				if("N".equals(change.getPgStat())) {
					// WMS 예외로 넘어온 데이터인지 확인 후 네이버페이 진행
					Collection<OrderChange> exceptions = orderChangeDao.getOrderRecallExceptionInfo(change);		// 예외 품절 및 불량 정보 조회
					int i = 0;

					for(OrderChange exception : exceptions) {
						if(exception.getOrderDtlNo() > 0) {		// 확정 후 품절 및 불량이 있을경우
							if("O".equals(exception.getOrdExchGb())) {				// 원배송 확정 후 품절 및 불량
								// 품절 취소 송부
								Order param = new Order();
								param.setOrdDtlNo(exception.getOrdDtlNo());
								coreNaverPayService.sendNaverPaySoldoutCancel(param, userNo);			// 품절취소
							} else if ("E".equals(exception.getOrdExchGb())){		// 교환 후 확정 후 품절 및 불량
								// 교환 반려 > 반품 접수 > 반품 완료
								Order param = new Order();
								param.setOrdDtlNo(exception.getOrdDtlNo());

								if(i < 1) {
									coreNaverPayService.sendNaverPayRejectExchange(exception, userNo);        // 교환반려
								}

								coreNaverPayService.sendNaverPaySoldoutReturnReq(param, userNo);		// 품절반품접수

								if(i < 1) {
									coreNaverPayService.sendNaverPayReturnComplete(exception, userNo);        // 반품완료
								}
							}
						} else {								// 정상 반품 완료
							if(i < 1) {
								coreNaverPayService.sendNaverPayReturnComplete(exception, userNo);            // 반품완료
							}
						}

						i++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalStateException("실패");
		}
	}



}
