package com.style24.admin.biz.service;

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

import org.apache.commons.lang3.StringUtils;
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 org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.style24.admin.biz.dao.TsaDeliveryDao;
import com.style24.admin.support.env.TsaConstants;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.admin.support.util.TsitUtil;
import com.style24.core.biz.dao.TscOrderDao;
import com.style24.core.biz.service.TscDeliveryService;
import com.style24.core.biz.service.TscWmsService;
import com.style24.core.support.env.TscConstants.OrderDetailStat;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Delivery;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.WmsDelivery;

import lombok.extern.slf4j.Slf4j;

/**
 * 배송관리 Service
 *
 * @author moon
 * @since 2020. 11. 05
 */
@Service
@Slf4j
public class TsaDeliveryService {

	@Autowired
	private TscMessageByLocale message;
	
	@Autowired
	private TsaDeliveryDao deliveryDao;
	
	@Autowired
	private TscOrderDao orderDao;
	
	@Autowired
	private ObjectMapper mapper;
	
	@Autowired
	private TscWmsService wmsService;
	
	@Autowired
	private TsaWmsWithdrawService wmsWithdrawService;
	
	@Autowired
	private TscDeliveryService coreDeliveryService;	
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private Environment env;
	
	/**
	 * 배송 목록 건수
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 02. 26
	 */
	public int getDeliveryListCount(Delivery delivery) {
		
		if (StringUtils.isNotBlank(delivery.getCondition())) {
			delivery.setConditions(delivery.getCondition().replaceAll("\r", "").split("\n"));
		}
		
		// 외부몰권한일 때 외부몰벤더ID 설정
		if (TsaSession.getInfo().getRoleCd().startsWith("G001_C")) {
			delivery.setMallGb(TsaConstants.MallGb.EXTMALL.value());
			delivery.setVendorId(TsaSession.getInfo().getVendorId());
		}
		
		if (!StringUtils.isBlank(delivery.getBrandList())) {
			try {
				String [] arrBrandCd = mapper.readValue(delivery.getBrandList(), String[].class);
				delivery.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("브랜드코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		if (!StringUtils.isBlank(delivery.getSupplyCompList())) {
			try {
				String [] arrSupplyComp = mapper.readValue(delivery.getSupplyCompList(), String[].class);
				delivery.setMultiSupplyCompCd(arrSupplyComp);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}		
		return deliveryDao.getDeliveryListCount(delivery);
	}
	
	/**
	 * 배송 목록
	 *
	 * @param -Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2020. 11. 05
	 */
	public Collection<Delivery> getDeliveryList(Delivery delivery) {
		// multi row 검색관련 처리
		
		if (StringUtils.isNotBlank(delivery.getCondition())) {
			delivery.setConditions(delivery.getCondition().replaceAll("\r", "").split("\n"));
		}

		// 외부몰권한일 때 외부몰벤더ID 설정
		if (TsaSession.getInfo().getRoleCd().startsWith("G001_C")) {
			delivery.setMallGb(TsaConstants.MallGb.EXTMALL.value());
			delivery.setVendorId(TsaSession.getInfo().getVendorId());
		}
		
		if (!StringUtils.isBlank(delivery.getBrandList())) {
			try {
				String [] arrBrandCd = mapper.readValue(delivery.getBrandList(), String[].class);
				delivery.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("브랜드코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		if (!StringUtils.isBlank(delivery.getSupplyCompList())) {
			try {
				String [] arrSupplyComp = mapper.readValue(delivery.getSupplyCompList(), String[].class);
				delivery.setMultiSupplyCompCd(arrSupplyComp);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}
		
		
		return deliveryDao.getDeliveryList(delivery);
	}
	
	/**
	 * 주문상세 단품 목록
	 *
	 * @param  ordDtlNo
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2021. 03. 05
	 */
	public Collection<Delivery> getDelvDetailItemList(Integer ordDtlNo) {
		
		Delivery delivery = new Delivery();
		delivery.setOrdDtlNo(ordDtlNo);
		return deliveryDao.getDelvDetailItemList(delivery);
	}	
	
	/**
	 * 배송완료처리
	 *
	 * @param -Delivery
	 * @return void
	 * @author moon
	 * @since 2021. 03. 05
	 */
	@Transactional("shopTxnManager")
	public void saveDeliveryComplete(Delivery delivery) {

		Integer userNo = TsaSession.getInfo().getUserNo();
		
		delivery.setUpdNo(userNo);
		delivery.setRegNo(userNo);
		// 주문상세상태 => 배송완료
		delivery.setOrdDtlStat(OrderDetailStat.DELIVERY_COMPLETE.value());
		//delivery.setHstMemo("수기배송완료처리");

		// 주문상세 상태 값 수정
		deliveryDao.updateOrderDetailStat(delivery);

		// 주문상세이력 - 주문Dao 사용
		Order order = new Order();
		order.setOrdDtlNo(delivery.getOrdDtlNo());
		order.setUpdNo(userNo);
		order.setRegNo(userNo);
		orderDao.createOrderDetailHst(order);

	}
	
	
	/**
	 * 주문상세
	 *
	 * @param  ordDtlNo
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2020. 11. 05
	 */
	public Collection<Delivery> getOrderDetail(Integer ordDtlNo) {
		return deliveryDao.getOrderDetail(ordDtlNo);
	}	
	
	/**
	 * 수기송장등록/수정
	 *
	 * @param -Delivery
	 * @return void
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@Transactional("shopTxnManager")
	public void saveChangeInvoice(Collection<Delivery> deliveryList) {
	
		Integer userId = TsaSession.getInfo().getUserNo();

		for (Delivery oneDelivery : deliveryList) {
			oneDelivery.setUpdNo(userId);
			oneDelivery.setRegNo(userId);
			
			// 송장번호 변경
			int rtn = deliveryDao.saveChangeInvoice(oneDelivery);
			
			deliveryDao.updateOrderDtlInvoice(oneDelivery);
			
			// 주문상세이력
			Order order = new Order();
			order.setOrdDtlNo(oneDelivery.getOrdDtlNo());
			order.setUpdNo(userId);
			order.setRegNo(userId);
			orderDao.createOrderDetailHst(order);
		}
	}	
	
	/**
	 * 품절취소
	 *
	 * @param  
	 * @return void
	 * @author moon
	 * @since 2020. 04. 23
	 */
	@Transactional("shopTxnManager")
	public void cancelSoldout(Collection<Delivery> soldoutList) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		
		Collection<Order> ordSoldoutList = new ArrayList<Order>();
		for(Delivery item : soldoutList ) {
			Order param = new Order();
			param.setOrdNo(item.getOrdNo());
			param.setCustNo(item.getCustNo());
			param.setOrdNm(item.getOrdNm());
			param.setPgGb(item.getPgGb());
			param.setPayMeans(item.getPayMeans());
			param.setBankCd(item.getBankCd());
			param.setAccountNm(item.getAccountNm());
			param.setAccountNo(item.getAccountNo());
			param.setOrdDtlNo(item.getOrdDtlNo());
			param.setCnclRtnQty(item.getSaleQty());
			param.setOrdPhnno(item.getOrdPhnno());
			log.info("item.getOrdPhnno(): "+item.getOrdPhnno());
			ordSoldoutList.add(param);
			
		}
		coreDeliveryService.cancelSoldout(ordSoldoutList,userNo, "N"); 
		
		/*
		for(Delivery data : soldoutList) {
			data.setSoldoutMemo("수동 품절처리");
			data.setUpdNo(userNo);
			deliveryDao.updateSoldOut(data);
		}
		*/
		
	}	
	
	
	/**
	 * 출고금지상품 목록
	 *
	 * @param  Delivery
	 * @return Delivery List
	 * @author moon
	 * @since 2020. 11. 05
	 */
	public Collection<Delivery> getBangoodsList(Delivery delivery) {
		return deliveryDao.getBangoodsList(delivery);
	}	
	
	/**
	 * 출고금지상품 삭제
	 *
	 * @param -Delivery
	 * @return void
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@Transactional("shopTxnManager")
	public void deleteBangoods(Collection<Delivery> bangoodsList) {
		Integer userId = TsaSession.getInfo().getUserNo();

		for (Delivery oneBangood : bangoodsList) {
			oneBangood.setUpdNo(userId);
			deliveryDao.deleteBangoods(oneBangood);
		}
	}
	
	/**
	 * 출고금지상품 등록 대상목록
	 *
	 * @param  Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2020. 11. 05
	 */
	public Collection<Delivery> getBangoodsRegistList(Delivery delivery) {
		return deliveryDao.getBangoodsRegistList(delivery);
	}
	
	/**
	 * 출고금지상품 등록
	 *
	 * @param -Delivery
	 * @return void
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@Transactional("shopTxnManager")
	public void createBangoods(Collection<Delivery> bangoodsList) {
		Integer userId = TsaSession.getInfo().getUserNo();

		for (Delivery oneBangood : bangoodsList) {

			int cnt = deliveryDao.getBangoodsListCnt(oneBangood);
			if (cnt > 0) {
				throw new IllegalStateException(message.getMessage("DELIVERY_0001"));
			}

			oneBangood.setRegNo(userId);
			oneBangood.setUpdNo(userId);
			deliveryDao.createBangoods(oneBangood);
		}
	}
	
	/**
	 * 배송/회수지시 목록 건수
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 02. 26
	 */
	public int getDeliveryWithdrawDirectiveListCount(Delivery delivery) {
		return deliveryDao.getDeliveryWithdrawDirectiveListCount(delivery);
	}	
	
	
	
	/**
	 * 배송/회수지시 목록
	 *
	 * @param -Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2021. 04. 12
	 */	
	public Collection<Delivery> getDeliveryWithdrawDirectiveList(Delivery delivery) {
		return deliveryDao.getDeliveryWithdrawDirectiveList(delivery);
	}
	
	/**
	 * 출고처지정 목록 건수
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 04. 19
	 */
	public int getAssignListCount(Delivery delivery) {
		return deliveryDao.getAssignListCount(delivery);
	}
	
	/**
	 * 출고처지정 목록
	 *
	 * @param -Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2021. 04. 19
	 */
	public Collection<Delivery> getAssignList(Delivery delivery) {
		// multi row 검색관련 처리
//		
//		if (StringUtils.isNotBlank(delivery.getCondition())) {
//			TsitUtil tsitUtil = new TsitUtil();
//			String searchCondition = tsitUtil.replaceMultiSelectParamsArr(delivery.getCondition());
//			delivery.setConditions(searchCondition.split(","));
//		}

		// 외부몰권한일 때 외부몰벤더ID 설정
		if (TsaSession.getInfo().getRoleCd().startsWith("G001_C")) {
			delivery.setMallGb(TsaConstants.MallGb.EXTMALL.value());
			delivery.setVendorId(TsaSession.getInfo().getVendorId());
		}
//		
//		if (!StringUtils.isBlank(delivery.getBrandList())) {
//			try {
//				String [] arrBrandCd = mapper.readValue(delivery.getBrandList(), String[].class);
//				delivery.setMultiBrand(arrBrandCd);
//			} catch (Exception e) {
//				e.printStackTrace();
//				throw new IllegalStateException("브랜드코드 검색중 오류로 인해 조회되지 않았습니다.");
//			}
//		}
//
//		if (!StringUtils.isBlank(delivery.getSupplyCompList())) {
//			try {
//				String [] arrSupplyComp = mapper.readValue(delivery.getSupplyCompList(), String[].class);
//				delivery.setMultiSupplyCompCd(arrSupplyComp);
//			} catch (Exception e) {
//				e.printStackTrace();
//				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
//			}
//		}
		
		
		return deliveryDao.getAssignList(delivery);
	}	
	
	/**
	 * 출고처 수동지정 대상 조회
	 *
	 * @param ordDtlNo - 주문상세번호
	 * @return Delivery
	 * @author moon
	 * @since 2021. 04. 19
	 */
	public Delivery getDeliveryAssignPopup(Integer ordDtlNo) {
		return deliveryDao.getDeliveryAssignPopup(ordDtlNo);
	}
	
	/**
	 * 출고처지정 팝업 목록
	 *
	 * @param -Delivery
	 * @return Collection<Delivery>
	 * @author moon
	 * @since 2021. 04. 19
	 */
	@Transactional("shopTxnManager")
	public Collection<Delivery> getDeliveryLocStockList(Delivery delivery) {
		Collection<Delivery> delvLocList = null;
		String goodsType    = "";
		String supplyCompCd = "";
		String tmpKey = "ITEM"+TsaSession.getInfo().getUserNo();
		
		/** 1. 주문상세번호에 대한 단품 리스트 조회 */
		Collection<Delivery>  itemList = deliveryDao.getOrdDtlNoItemList(delivery);
		
		/** 2. 임시 테이블 삭제                         */
		Delivery tempKey = new Delivery();
		tempKey.setUseGb(tmpKey);
		deliveryDao.deleteTbDeliveryLocTmp(tempKey);
		
		/** 3. 실재고 조회   && 임시 테이블 저장   */
		for(Delivery item : itemList) {
			Integer productNo = item.getProductNo();
			String skuCode    = item.getOptCd();
			String styleCd    = item.getGoodsCd();
			String itemCd     = item.getItemCd();
			String colorCd    = item.getOptCd1();
			String sizeCd     = item.getOptCd2();
			supplyCompCd = item.getSupplyCompCd();
			// 실재고 조회 
			Collection<WmsDelivery> stockList = wmsService.getRealStock(productNo, skuCode, itemCd, colorCd, sizeCd);
			
			if(stockList != null ) {
				for(WmsDelivery relStock : stockList) {
					item.setDelvLocCd(relStock.getStockLoc());
					item.setLocQty(relStock.getLocQty());
					item.setUseGb(tmpKey);
					if(relStock.getLocQty() >= item.getOrdQty()) {
						if("G056_S".equals(item.getGoodsType())) {
							goodsType = "G056_S";
							// 세트 상품일경우 임시테이블 저장 ( 재고수와  주문수량 나눈값의 최소값 저장 )
							deliveryDao.insertTbDeliveryLocSetTmp(item);
						} else {
							// 일반 상품일경우 임시테이블 저장 ( 재고수와  주문수량 나눈값의 최소값 저장 )
							deliveryDao.insertTbDeliveryLocTmp(item);
						}
					}
				}
			}
		}
		
		if("G056_S".equals(goodsType)) {
			
			// 임시테이블 MAX(GOODS_LOC_SET_CNT) 조회 
			Delivery tmep = new Delivery();
			tmep.setUseGb(tmpKey);
			int setCnt = deliveryDao.getDeliveryLocTmpGoodsSetMaxCnt(tmep);
			
			// 임시테이블  세트갯수 비교  세트 있는 모든 매장 업데이트
			if(itemList.size() == setCnt ) {
				Delivery tmp = new Delivery();
				tmp.setOrdDtlNo(delivery.getOrdDtlNo());
				tmp.setGoodsLocSetCnt(setCnt);
				tmp.setUseGb(tmpKey);
				deliveryDao.updateTbDeliveryLocSetTmp(tmp);
			}			
		}
		
		/** 5. 재고 있는 출고처만 조회  */
		delivery.setGoodsLocCnt(itemList.size());
		delivery.setSupplyCompCd(supplyCompCd);
		delivery.setUseGb(tmpKey);
		delvLocList = deliveryDao.getOrdDtlAssignLocList(delivery);
		
		return delvLocList;
	}
	

	/**
	 * 출고처지정 처리
	 *
	 * @param Delivery
	 * @return
	 * @author moon
	 * @since 2021. 04. 20
	 */
	@Transactional("shopTxnManager")
	public int saveDeliveryLocAssign(Delivery delivery) {
		int succ =0;
		Integer userNo = TsaSession.getInfo().getUserNo();
		delivery.setRegNo(userNo);
		delivery.setUpdNo(userNo);
		
		
		// 주문상세 조회 
		Collection<Delivery> itemList = deliveryDao.getOrdDtlItemList(delivery);
		Delivery chk = itemList.iterator().next();
		if(OrderDetailStat.PAYMENT_COMPLETE.value().equals(chk.getOrdDtlStat())) {

			// 출고처지정 등록  (출고처가 창고이면  수락여부 Y:수락  아니면 P:대기)
			if(TsaConstants.DeliveryClassification.WARE_HOUSE.value().equals(delivery.getDelvLocClsf())) {
				delivery.setDelvArGb("Y");
			} else {
				delivery.setDelvArGb("P");
			}
			delivery.setLocQty(0);
			deliveryDao.createDeliveryAssign(delivery);
			
			// 출고처지정 이력 등록 
			deliveryDao.createDeliveryAssignHst(delivery);
			
			// 주문상세 출고처 및 상태 업데이트
			delivery.setOrdDtlStat(OrderDetailStat.DELIVERY_LOC_ASSIGN.value());
			deliveryDao.updateOrdDtlDelvCd(delivery);
	
			// 주문상세이력
			Order order = new Order();
			order.setOrdDtlNo(delivery.getOrdDtlNo());
			order.setUpdNo(userNo);
			order.setRegNo(userNo);
			orderDao.createOrderDetailHst(order);		
			
			// 창고일경우 와 매장일경우  분리해서 재고지연테이블에 등록    
			if(TsaConstants.DeliveryClassification.WARE_HOUSE.value().equals(delivery.getDelvLocClsf())) {
				for(Delivery item : itemList) {
					item.setOrdQty(item.getItemQty());
					wmsWithdrawService.insertWmsTbIfDelifixQty(item);
				}
			} else {
	//			for(Delivery item : itemList) {
	//				// 매장쪽 
	//			}
			}
			succ =1;
		}
		
		return succ;
	}
	
	/**
	 * 출고처지정 취소
	 *
	 * @param Delivery
	 * @return void
	 * @author moon
	 * @since 2021. 04. 20
	 */
	@Transactional("shopTxnManager")
	public void cancelAssignDelvLoc(Delivery delivery) {
		log.info("delivery {}"+delivery);
		Integer userId = TsaSession.getInfo().getUserNo();
		
		//1. 창고 매장 구분  지연재고 삭제 
		if(TsaConstants.DeliveryClassification.WARE_HOUSE.value().equals(delivery.getDelvLocClsf())) {
			wmsWithdrawService.deleteWmsTbIfDelifixQty(delivery);
		} else {  // 매장일때 
			
		}
		
		//2. 출고처지정 삭제 
		deliveryDao.deleteTbDeliveryAssign(delivery);
		
		//3. 주문상세 출고처지정 초기화  및 주문상세 이력 
		delivery.setRegNo(userId);
		delivery.setUpdNo(userId);
		delivery.setOrdDtlStat(OrderDetailStat.PAYMENT_COMPLETE.value());
		deliveryDao.cancelAssignDelvLoc(delivery);
		
		//4. 주문상세이력
		Order order = new Order();
		order.setOrdDtlNo(delivery.getOrdDtlNo());
		order.setUpdNo(userId);
		order.setRegNo(userId);
		orderDao.createOrderDetailHst(order);		
	}
	
	/**
	 * 교환배송미출고대상 목록
	 *
	 * @param -Delivery
	 * @return Collection<Delivery>
	 * @author jsh77b
	 * @since 2021. 06. 07
	 */
	public Collection<Delivery> getExchangeDelvFailList(Delivery delivery) {
		return deliveryDao.getExchangeDelvFailList(delivery);
	}
	
}
