package com.style24.admin.biz.service;

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

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

import com.gagaframework.web.parameter.GagaMap;
import com.style24.core.biz.service.TscOrderChangeService;
import com.style24.core.biz.service.TscOrderRefundService;
import com.style24.core.biz.service.TscWmsService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.OrderChange;
import com.style24.persistence.domain.WmsDelivery;

import lombok.extern.slf4j.Slf4j;

/**
 * 주문 변경 Service
 *
 * @author card007
 * @since 2021. 06. 15
 */
@Service
@Slf4j
public class TsaOrderChangeService {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TscOrderChangeService coreOrderChangeService;
	
	@Autowired
	private TscWmsService coreWmsService;
	
	@Autowired
	private TscOrderRefundService coreOrderRefundService;

	/**
	 * 반품 TO 교환 처리
	 * 
	 * @param orderChange
	 * @author card007
	 * @since 2021. 06. 15
	 */
	@Transactional("shopTxnManager")
	public void returnToExchange(OrderChange orderChange) {
		int userNo = orderChange.getUserNo();
		orderChange.setRegNo(userNo);
		orderChange.setUpdNo(userNo);

		// 1. 반품 철회 처리
		this.returnCancel(orderChange);

		// 2. WMS 회수지시 여부 체크 후 회시지시대상여부 컬럼 정보 설정
		orderChange.setWdTargetYn(this.getWdTargetYnInfo(orderChange));

		// 3. WMS 반품 정보 삭제 처리
		// 2021.07.14 card007 반품 철회 시 WMS 정보 삭제 처리
		// coreWmsService.updateWmsRecallCancel(orderChange.getOrdNo(), orderChange.getOrdChgSq());

		// 4. 회수송장정보 설정
		orderChange = this.setWdInvoiceInfo(orderChange);

		// 5. 교환 접수 처리
		coreOrderChangeService.exchReq(orderChange);
	}

	/**
	 * 반품 TO 반품 처리
	 *
	 * @param orderChange
	 * @author card007
	 * @since 2021. 06. 21
	 */
	@Transactional("shopTxnManager")
	public void returnToReturn(OrderChange orderChange) {
		// 1. 반품 철회 처리
		GagaMap result = this.returnCancel(orderChange);

		// 2. WMS 회수지시 여부 체크 후 회시지시대상여부 컬럼 정보 설정
		orderChange.setWdTargetYn("N");

		// 3. WMS 반품 정보 삭제 처리
		// 2021.07.14 card007 반품 철회 시 WMS 정보 삭제 처리
		// coreWmsService.updateWmsRecallCancel(orderChange.getOrdNo(), orderChange.getOrdChgSq());

		// 4. 회수송장정보 설정
		orderChange = this.setWdInvoiceInfo(orderChange);

		// 5. 반품 사전 정보 설정
		GagaMap map = this.getReturnInfo(orderChange);
		
		// 6. 반품 접수 처리
		map.setString("ordChgGb", orderChange.getOrdChgGb());
		map.setInt("orgOrdChgSq", orderChange.getOrdChgSq());
		map.setString("wdTargetYn", orderChange.getWdTargetYn());
		map.setInt("orgAddPayCost", result.getInt("orgAddPayCost"));
		coreOrderChangeService.returnRequest(map);
	}

	/**
	 * 교환 TO 교환 처리
	 *
	 * @param orderChange
	 * @author card007
	 * @since 2021. 06. 21
	 */
	@Transactional("shopTxnManager")
	public void exchangeToExchange(OrderChange orderChange) {
		int userNo = orderChange.getUserNo();
		orderChange.setRegNo(userNo);
		orderChange.setUpdNo(userNo);

		// 1. 교환 철회 처리
		this.exchangeCancel(orderChange);

		// 2. WMS 회수지시 여부 체크 후 회시지시대상여부 컬럼 정보 설정
		orderChange.setWdTargetYn("N");

		// 3. WMS 교환 정보 삭제 처리
		// 2021.07.14 card007 교환 철회 시 WMS 정보 삭제 처리
		// coreWmsService.updateWmsRecallCancel(orderChange.getOrdNo(), orderChange.getOrdChgSq());

		// 4. 회수송장정보 설정
		orderChange = this.setWdInvoiceInfo(orderChange);

		// 5. 교환 접수 처리
		coreOrderChangeService.exchReq(orderChange);
	}

	/**
	 * 반품 철회 처리
	 * 
	 * @param OrderChange
	 * @author card007
	 * @since 2021. 06. 21
	 */
	private GagaMap returnCancel(OrderChange orderChange) {
		GagaMap map = new GagaMap();
		map.setInt("ordChgSq", orderChange.getOrdChgSq());
		map.setInt("ordNo", orderChange.getOrdNo());
		
		if (TscConstants.ChangeGb.RETURN_TO_RETURN.value().equals(orderChange.getOrdChgGb())) {
			map.setString("ordChgGb", orderChange.getOrdChgGb());
		}

		return coreOrderChangeService.rtnReqCancel(map, orderChange.getUserNo());
	}

