package com.style24.batch.biz.service;

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

import com.style24.core.biz.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.gagaframework.web.parameter.GagaMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.style24.batch.biz.dao.TsbDeliveryDao;
import com.style24.batch.support.env.TsbConstants;
import com.style24.core.biz.dao.TscOrderChangeDao;
import com.style24.core.biz.dao.TscOrderDao;
import com.style24.core.biz.thirdparty.HansaeErp;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.env.TscConstants.OrderChangeGb;
import com.style24.core.support.env.TscConstants.OrderChangeStat;
import com.style24.core.support.env.TscConstants.OrderDetailStat;
import com.style24.core.support.env.TscConstants.OrdDtlItemStat;
import com.style24.persistence.domain.Delivery;
import com.style24.persistence.domain.Erp;
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 moon
 * @since 2020. 12. 08
 */
@Service
@Slf4j
public class TsbDeliveryService {

	@Autowired
	private Environment env;

	@Autowired
	private TsbDeliveryDao deliveryDao;

	@Autowired
	private TscOrderDao orderDao;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private TscWmsService wmsService;

	@Autowired
	private TscErpService erpService;

	@Autowired
	private TscOrderChangeDao orderChangeDao;

	@Autowired
	private TscDeliveryService coreDeliveryService;

	@Autowired
	private TscOrderChangeService orderChangeService;	
	
	@Autowired
	private TscOrderRefundService orderRefundService;

	@Autowired
	private TscNaverPayService coreNaverPayService;
	
	@Autowired
	private HansaeErp hansaeErp;
	
	@Autowired
	private TsbWmsDeliveryService wmsDeliveryService;	

	/**
	 * 총알배송 권역정보 갱신 
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2020. 12. 08
	 */
	@Transactional("shopTxnManager")
	public void mergeDailyDeliveryZone(Delivery data) {

		deliveryDao.mergeDailyDeliveryZone(data);

	}

	/**
	 * 총알배송 권역정보 갱신 초기화
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2020. 12. 08
	 */
	@Transactional("shopTxnManager")
	public void deleteDailyDeliveryZone() {

		deliveryDao.deleteDailyDeliveryZone();

	}	
	/**
	 * 회수예외 등록 
	 * @param  Collection<Delivery>
	 * @return 
	 * @author moon
	 * @since  2021. 03. 02
	 */
	@Transactional("shopTxnManager")
	public void insertTbOrderRecallException(Collection<Delivery> excList, Collection<Delivery> itemList, Collection<Delivery> memoList) {

		// 회수예외 등록 -H
		for (Delivery excData : excList) {
			excData.setRegNo(TsbConstants.REG_NO);
			deliveryDao.insertTbOrderRecallException(excData);
		}

		// 회수예외 등록 -D
		for (Delivery itemData : itemList) {
			itemData.setRegNo(TsbConstants.REG_NO);
			if(999999999 == itemData.getOrderdtlno() || 0 == itemData.getOrderdtlno()) {
				Delivery ordDtlNo = deliveryDao.getOrderDtlno(itemData);
				itemData.setOrderdtlno(ordDtlNo.getOrdDtlNo());
			}
			deliveryDao.insertTbOrderRecallExceptionItem(itemData);
		}

		// 회수예외 등록 -M
		for (Delivery memoData : memoList) {
			memoData.setRegNo(TsbConstants.REG_NO);
			deliveryDao.insertTbOrderRecallExceptionMemo(memoData);
		}

		/*
		// 교환인건 TB_EXCHANGE_DELV_FAIL 등록 
		for (Delivery excData : excList) {
			Collection<Delivery> excRecallList = deliveryDao.getChgRecallExcList(excData);
			for(Delivery recall : excRecallList) {
				recall.setRegNo(TsbConstants.REG_NO);
				deliveryDao.insertTbExchangeDelvFail(recall);
			}
		}
		*/
	}

	/**
	 * 회수예외 처리결과 조회 
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 03. 02
	 */
	public Collection<Delivery> getWithdrawExcRsltList() {

		Collection<Delivery> list = deliveryDao.getWithdrawExcRsltList();
		return list;
	}

	/**
	 * 회수예외 처리결과 전송여부 
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 03. 03
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderRecallException(Delivery excData) {
		deliveryDao.updateTbOrderRecallException(excData);
	}

	/**
	 * 출고예외 등록 
	 * @param  Collection<Delivery>
	 * @return 
	 * @author moon
	 * @since  2021. 03. 08
	 */
	@Transactional("shopTxnManager")
	public void insertTbOrderDeliveryException(Collection<Delivery> excList, Collection<Delivery> itemList) {

		// 출고예외 등록 -H
		for (Delivery excData : excList) {
			excData.setRegNo(TsbConstants.REG_NO);
			deliveryDao.insertTbOrderDeliveryException(excData);
		}

		// 출고예외 등록 -D
		for (Delivery itemData : itemList) {
			itemData.setRegNo(TsbConstants.REG_NO);
			deliveryDao.insertTbOrderDeliveryExceptionItem(itemData);

			if ("Y".equals(itemData.getGiftyn())) {
				// 출고 예외  사은품인경우  사은품상품혜택 테이블(tb_freegift_val) 사은품남은수량(LEFT_QTY) =0 으로 업데이트 
				itemData.setUpdNo(TsbConstants.REG_NO);
				deliveryDao.updateTbFreegiftValSoldout(itemData);
			}
		}
		
	
		// 교환 재고부족시 TB_EXCHANGE_DELV_FAIL 등록 
		for (Delivery excData : excList) {
			Collection<Delivery> chgExcList = deliveryDao.getChgDelvExcList(excData);	
			for(Delivery data : chgExcList) {
				data.setRegNo(TsbConstants.REG_NO);
				deliveryDao.insertTbExchangeDelvFail(data);
			}
		}
		

	}

