package com.style24.front.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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.style24.core.support.env.TscConstants;
import com.style24.front.biz.dao.TsfDisplayDao;
import com.style24.front.biz.dao.TsfGoodsDao;
import com.style24.front.biz.thirdparty.EigeneaiApi;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.CardPromotion;
import com.style24.persistence.domain.Cate4Srch;
import com.style24.persistence.domain.Delivery;
import com.style24.persistence.domain.Freegift;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.GoodsCompose;
import com.style24.persistence.domain.GoodsContents;
import com.style24.persistence.domain.GoodsDesc;
import com.style24.persistence.domain.GoodsImg;
import com.style24.persistence.domain.GoodsNotiInfo;
import com.style24.persistence.domain.GoodsSafeNo;
import com.style24.persistence.domain.GoodsSearch;
import com.style24.persistence.domain.GoodsStock;
import com.style24.persistence.domain.GoodsVideo;
import com.style24.persistence.domain.GoodsViewHst;
import com.style24.persistence.domain.Measurement;
import com.style24.persistence.domain.MeasurementStyle;
import com.style24.persistence.domain.Notice;
import com.style24.persistence.domain.ReinboundInform;
import com.style24.persistence.domain.SizeInfo;
import com.style24.persistence.domain.Tmtb;
import com.style24.persistence.domain.eigene.Eigeneai;
import com.style24.persistence.domain.searchengine.SearchEngine;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;