	/**
	 * 교환 철회 처리
	 * 
	 * @param OrderChange
	 * @author card007
	 * @since 2021. 06. 21
	 */
	private void exchangeCancel(OrderChange orderChange) {
		coreOrderChangeService.exchangeCancel(orderChange);
	}

	/**
	 * 회수지시대상여부 컬럼 정보 설정
	 * 
	 * @param OrderChange
	 * @return String
	 * @author card007
	 * @since 2021. 06. 21
	 */
	private String getWdTargetYnInfo(OrderChange orderChange) {
		String wdTargetYn = "Y";

		WmsDelivery wmsDelivery = new WmsDelivery();
		wmsDelivery.setOrderExceptionNo(orderChange.getOrdChgSq());
		Collection<WmsDelivery> list = coreWmsService.getWmsWithdrawRequestInfo(wmsDelivery);

		if (list != null && list.size() > 0) {
			String ifStat = list.iterator().next().getIfStat();
			if (!"0".equals(ifStat)) {
				wdTargetYn = "N";
			}
		}
		
		return wdTargetYn;
	}

	/**
	 * 회수송장번호 설정
	 * 
	 * @param OrderChange
	 * @return OrderChange
	 * @author card007
	 * @since 2021. 06. 21
	 */
	private OrderChange setWdInvoiceInfo(OrderChange orderChange) {
		Collection<OrderChange> orderChangeDetailInfoList = coreOrderChangeService.getOrderChangeDetailInfo(orderChange);
		if (orderChangeDetailInfoList != null && orderChangeDetailInfoList.size() > 0) {
			orderChange.setWdInvoiceNo(orderChangeDetailInfoList.iterator().next().getWdInvoiceNo());
			orderChange.setWdInvoiceSendYn(orderChangeDetailInfoList.iterator().next().getWdInvoiceSendYn());
		}

		return orderChange;
	}

	/**
	 * 반품 정보 설정
	 * 
	 * @param OrderChange
	 * @author card007
	 * @since 2021. 06. 21
	 */
	@SuppressWarnings("unchecked")
	private GagaMap getReturnInfo(OrderChange orderChange) {
		// 1. 환불 사전 정보 조회
		GagaMap refundPreInfo = coreOrderChangeService.getRefundPreInfo(orderChange);
		List<Order> returnReqList = (List<Order>)refundPreInfo.get("cnclReqList");
		String allLastCanYn = refundPreInfo.getString("allLastCanYn");
		String supplyCompCd = refundPreInfo.getString("supplyCompCd");

		// 2. 환불금액계산
		GagaMap result = coreOrderRefundService.cnclRtnRefundAmt(returnReqList);

		// 3. 주문변경 기본정보 설정
		result.set("ordNo", orderChange.getOrdNo());					// 주문번호
		result.setInt("custNo", orderChange.getCustNo());				// 고객번호
		// result.set("ordChgSq", orderChange.getOrdChgSq());			// 주문변경번호
		result.set("chgReason", orderChange.getChgReason());			// 변경사유
		result.set("chgMemo", orderChange.getChgMemo());				// 변경메모
		result.set("accountNo", orderChange.getAccountNo());			// 환불계좌번호
		result.set("accountNm", orderChange.getAccountNm());			// 환불계좌예금주명
		result.set("bankCd", orderChange.getBankCd());					// 환불계좌은행코드
		result.setString("allLastCanYn", allLastCanYn);					// 전체 마지막 취소 여부
		result.set("isCustomer", orderChange.getIsCustomer());			// 변경사유 (고객, 회사)
		result.set("wdGb", orderChange.getWdGb());						// 회수방법
		result.set("wdInvoiceNo", orderChange.getWdInvoiceNo());		// 회수송장번호
		result.set("chgerNm", orderChange.getChgerNm());				// 변경자명
		result.set("chgerEmail", orderChange.getChgerEmail());			// 변경자이메일주소
		result.set("chgerZipcode", orderChange.getChgerZipcode());		// 회수지우편번호
		result.set("chgerBaseAddr", orderChange.getChgerBaseAddr());	// 회수지기본주소
		result.set("chgerDtlAddr", orderChange.getChgerDtlAddr());		// 회수지상세주소
		result.set("chgerPhnno", orderChange.getChgerPhnno());			// 변경자핸드폰번호
		result.set("chgerTelno", orderChange.getChgerTelno());			// 변경자전화번호
		result.set("chgerRtnMemo", orderChange.getChgerRtnMemo());		// 반품메모

		return result;
	}
}