	/**
	 * 출고결과 반영 
	 * @param  Collection<Delivery>
	 * @return 
	 * @author moon
	 * @since  2021. 03. 09
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderDtlStat(Collection<Delivery> List, String statGb) {
		// TB_ORDER_DETAIL , TB_ORDER_DETAIL_ITEM 상태값 변경 
		for(Delivery data : List) {
			if ("SHIPPING".equals(statGb)) {
				data.setInvoiceSendYn("Y");
				data.setOrdDtlStat(OrderDetailStat.SHIPPING.value());
			} else if ("PREPARE".equals(statGb)) {
				data.setOrdDtlStat(OrderDetailStat.GOODS_PREPARE.value());
			}
	
			if (999999999 == data.getOrderdtlno()) {
				Delivery dtlNo = deliveryDao.getOrdDtlno(data);
				data.setOrdDtlNo(dtlNo.getOrdDtlNo());
			}
	
			data.setUpdNo(TsbConstants.REG_NO);
			data.setRegNo(TsbConstants.REG_NO);
			int rtn = deliveryDao.updateTbOrderDtlStat(data);
			
			if(rtn > 0) {
				// 주문상세이력
				Order order = new Order();
				order.setOrdDtlNo(data.getOrderdtlno());
				order.setUpdNo(TsbConstants.REG_NO);
				order.setRegNo(TsbConstants.REG_NO);
				orderDao.createOrderDetailHst(order);
			}
		}

	}

	/**
	 * 출고결과 반영 
	 * @param  Collection<Delivery>
	 * @return 
	 * @author moon
	 * @since  2021. 03. 09
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderDtlStat(Delivery data, String statGb) {
		// TB_ORDER_DETAIL , TB_ORDER_DETAIL_ITEM 상태값 변경 
		if ("SHIPPING".equals(statGb)) {
			data.setInvoiceSendYn("Y");
			data.setOrdDtlStat(OrderDetailStat.SHIPPING.value());      // 배송중
		} else if ("PREPARE".equals(statGb)) {
			data.setOrdDtlStat(OrderDetailStat.GOODS_PREPARE.value()); // 상품준비중
		}

		if (999999999 == data.getOrderdtlno()) {
			Delivery dtlNo = deliveryDao.getOrdDtlno(data);
			data.setOrdDtlNo(dtlNo.getOrdDtlNo());
		}

		data.setUpdNo(TsbConstants.REG_NO);
		data.setRegNo(TsbConstants.REG_NO);
		int rtn = deliveryDao.updateTbOrderDtlStat(data);
		
		if(rtn > 0) {
			// 주문상세이력
			Order order = new Order();
			order.setOrdDtlNo(data.getOrderdtlno());
			order.setUpdNo(TsbConstants.REG_NO);
			order.setRegNo(TsbConstants.REG_NO);
			orderDao.createOrderDetailHst(order);
		}
		
		// 정산관련 등록 TB_ORDER_DETAIL_ITEM_HST  [G720_20] 판매-배송중
		if ("SHIPPING".equals(statGb)) {
			Collection<Delivery> itemList = deliveryDao.getOrdDtlItemSq(data);
			for(Delivery item : itemList) {
				Order ordItem = new Order();
				ordItem.setRegNo(TsbConstants.REG_NO);
				ordItem.setUpdNo(TsbConstants.REG_NO);
				ordItem.setOrdDtlItemSq(item.getOrdDtlItemSq());
				ordItem.setOrdDtlStat(OrdDtlItemStat.SALE_SHIPPING.value()); // [G720_20] 판매-배송중
				orderDao.createOrderDetailItemHst(ordItem);
			}
		}
	}
	
	/**
	 * 회수결과 주문변경 처리 
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 07. 12
	 */
	@Transactional("shopTxnManager")
	public void saveWithdraw2(Delivery data) {
		
		
		Delivery chgSqInfo = deliveryDao.getOrdchgSqInfo(data);
		
		data.setChgGb(chgSqInfo.getChgGb());
		data.setWdBfSendYn(chgSqInfo.getWdBfSendYn());
		data.setWdInvoiceSendYn("Y");
		data.setRtnLocCd(TscConstants.WMS_DELV_LOC_CD);
		data.setRegNo(TsbConstants.REG_NO);
		
		// TB_ORDER_CHANGE 
		deliveryDao.updateTbOrderChange(data);       // 주문변경번호 단위 
		
		
		// 교환일경우 자동 완료처리 
		
		if (OrderChangeGb.EXCHANGE.value().equals(data.getChgGb())) {  // 교환 
			data.setChgStat(OrderChangeStat.EXCHANGE_COMPLETE.value()); // 교환완료  G685_40
		} else {
			data.setChgStat(OrderChangeStat.RETURN_ING.value());  // 반품진행중 G685_33
		}
		
		Collection<Delivery> ordDtlNoList = wmsDeliveryService.getWmsOrdDtlNoList(data);
		
		for(Delivery dtlNo : ordDtlNoList) {
			
			if (999999999 == dtlNo.getOrdDtlNo()) {
				dtlNo.setOrderno(data.getOrderno());
				Delivery ordDtlNo = deliveryDao.getOrdDtlno2(dtlNo);
				dtlNo.setOrdDtlNo(ordDtlNo.getOrdDtlNo());
			}
			
			dtlNo.setUpdNo(TsbConstants.REG_NO);
			dtlNo.setRegNo(TsbConstants.REG_NO);
			dtlNo.setWmsmemo(data.getWmsmemo());
			dtlNo.setChgGb(data.getChgGb());
			dtlNo.setChgStat(data.getChgStat());
			dtlNo.setOrdChgSq(data.getOrdChgSq());
			dtlNo.setOrdDtlNo(dtlNo.getOrdDtlNo());	
			dtlNo.setOrderdtlno(dtlNo.getOrdDtlNo());
			
			// TB_ORDER_CHANGE_DETAIL
			deliveryDao.updateTbOrderChangeDetail(dtlNo);  //  주문상세번호 단위 

			// 주문상세변경 이력 
			OrderChange ordChg = new OrderChange();
			ordChg.setRegNo(TsbConstants.REG_NO);
			ordChg.setUpdNo(TsbConstants.REG_NO);
			ordChg.setOrdChgSq(dtlNo.getOrdChgSq());
			ordChg.setOrdDtlNo(dtlNo.getOrderdtlno());
			ordChg.setChgStat(dtlNo.getChgStat());
			orderChangeDao.createOrderChangeDetailHst(ordChg);
			
			dtlNo.setOrderno(data.getOrderno());
			Delivery ordInfo = deliveryDao.getOrderInfoList2(dtlNo);
			
			data.setCustNo(ordInfo.getCustNo());
			dtlNo.setChgOrdDtlNo(ordInfo.getChgOrdDtlNo());  // getChgOrdDtlNo
			// 교환일 경우  주문상세 상태값 처리  -> 
			if(OrderChangeGb.EXCHANGE.value().equals(data.getChgGb()) && "N".equals(data.getWdBfSendYn())) {
			
				OrderChange orderChange = new OrderChange();
				orderChange.setOrdChgSq(data.getOrdChgSq());
				orderChange.setCustNo(data.getCustNo());
				
				// 주문변경상세정보 조회
				Collection<OrderChange> orderChangeList = deliveryDao.getOrderChangeDetailInfo(orderChange);

				// 환불 사전 정보 설정
				int idx = 0;
				int size = orderChangeList.size();
				String chgGb = orderChangeList.iterator().next().getChgGb();
				Integer ordNo = orderChangeList.iterator().next().getOrdNo();
				Integer custNo = orderChangeList.iterator().next().getCustNo();
				String ordNm = orderChangeList.iterator().next().getOrdNm();
				String ordPhnno = orderChangeList.iterator().next().getOrdPhnno();
				int[] ordDtlNoArr = new int[size];
				int[] cnclRtnReqQtyArr = new int[size];

				for (OrderChange param : orderChangeList) {
					ordDtlNoArr[idx] = param.getOrdDtlNo();
					cnclRtnReqQtyArr[idx] = param.getChgQty();
					idx++;
				}

				// 회원/비회원 정보 설정
				if (custNo > 0) {
					orderChange.setCustNo(custNo);
				} else {
					orderChange.setOrdNm(ordNm);
					orderChange.setOrdPhnno(ordPhnno);
				}

				orderChange.setOrdNo(ordNo);
				orderChange.setChgGb(chgGb);
				orderChange.setOrdDtlNoArr(ordDtlNoArr);
				orderChange.setCnclRtnReqQtyArr(cnclRtnReqQtyArr);

				// 환불 사전 정보 조회
				GagaMap refundPreInfo = orderChangeService.getRefundPreInfo(orderChange);
				List<Order> cnclReqList2 = (List<Order>)refundPreInfo.get("cnclReqList");
				
				GagaMap info = orderRefundService.cnclRtnRefundAmt(cnclReqList2);

				List<Order> cancelOrderRefundList = (List<Order>)info.get("cancelOrderRefundList");
				//log.info("cnclReqList {}"+cnclReqList);
				log.info("cancelOrderRefundList {}"+cancelOrderRefundList);
				
				for (Order vo : cancelOrderRefundList) {
					
					if(dtlNo.getOrdDtlNo().equals(vo.getOrdDtlNo()))
					{
						vo.setRegNo(TsbConstants.REG_NO);
						vo.setUpdNo(TsbConstants.REG_NO);
						vo.setOrdDtlStat(OrderDetailStat.PAYMENT_AFTER_CANCEL.value());
							// 원주문 상세정보 수정
							orderChangeDao.updateOrderDetail(vo);
							// 원주문 상세 이력 등록
							orderDao.createOrderDetailHst(vo);
		
							//vo.setOrdDtlNo(data.getOrderdtlno());
							// 3-2-3. 주문상세단품정보 수정 및 주문상세단품이력 등록
							// 주문상세단품정보조회
							Collection<Order> orderDetailItemList = orderChangeDao.getOrderDetailItemForCnclRtn(vo);
							int ordDtlOrdAmt 			= orderDetailItemList.iterator().next().getOrdAmt();
							int ordDtlCnclRtnAmt	 	= orderDetailItemList.iterator().next().getCnclRtnAmt();
							int ordDtlCpn1DcAmt 		= orderDetailItemList.iterator().next().getCpn1DcAmt();
							int ordDtlTmtb1DcAmt 		= orderDetailItemList.iterator().next().getTmtb1DcAmt();
							int ordDtlTmtb2DcAmt 		= orderDetailItemList.iterator().next().getTmtb2DcAmt();
							int ordDtlGoodsCpnDcAmt 	= orderDetailItemList.iterator().next().getGoodsCpnDcAmt();
							int ordDtlCartCpnDcAmt 		= orderDetailItemList.iterator().next().getCartCpnDcAmt();
							int ordDtlPntDcAmt 			= orderDetailItemList.iterator().next().getPntDcAmt();
							int ordDtlPrePntDcAmt 		= orderDetailItemList.iterator().next().getPrePntDcAmt();
							int ordDtlSavePntAmt 		= orderDetailItemList.iterator().next().getSavePntAmt();
							int ordDtlRealOrdAmt 		= orderDetailItemList.iterator().next().getRealOrdAmt();
							int ordDtlGfcdUseAmt 		= orderDetailItemList.iterator().next().getGfcdUseAmt();
		
							// 주문상세단품단위 금액 등록
							int length					= orderDetailItemList.size();
							int index					= 1;
							int leftOrdAmt 				= ordDtlOrdAmt;
							int leftCnclRtnAmt			= ordDtlCnclRtnAmt;
							int leftCpn1DcAmt 			= ordDtlCpn1DcAmt;
							int leftTmtb1DcAmt 			= ordDtlTmtb1DcAmt;
							int leftTmtb2DcAmt 			= ordDtlTmtb2DcAmt;
							int leftGoodsCpnDcAmt 		= ordDtlGoodsCpnDcAmt;
							int leftCartCpnDcAmt 		= ordDtlCartCpnDcAmt;
							int leftPntDcAmt 			= ordDtlPntDcAmt;
							int leftPrePntDcAmt 		= ordDtlPrePntDcAmt;
							int leftSavePntAmt 			= ordDtlSavePntAmt;
							int leftRealOrdAmt 			= ordDtlRealOrdAmt;
							int leftGfcdUseAmt 			= ordDtlGfcdUseAmt;
		
							for (Order orderDetailItem : orderDetailItemList) {
								double dtlOrdAmt		= orderDetailItem.getDtlOrdAmt();
								double dtlItemOrdAmt	= orderDetailItem.getDtlItemOrdAmt();
								double tempDivD			= (dtlItemOrdAmt / dtlOrdAmt) * 100;
								
								int tempDiv				= Integer.parseInt(String.valueOf(Math.round(tempDivD)));
		
								if (index == length) {
									orderDetailItem.setCnclRtnAmt(leftCnclRtnAmt);
									orderDetailItem.setCpn1DcAmt(leftCpn1DcAmt);
									orderDetailItem.setTmtb1DcAmt(leftTmtb1DcAmt);
									orderDetailItem.setTmtb2DcAmt(leftTmtb2DcAmt);
									orderDetailItem.setGoodsCpnDcAmt(leftGoodsCpnDcAmt);
									orderDetailItem.setCartCpnDcAmt(leftCartCpnDcAmt);
									orderDetailItem.setPrePntDcAmt(leftPrePntDcAmt);
									orderDetailItem.setPntDcAmt(leftPntDcAmt);
									orderDetailItem.setGfcdUseAmt(leftGfcdUseAmt);
									orderDetailItem.setRealOrdAmt(leftRealOrdAmt);
									orderDetailItem.setSavePntAmt(leftSavePntAmt);
									
								} else {
									orderDetailItem.setCnclRtnAmt((ordDtlCnclRtnAmt 		* tempDiv) / 100);
									orderDetailItem.setCpn1DcAmt((ordDtlCpn1DcAmt 			* tempDiv) / 100);
									orderDetailItem.setTmtb1DcAmt((ordDtlTmtb1DcAmt 		* tempDiv) / 100);
									orderDetailItem.setTmtb2DcAmt((ordDtlTmtb2DcAmt 		* tempDiv) / 100);
									orderDetailItem.setGoodsCpnDcAmt((ordDtlGoodsCpnDcAmt 	* tempDiv) / 100);
									orderDetailItem.setCartCpnDcAmt((ordDtlCartCpnDcAmt 	* tempDiv) / 100);
									orderDetailItem.setPrePntDcAmt((ordDtlPrePntDcAmt 		* tempDiv) / 100);
									orderDetailItem.setPntDcAmt((ordDtlPntDcAmt 			* tempDiv) / 100);
									orderDetailItem.setGfcdUseAmt((ordDtlGfcdUseAmt 		* tempDiv) / 100);
									orderDetailItem.setRealOrdAmt((ordDtlRealOrdAmt 		* tempDiv) / 100);
									orderDetailItem.setSavePntAmt((ordDtlSavePntAmt 		* tempDiv) / 100);
		
									leftCnclRtnAmt		-= ((ordDtlCnclRtnAmt 				* tempDiv) / 100);
									leftCpn1DcAmt 		-= ((ordDtlCpn1DcAmt 				* tempDiv) / 100);
									leftTmtb1DcAmt 		-= ((ordDtlTmtb1DcAmt 				* tempDiv) / 100);
									leftTmtb2DcAmt 		-= ((ordDtlTmtb2DcAmt 				* tempDiv) / 100);
									leftGoodsCpnDcAmt 	-= ((ordDtlGoodsCpnDcAmt 			* tempDiv) / 100);
									leftCartCpnDcAmt 	-= ((ordDtlCartCpnDcAmt 			* tempDiv) / 100);
									leftPrePntDcAmt 	-= ((ordDtlPrePntDcAmt 				* tempDiv) / 100);
									leftPntDcAmt 		-= ((ordDtlPntDcAmt 				* tempDiv) / 100);
									leftGfcdUseAmt 		-= ((ordDtlGfcdUseAmt 				* tempDiv) / 100);
									leftRealOrdAmt 		-= ((ordDtlRealOrdAmt 				* tempDiv) / 100);
									leftSavePntAmt 		-= ((ordDtlSavePntAmt 				* tempDiv) / 100);
								}
		
								orderDetailItem.setRegNo(TsbConstants.REG_NO);
								orderDetailItem.setUpdNo(TsbConstants.REG_NO);
								orderDetailItem.setOrdDtlStat(vo.getOrdDtlStat());
								
								// 2021.06.25 WMS 회수정보 수집 (교환완료) (정산구분값추가)
								orderDetailItem.setOrdDtlStat(TscConstants.OrdDtlItemStat.SALE_RETURN_EXCHANGE_COMPLETE.value());
								orderDetailItem.setCnclRtnQty(vo.getOrdCanChgQty());  
								orderDetailItem.setOrdChgSq(data.getOrdChgSq());
								orderChangeDao.createOrderDetailItemHst(orderDetailItem);
		
								orderChangeDao.updateOrderDetailItem(orderDetailItem);

								index++;
							}
							
							// 교환주문 상세 수정
							vo.setOrdDtlStat(OrderDetailStat.PAYMENT_COMPLETE.value()); // 교환주문상세 결제완료
							vo.setOrdDtlNo(dtlNo.getChgOrdDtlNo());
							vo.setWdBfSendYn(data.getWdBfSendYn());
							orderChangeDao.updateChgOrderDetailTemp(vo);
							// 교환주문 상세 이력 등록 
							orderDao.createOrderDetailHst(vo);
							
							// 주문상세단품정보조회
							Collection<Order> orderDetailItemList2 = orderChangeDao.getOrderDetailItemForCnclRtn(vo);
							int ordDtlOrdAmt2 			= orderDetailItemList2.iterator().next().getOrdAmt();
							int ordDtlCnclRtnAmt2	 	= orderDetailItemList2.iterator().next().getCnclRtnAmt();
							int ordDtlCpn1DcAmt2 		= orderDetailItemList2.iterator().next().getCpn1DcAmt();
							int ordDtlTmtb1DcAmt2 		= orderDetailItemList2.iterator().next().getTmtb1DcAmt();
							int ordDtlTmtb2DcAmt2 		= orderDetailItemList2.iterator().next().getTmtb2DcAmt();
							int ordDtlGoodsCpnDcAmt2 	= orderDetailItemList2.iterator().next().getGoodsCpnDcAmt();
							int ordDtlCartCpnDcAmt2 	= orderDetailItemList2.iterator().next().getCartCpnDcAmt();
							int ordDtlPntDcAmt2 		= orderDetailItemList2.iterator().next().getPntDcAmt();
							int ordDtlPrePntDcAmt2 		= orderDetailItemList2.iterator().next().getPrePntDcAmt();
							int ordDtlSavePntAmt2 		= orderDetailItemList2.iterator().next().getSavePntAmt();
							int ordDtlRealOrdAmt2 		= orderDetailItemList2.iterator().next().getRealOrdAmt();
							int ordDtlGfcdUseAmt2 		= orderDetailItemList2.iterator().next().getGfcdUseAmt();
		
							// 주문상세단품단위 금액 등록
							int length2					= orderDetailItemList2.size();
							int index2					= 1;
							int leftOrdAmt2 			= ordDtlOrdAmt2;
							int leftCnclRtnAmt2			= ordDtlCnclRtnAmt2;
							int leftCpn1DcAmt2 			= ordDtlCpn1DcAmt2;
							int leftTmtb1DcAmt2 		= ordDtlTmtb1DcAmt2;
							int leftTmtb2DcAmt2 		= ordDtlTmtb2DcAmt2;
							int leftGoodsCpnDcAmt2 		= ordDtlGoodsCpnDcAmt2;
							int leftCartCpnDcAmt2 		= ordDtlCartCpnDcAmt2;
							int leftPntDcAmt2 			= ordDtlPntDcAmt2;
							int leftPrePntDcAmt2 		= ordDtlPrePntDcAmt2;
							int leftSavePntAmt2 		= ordDtlSavePntAmt2;
							int leftRealOrdAmt2 		= ordDtlRealOrdAmt2;
							int leftGfcdUseAmt2 		= ordDtlGfcdUseAmt2;
		
							for (Order orderDetailItem : orderDetailItemList2) {
								double dtlOrdAmt		= orderDetailItem.getDtlOrdAmt();
								double dtlItemOrdAmt	= orderDetailItem.getDtlItemOrdAmt();
								double tempDivD			= (dtlItemOrdAmt / dtlOrdAmt) * 100;
								
								int tempDiv				= Integer.parseInt(String.valueOf(Math.round(tempDivD)));
		
								if (index2 == length2) {
									orderDetailItem.setOrdAmt(leftOrdAmt2);
									orderDetailItem.setCnclRtnAmt(leftCnclRtnAmt2);
									orderDetailItem.setCpn1DcAmt(leftCpn1DcAmt2);
									orderDetailItem.setTmtb1DcAmt(leftTmtb1DcAmt2);
									orderDetailItem.setTmtb2DcAmt(leftTmtb2DcAmt2);
									orderDetailItem.setGoodsCpnDcAmt(leftGoodsCpnDcAmt2);
									orderDetailItem.setCartCpnDcAmt(leftCartCpnDcAmt2);
									orderDetailItem.setPrePntDcAmt(leftPrePntDcAmt2);
									orderDetailItem.setPntDcAmt(leftPntDcAmt2);
									orderDetailItem.setGfcdUseAmt(leftGfcdUseAmt2);
									orderDetailItem.setRealOrdAmt(leftRealOrdAmt2);
									orderDetailItem.setSavePntAmt(leftSavePntAmt2);
									
								} else {
									orderDetailItem.setOrdAmt((ordDtlOrdAmt2 				* tempDiv) / 100);
									orderDetailItem.setCnclRtnAmt((ordDtlCnclRtnAmt2 		* tempDiv) / 100);
									orderDetailItem.setCpn1DcAmt((ordDtlCpn1DcAmt2 			* tempDiv) / 100);
									orderDetailItem.setTmtb1DcAmt((ordDtlTmtb1DcAmt2 		* tempDiv) / 100);
									orderDetailItem.setTmtb2DcAmt((ordDtlTmtb2DcAmt2 		* tempDiv) / 100);
									orderDetailItem.setGoodsCpnDcAmt((ordDtlGoodsCpnDcAmt2 	* tempDiv) / 100);
									orderDetailItem.setCartCpnDcAmt((ordDtlCartCpnDcAmt2 	* tempDiv) / 100);
									orderDetailItem.setPrePntDcAmt((ordDtlPrePntDcAmt2 		* tempDiv) / 100);
									orderDetailItem.setPntDcAmt((ordDtlPntDcAmt2 			* tempDiv) / 100);
									orderDetailItem.setGfcdUseAmt((ordDtlGfcdUseAmt2 		* tempDiv) / 100);
									orderDetailItem.setRealOrdAmt((ordDtlRealOrdAmt2 		* tempDiv) / 100);
									orderDetailItem.setSavePntAmt((ordDtlSavePntAmt2 		* tempDiv) / 100);
		
									leftOrdAmt2         -= ((ordDtlOrdAmt2 					* tempDiv) / 100);
									leftCnclRtnAmt2		-= ((ordDtlCnclRtnAmt2 				* tempDiv) / 100);
									leftCpn1DcAmt2 		-= ((ordDtlCpn1DcAmt2 				* tempDiv) / 100);
									leftTmtb1DcAmt2 	-= ((ordDtlTmtb1DcAmt2 				* tempDiv) / 100);
									leftTmtb2DcAmt2 	-= ((ordDtlTmtb2DcAmt2 				* tempDiv) / 100);
									leftGoodsCpnDcAmt2 	-= ((ordDtlGoodsCpnDcAmt2 			* tempDiv) / 100);
									leftCartCpnDcAmt2 	-= ((ordDtlCartCpnDcAmt2 			* tempDiv) / 100);
									leftPrePntDcAmt2 	-= ((ordDtlPrePntDcAmt2 			* tempDiv) / 100);
									leftPntDcAmt2 		-= ((ordDtlPntDcAmt2 				* tempDiv) / 100);
									leftGfcdUseAmt2 	-= ((ordDtlGfcdUseAmt2 				* tempDiv) / 100);
									leftRealOrdAmt2 	-= ((ordDtlRealOrdAmt2 				* tempDiv) / 100);
									leftSavePntAmt2 	-= ((ordDtlSavePntAmt2 				* tempDiv) / 100);
								}
								log.info("orderDetailItem: "+orderDetailItem.getOrdAmt());
								orderDetailItem.setRegNo(TsbConstants.REG_NO);
								orderDetailItem.setUpdNo(TsbConstants.REG_NO);
								orderDetailItem.setOrdDtlStat(vo.getOrdDtlStat());
								
								// 2021.06.25 WMS 회수정보 수집 (교환결제완료) (정산구분값추가)
								orderDetailItem.setOrdDtlStat(TscConstants.OrdDtlItemStat.SALE_PAYMENT_COMPLETE.value()); // G720_10  판매-결제완료
								orderDetailItem.setCnclRtnQty(0);
								orderDetailItem.setOrdChgSq(data.getOrdChgSq());
								orderChangeDao.updateChgOrderDetailItemTemp(orderDetailItem);
								orderDetailItem.setExchangeOrdDtlItemSq(orderDetailItem.getOrdDtlItemSq());
								orderChangeDao.createOrderDetailItemHstForExchange(orderDetailItem);
								
								index2++;
							}
						}
					}
				} 

		}
		
		// TB_WITHDRAW 입력
		deliveryDao.insertTbWithdraw(data);  // 주문변경번호단위 
		
		Collection<Delivery> ordDtlItemList = wmsDeliveryService.getWmsOrdDtlItemList(data);
		Integer[] ordDtlNoArr = new Integer[ordDtlItemList.size()];
		int i = 0;
		for(Delivery item : ordDtlItemList) {
			
			if (999999999 == item.getOrdDtlNo()) {
				item.setOrderno(data.getOrderno());
				Delivery ordDtlNo = deliveryDao.getOrdDtlno2(item);
				item.setOrdDtlNo(ordDtlNo.getOrdDtlNo());
			}
			
			item.setRegNo(TsbConstants.REG_NO);
			item.setOrdChgSq(data.getOrdChgSq());
			item.setOrderno(data.getOrderno());
			Delivery ordInfo = deliveryDao.getOrderInfoList(item);
			
			item.setItemCd(ordInfo.getItemCd());
			item.setOptCd1(ordInfo.getOptCd1());
			item.setOptCd2(ordInfo.getOptCd2());
			item.setSellStoreCd(ordInfo.getSellStoreCd());
			item.setRtnLocCd(TscConstants.WMS_DELV_LOC_CD);
			// TB_WITHDRAW_DETAIL 입력
			deliveryDao.insertTbWithdrawDetail(item);	// 주문변경번호  ITEM단위

			ordDtlNoArr[i++] = item.getOrdDtlNo();
		}

		data.setOrdDtlNoArr(ordDtlNoArr);

	}	