/**
 * 상품 Service
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Service
@Slf4j
public class TsfGoodsService {

	@Autowired
	private TsfGoodsDao goodsDao;

	@Autowired
	private TsfCouponService couponService;

	@Autowired
	private TsfDisplayDao displayDao;

	@Autowired
	private ObjectMapper mapper;

	@Autowired
	private EigeneaiApi eigeneaiApi;

	/**
	 * 상품뷰이력 생성
	 *
	 * @param goodsCd - 상품코드
	 * @param ithrCd - 유입코드
	 * @return
	 * @author eskim
	 * @since 2021. 2. 09
	 */
	@Transactional("shopTxnManager")
	public void createGoodsViewHst(String goodsCd, String ithrCd) {
		// 상품뷰이력 생성
		GoodsViewHst goodsViewHst = new GoodsViewHst();
		goodsViewHst.setGoodsCd(goodsCd);
		goodsViewHst.setJsessionId(TsfSession.getSessionId());
		goodsViewHst.setSiteCd(TscConstants.Site.STYLE24.value());
		goodsViewHst.setFrontGb(TsfSession.getFrontGb());
		goodsViewHst.setAfLinkCd(ithrCd);
		String referer = TsfSession.getHttpServletRequest().getHeader("Referer");
		if (StringUtils.isNotBlank(referer)) {
			byte[] referBytes = referer.getBytes();
			if (referBytes.length > 1000) {
				goodsViewHst.setReferer(new String(referBytes, 0, 1000));
			} else {
				goodsViewHst.setReferer(referer);
			}
		}

		if (TsfSession.getInfo() != null) {
			goodsViewHst.setCustNo(TsfSession.getInfo().getCustNo());
		}

		goodsDao.createGoodsViewHst(goodsViewHst);
	}

	/**
	 * 상품 네비게이션 조회
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 02. 09
	 */
	public Cate4Srch getGoodsNavigation(Goods goods) {
		return goodsDao.getGoodsNavigation(goods);
	}

	/**
	 * 상품 정보 조회
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 01. 28
	 */
	public Goods getGoodsInfo(Goods goods) {
		return goodsDao.getGoodsInfo(goods);
	}

	/**
	 * 상품 DESC 조회
	 *
	 * @param resultGoods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 17
	 */
	public Goods getGoodsDesc(Goods resultGoods) {

		GoodsDesc goods = new GoodsDesc();
		goods.setGoodsCd(resultGoods.getGoodsCd());

		//상품상세 구분(10:상품타이틀,20:상품타이틀내용,30:상품특징,40:상위컨텐츠,50:하위컨텐츠,60:상위컨텐츠-모바일,70:하위컨텐츠-모바일,80:상품상세(as-is,입점))

		// 상품타이틀
		goods.setDescGb("10");
		String goodsTitle = this.getGoodsDescList(goods);
		resultGoods.setGoodsTitle(goodsTitle);
		// 상품타이틀내용
		goods.setDescGb("20");
		String goodsTitleDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsTitleDesc(goodsTitleDesc);
		// 상품특징
		goods.setDescGb("30");
		String goodsSpecialDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsSpecialDesc(goodsSpecialDesc);

		if ("P".equals(TsfSession.getFrontGb())) {
			// 상품 상세 pc 상단
			goods.setDescGb("40");
			String goodsPcTopDesc = this.getGoodsDescList(goods);
			resultGoods.setGoodsTopDesc(goodsPcTopDesc);

			// 상품 상세 pc 하단
			goods.setDescGb("50");
			String goodsPcDownDesc = this.getGoodsDescList(goods);
			resultGoods.setGoodsDownDesc(goodsPcDownDesc);

		} else {
			// 상품 상세 mobile 상단
			goods.setDescGb("60");
			String goodsMobileTopDesc = this.getGoodsDescList(goods);
			resultGoods.setGoodsTopDesc(goodsMobileTopDesc);

			// 상품 상세 mpbile 하단
			goods.setDescGb("70");
			String goodsMobileDownDesc = this.getGoodsDescList(goods);
			resultGoods.setGoodsDownDesc(goodsMobileDownDesc);
		}

		// 상품특징
		goods.setDescGb("80");
		String goodsDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsDesc(goodsDesc);

		return resultGoods;
	}

	/**
	 * 상품 상세 정보 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 17
	 */
	private String getGoodsDescList(GoodsDesc goods) {
		Collection<GoodsDesc> goodsDescList = goodsDao.getGoodsDescList(goods);
		StringBuilder goodsDesc = new StringBuilder();
		if (goodsDescList != null && !goodsDescList.isEmpty()) {
			for (GoodsDesc tmpGoodsDesc : goodsDescList) {
				goodsDesc.append(tmpGoodsDesc.getGoodsDesc());
			}
		}
		return goodsDesc.toString();
	}

	/**
	 * 상품 이미지 정보
	 *
	 * @param goodsCd
	 * @return
	 * @author eskim
	 * @since 2021. 2. 9
	 */
	public Collection<GoodsImg> getGoodsImgList(Goods goods) {
		return goodsDao.getGoodsImgList(goods);
	}

	/**
	 * 상품 동영상정보
	 *
	 * @param goodsCd
	 * @return
	 * @author eskim
	 * @since 2021. 2. 9
	 */
	public Collection<GoodsVideo> getVideoList(GoodsVideo goodsVideo) {
		return goodsDao.getVideoList(goodsVideo);
	}

	/**
	 * 구성 상품 정보 조회
	 * @param goods
	 * @return
	 * @author xodud1202
	 * @since 2021. 01. 28
	 */
	public Goods getGoodsCompsInfo(Goods goods) {
		return goodsDao.getGoodsCompsInfo(goods);
	}

	/**
	 * 상품 재고 정보
	 * @param goodsStock
	 * @return
	 * @author xodud1202
	 * @since 2021. 01. 28
	 */
	public GoodsStock getGoodsStockInfo(GoodsStock goodsStock) {
		return goodsDao.getGoodsStockInfo(goodsStock);
	}

	/**
	 * 상품 재고 체크
	 * @param param
	 * goodsCd   (원상품코드) 필수
	 * goodsType (상품타입) 필수
	 * optCd     (옵션코드) 필수
	 * goodsQty  (확인 재고 수량) 필수
	 * itemCd    (세트 구성 상품코드) 세트
	 * @return String
	 * @author xodud1202
	 * @since 2021. 01. 28
	 */
	public String getCheckStock(GoodsStock param) {
		// 상품 마스터 정보 확인
		Goods goodsInfo = new Goods();
		goodsInfo.setGoodsCd(param.getGoodsCd());
		goodsInfo.setSiteCd(TscConstants.Site.STYLE24.value());
		goodsInfo = getGoodsInfo(goodsInfo);

		if (TscConstants.GoodsStat.SOLDOUT.value().equals(goodsInfo.getGoodsStat())) {
			return param.getGoodsCd() + "는 품절 상품입니다.";
		}

		if (param.getGoodsType().equals(TscConstants.GoodsType.SET.value())) {		// 세트상품이면 구성 상품코드로 조회
			Goods compsInfo = new Goods();
			compsInfo.setGoodsCd(param.getGoodsCd());
			compsInfo.setCompsGoodsCd(param.getItemCd());
			compsInfo.setGoodsType(param.getGoodsType());

			compsInfo = goodsDao.getGoodsCompsInfo(compsInfo);						// 구성상품 정보 조회

			if (TscConstants.GoodsStat.SOLDOUT.value().equals(compsInfo.getGoodsStat())) {
				return compsInfo.getGoodsNm() + " 상품은 품절입니다.";
			} else if (!TscConstants.GoodsStat.APPR.value().equals(compsInfo.getGoodsStat())) {
				return compsInfo.getGoodsNm() + " 상품은 구매할 수 없습니다.";
			}

			GoodsStock stockCheck = new GoodsStock();								// 재고 조회 결과
			stockCheck.setGoodsCd(param.getItemCd());
			stockCheck.setOptCd(param.getOptCd());

			stockCheck = goodsDao.getGoodsStockInfo(stockCheck);					// 구성 상품 재고 조회

			if (stockCheck == null) {
				return "재고체크 실패했습니다. 새로고침 후 다시 시도해주세요.";
			}

			if ("Y".equals(stockCheck.getSoldoutYn())) {
				return stockCheck.getOptCd2() + " 옵션은 품절입니다.";
			}

			if (param.getGoodsQty() * compsInfo.getQty() > stockCheck.getCurrStockQty()) {
				return compsInfo.getGoodsNm() + " 옵션의 재고가 충분하지 않습니다.";
			}
		} else {
			GoodsStock stockCheck = new GoodsStock();								// 재고 조회 결과
			stockCheck.setGoodsCd(param.getGoodsCd());
			stockCheck.setOptCd(param.getOptCd());

			stockCheck = goodsDao.getGoodsStockInfo(stockCheck);					// 구성 상품 재고 조회

			if (stockCheck == null) {
				return "재고체크 실패했습니다. 새로고침 후 다시 시도해주세요.";
			}

			if ("Y".equals(stockCheck.getSoldoutYn())) {
				return stockCheck.getOptCd2() + " 옵션은 품절입니다.";
			}

			if (param.getGoodsQty() > stockCheck.getCurrStockQty()) {
				return "옵션의 재고가 충분하지 않습니다.";
			}
		}

		return "SUCCESS";
	}

	/**
	 * 딜상품 구성상품정보 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 9
	 */
	public Collection<Goods> getGoodsDealComposeList(Goods goods) {
		return goodsDao.getGoodsDealComposeList(goods);
	}

	/**
	 * 상품 옵션1 목록
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 9
	 */
	public Collection<GoodsStock> getGoodsOption1List(Goods goods) {
		return goodsDao.getGoodsOption1List(goods);
	}

	/**
	 * 상품 옵션2 목록
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 9
	 */
	public Collection<GoodsStock> getGoodsOption2List(Goods goods) {
		return goodsDao.getGoodsOption2List(goods);
	}

	/**
	 * 상품 옵션 목록 - 입점용
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 3. 18
	 */
	public Collection<GoodsStock> getGoodsOptionList(Goods goods) {
		return goodsDao.getGoodsOptionList(goods);
	}

	/**
	 * 상품 고시정보
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 17
	 */
	public Collection<GoodsNotiInfo> getGoodsNotiList(Goods goods) {
		return goodsDao.getGoodsNotiList(goods);
	}

	/**
	 * 카드 혜택
	 *
	 * @param cardPromotion
	 * @return
	 * @author eskim
	 * @since 2021. 2. 17
	 */
	public Collection<CardPromotion> getCardPromotionList(CardPromotion cardPromotion) {
		return goodsDao.getCardPromotionList(cardPromotion);
	}

	/**
	 * 핫딜 상품 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 17
	 */
	public Goods getSocialGoods(Goods goods) {
		return goodsDao.getSocialGoods(goods);
	}

	/**
	 * 상품예약판매정보 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 2. 17
	 */
	public Goods getGoodsResSell(Goods resultGoods) {

		Goods goods = goodsDao.getGoodsResSell(resultGoods);
		if (goods != null) {
			resultGoods.setDelvResDt(goods.getDelvResDt());
		}

		return resultGoods;
	}

	/**
	 * 상품 사이즈 선택 시 재고수량 가져오기
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 7. 9
	 */
	public int getGoodsStockQty(GoodsStock goodsStock) {
		int result = 0;
		// 예약상품 여부 확인
		//int goodsResSellCount = goodsDao.getGoodsResSellCount(goodsStock.getGoodsCd());

		//if ("N".equals(goodsStock.getSelfGoodsYn()) || goodsResSellCount > 0) {
			result = goodsDao.getGoodsStockQty(goodsStock);
		//} else {
		//	result = goodsDao.getGoodsStoreStockQty(goodsStock);
		//}
		return result;
	}

	/**
	 * 세트 상품 사이즈 선택 시 재고수량 가져오기
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 3. 22
	 */
	public int getGoodsSetStockQty(GoodsStock goodsStock) {

//		input param
//		arrGoodsOption : goodsOption // [{goodsCd|optCd|qty},{goodsCd|optCd|qty}]
//		,minOrdQty : minOrdQty
//		,maxOrdQty : maxOrdQty
//		,goodsCd : mGoodsCd
//		,selfGoodsYn : selfGoodsYn

		int result = 0;
		int index = 0;	// 상품순서
		//int masterStoreCnt = 0;
		//boolean stockCheck = false;
		boolean returnFlag = false;
		//String[][] arrGoodsStoreList = null;	// 상품코드, 매장코드, 상품별 주문수량

		//log.info("[getGoodsSetStockQty] goodsStock = {}", goodsStock);

		// 예약상품 여부 확인
		//int goodsResSellCount = goodsDao.getGoodsResSellCount(goodsStock.getGoodsCd());

		int ableOrderCnt = 0;
		for (String arrGoodsCd : goodsStock.getArrGoodsOption()) {	// [{goodsCd|optCd|qty},{goodsCd|optCd|qty}]

			String[] goodsSizeInfo = arrGoodsCd.split("\\|");
			//log.info("[getGoodsSetStockQty] goodsSizeInfo = {}", goodsSizeInfo);
			if (goodsSizeInfo.length == 3) {

				GoodsStock tmpStock = new GoodsStock();
				tmpStock.setGoodsCd(goodsSizeInfo[0]);
				tmpStock.setOptCd(goodsSizeInfo[1]);
				int qty = Integer.parseInt(goodsSizeInfo[2]);	// 한번에 주문해야하는 상품수량
//				int stockByGoodsSize = goodsDao.getGoodsStockQty(tmpStock);
				int stockByGoodsSize = 0;
				//if ("N".equals(goodsStock.getSelfGoodsYn()) || goodsResSellCount > 0) {
					stockByGoodsSize = goodsDao.getGoodsStockQty(tmpStock);
				//} else {
				//	stockByGoodsSize = goodsDao.getGoodsStoreStockQty(tmpStock);
				//}

				//log.info("[getGoodsSetStockQty] stockByGoodsSize = {}", stockByGoodsSize);
				if (stockByGoodsSize <= 0) {
					returnFlag = true;
					break;
				} else {
					if (index == 0) {	//첫번째 상품 기준 생성
						ableOrderCnt = stockByGoodsSize / qty;	// 주문가능 횟수
					} else {
						int orderCnt = stockByGoodsSize / qty;	// 주문가능 횟수

						if (ableOrderCnt >= orderCnt) {
							ableOrderCnt = orderCnt;
						}
					}
				}
				//log.info("[getGoodsSetStockQty] ableOrderCnt = {}", ableOrderCnt);
			} else {
				returnFlag = true;
				break;
			}
			index++;
		}
		result = ableOrderCnt;	//주문 가능 수량

		if (returnFlag) {
			return 0;
		}

		if (goodsStock.getMinOrdQty() > result) {
			result = 0;
		}

		if (goodsStock.getMaxOrdQty() < result) {
			result = goodsStock.getMaxOrdQty();
		}

		return result;
	}

	/**
	 * 상품  공지 목록
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 03. 07
	 */
	public Collection<Notice> getGoodsNoticeList(Goods goods) {
		return goodsDao.getGoodsNoticeList(goods);
	}
	
	/**
	 * 상세용 컨텐츠 목록
	 * @param goodsContents
	 * @return
	 * @author eskim
	 * @since 2021. 07. 14
	 */
	public Collection<GoodsContents> getGoodsContentsList(GoodsContents goodsContents) {
		return goodsDao.getGoodsContentsList(goodsContents);
	}
	
	

	/**
	 * 상품  안전인증 정보
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 03. 07
	 */
	public GoodsSafeNo getGoodsSafeNo(Goods goods) {
		return goodsDao.getGoodsSafeNo(goods);
	}

	/**
	 * 상품  배송안내정보
	 * @param goodsCd
	 * @return
	 * @author eskim
	 * @since 2021. 03. 08
	 */
	public Delivery getGoodsDeliveryInfo(String goodsCd) {
		return goodsDao.getGoodsDeliveryInfo(goodsCd);
	}

	/**
	 * 상품 다다익선 목록
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 8
	 */
	public Collection<Goods> getTmtbGoodsList(Goods goods) {
		Integer[] arrTmtbSq = goods.getArrTmtbSq();		// 장바구니 다다익선 추천상품 적용을 위해 백업.
		goods.setArrTmtbSq(null);		// 배열 사용하여 진행시에 IN절에 걸려 query timeout 걸려 null처리
		Collection<Goods> result = new ArrayList<Goods>();

		Collection<Tmtb> tmtbSqList = goodsDao.getTmtbSqList(goods);
		if (tmtbSqList == null || tmtbSqList.isEmpty()) {
			return result;
		}
		//log.info("[tmtbSqList]={}",tmtbSqList);
		//log.info("[goods]={}",goods);
		int rCount = 0;	//다다익선 조회수
		int tCount = goods.getMaxRownum();	//리턴 잔여수
		if (tCount == 0) {
			tCount = 20;
		}

		// 상품상세 다다익선 조회 쿼리
		if(arrTmtbSq == null || arrTmtbSq.length < 1) {
			for (Tmtb tmtb : tmtbSqList) {
				goods.setTmtbSq(tmtb.getTmtbSq());
				Collection<Goods> tmtbGoodsList = goodsDao.getTmtbGoodsList(goods);
				if (tmtbGoodsList == null || tmtbGoodsList.isEmpty()) {
					continue;
				}

				if (tCount <= 0) { //잔여수가 없으면 종료
					break;
				}

				//다다익선 조회 상품 수
				rCount = tmtbGoodsList.size();

				if (tCount > rCount) { 	//조회수보다 잔여수가 클경우
					result.addAll(tmtbGoodsList);
					tCount = tCount - rCount; //남은 잔여수 계산
				} else {
					if (tCount == rCount) {	//잔여 수량과 조회수가 같은면 종료
						result.addAll(tmtbGoodsList);
						break;
					} else {

						for (int i = 0; i < tCount; i++) {  //잔여수량만큼 loop
							int tmtbGoodsListCnt = 0;
							for (Goods tmtbGoods : tmtbGoodsList) {
								if (i == tmtbGoodsListCnt) {
									result.add(tmtbGoods);
									tCount--;
									break;
								}
								tmtbGoodsListCnt++;
							}
						}
					}

				}
			}
		} else {		// 장바구니 다다익선 팝업 조회 쿼리
			for (int tmtb : arrTmtbSq) {
				if(tmtb > 0) {
					goods.setTmtbSq(tmtb);
					Collection<Goods> tmtbGoodsList = goodsDao.getTmtbGoodsList(goods);
					if (tmtbGoodsList == null || tmtbGoodsList.isEmpty()) {
						continue;
					}

					if (tCount <= 0) { //잔여수가 없으면 종료
						break;
					}

					//다다익선 조회 상품 수
					rCount = tmtbGoodsList.size();

					if (tCount > rCount) { 	//조회수보다 잔여수가 클경우
						result.addAll(tmtbGoodsList);
						tCount = tCount - rCount; //남은 잔여수 계산
					} else {
						if (tCount == rCount) {	//잔여 수량과 조회수가 같은면 종료
							result.addAll(tmtbGoodsList);
							break;
						} else {

							for (int i = 0; i < tCount; i++) {  //잔여수량만큼 loop
								int tmtbGoodsListCnt = 0;
								for (Goods tmtbGoods : tmtbGoodsList) {
									if (i == tmtbGoodsListCnt) {
										result.add(tmtbGoods);
										tCount--;
										break;
									}
									tmtbGoodsListCnt++;
								}
							}
						}

					}
				}
			}
		}

		return result;
	}

	/**
	 * 상품 추천상품 목록
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 8
	 */
	public Collection<Goods> getRecommendGoodsList(Goods goods) {
		return goodsDao.getRecommendGoodsList(goods);
	}

	/**
	 * 재입고 알림 미 알림 조회
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 10
	 */
	public ReinboundInform getNotReinboundInform(ReinboundInform reinboundInform) {
		return goodsDao.getNotReinboundInform(reinboundInform);
	}

	/**
	 * 재입고알림 생성
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 10
	 */
	@Transactional("shopTxnManager")
	public void createReinboundInform(ReinboundInform reinboundInform) {
		goodsDao.createReinboundInform(reinboundInform);
	}

	/**
	 * 재입고알림 수정
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 10
	 */
	@Transactional("shopTxnManager")
	public void updateReinboundInform(ReinboundInform reinboundInform) {
		goodsDao.updateReinboundInform(reinboundInform);
	}

	/**
	 * 재입고 알림 신청 저장
	 *
	 * @param reinboundInform
	 * @return void
	 * @author eskim
	 * @since 2021. 03. 17
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsInstockAlarmForm(ReinboundInform reinboundInform) {

		if (!TsfSession.isLogin()) {
			throw new IllegalStateException("로그인을 해야합니다.");
		}

		reinboundInform.setCustNo(TsfSession.getInfo().getCustNo());
		reinboundInform.setRegNo(TsfSession.getInfo().getCustNo());
		reinboundInform.setUpdNo(TsfSession.getInfo().getCustNo());

		// 미알림 조회
		ReinboundInform tmpReinboundInform = goodsDao.getNotReinboundInform(reinboundInform);

		if (tmpReinboundInform == null || tmpReinboundInform.getRinbdInfoSq() <= 0) {
			goodsDao.createReinboundInform(reinboundInform);
		} else {
			reinboundInform.setRinbdInfoSq(tmpReinboundInform.getRinbdInfoSq());
			goodsDao.updateReinboundInform(reinboundInform);
		}

	}

	/**
	 * 실측사이즈 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 10
	 */
	public Collection<Measurement> getMeasurementList(Goods goods) {

		return goodsDao.getMeasurementList(goods);
	}

	/**
	 * 실측사이즈 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 3. 10
	 */
	public Collection<MeasurementStyle> getMeasurementListNew(Goods goods) {
		GagaMap result = new GagaMap();
		// 행, 열 변환
		Collection<Measurement> measurementList = goodsDao.getMeasurementList(goods);
		Collection<MeasurementStyle> measurementStyleList = new ArrayList<MeasurementStyle>();

		if (measurementList == null || measurementList.isEmpty()) {
			return measurementStyleList;
		}

		int colSize = measurementList.size(); 	// 열 column
		int rowSize = 5; // 상의하위포함 최대사이즈

		String[][] arrMeasurementList = new String[rowSize + 1][colSize + 1];

		// 사이즈 설정
		int yIndex = 0;
		for (Measurement measurement : measurementList) {
			arrMeasurementList[0][0] = measurement.getTypecd();
			yIndex++;
			arrMeasurementList[0][yIndex] = measurement.getOptCd2();

			// 부위명 설정
			arrMeasurementList[1][0] = measurement.getTypecd();
			arrMeasurementList[2][0] = measurement.getTypecd();
			arrMeasurementList[3][0] = measurement.getTypecd();
			arrMeasurementList[4][0] = measurement.getTypecd();
			arrMeasurementList[5][0] = measurement.getTypecd();
			arrMeasurementList[1][yIndex] = String.valueOf(measurement.getValue1());
			arrMeasurementList[2][yIndex] = String.valueOf(measurement.getValue2());
			arrMeasurementList[3][yIndex] = String.valueOf(measurement.getValue3());
			arrMeasurementList[4][yIndex] = String.valueOf(measurement.getValue4());
			arrMeasurementList[5][yIndex] = String.valueOf(measurement.getValue5());

//			 arrMeasurementList = [[하의, 100, 110, 120, 130, 140, 150],
//			                       [하의, 42.0, 44.0, 46.0, 48.0, 52.0, 54.0],
//			                       [하의, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
//			                       [하의, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
//			                       [하의, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
//			                       [하의, 51.0, 60.0, 65.0, 75.0, 79.0, 87.0]]
//			                    	   
		}

		for (int i = 0; i < 6; i++) {
			MeasurementStyle measurementStyle = new MeasurementStyle();
			measurementStyle.setGoodsCd(goods.getGoodsCd());
			measurementStyle.setSizeCount(colSize);

			//log.info("arrMeasurementList[0].length = {}", arrMeasurementList[0].length);
			for (int j = 0; j < arrMeasurementList[0].length; j++) {
				switch (j) {
					case 0:
						measurementStyle.setTypecd(arrMeasurementList[i][j]);
						break;
					case 1:
						measurementStyle.setSize1(arrMeasurementList[i][j]);
						break;
					case 2:
						measurementStyle.setSize2(arrMeasurementList[i][j]);
						break;
					case 3:
						measurementStyle.setSize3(arrMeasurementList[i][j]);
						break;
					case 4:
						measurementStyle.setSize4(arrMeasurementList[i][j]);
						break;
					case 5:
						measurementStyle.setSize5(arrMeasurementList[i][j]);
						break;
					case 6:
						measurementStyle.setSize6(arrMeasurementList[i][j]);
						break;
					case 7:
						measurementStyle.setSize7(arrMeasurementList[i][j]);
						break;
					case 8:
						measurementStyle.setSize8(arrMeasurementList[i][j]);
						break;
					case 9:
						measurementStyle.setSize9(arrMeasurementList[i][j]);
						break;
					case 10:
						measurementStyle.setSize10(arrMeasurementList[i][j]);
						break;
					case 11:
						measurementStyle.setSize11(arrMeasurementList[i][j]);
						break;
					case 12:
						measurementStyle.setSize12(arrMeasurementList[i][j]);
						break;
					case 13:
						measurementStyle.setSize13(arrMeasurementList[i][j]);
						break;
					case 14:
						measurementStyle.setSize14(arrMeasurementList[i][j]);
						break;
					case 15:
						measurementStyle.setSize15(arrMeasurementList[i][j]);
						break;
					case 16:
						measurementStyle.setSize16(arrMeasurementList[i][j]);
						break;
					case 17:
						measurementStyle.setSize17(arrMeasurementList[i][j]);
						break;
					case 18:
						measurementStyle.setSize18(arrMeasurementList[i][j]);
						break;
					case 19:
						measurementStyle.setSize19(arrMeasurementList[i][j]);
						break;
					case 20:
						measurementStyle.setSize20(arrMeasurementList[i][j]);
						break;
				}
			}
			measurementStyleList.add(measurementStyle);
		}

		//log.info("measurementStyleList = {}", measurementStyleList);

		return measurementStyleList;
	}

	/**
	 * 사이즈 정보 조회
	 *
	 * @param sizeInfo
	 * @return
	 * @author eskim
	 * @date 2021. 3. 10
	 */
	public Collection<SizeInfo> getSizeInfoList(SizeInfo sizeInfo) {
		return goodsDao.getSizeInfoList(sizeInfo);
	}

	/**
	 * 상품 쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return int
	 * @author eskim
	 * @since 2021.03.15
	 */
	@Transactional("shopTxnManager")
	public String createGoodsCoupon(Goods goods) {
		return couponService.createGoodsCoupon(goods);
	}

	/**
	 * 세트상품 구성상품정보 조회
	 *
	 * @param
	 * @return
	 * @author eskim
	 * @since 2021. 3. 21
	 */
	public Collection<GoodsCompose> getGoodsSetComposeList(Goods goods) {
		Collection<GoodsCompose> getGoodsSetComposeList = goodsDao.getGoodsSetComposeList(goods);
		for (GoodsCompose goodsCompose : getGoodsSetComposeList) {
			Goods tmpGoods = new Goods();
			tmpGoods.setGoodsCd(goodsCompose.getCompsGoodsCd());
			tmpGoods.setSupplyCompCd(goods.getSupplyCompCd());
			tmpGoods.setFrontGb(goods.getFrontGb());
			tmpGoods.setIsApp(goods.getIsApp());
			tmpGoods.setSiteCd(goods.getSiteCd());
			tmpGoods.setCustGb(goods.getCustGb());
			tmpGoods.setCustNo(goods.getCustNo());

			// 상품상세
			Goods resultGoods = this.getGoodsDesc(tmpGoods);
			if (resultGoods != null) {
//				goodsCompose.setGoodsTitle(resultGoods.getGoodsTitle());
//				goodsCompose.setGoodsTitleDesc(resultGoods.getGoodsTitleDesc());
//				goodsCompose.setGoodsSpecialDesc(resultGoods.getGoodsSpecialDesc());
//				goodsCompose.setGoodsTopDesc(resultGoods.getGoodsTopDesc());
//				goodsCompose.setGoodsDownDesc(resultGoods.getGoodsDownDesc());
				goodsCompose.setGoodsDesc(resultGoods.getGoodsDesc());
			}

			// 상품 옵션1(색상) 정보
			goodsCompose.setGoodsOption1List(goodsDao.getGoodsOption1List(tmpGoods));
			// 상품 옵션2(사이즈) 정보
			//goodsExtend.setGoodsOption2List(goodsDao.getGoodsOption2List(tmpGoods));
			// 고시 정보
			goodsCompose.setGoodsNotiList(goodsDao.getGoodsNotiList(tmpGoods));
			// 이미지 정보
			goodsCompose.setGoodsImgList(goodsDao.getGoodsImgList(tmpGoods));
			// 상품 안전인증 정보
			goodsCompose.setGoodsSafeNo(goodsDao.getGoodsSafeNo(tmpGoods));

		}
		return getGoodsSetComposeList;
	}

	/**
	 * 상품의 다다익선 목록 
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 4. 11
	 */
	public Collection<Tmtb> getTmtbList(Goods goods) {
		return goodsDao.getTmtbList(goods);
	}

	/**
	 * 상품의 다다익선 목록 
	 * @param goods
	 * @return
	 * @author eskim
	 * @date 2021. 4. 13
	 */
	public Collection<Freegift> getFreeGoodsList(Goods goods) {
		return goodsDao.getFreeGoodsList(goods);
	}

	/**
	 * 컨텐츠카테고리상품 목록(메인용)
	 * @param cate - 카테고리 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 25
	 */
	public Collection<Goods> getContentsCategoryGoodsListMain(Cate4Srch cate) {
		cate.setSiteCd(TscConstants.Site.STYLE24.value());
		cate.setFrontGb(TsfSession.getFrontGb());
		cate.setCustGb(TsfSession.getCustGb());
		cate.setCustNo(TsfSession.isLogin() ? TsfSession.getInfo().getCustNo() : 0);

		Collection<Goods> goodsList = new ArrayList<>();

		if (cate.getContentsLoc().equals("SCM002") || cate.getContentsLoc().equals("SBM007") || cate.getContentsLoc().equals("SMM003") || cate.getContentsLoc().equals("SBM003") || cate.getContentsLoc().equals("SBMM007")) { // 신상품인 경우
			int maxRow = 20;
			if (cate.getContentsLoc().equals("SBM003")) {
				maxRow = 3;
			}

			goodsList = goodsDao.getContentsCategoryGoodsListMain(cate);

			// 조회된 데이터가 없거나 건수가 20개 미만이면 신규상품(=정상상품) 조회
			if (goodsList == null || goodsList.size() < maxRow) {
				if (goodsList != null) {
					// 제외상품 설정
					StringBuilder sb = new StringBuilder();
					for (Goods goods : goodsList) {
						sb.append(goods.getGoodsCd()).append(",");
					}
					if (sb != null && !sb.toString().equals("")) {
						cate.setExceptGoodsArr(sb.toString().substring(0, sb.toString().length() - 1).split(","));
					}
				}
				maxRow = maxRow - goodsList.size();
				cate.setMaxRow(maxRow);
				cate.setCateGb("G032_101");
				if (cate.getContentsLoc().equals("SMM003") || cate.getContentsLoc().equals("SBM003") || cate.getContentsLoc().equals("SBM007")) {
					cate.setCate1No(null);
				}

				if (cate.getContentsLoc().equals("SCM002")) {
					goodsList.addAll(goodsDao.getCategoryMainNewGoodsList(cate));
				} else {
					goodsList.addAll(goodsDao.getContentsCategoryNewGoodsList(cate));
				}
			}
		} else if (cate.getContentsLoc().equals("SCM003") || cate.getContentsLoc().equals("SBM008") || cate.getContentsLoc().equals("SBM009") || cate.getContentsLoc().equals("SOM003") || cate.getContentsLoc().equals("SOM002")) { // 베스트상품인 경우
			// TODO: 추천솔루션
			int dispCnt = cate.getMaxRow();

			goodsList = goodsDao.getContentsCategoryGoodsListMain(cate);
			// 수동설정 데이터 없거나 노출갯수보다 작으면 추천솔루션 데이터 표출
			if(dispCnt > goodsList.size()){
				int cnt = 0;
				cnt = dispCnt - goodsList.size();

				// TODO : 추천솔루션
				Collection<Eigeneai.Result> itemList = new ArrayList<>();
				if(cate.getContentsLoc().equals("SCM003")){
					itemList = eigeneaiApi.getCategoryWeeklySellBestGoodsList(cnt, cate.getCate1No());
				}else if(cate.getContentsLoc().equals("SBM008")){
					itemList = eigeneaiApi.getBrandWeeklySellBestGoodsList(cnt, cate.getBrandGroupNo());
				}else if(cate.getContentsLoc().equals("SBM009")){
					itemList = eigeneaiApi.getBrandMonthlyClickBestGoodsList(cnt, cate.getBrandGroupNo());
				}else if(cate.getContentsLoc().equals("SOM002")){
					itemList = eigeneaiApi.getOutletMonthlyClickBestGoodsList(cnt);
				}else{
					// SOM003 아울렛 베스트
					itemList = eigeneaiApi.getOutletWeeklySellBestGoodsList(cnt);
				}

				for(Eigeneai.Result tempData: itemList){
					Goods tempBest = new Goods();
					tempBest.setBrandGroupNm(tempData.getProduct().getBrandName());
					tempBest.setGoodsCd(tempData.getProduct().getItemId());
					tempBest.setGoodsFullNm(tempData.getProduct().getItemName());
					tempBest.setListPrice((int) tempData.getProduct().getOriginalPrice());
					tempBest.setCurrPrice((int) tempData.getProduct().getSalePrice());
					tempBest.setSysImgNm(tempData.getProduct().getItemImage());
					tempBest.setItemUrl(tempData.getProduct().getItemUrl());
					goodsList.add(tempBest);
				}
			}

			for (Goods temp : goodsList) {
				if (temp.getSizes() != null) {
					temp.setSizeArr(temp.getSizes().split(","));
				}
				if (temp.getColorChips() != null) {
					temp.setColorArr(temp.getColorChips().split(","));
				}
				if (temp.getIcon() != null) {
					temp.setBenefitArr(temp.getIcon().split(","));
				}
			}
		} else if (cate.getContentsLoc().equals("SBM013") || cate.getContentsLoc().equals("SBMM013")) {
			GoodsSearch goodsSearch = new GoodsSearch();
			goodsSearch.setSiteCd(TscConstants.Site.STYLE24.value());
			goodsSearch.setCateGb("G032_101");
			goodsSearch.setFrontGb(TsfSession.getFrontGb());
			goodsSearch.setFormalGb(cate.getFormalGb());
			goodsSearch.setCustGb(cate.getCustGb());
			goodsSearch.setCustNo(cate.getCustNo());
			goodsSearch.setBrandGroupNo(cate.getBrandGroupNo());
			goodsSearch.setMaxRow(cate.getMaxRow());
			goodsList = goodsDao.getBrandNewGoodsList(goodsSearch);

			for (Goods temp : goodsList) {
				if (temp.getSizes() != null) {
					temp.setSizeArr(temp.getSizes().split(","));
				}
				if (temp.getColorChips() != null) {
					temp.setColorArr(temp.getColorChips().split(","));
				}
				if (temp.getBenefits() != null) {
					temp.setBenefitArr(temp.getBenefits().split(","));
				}
			}
		} else {
			goodsList = goodsDao.getContentsCategoryGoodsListMain(cate);
		}

		return goodsList;
	}
	
	/**
	 * 컨텐츠카테고리상품 목록
	 * @param cate - 카테고리 정보
	 * @return
	 * @author jmh
	 * @since 2021. 8. 13
	 */
	public Collection<Goods> getContentsCategoryGoodsList(Cate4Srch cate) {
		cate.setSiteCd(TscConstants.Site.STYLE24.value());
		cate.setFrontGb(TsfSession.getFrontGb());
		cate.setCustGb(TsfSession.getCustGb());
		cate.setCustNo(TsfSession.isLogin() ? TsfSession.getInfo().getCustNo() : 0);

		Collection<Goods> goodsList = new ArrayList<>();

		if (cate.getContentsLoc().equals("SCM002") || cate.getContentsLoc().equals("SBM007") || cate.getContentsLoc().equals("SMM003") || cate.getContentsLoc().equals("SBM003") || cate.getContentsLoc().equals("SBMM007")) { // 신상품인 경우
			int maxRow = 20;
			if (cate.getContentsLoc().equals("SBM003")) {
				maxRow = 3;
			}

			goodsList = goodsDao.getContentsCategoryGoodsList(cate);

			// 조회된 데이터가 없거나 건수가 20개 미만이면 신규상품(=정상상품) 조회
			if (goodsList == null || goodsList.size() < maxRow) {
				if (goodsList != null) {
					// 제외상품 설정
					StringBuilder sb = new StringBuilder();
					for (Goods goods : goodsList) {
						sb.append(goods.getGoodsCd()).append(",");
					}
					if (sb != null && !sb.toString().equals("")) {
						cate.setExceptGoodsArr(sb.toString().substring(0, sb.toString().length() - 1).split(","));
					}
				}
				maxRow = maxRow - goodsList.size();
				cate.setMaxRow(maxRow);
				cate.setCateGb("G032_101");
				if (cate.getContentsLoc().equals("SMM003") || cate.getContentsLoc().equals("SBM003") || cate.getContentsLoc().equals("SBM007")) {
					cate.setCate1No(null);
				}

				if (cate.getContentsLoc().equals("SCM002")) {
					goodsList.addAll(goodsDao.getCategoryMainNewGoodsList(cate));
				} else {
					goodsList.addAll(goodsDao.getContentsCategoryNewGoodsList(cate));
				}
			}
		} else if (cate.getContentsLoc().equals("SCM003") || cate.getContentsLoc().equals("SBM008") || cate.getContentsLoc().equals("SBM009") || cate.getContentsLoc().equals("SOM003") || cate.getContentsLoc().equals("SOM002")) { // 베스트상품인 경우
			// TODO: 추천솔루션
			int dispCnt = cate.getMaxRow();

			goodsList = goodsDao.getContentsCategoryGoodsList(cate);
			// 수동설정 데이터 없거나 노출갯수보다 작으면 추천솔루션 데이터 표출
			if(dispCnt > goodsList.size()){
				int cnt = 0;
				cnt = dispCnt - goodsList.size();

				// TODO : 추천솔루션
				Collection<Eigeneai.Result> itemList = new ArrayList<>();
				if(cate.getContentsLoc().equals("SCM003")){
					itemList = eigeneaiApi.getCategoryWeeklySellBestGoodsList(cnt, cate.getCate1No());
				}else if(cate.getContentsLoc().equals("SBM008")){
					itemList = eigeneaiApi.getBrandWeeklySellBestGoodsList(cnt, cate.getBrandGroupNo());
				}else if(cate.getContentsLoc().equals("SBM009")){
					itemList = eigeneaiApi.getBrandMonthlyClickBestGoodsList(cnt, cate.getBrandGroupNo());
				}else if(cate.getContentsLoc().equals("SOM002")){
					itemList = eigeneaiApi.getOutletMonthlyClickBestGoodsList(cnt);
				}else{
					// SOM003 아울렛 베스트
					itemList = eigeneaiApi.getOutletWeeklySellBestGoodsList(cnt);
				}

				for(Eigeneai.Result tempData: itemList){
					Goods tempBest = new Goods();
					tempBest.setBrandGroupNm(tempData.getProduct().getBrandName());
					tempBest.setGoodsCd(tempData.getProduct().getItemId());
					tempBest.setGoodsFullNm(tempData.getProduct().getItemName());
					tempBest.setListPrice((int) tempData.getProduct().getOriginalPrice());
					tempBest.setCurrPrice((int) tempData.getProduct().getSalePrice());
					tempBest.setSysImgNm(tempData.getProduct().getItemImage());
					tempBest.setItemUrl(tempData.getProduct().getItemUrl());
					goodsList.add(tempBest);
				}
			}

			for (Goods temp : goodsList) {
				if (temp.getSizes() != null) {
					temp.setSizeArr(temp.getSizes().split(","));
				}
				if (temp.getColorChips() != null) {
					temp.setColorArr(temp.getColorChips().split(","));
				}
				if (temp.getIcon() != null) {
					temp.setBenefitArr(temp.getIcon().split(","));
				}
			}
		} else if (cate.getContentsLoc().equals("SBM013") || cate.getContentsLoc().equals("SBMM013")) {
			GoodsSearch goodsSearch = new GoodsSearch();
			goodsSearch.setSiteCd(TscConstants.Site.STYLE24.value());
			goodsSearch.setCateGb("G032_101");
			goodsSearch.setFrontGb(TsfSession.getFrontGb());
			goodsSearch.setFormalGb(cate.getFormalGb());
			goodsSearch.setCustGb(cate.getCustGb());
			goodsSearch.setCustNo(cate.getCustNo());
			goodsSearch.setBrandGroupNo(cate.getBrandGroupNo());
			goodsSearch.setMaxRow(cate.getMaxRow());
			goodsList = goodsDao.getBrandNewGoodsList(goodsSearch);

			for (Goods temp : goodsList) {
				if (temp.getSizes() != null) {
					temp.setSizeArr(temp.getSizes().split(","));
				}
				if (temp.getColorChips() != null) {
					temp.setColorArr(temp.getColorChips().split(","));
				}
				if (temp.getBenefits() != null) {
					temp.setBenefitArr(temp.getBenefits().split(","));
				}
			}
		} else {
			goodsList = goodsDao.getContentsCategoryGoodsList(cate);
		}

		return goodsList;
	}

	/**
	 * ep쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return int
	 * @author eskim
	 * @since 2021.04.15
	 */
	@Transactional("shopTxnManager")
	public String createEpCoupon(Goods goods) {
		return couponService.createEpCoupon(goods);
	}

	/**
	 * 카테고리별 상품수
	 * @param params - 검색엔진 정보
	 * @return
	 * @author bin2107
	 * @date 2021. 4. 7
	 */
	public int getCategoryGoodsCount(SearchEngine params) {
		return goodsDao.getCategoryGoodsCount(params);
	}

	/**
	 * 카테고리별 상품 목록
	 * @param params - 검색엔진 정보
	 * @return
	 * @author bin2107
	 * @date 2021. 4. 8
	 */
	public Collection<SearchEngine> getCategoryGoodsList(SearchEngine params) {
		return goodsDao.getCategoryGoodsList(params);
	}

	/**
	 * 검색상품 총건수
	 * @param params - 검색엔진 정보
	 * @return
	 * @author gagamel
	 * @date 2021. 5. 6
	 */
	public int getSearchGoodsCount(SearchEngine params) {
		return goodsDao.getSearchGoodsCount(params);
	}

	/**
	 * 검색상품 목록
	 * @param params - 검색엔진 정보
	 * @return
	 * @author gagamel
	 * @date 2021. 5. 6
	 */
	public Collection<SearchEngine> getSearchGoodsList(SearchEngine params) {
		return goodsDao.getSearchGoodsList(params);
	}
	
	
	/**
	 * 상품 다른 색상의 productno 찾기
	 * @param goods - 상품정보
	 * @return
	 * @author eskim
	 * @date 2021. 7. 28
	 */
	public Collection<GoodsStock> getProductNoByGoodsColor(Goods goods) {
		return goodsDao.getProductNoByGoodsColor(goods);
	}

}