	/**	
	 * 출고 송장번호 등록 
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 03. 25
	 */
	@Transactional("shopTxnManager")
	public void saveInvoice(Delivery data) {

		data.setUpdNo(TsbConstants.REG_NO);
		data.setRegNo(TsbConstants.REG_NO);
		if ("N".equals(data.getOrdDtlNoYn())) {
			Delivery dataDtlNo = deliveryDao.getOrdDtlno(data);
			data.setOrderdtlno(dataDtlNo.getOrdDtlNo());
		}
		deliveryDao.insertTbOrdDtlInvoice(data);

		if ("N".equals(data.getAddinvoiceyn())) {
			data.setOrdDtlStat(OrderDetailStat.DELIVERY_PREPARE.value());  // DELIVERY_PREPARE("G013_40"),		// 배송준비중
			// INVOICE_SEND_YN    Y N  대상 확인후 case에 반영 

			int rtn = deliveryDao.updateOrdDtlStat(data);

			log.info("rtn: " + rtn);

			if (rtn > 0) {
				// 주문상세이력
				Order order = new Order();
				order.setOrdDtlNo(data.getOrderdtlno());
				order.setUpdNo(TsbConstants.REG_NO);
				order.setRegNo(TsbConstants.REG_NO);
				orderDao.createOrderDetailHst(order);
			}
		}
	}

	/**	
	 * ERP 매장상품재고 조회 및 등록  
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 03. 28
	 */
	@Transactional("shopTxnManager")
	public void saveErpGoodsStock() {

		Collection<Erp> dataList = hansaeErp.getErpGoodsStockList(HansaeErp.ErpGb.HANSAE_DR.value());
		if (dataList != null && !dataList.isEmpty()) {
			deliveryDao.deleteShopStock();

			for (Erp erpStock : dataList) {
				Delivery goods = new Delivery();
				goods.setRegNo(TsbConstants.REG_NO);
				goods.setSupplyCompCd(TsbConstants.COMPANY_CD_DR); // 3 한세드립
				goods.setCdShop(erpStock.getCD_SHOP());
				goods.setCdStyle(erpStock.getCD_STYLE());
				goods.setCdColor(erpStock.getCD_COLOR());
				goods.setCdSize(erpStock.getCD_SIZE());
				goods.setQtStock(erpStock.getQT_STOCK());
				deliveryDao.insertShopStock(goods);
			}
		}
	}

	/**
	 * 출고대상 주문번호 조회 
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public Collection<Delivery> getOrderNoList() {

		Collection<Delivery> list = deliveryDao.getOrderNoList();
		return list;
	}

	/**
	 * 출고대상 주문상세번호 조회 
	 * @param  Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public Collection<Delivery> getOrderDtlNoList(Delivery ordNoData) {

		Collection<Delivery> list = deliveryDao.getOrderDtlNoList(ordNoData);
		return list;
	}

	/**
	 * 출고대상 주문상세번호 조회 
	 * @param  Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public Collection<Delivery> getOrderDtlItemList(Delivery ordDtlNoData) {

		Collection<Delivery> list = deliveryDao.getOrderDtlItemList(ordDtlNoData);
		return list;
	}

	/**
	 * WMS 재고체크 
	 * @param  Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public WmsDelivery getWmsRealStockChk(Delivery item) {

		WmsDelivery wmsStock = wmsService.getWmsRealStock(item.getProductno(), item.getOptCd());

		if (wmsStock != null) {
			item.setDelvLocCd(TscConstants.WMS_DELV_LOC_CD);
			// 출고처지정 거부 주문 또는 출고거부상품이 존재시  재고를 0으로 만든다.
//			log.info("getOrdNo: " + item.getOrdNo());
//			log.info("getOrdDtlNo: " + item.getOrdDtlNo());
//			log.info("getDelvLocCd: " + item.getDelvLocCd());
//			log.info("getOptCd: " + item.getOptCd());
//			log.info("getOptCd1: " + item.getOptCd1());
//			log.info("getOptCd2: " + item.getOptCd2());

			int rtnCnt = deliveryDao.getDeliveryAssignBanGoods(item);
			if (rtnCnt != 0) {
				wmsStock.setLocQty(0);
			}
		}
		return wmsStock;
	}

	/**
	 * 직송매장 재고체크
	 * @param  Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public void getShopRealStockChk(Collection<Delivery> itemList) {
		for (Delivery item : itemList) {
			Collection<Erp> shopStockList = hansaeErp.getErpRealStockList(HansaeErp.ErpGb.HANSAE_DR.value(), item.getGoodsCd(), item.getOptCd1(), item.getOptCd2());

			if (shopStockList != null) {
				for (Erp shop : shopStockList) {
					item.setDelvLocCd(shop.getStockLoc());
					item.setLocQty(shop.getLocQty());
					if (shop.getLocQty() >= item.getOrdQty()) {
						Delivery rtn = deliveryDao.getDeliveryAssignBanGoodsShop(item);
						if (rtn != null) {
							deliveryDao.insertTbDeliveryLocTmp(rtn);
						} else {
							log.info(" getDeliveryAssignBanGoodsShop rtn = null");
						}
					}
				}
			} else {
				log.info("getErpRealStock shopStockList = null");
			}
		}
	}

	/**
	 * 직송매장 재고체크(세트)
	 * @param  Collection<Delivery>, Integer (주문상세번호)
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 07
	 */
	public void getShopRealStockSetChk(Collection<Delivery> itemList, Integer ordDtlNo) {
		for (Delivery item : itemList) {
			Collection<Erp> shopStockList = hansaeErp.getErpRealStockList(HansaeErp.ErpGb.HANSAE_DR.value(), item.getItemCd(), item.getOptCd1(), item.getOptCd2());

			if (shopStockList != null) {
				for (Erp shop : shopStockList) {
					item.setDelvLocCd(shop.getStockLoc());
					item.setLocQty(shop.getLocQty());
					if (shop.getLocQty() >= item.getOrdQty()) {
						Delivery rtn = deliveryDao.getDeliveryAssignBanGoodsShop(item);
						if (rtn != null) {
							deliveryDao.insertTbDeliveryLocSetTmp(rtn);
						} else {
							log.info(" getDeliveryAssignBanGoodsShop rtn = null");
						}
					}
				}
			} else {
				log.info("getErpRealStock shopStockList = null");
			}
		}
		// 임시테이블 MAX(GOODS_LOC_SET_CNT) 조회 
		int setCnt = deliveryDao.getDeliveryLocTmpGoodsSetMaxCnt();

		// 임시테이블  세트갯수 비교  세트 있는 모든 매장 업데이트
		if (itemList.size() == setCnt) {
			Delivery tmp = new Delivery();
			tmp.setOrdDtlNo(ordDtlNo);
			tmp.setGoodsLocSetCnt(setCnt);
			deliveryDao.updateTbDeliveryLocSetTmp(tmp);
		}

		// 임시테이블 셋트 카운트 초기화 
		deliveryDao.updateTbDeliveryLocSetTmpInit();
	}

	/**	
	 * ERP 매장상품재고 조회 및 등록  
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public void saveDeliveryAssign(Delivery delivery) {
		delivery.setRegNo(TsbConstants.REG_NO);
		deliveryDao.insertTbDeliveryAssign(delivery);
		deliveryDao.insertTbDeliveryAssignHst(delivery);
	}

	/**	
	 * ERP 매장상품재고 조회 및 등록  
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 05
	 */
	public void updateTbOrderDtlAssign(Delivery delivery) {

		delivery.setRegNo(TsbConstants.REG_NO);

		deliveryDao.updateTbOrderDtlAssign(delivery);

		// 주문상세이력
		Order order = new Order();
		order.setOrdDtlNo(delivery.getOrdDtlNo());
		order.setUpdNo(TsbConstants.REG_NO);
		order.setRegNo(TsbConstants.REG_NO);
		orderDao.createOrderDetailHst(order);

	}

	/**
	 * 출고처지정 임시 테이블 삭제
	 * @param  
	 * @return 
	 * @author moon
	 * @since  2021. 04. 06
	 */
	public void deleteTbDeliveryLocTmp() {
		deliveryDao.deleteTbDeliveryLocTmp();
	}

	/**
	 * 출고처지정 임시 테이블 조회 
	 * @param  
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 06
	 */
	public Delivery getDeliveryLocTmp(int ordDtlCnt) {

		int totalCnt = ordDtlCnt;
		Delivery rtn = null;
		for (int i = totalCnt; i >= 1; i--) {
			Delivery chk = new Delivery();
			chk.setGoodsLocCnt(i);
			rtn = deliveryDao.getDeliveryLocTmp(chk);
			if (rtn != null) {
				break;
			}
		}

		return rtn;
	}

	/**
	 * WMS 출고요청 대상 주문번호 조회 
	 * @param  
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 08
	 */
	public Collection<Delivery> getWmsDeliveryOrdNoList() {
		Collection<Delivery> rtn = deliveryDao.getWmsDeliveryOrdNoList();
		return rtn;
	}

	/**
	 * WMS 출고요청 대상 조회
	 * @param  
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 08
	 */
	public Collection<Delivery> getWmsDeliveryList(Delivery delivery) {
		Collection<Delivery> rtn = deliveryDao.getWmsDeliveryList(delivery);
		return rtn;
	}

	/**
	 * 출고결과 반영 (상품상태)
	 * @param  Collection<Delivery>
	 * @return 
	 * @author moon
	 * @since  2021. 03. 09
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderDtlStat(Collection<Delivery> list) {

		// 출고예외 등록 -H
		for (Delivery data : list) {
			data.setOrdDtlStat(OrderDetailStat.GOODS_PREPARE.value());
			data.setUpdNo(TsbConstants.REG_NO);
			deliveryDao.updateTbOrderDtlStat(data);

			// 주문상세이력
			Order order = new Order();
			order.setOrdDtlNo(data.getOrderdtlno());
			order.setUpdNo(TsbConstants.REG_NO);
			order.setRegNo(TsbConstants.REG_NO);
			orderDao.createOrderDetailHst(order);

		}
	}

	/**
	 * 회수요청 대상 조회 
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 08 
	 */
	public Collection<Delivery> getWithdrawRequestList() {

		Collection<Delivery> list = deliveryDao.getWithdrawRequestList();
		return list;
	}

	/**
	 * 주문변경상세 상태값 변경
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 08
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderChaneDetailStat(Delivery data) {


		data.setUpdNo(TsbConstants.REG_NO);
		
		if("N".equals(data.getWdTargetYn())) {
			data.setChgStat(OrderChangeStat.WITHDRAW_GOODS_CHECK.value()); // 상품검수중
		} else {
			if ("W".equals(data.getWdGb())) {// 회수요청 
				data.setChgStat(OrderChangeStat.WITHDRAW.value()); // 회수요청 
			} else { // 직접배송 - 상태값 상품검수중
				data.setChgStat(OrderChangeStat.WITHDRAW_GOODS_CHECK.value()); // 상품검수중
			}
		}

		int rtn = deliveryDao.updateTbOrderChaneDetailStat(data);

		if(rtn > 0) {
			// 주문상세변경 이력 
			OrderChange ordChg = new OrderChange();
			ordChg.setRegNo(TsbConstants.REG_NO);
			ordChg.setUpdNo(TsbConstants.REG_NO);
			ordChg.setOrdChgSq(data.getOrderexceptionno());
			ordChg.setOrdDtlNo(data.getOrderdtlno());
			ordChg.setChgStat(data.getChgStat());
			orderChangeDao.createOrderChangeDetailHst(ordChg);
		}

	}

	/**
	 * 주문변경상세  반운송장번호 업데이트 
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 12
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderChaneInvoc(Delivery delivery) {

		delivery.setUpdNo(TsbConstants.REG_NO);
		delivery.setShipCompCd("D1029");
		deliveryDao.updateTbOrderChaneInvoc(delivery);
	}

	/**
	 * 주문변경회수상태 및 상세상태 업데이트 
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 12
	 */
	@Transactional("shopTxnManager")
	public void updateTbOrderChangeStat(Delivery delivery) {

		delivery.setUpdNo(TsbConstants.REG_NO);
		deliveryDao.updateTbOrderChangeStat(delivery);

		if ("91".equals(delivery.getCrgSt())) {
			delivery.setChgStat(OrderChangeStat.WITHDRAW_GOODS_CHECK.value()); // 상품검수중
			
			int rtn = deliveryDao.updateTbOrderChangeDtlStat(delivery);
			
			if(rtn > 0) {
				Collection<Delivery> list = deliveryDao.getOrdChgDtlNoList(delivery);
				for (Delivery data : list) {
					// 주문상세변경 이력 
					OrderChange ordChg = new OrderChange();
					ordChg.setRegNo(TsbConstants.REG_NO);
					ordChg.setUpdNo(TsbConstants.REG_NO);
					ordChg.setOrdChgSq(data.getOrdChgSq());
					ordChg.setOrdDtlNo(data.getOrdDtlNo());
					ordChg.setChgStat(OrderChangeStat.WITHDRAW_GOODS_CHECK.value());
					orderChangeDao.createOrderChangeDetailHst(ordChg);
				}
			}
		}
	}

	/**
	 * 배송추적 대상 조회   
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 14 
	 */
	public Collection<Delivery> getDelvTrackingList() {

		Collection<Delivery> list = deliveryDao.getDelvTrackingList();
		return list;
	}

	/**
	 * 스윗트래커 배송추적 요청    
	 * @param Delivery
	 * @return GagaMap
	 * @author moon
	 * @since  2021. 04. 15 
	 */
	public GagaMap sweetTrackerInvcSend(Delivery delivery) {
		GagaMap result = new GagaMap();

		String swtTrurl = env.getProperty("sweet.api.url");
		String root = env.getProperty("sweet.api.domain.front");
		String subUrl = "/delivery/sweettracker/response";
		String tier = env.getProperty("sweet.api.tier");
		String key = env.getProperty("sweet.api.key");

		String callBackUrl = root + subUrl;

		log.info("swtTrurl: " + swtTrurl);

		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.add("num", delivery.getInvoiceno());
		params.add("code", delivery.getSwtShipCompCd()); 
		params.add("fid", delivery.getSwtShipCompCd() + delivery.getInvoiceno());
		params.add("callback_url", callBackUrl);
		params.add("callback_type", "json");
		params.add("tier", tier);
		params.add("key", key);
		params.add("type", "json");

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
		URI url = URI.create(swtTrurl);
		// POST방식으로 호출
		ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);

		log.debug("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

		String jsonResult = responseEntity.getBody();
		log.debug("responseEntity.getBody(): {} ", jsonResult);

		Gson gson = new GsonBuilder().create();

		GagaMap rtn = gson.fromJson(jsonResult, GagaMap.class);

		log.info("==============================================================");
		log.info("rtn: fid " + rtn.getString("fid"));
		log.info("rtn: success " + rtn.getBoolean("success"));
		log.info("rtn: num " + rtn.getString("num"));
		log.info("==============================================================");
		if (rtn.getBoolean("success")) {
			result.set("success", "S");
		} else {
			result.set("success", "F");
		}

		return result;
	}

	/**
	 * 배송추적 요청 완료  
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 12
	 */
	@Transactional("shopTxnManager")
	public void updateOrdInvcSendYn(Delivery data) {

		data.setUpdNo(TsbConstants.REG_NO);
		if ("O".equals(data.getGb())) {      // 주문 
			deliveryDao.updateSwtOrdInvcSendYn(data);
		} else if ("W".equals(data.getGb())) { // 회수 
			deliveryDao.updateSwtWdInvcSendYn(data);
		}
	}

	/**
	 * 자동 품절취소
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 04. 26
	 */
	@Transactional("shopTxnManager")
	public void SoldoutCancel(Delivery data, String gubun) {
		Integer userNo = TsbConstants.REG_NO;
		Collection<Delivery> list = null;
		if ("N".equals(gubun)) {
			list = deliveryDao.getSoldoutOrderDtlNoList(data);
		} else if ("E".equals(gubun)) {  // 출고예외 - 재고없음
			list = deliveryDao.getSoldoutOrderExcDtlNoList(data);
		} else if ("R".equals(gubun)) {  // 회수예외 - 확정 전 품절(재고없음). 확정 전 불량  
			list = deliveryDao.getSoldoutOrderRecallDtlNoList(data);
		}

		try {
			if(list != null) {
				Collection<Order> ordSoldoutList = new ArrayList<Order>();
				for (Delivery item : list) {
	
					Order param = new Order();
					param.setOrdNo(item.getOrdNo());
					param.setOrdDtlNo(item.getOrdDtlNo());
					param.setCustNo(item.getCustNo());
					param.setOrdNm(item.getOrdNm());
					param.setOrdPhnno(item.getOrdPhnno());
					param.setPgGb(item.getPgGb());
					param.setPayMeans(item.getPayMeans());
					param.setBankCd(item.getBankCd());
					param.setAccountNm(item.getAccountNm());
					param.setAccountNo(item.getAccountNo());
					param.setCnclRtnQty(item.getSaleQty());
					ordSoldoutList.add(param);
	
				}
				coreDeliveryService.cancelSoldout(ordSoldoutList, userNo, "Y");

				// 네이버페이 주문형 처리
				int i = 0;
				for(Order order : ordSoldoutList) {
					order = orderDao.getOrdDtlInfo(order);
					if("O".equals(order.getOrdExchGb())) {
						// coreNaverPayService.sendNaverPaySoldoutCancel(order, TsbConstants.REG_NO);
						String addUrl = "/naverpay/send/soldout/cancel?ordDtlNo=" + order.getOrdDtlNo() + "&userNo=" + userNo;
						coreNaverPayService.sendScmServerForNaverpay(addUrl);							// 품절취소
					} else {
						String addUrl = "";
						// coreNaverPayService.sendNaverPayRejectExchange(order, TsbConstants.REG_NO);
						addUrl = "/naverpay/send/reject/exchange?ordDtlNo=" + order.getOrdDtlNo() + "&userNo=" + userNo;
						coreNaverPayService.sendScmServerForNaverpay(addUrl);						// 교환 반려

						// coreNaverPayService.sendNaverPaySoldoutReturnReq(order, TsbConstants.REG_NO);
						addUrl = "/naverpay/send/soldout/return/req?ordDtlNo=" + order.getOrdDtlNo() + "&userNo=" + userNo;
						coreNaverPayService.sendScmServerForNaverpay(addUrl);						// 품절반품접수

						// coreNaverPayService.sendNaverPayReturnComplete(order, TsbConstants.REG_NO);
						addUrl = "/naverpay/send/return/complete?ordDtlNo=" + order.getOrdDtlNo() + "&userNo=" + userNo;
						coreNaverPayService.sendScmServerForNaverpay(addUrl);						// 반품완료
					}

					i++;
				}
	
				// TB_ORDER_DETAIL 결품여부 Y
				
				/*
				for(Delivery delv : list) {
					delv.setUpdNo(userNo);
					delv.setSoldoutMemo("자동 품절처리");
					deliveryDao.updateSoldOut(delv);
				}
				*/
	
				if ("E".equals(gubun)) {
					// 처리완료 업데이트
					data.setUpdNo(userNo);
					deliveryDao.updateTbOrderDeliveryException(data);
				} else if ("R".equals(gubun)) {
					// 처리완료 업데이트
					deliveryDao.updateTbRecallException(data);
				}
			}
		} catch(Exception e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	/**
	 * 자동품절취소 대상 목록
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 26
	 */
	public Collection<Delivery> getSoldoutOrderNoList() {

		Collection<Delivery> list = deliveryDao.getSoldoutOrderNoList();
		return list;
	}

	public GagaMap sweetTrackerInvcSendTest() {
		GagaMap result = new GagaMap();

		String swtTrurl = env.getProperty("sweet.api.url");
		String root = env.getProperty("sweet.api.domain.front");
		String subUrl = "/delivery/sweettracker/response";
		String tier = env.getProperty("sweet.api.tier");
		String key = env.getProperty("sweet.api.key");

		String callBackUrl = root + subUrl;

		log.info("swtTrurl: " + swtTrurl);
		log.info("tier: " + tier);
		log.info("key: " + key);
		log.info("callBackUrl: " + callBackUrl);

		MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
		params.add("num", "420693421175");
		params.add("code", "05");
		params.add("fid", "05420693421175");
		params.add("callback_url", callBackUrl);
		params.add("callback_type", "json");
		params.add("tier", tier);
		params.add("key", key);
		params.add("type", "json");

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
		URI url = URI.create(swtTrurl);
		// POST방식으로 호출
		ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);

		log.info("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

		String jsonResult = responseEntity.getBody();
		log.info("responseEntity.getBody(): {} ", jsonResult);

		Gson gson = new GsonBuilder().create();

		GagaMap rtn = gson.fromJson(jsonResult, GagaMap.class);

		log.info("==============================================================");
		log.info("rtn: fid " + rtn.getString("fid"));
		log.info("rtn: success " + rtn.getBoolean("success"));
		log.info("rtn: num " + rtn.getString("num"));
		log.info("==============================================================");
		if (rtn.getBoolean("success")) {
			result.set("success", "S");
		} else {
			result.set("success", "F");
		}

		return result;
	}

	/**
	 * WMS 출고요청 대상 사은품 조회
	 * @param  
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 04. 29
	 */
	public Collection<Delivery> getWmsDeliveryGiftList(Delivery delivery) {
		Collection<Delivery> rtn = deliveryDao.getWmsDeliveryGiftList(delivery);
		return rtn;
	}

	/**
	 * 품절대상 출고예외 주문 목록 조회
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 05. 06
	 */
	public Collection<Delivery> getSoldoutOrderExcNoList() {

		Collection<Delivery> list = deliveryDao.getSoldoutOrderExcNoList();
		return list;
	}

	/**
	 * 품절대상 회수예외 주문 목록 조회
	 * @param 
	 * @return Collection<Delivery>
	 * @author moon
	 * @since  2021. 05. 06
	 */
	public Collection<Delivery> getSoldoutOrderRecallNoList() {

		Collection<Delivery> list = deliveryDao.getSoldoutOrderRecallNoList();
		return list;
	}

	/**
	 * 교환상품 출고예외등록
	 * @param  Delivery
	 * @return 
	 * @author moon
	 * @since  2021. 06. 07
	 */
	@Transactional("shopTxnManager")
	public void insertTbExchangeDelvFail(Delivery data) {
		Integer userNo = TsbConstants.REG_NO;
		data.setRegNo(userNo);
		deliveryDao.insertTbExchangeDelvFail(data);
	}
	
	/**
	 * 배송출발 알림문구 조회 
	 * @param 
	 * @return Delivery
	 * @author moon
	 * @since  2021. 07. 15
	 */
	public Delivery getDeliveryStart(Delivery delivery) {
		return deliveryDao.getDeliveryStart(delivery);
	}
	
	/**
	 * 회수시작 알림문구 조회
	 * @param 
	 * @return Delivery
	 * @author moon
	 * @since  2021. 07. 15
	 */
	public Delivery getWithdrawStart(Delivery delivery) {
		return deliveryDao.getWithdrawStart(delivery);
	}
}
