package com.style24.front.biz.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.rest.server.GagaResponse;
import com.gagaframework.web.rest.server.GagaResponseStatus;
import com.gagaframework.web.util.GagaCookieUtil;
import com.style24.core.biz.service.TscEnvsetService;
import com.style24.core.biz.service.TscLookbookService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.front.biz.service.TsfCounselService;
import com.style24.front.biz.service.TsfCouponService;
import com.style24.front.biz.service.TsfDisplayService;
import com.style24.front.biz.service.TsfGoodsService;
import com.style24.front.biz.service.TsfRecentlyGoodsService;
import com.style24.front.biz.service.TsfRendererService;
import com.style24.front.biz.service.TsfReviewService;
import com.style24.front.biz.service.TsfWishlistService;
import com.style24.front.biz.thirdparty.EigeneaiApi;
import com.style24.front.biz.thirdparty.SearchEngineDiquest;
import com.style24.front.support.controller.TsfBaseController;
import com.style24.front.support.env.TsfConstants;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.CardPromotion;
import com.style24.persistence.domain.CommonCode;
import com.style24.persistence.domain.Counsel;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.GoodsContents;
import com.style24.persistence.domain.GoodsStock;
import com.style24.persistence.domain.GoodsVideo;
import com.style24.persistence.domain.Lookbook;
import com.style24.persistence.domain.Measurement;
import com.style24.persistence.domain.MeasurementStyle;
import com.style24.persistence.domain.RecentlyGoods;
import com.style24.persistence.domain.ReinboundInform;
import com.style24.persistence.domain.Review;
import com.style24.persistence.domain.SizeInfo;
import com.style24.persistence.domain.WishList;
import com.style24.persistence.domain.eigene.Eigeneai.Result;
import com.style24.persistence.domain.searchengine.FeedbackResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 상품 Controller
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Controller
@RequestMapping("/goods")
@Slf4j
public class TsfGoodsController extends TsfBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsfGoodsService goodsService;

	@Autowired
	private TscEnvsetService envsetService;

	@Autowired
	private TsfCounselService counselService;

	@Autowired
	private TscLookbookService coreLookbookService;

	@Autowired
	private TsfCouponService couponService;

	@Autowired
	private TsfReviewService reviewService;

	@Autowired
	private TsfRendererService rendererService;

	@Autowired
	private TsfWishlistService wishListService;

	@Autowired
	private TsfDisplayService displayService;

	@Value("${has-ssl}")
	private String hasSsl;

	@Autowired
	private TsfRecentlyGoodsService recentlyGoodsService;

	@Autowired
	private EigeneaiApi eigeneaiApi;

	@Autowired
	private SearchEngineDiquest diquest;

	/**
	 * 상품상세
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 7. 4
	 */
	@GetMapping("/detail/form")
	public ModelAndView detail(Goods paramsGoods) {

		ModelAndView mav = new ModelAndView();
		log.info("detail paramsGoods::::{}",paramsGoods);

		// 연관검색 로그 쌓기 추가 21.07.20
		FeedbackResponse responseFb = diquest.sendFeedbackLog(paramsGoods.getKeyword() ,paramsGoods.getSearchId());
		log.info("responseFb::::{}",responseFb);

		String afLinkCd = paramsGoods.getAfLinkCd();
		
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(paramsGoods);

		String mobileYn = paramsGoods.getMobileYn();
		if ("Y".equals(mobileYn)) {
			paramsGoods.setFrontGb("M");
		}
		
		if (StringUtils.isBlank(paramsGoods.getGoodsCd())) {
//			if (StringUtils.isBlank(afLinkCd)) {
//				mav.setViewName("redirect:/display/mall/main/form");
//			} else {
//				mav.setViewName("redirect:/display/mall/main/form?af=" + afLinkCd);
//			}
			if ("Y".equals(mobileYn)) {
				mav.setViewName("mob/goods/Goods404FormMob");
			} else {
				mav.setViewName(super.getDeviceViewName("goods/Goods404Form"));
			}
			return mav;
		}

		
		Goods goods = goodsService.getGoodsInfo(paramsGoods);
		if (goods == null || goods.getGoodsCd().isEmpty()) {
//			if (StringUtils.isBlank(afLinkCd)) {
//				mav.setViewName("redirect:/display/mall/main/form");
//			} else {
//				mav.setViewName("redirect:/display/mall/main/form?af=" + afLinkCd);
//			}
			if ("Y".equals(mobileYn)) {
				mav.setViewName("mob/goods/Goods404FormMob");
			} else {
				mav.setViewName(super.getDeviceViewName("goods/Goods404Form"));
			}
			return mav;
		}

		// 조회색상이 없으면 메인컬러 설정
		if (StringUtils.isEmpty(paramsGoods.getColorCd())) {
			paramsGoods.setColorCd(goods.getMainColorCd());
			paramsGoods.setOptCd1(goods.getMainColorCd());
		}else if ("null".equals(paramsGoods.getColorCd())) {
			paramsGoods.setColorCd(goods.getMainColorCd());
			paramsGoods.setOptCd1(goods.getMainColorCd());
		}else {
			paramsGoods.setOptCd1(paramsGoods.getColorCd());
		}

		paramsGoods.setSelfGoodsYn(goods.getSelfGoodsYn());
		if (TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType()) || TscConstants.GoodsType.SET.value().equals(goods.getGoodsType())) {
			paramsGoods.setColorCd("XX");
		}

		// 상품 상세
		goods = goodsService.getGoodsDesc(goods);

		// 핫딜정보
		Goods socialGoods = goodsService.getSocialGoods(paramsGoods);
		if (socialGoods != null && !StringUtils.isBlank(socialGoods.getGoodsCd())) {
			goods.setSocialSq(socialGoods.getSocialSq());
			goods.setSocialTnm(socialGoods.getSocialTnm());
			goods.setSocialEddt(socialGoods.getSocialEddt());
		}
		// 예약판매정보
		goods = goodsService.getGoodsResSell(goods);

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);
		// 상품 네비정보
		paramsGoods.setCateGb("G032_101"); 		//by item
		mav.addObject("goodsNavigation", goodsService.getGoodsNavigation(paramsGoods));
		// 상품 이미지정보
		mav.addObject("goodsImgList", goodsService.getGoodsImgList(paramsGoods));
		// 상품 동영상정보
		GoodsVideo goodsVideo = new GoodsVideo();
		goodsVideo.setGoodsCd(paramsGoods.getGoodsCd());
		goodsVideo.setMaxRownum(1);
		mav.addObject("goodsVideoList", goodsService.getVideoList(goodsVideo));
		
		
		int goodsReviewCnt = 0;
		if (TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType())) {	// 딜상품

			Collection<Goods> goodsDealComposeList = goodsService.getGoodsDealComposeList(paramsGoods);
			// 딜 구성상품 정보
			mav.addObject("goodsDealComposeList", goodsDealComposeList);

			Collection<Coupon> goodsCouponList = new ArrayList<Coupon>();
			ArrayList<String> arrGoodsList = new ArrayList<>();
			// 상품쿠폰
			if (goodsDealComposeList != null && !goodsDealComposeList.isEmpty()) {
				for (Goods goodsCompose : goodsDealComposeList) {
					arrGoodsList.add(goodsCompose.getCompsGoodsCd());
				}

				String[] arrGoodsCd = arrGoodsList.stream().toArray(String[]::new);

				paramsGoods.setArrGoodsCd(arrGoodsCd);
			}
			paramsGoods.setMaxRownum(1);
			goodsCouponList = couponService.getGoodsCouponList(paramsGoods);
			mav.addObject("goodsCouponList", goodsCouponList);

			//즉시쿠폰
			paramsGoods.setMaxRownum(1);
			goodsCouponList = couponService.getGoodsCoupon1List(paramsGoods);
			mav.addObject("goodsCoupon1List", goodsCouponList);

			// 다다익선
			paramsGoods.setMaxRownum(1);
			mav.addObject("tmtbList", goodsService.getTmtbList(paramsGoods));

			// 사은품
			paramsGoods.setMaxRownum(1);
			mav.addObject("freeGoodsList", goodsService.getFreeGoodsList(paramsGoods));

			// 딜용 상품평건수
			Review review = new Review();
			review.setGoodsCd(goods.getGoodsCd());
			review.setGoodsType(goods.getGoodsType());
			goodsReviewCnt = reviewService.getReviewTotalCount(review);

			// 딜용상품평건수
			mav.addObject("goodsReviewCnt", goodsReviewCnt);

			// pc 추천 영역
			if ("P".equals(paramsGoods.getFrontGb())) {
				// 이상픔과 함께본 상품
				mav.addObject("togetherGoodsList", eigeneaiApi.getRelatedGoodsList(goods.getGoodsCd(),15));
			}

		} else {
			
			//해당색상아닌 다른색상의 productno찾기 - 상품상세에서 사용
			StringBuffer sbProductNo = new StringBuffer();
			Collection<GoodsStock> goodsProductNoList = goodsService.getProductNoByGoodsColor(paramsGoods);
			if (goodsProductNoList != null && !goodsProductNoList.isEmpty()) {
				
				for (GoodsStock goodsProductNo: goodsProductNoList) {
					sbProductNo.append(Integer.toString(goodsProductNo.getProductNo())).append(",");
				}
				
			}
			mav.addObject("arrNoneProductNo", sbProductNo.toString());
			
			if (TscConstants.GoodsType.NORMAL.value().equals(goods.getGoodsType())) {	// 일반상품
				//if ("Y".equals(goods.getSelfGoodsYn())) {  // 자사상품
				// 상품 옵션1(색상) 정보
				mav.addObject("goodsOption1List", goodsService.getGoodsOption1List(paramsGoods));
				// 상품 옵션2(사이즈) 정보
				if (StringUtils.isEmpty(paramsGoods.getMastrGoodsCd())) {
					paramsGoods.setMastrGoodsCd(goods.getGoodsCd());
				}
				mav.addObject("goodsOption2List", goodsService.getGoodsOption2List(paramsGoods));
//				} else {
//					mav.addObject("goodsOptionList", goodsService.getGoodsOptionList(paramsGoods));
//				}

//				// 상품 고시정보
				mav.addObject("goodsNotiList", goodsService.getGoodsNotiList(goods));
				// 상품 안전인증 정보
				mav.addObject("goodsSafeNo", goodsService.getGoodsSafeNo(goods));

			} else if (TscConstants.GoodsType.SET.value().equals(goods.getGoodsType())) {		// 셋트상품
				mav.addObject("goodsComposeList", goodsService.getGoodsSetComposeList(paramsGoods));
			}

			// 룩북
			Lookbook lookbook = new Lookbook();
			lookbook.setGoodsCd(paramsGoods.getGoodsCd());
			lookbook.setCustNo(paramsGoods.getCustNo());
			mav.addObject("lookbookList", coreLookbookService.getLookbookListForGoods(lookbook));

			// 상품 즉시할인 쿠폰정보
			paramsGoods.setMaxRownum(1);
			mav.addObject("goodsCoupon1List", couponService.getGoodsCoupon1List(paramsGoods));

			// 상품쿠폰
			paramsGoods.setMaxRownum(1);
			mav.addObject("goodsCouponList", couponService.getGoodsCouponList(paramsGoods));

			// 다다익선
			paramsGoods.setMaxRownum(1);
			mav.addObject("tmtbList", goodsService.getTmtbList(paramsGoods));

			// 사은품
			paramsGoods.setMaxRownum(1);
			mav.addObject("freeGoodsList", goodsService.getFreeGoodsList(paramsGoods));

			// 베스트 상품평
			Review review = new Review();
			review.setGoodsCd(goods.getGoodsCd());
			review.setBestYn("Y");
			review.setGoodsType(goods.getGoodsType());
			if ("P".equals(paramsGoods.getFrontGb())) {
				review.setRownum(1);
			}
			mav.addObject("bestReviewList", reviewService.getReviewList(review));

			//다다익선
			paramsGoods.setMaxRownum(20);
			mav.addObject("goodsList", goodsService.getTmtbGoodsList(paramsGoods));

			// pc 추천 영역
			if ("P".equals(paramsGoods.getFrontGb())) {
				// 이상픔과 함께본 상품
//				log.info("[상품상세  이상픔과 함께본 상품] =={}", eigeneaiApi.getRelatedGoodsList(goods.getGoodsCd(),15));
				mav.addObject("togetherGoodsList", eigeneaiApi.getRelatedGoodsList(goods.getGoodsCd(),15));

				// 브랜드 추천 상품
//				log.info("[상품상세  브랜드 추천 상품] =={}", eigeneaiApi.getBrandRelatedGoodsList(15,goods.getGoodsCd(), goods.getBrandGroupNo()));
				mav.addObject("recommendGoodsList", eigeneaiApi.getBrandRelatedGoodsList(15,goods.getGoodsCd(), goods.getBrandGroupNo()));

				// 비슷한 상품
//				log.info("[상품상세  비슷한 상품] =={}", eigeneaiApi.getSameCategoryRelatedGoodsList(15,goods.getGoodsCd()));
				mav.addObject("likeGoodsList", eigeneaiApi.getSameCategoryRelatedGoodsList(15,goods.getGoodsCd()));

			}
			
			// 상품 공지
			mav.addObject("goodsNoticeList", goodsService.getGoodsNoticeList(paramsGoods));
			
			GoodsContents goodsContents = new GoodsContents();
			goodsContents.setGoodsCd(paramsGoods.getGoodsCd());
			// 상세용 동영상
			goodsContents.setGoodsContentsType("G086_1"); //동영상 -1건
			mav.addObject("goodsDescVideoList", goodsService.getGoodsContentsList(goodsContents));
			// 상세용 베너
			goodsContents.setGoodsContentsType("G086_2"); //베너 -1건
			mav.addObject("goodsDescBannerList", goodsService.getGoodsContentsList(goodsContents));
		}

		// 상품평노출여부 
		//mav.addObject("reviewDisplayYn", envsetService.getGoodsReviewDisplayYn(TscConstants.Site.STYLE24.value()));
		mav.addObject("reviewDisplayYn", "Y");

		// 카드 혜택안내
		CardPromotion cardPromotion = new CardPromotion();
		cardPromotion.setRownum(1); // 혜택유형별로 1건씩
		mav.addObject("cardInfoList", goodsService.getCardPromotionList(cardPromotion));

		// 오늘본 상품 쿠키 담기
		// SSL Server
		boolean isSslServer = Boolean.parseBoolean(hasSsl);
		//log.info("isSslServer: [{}]", isSslServer);
		setTodayGoodsCd(paramsGoods);

		mav.addObject("params", paramsGoods);
		mav.addObject("afLinkCd", afLinkCd);	// 파라미터 제휴코드

		if (TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType())) {
			if ("Y".equals(mobileYn)) {
				mav.setViewName("mob/goods/GoodsDealDetailFormMob");
			} else {
				mav.setViewName(super.getDeviceViewName("goods/GoodsDealDetailForm"));
			}
		} else {
			if ("Y".equals(mobileYn)) {
				mav.setViewName("mob/goods/GoodsDetailFormMob");
			} else {
				mav.setViewName(super.getDeviceViewName("goods/GoodsDetailForm"));
			}
		}

		return mav;
	}

	/**
	 * 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
	 *
	 * @param goods
	 * @author eskim
	 * @since 2021. 2. 09.
	 */
	private void setGoods(Goods goods) {
		goods.setFrontGb(TsfSession.getFrontGb());
		goods.setIsApp(TsfSession.getAttribute("isApp"));	//앱여부 true
		goods.setSiteCd(TscConstants.Site.STYLE24.value());
		goods.setAfLinkCd(TsfSession.getAttribute("afLinkCd"));
		goods.setSoldoutGoodsDisplayYn(envsetService.getSoldoutGoodsDisplayYn(TscConstants.Site.STYLE24.value())); // 품절상품노출여부
		goods.setPointUnit(envsetService.getPayUnit(TscConstants.Site.STYLE24.value())); // 10:원단위절사(int)
		goods.setFloorUnit(envsetService.getPayUnit(TscConstants.Site.STYLE24.value()));

		// 회원 구분
		if (TsfSession.getInfo() != null) {
			goods.setCustGb(TsfSession.getInfo().getCustGb());
			goods.setCustNo(TsfSession.getInfo().getCustNo());
			goods.setCustGrade(TsfSession.getInfo().getCustGrade());
		} else {
			goods.setCustGb(TsfSession.getCustGb());
			goods.setCustNo(0);
			goods.setCustGrade(""); //?  확인해보자
		}
	}

	/**
	 * 상품 쿠키 생성
	 *
	 * @param paramsGoods
	 * @author eskim
	 * @since 2021. 2. 17.
	 */
	private void setTodayGoodsCd(Goods paramsGoods) {
		String ckGoodsCd = GagaCookieUtil.getCookie(TsfSession.getHttpServletRequest(), TsfConstants.CK_PREFIX + "_today_goodsCd");
		//log.info("[detail] ckGoodsCd = {}", ckGoodsCd);
		String arrGetCkGoodsCd[] = ckGoodsCd.split("\\,");
		String setCkGoodsCd = "";
		StringBuilder ckGoodsCdSb = new StringBuilder();
		if (arrGetCkGoodsCd.length > 0) {
			for (String cookieGoodsCd : arrGetCkGoodsCd) {
				if (!cookieGoodsCd.equals(paramsGoods.getGoodsCd()) && !StringUtils.isBlank(cookieGoodsCd)) {
					ckGoodsCdSb.append(cookieGoodsCd).append(",");
				}
			}
			ckGoodsCdSb.insert(0, ",");
			ckGoodsCdSb.insert(0, paramsGoods.getGoodsCd());
		} else {
			ckGoodsCdSb.append(paramsGoods.getGoodsCd()).append(",");
		}
		setCkGoodsCd = ckGoodsCdSb.toString();
		setCkGoodsCd = setCkGoodsCd.substring(0, setCkGoodsCd.lastIndexOf(","));

		// 오늘본 상품 최대 30개 처리
		String arrSetCkGoodsCd[] = setCkGoodsCd.split("\\,");
		if (arrSetCkGoodsCd.length > 30) {
			ckGoodsCdSb.setLength(0);
			for (String tempSetCkGoodsCd : arrSetCkGoodsCd) {
				ckGoodsCdSb.append(tempSetCkGoodsCd).append(",");
			}
			setCkGoodsCd = ckGoodsCdSb.toString();
			setCkGoodsCd = setCkGoodsCd.substring(0, setCkGoodsCd.lastIndexOf(","));
		}

		//log.info("[detail] setCkGoodsCd = {}", setCkGoodsCd);

		//		if (isSslServer) {
		//			GagaCookieUtil.setSecureCookie(TsfSession.getHttpServletResponse(), TsfConstants.CK_PREFIX + "_today_goodsCd", setCkGoodsCd, 1);
		//		} else {
		GagaCookieUtil.setCookie(TsfSession.getHttpServletResponse(), TsfConstants.CK_PREFIX + "_today_goodsCd", setCkGoodsCd, 24 * 60 * 60);
		//		}
	}

	/**
	 * 상품상세 -  카드혜택안내 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 4
	 */
	@PostMapping("/card/prmt/layer")
	public ModelAndView cardPrmtForm() {
		ModelAndView mav = new ModelAndView();
		CardPromotion cardPromotion = new CardPromotion();
		mav.addObject("cardInfoList", goodsService.getCardPromotionList(cardPromotion));
		mav.setViewName(super.getDeviceViewName("goods/CardPrmtForm"));
		return mav;
	}

	/**
	 * 상품 사이즈 선택 시 재고수량 가져오기
	 * 
	 * @return
	 * @author eskim
	 * @since 2021. 3. 4
	 */
	@GetMapping("/detail/ajaxGoodsStockQty")
	@ResponseBody
	public int getAjaxGoodsStockQty(GoodsStock goodsStock) {
		int stockQty = 0;
		stockQty = goodsService.getGoodsStockQty(goodsStock);
		return stockQty;
	}

	/**
	 * 세트 상품 사이즈 선택 시 재고수량 가져오기
	 * 
	 * @return
	 * @author eskim
	 * @since 2021. 3. 22
	 */
	@PostMapping("/detail/ajaxGoodsSetStockQty")
	@ResponseBody
	public String getAjaxGoodsSetStockQty(@RequestBody GoodsStock goodsStock) {

		int stockQty = 0;

		stockQty = goodsService.getGoodsSetStockQty(goodsStock);
		//log.info("[getAjaxGoodsSetStockQty] stockQty = {}", stockQty);
		return String.valueOf(stockQty);
	}

	/**
	 * 상품상세 -  상품 QNA LIST 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 5
	 */
	@PostMapping("/qna/layer/{goodsCd}")
	public ModelAndView goodsQnaForm(@PathVariable String goodsCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		setGoods(paramsGoods);
		Goods goods = goodsService.getGoodsInfo(paramsGoods);
		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsQnaForm"));
		return mav;
	}

	/**
	 * 상품문의 목록
	 * @param counsel - 상담정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 5
	 */
	@PostMapping("/qna/list")
	@ResponseBody
	public GagaMap getGoodsQnaList(@RequestBody Counsel counsel) {

		log.info(" getGoodsQnaList =>{}", counsel);
		counsel.setSiteCd(TscConstants.Site.STYLE24.value());

		GagaMap result = new GagaMap();

		TscPageRequest pageable = new TscPageRequest((counsel.getPageNo() > 0 ? counsel.getPageNo() - 1 : 0), counsel.getPageSize(), counsel.getPageUnit());
		pageable.setTotalCount(counselService.getGoodsQnaTotalCount(counsel));
		counsel.setPageable(pageable);

		if (TsfSession.isLogin()) {
			counsel.setCustNo(TsfSession.getInfo().getCustNo());
		}

		result.set("paging", counsel);
		result.set("dataList", counselService.getGoodsQnaListForGoods(counsel));

		return result;
	}

	/**
	 * 상품상세 -  상품 QNA 등록
	 * @return
	 * @author eskim
	 * @since 2021. 3. 5
	 */
	@PostMapping("/qna/create/layer/{goodsCd}")
	public ModelAndView qnaCreateForm(@PathVariable String goodsCd) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("goodsCd", goodsCd);
		mav.setViewName(super.getDeviceViewName("goods/GoodsQnaDetailForm"));
		return mav;
	}

	/**
	 * 상품상세 -  배송안내 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/delivery/layer/{goodsCd}")
	public ModelAndView goodsDeliveryForm(@PathVariable String goodsCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		setGoods(paramsGoods);
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsDeliveryForm"));
		return mav;
	}

	/**
	 * 상품상세 -  쿠폰 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/coupon/layer")
	public ModelAndView goodsCouponForm(Goods goods) {
		ModelAndView mav = new ModelAndView();
		Collection<Coupon> goodsCouponList;
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(goods);

		if (!StringUtils.isBlank(goods.getGoodsType()) && TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType())) {
			Collection<Goods> goodsDealComposeList = goodsService.getGoodsDealComposeList(goods);
			// 상품쿠폰
			if (goodsDealComposeList != null && !goodsDealComposeList.isEmpty()) {

				ArrayList<String> arrGoodsList = new ArrayList<>();
				for (Goods goodsCompose : goodsDealComposeList) {
					arrGoodsList.add(goodsCompose.getCompsGoodsCd());
				}

				String[] arrGoodsCd = arrGoodsList.stream().toArray(String[]::new);
				goods.setArrGoodsCd(arrGoodsCd);
			}

			// 딜상품쿠폰정보(중복제거)
			goodsCouponList = couponService.getGoodsDealCouponList(goods);
		} else {
			// 상품쿠폰정보
			goodsCouponList = couponService.getGoodsCouponList(goods);
		}

		// 상품쿠폰정보
		mav.addObject("goodsCouponList", goodsCouponList);

		// 상품 기본정보
		mav.addObject("params", goods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsCouponForm"));

		return mav;
	}

	/**
	 * 상품상세 -  쇼핑혜택 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/shop/benefit/layer/{goodsCd}")
	public ModelAndView goodsShopBenefitForm(@PathVariable String goodsCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		setGoods(paramsGoods);
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		if (TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType())) {	// 딜상품
			Collection<Goods> goodsDealComposeList = goodsService.getGoodsDealComposeList(paramsGoods);
			Collection<Coupon> goodsCouponList = new ArrayList<Coupon>();
			ArrayList<String> arrGoodsList = new ArrayList<>();
			// 상품쿠폰
			if (goodsDealComposeList != null && !goodsDealComposeList.isEmpty()) {
				for (Goods goodsCompose : goodsDealComposeList) {
					arrGoodsList.add(goodsCompose.getCompsGoodsCd());
				}

				String[] arrGoodsCd = arrGoodsList.stream().toArray(String[]::new);

				paramsGoods.setArrGoodsCd(arrGoodsCd);
			}
		}
		// 상품 즉시할인 쿠폰정보
		paramsGoods.setMaxRownum(1);
		mav.addObject("goodsCoupon1List", couponService.getGoodsCoupon1List(paramsGoods));

		// 상품 다운로드 쿠폰
		paramsGoods.setMaxRownum(1);
		mav.addObject("goodsCouponList", couponService.getGoodsCouponList(paramsGoods));
		// 다다익선
		paramsGoods.setMaxRownum(0);
		mav.addObject("tmtbList", goodsService.getTmtbList(paramsGoods));
		// 사은품
		paramsGoods.setMaxRownum(0);
		mav.addObject("freeGoodsList", goodsService.getFreeGoodsList(paramsGoods));

		// 상품 기본정보 --즉시할인정보
		mav.addObject("goodsInfo", goods);
		mav.setViewName(super.getDeviceViewName("goods/GoodsShopBenefitForm"));
		return mav;
	}

	/**
	 * 상품상세 -  사이즈 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/sizeInfo/layer/{goodsCd}/{colorCd}")
	public ModelAndView goodsSizeInfoForm(@PathVariable String goodsCd, @PathVariable String colorCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		paramsGoods.setColorCd(colorCd);
		setGoods(paramsGoods);
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		// 실측 사이즈 정보 - 자사상품만
		String typeCd = "";
		String typeWith = "";
		int sizeCount = 0;
		Collection<Measurement> measurementList = new ArrayList<Measurement>();
		Collection<MeasurementStyle> measurementStyleList = new ArrayList<MeasurementStyle>();
		if ("Y".equals(goods.getSelfGoodsYn())) {
			paramsGoods.setOptCd1(colorCd);

//			measurementList = goodsService.getMeasurementList(paramsGoods);
//			if (measurementList != null && !measurementList.isEmpty()) {
//				typeCd = measurementList.iterator().next().getTypecd();
//				if ("하의".equals(typeCd)) {
//					typeWith = Integer.toString(((int)Math.floor(100 / 6)));
//				}
//			}

			measurementStyleList = goodsService.getMeasurementListNew(paramsGoods);
			if (measurementStyleList != null && !measurementStyleList.isEmpty()) {
				sizeCount = measurementStyleList.iterator().next().getSizeCount();
				typeWith = Integer.toString(((int)Math.floor(100 / sizeCount)));
			}
		}

		// 표준사이즈 - 공통
		SizeInfo sizeInfo = new SizeInfo();
		sizeInfo.setSizeGb("1"); 	// 사이즈구분정보 1:표준사이즈. 2:측정사이즈
		sizeInfo.setSizeCate1Cd("00"); 	// 사이즈카테고리1 표준사이즈일경우   공통(00),자사브랜드코드)
		Collection<SizeInfo> commonSizeInfoList = goodsService.getSizeInfoList(sizeInfo);

		// 표준사이즈 - 자사브랜드
		Collection<SizeInfo> brandSizeInfoList = new ArrayList<SizeInfo>();
		if ("Y".equals(goods.getSelfGoodsYn())) {
			sizeInfo.setSizeCate1Cd(goods.getBrandCd());	// 자사브랜드코드(브랜드그룹코드아님)
			brandSizeInfoList = goodsService.getSizeInfoList(sizeInfo);
		}

		// 측정사이즈
		sizeInfo.setSizeGb("2");
		sizeInfo.setSizeCate1Cd("");
		Collection<SizeInfo> measurementSizeInfoList = goodsService.getSizeInfoList(sizeInfo);

		mav.addObject("measurementList", measurementStyleList);
		mav.addObject("typeCd", typeCd);
		mav.addObject("typeWith", typeWith);
		mav.addObject("commonSizeInfoList", commonSizeInfoList);
		mav.addObject("brandSizeInfoList", brandSizeInfoList);
		mav.addObject("measurementSizeInfoList", measurementSizeInfoList);

		mav.setViewName(super.getDeviceViewName("goods/GoodsSizeInfoForm"));
		return mav;
	}

	/**
	 * 상품상세 -  재입고 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/instock/alarm/layer/{goodsCd}/{colorCd}")
	public ModelAndView goodsInstockAlarmForm(@PathVariable String goodsCd, @PathVariable String colorCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		paramsGoods.setColorCd(colorCd);
		setGoods(paramsGoods);
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		// 자사 일반상품- 옵션2(사이즈) 정보
		paramsGoods.setOptCd1(colorCd);
		if (StringUtils.isEmpty(paramsGoods.getMastrGoodsCd())) {
			paramsGoods.setMastrGoodsCd(goods.getGoodsCd());
		}
		mav.addObject("goodsOption2List", goodsService.getGoodsOption2List(paramsGoods));

		mav.setViewName(super.getDeviceViewName("goods/GoodsInstockAlarmForm"));
		return mav;
	}

	/**
	 * 상품상세 -  재입고 등록
	 * @return
	 * @author eskim
	 * @since 2021. 3. 10
	 */
	@PostMapping("/instock/alarm/save")
	@ResponseBody
	public GagaResponse saveGoodsInstockAlarmForm(@RequestBody ReinboundInform reinboundInform) {
		log.info("reinboundInform {}", reinboundInform);
		goodsService.saveGoodsInstockAlarmForm(reinboundInform);
		return super.ok("재입고 알림 신청이 완료되었습니다. 재입고 시 알림톡이 발송됩니다.");
	}

	/**
	 * 상품상세 -  상품평 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/review/layer/{goodsCd}")
	public ModelAndView goodsReviewForm(@PathVariable String goodsCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		setGoods(paramsGoods);
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		// 상품평 포인트
		GagaMap reviewPoint = new GagaMap();
		reviewPoint.set("textReviewPoint", envsetService.getTextReviewPoint(TscConstants.Site.STYLE24.value()));	//텍스트상품평포인트
		reviewPoint.set("photoReviewPoint", envsetService.getPhotoReviewPoint(TscConstants.Site.STYLE24.value()));	//포토상품평포인트
		reviewPoint.set("bestReviewPoint", envsetService.getBestReviewPoint(TscConstants.Site.STYLE24.value()));	//베스트상품평포인트
		mav.addObject("reviewPoint", reviewPoint);

		Review review = new Review();
		review.setGoodsCd(goods.getGoodsCd());
		mav.addObject("reviewCount", reviewService.getReviewTotalCount(review));	// 전체상품평 건수 
		review.setRownum(1);
		review.setGoodsType(goods.getGoodsType());
		mav.addObject("reviewList", reviewService.getReviewList(review));	// 전체상품평 유무 확인
		review.setBestYn("Y");
		review.setRownum(0);	// 전체 조회
		mav.addObject("bestReviewList", reviewService.getReviewList(review));	//베스트상품평
		review.setPhotoYn("Y");
		review.setBestYn("");
		review.setRownum(0);	// 전체 조회
		mav.addObject("photoReviewList", reviewService.getReviewList(review));	//포토상품평

		// 상품평에 등록된 사이즈 정보
		mav.addObject("reviewOptionList", reviewService.getReviewOptionList(goods));

		// 유야동: 베이비(07), 키즈여아(08), 키즈남아(09), 키즈공통(10), 주니어여야(11), 주니어남아(12), 주니어공통(13), 성인G: 유아동 제외 전체
		// 유야동 키 공통코드 G091, 성인 키 공통코드 G090
		String[] arrItem = {"07", "08", "09", "10", "11", "12", "13"};
		ArrayList<String> itemList = new ArrayList<>(Arrays.asList(arrItem));

		// 키전체 
		Collection<CommonCode> reviewHeightList = new ArrayList<CommonCode>();
		log.info("goods.getItemkindCd().substring(0, 2) => {} ", goods.getItemkindCd().substring(0, 2));
		if (itemList.contains(goods.getItemkindCd().substring(0, 2))) {
			reviewHeightList = rendererService.getAvailCommonCodeList("G091");
		} else {
			reviewHeightList = rendererService.getAvailCommonCodeList("G090");
		}

		// 상품평 키
		mav.addObject("reviewHeightList", reviewHeightList);

		// 유야동 몸무게 공통코드 G093, 성인 몸무게 공통코드 G092
		// 몸무게
		Collection<CommonCode> reviewWeightList = new ArrayList<CommonCode>();
		if (itemList.contains(goods.getItemkindCd().substring(0, 2))) {
			reviewWeightList = rendererService.getAvailCommonCodeList("G093");
		} else {
			reviewWeightList = rendererService.getAvailCommonCodeList("G092");
		}

		// 상품평 몸무게
		mav.addObject("reviewWeightList", reviewWeightList);

		mav.setViewName(super.getDeviceViewName("goods/GoodsReviewForm"));
		return mav;
	}

	/**
	 * 상품평 목록
	 * @param review
	 * @return
	 * @author eskim
	 * @since 2021. 3. 16
	 */
	@PostMapping("/review/list")
	@ResponseBody
	public GagaMap getGoodsReviewList(@RequestBody Review review) {

		log.info(" getGoodsReviewList =>{}", review);

		GagaMap result = new GagaMap();

		review.setReviewHeightSt(0);
		review.setReviewHeightEd(0);
		if (StringUtils.isNotBlank(review.getReviewHeight())) {
			String[] arrHeight = review.getReviewHeight().split("\\-");
			review.setReviewHeightSt(Integer.parseInt(arrHeight[0]));
			review.setReviewHeightEd(Integer.parseInt(arrHeight[1]));
		}

		review.setReviewWeightSt(0);
		review.setReviewWeightEd(0);
		if (StringUtils.isNotBlank(review.getReviewWeight())) {
			String[] arrWeight = review.getReviewWeight().split("\\-");
			review.setReviewWeightSt(Integer.parseInt(arrWeight[0]));
			review.setReviewWeightEd(Integer.parseInt(arrWeight[1]));
		}

		TscPageRequest pageable = new TscPageRequest((review.getPageNo() > 0 ? review.getPageNo() - 1 : 0), review.getPageSize(), review.getPageUnit());
		pageable.setTotalCount(reviewService.getReviewTotalCount(review));
		review.setPageable(pageable);

		if (TsfSession.isLogin()) {
			review.setCustNo(TsfSession.getInfo().getCustNo());
		}

		result.set("paging", review);
		result.set("dataList", reviewService.getReviewList(review));

		return result;
	}

	/**
	 * 상품상세 -  상품평 - 포토/영상 리스트 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/review/photo/layer/{goodsCd}")
	public ModelAndView goodsReviewPhotoForm(@PathVariable String goodsCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		setGoods(paramsGoods);
		//Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 상품 기본정보
		mav.addObject("params", paramsGoods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsReviewPhotoForm"));
		return mav;
	}

	/**
	 * 상품상세 -  상품평 상세 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/review/detail/layer")
	public ModelAndView goodsReviewDetailForm(Review review) {
		log.info("goodsReviewDetailForm {}", review);
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(review.getGoodsCd());
		setGoods(paramsGoods);

		// 상품 기본정보
		mav.addObject("params", paramsGoods);

		mav.addObject("review", review);

		mav.addObject("reviewList", reviewService.getReviewList(review));

		mav.setViewName(super.getDeviceViewName("goods/GoodsReviewDetailForm"));
		return mav;
	}

	/**
	 * 상품상세 -  상품평 상세 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/review/detail/list")
	@ResponseBody
	public GagaMap getReviewDetailList(@RequestBody Review review) {
		log.info("getReviewDetailList {}", review);
		GagaMap result = new GagaMap();
		result.set("reviewList", reviewService.getReviewList(review));
		return result;
	}

	/**
	 * 상품상세 - 다다익선 상품
	 * 
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/detail/tmtb/frame")
	public ModelAndView goodsTmtbForm(@RequestBody Goods goods) {

		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(goods);
		goods.setMaxRownum(20);
		mav.addObject("goodsList", goodsService.getTmtbGoodsList(goods));
		//log.info("goodsTmtbForm = goods{}", goods);
		goods.setIthrCd("IN15_02");
		mav.addObject("params", goods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsOtherForm"));
		return mav;
	}

	/**
	 * 상품상세 - 함께본 상품
	 * 
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/detail/together/frame")
	public ModelAndView goodsTogetherForm(@RequestBody Goods goods) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("goodsList", eigeneaiApi.getRelatedGoodsList(goods.getGoodsCd(),15));
		goods.setIthrCd("IN15_03");
		mav.addObject("params", goods);
		mav.setViewName(super.getDeviceViewName("goods/GoodsOtherForm"));
		return mav;
	}

	/**
	 * 상품상세 - 추천 상품
	 * 
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/detail/recommend/frame")
	public ModelAndView goodsRecommendForm(@RequestBody Goods goods) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("goodsList", eigeneaiApi.getBrandRelatedGoodsList(15,goods.getGoodsCd(), goods.getBrandGroupNo()));
		goods.setIthrCd("IN15_04");
		mav.addObject("params", goods);
		mav.setViewName(super.getDeviceViewName("goods/GoodsOtherForm"));
		return mav;
	}

	/**
	 * 상품상세 - 비슷한 상품
	 * 
	 * @return
	 * @author eskim
	 * @since 2021. 3. 8
	 */
	@PostMapping("/detail/like/frame")
	public ModelAndView goodsLikeForm(@RequestBody Goods goods) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("goodsList", eigeneaiApi.getSameCategoryRelatedGoodsList(15,goods.getGoodsCd()));
		goods.setIthrCd("IN15_05");
		mav.addObject("params", goods);
		mav.setViewName(super.getDeviceViewName("goods/GoodsOtherForm"));
		return mav;
	}

	/**
	 * 고객의 상품쿠폰 발급. 고객이 상품쿠폰 다운로드 시 발급됨.
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2021. 3. 12.
	 */
	@PostMapping(value = "/coupon/download")
	@ResponseBody
	public GagaMap createGoodsCoupon(@RequestBody Goods paramsGoods) throws Exception {

		GagaMap result = new GagaMap();

		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(paramsGoods);
		log.info("createGoodsCoupon  paramsGoods {}", paramsGoods);
//
//		// 일반상품과 딜상품 구분
//		Goods goods = goodsService.getGoodsInfo(paramsGoods);
//		if (goods == null || StringUtils.isBlank(goods.getGoodsCd())) {
//			result.set("message", "발급가능 쿠폰이 없습니다.");
//			result.set("status", "200");
//			result.set("params", paramsGoods);
//			return result;
//		}
//
//		//log.info("createGoodsCoupon  goods {}", goods);
//		if (TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType())) {
//			Collection<Goods> goodsDealComposeList = goodsService.getGoodsDealComposeList(paramsGoods);
//			// 상품쿠폰
//			if (goodsDealComposeList != null && !goodsDealComposeList.isEmpty()) {
//
//				ArrayList<String> arrGoodsList = new ArrayList<>();
//				for (Goods goodsCompose : goodsDealComposeList) {
//					arrGoodsList.add(goodsCompose.getCompsGoodsCd());
//				}
//
//				String[] arrGoodsCd = arrGoodsList.stream().toArray(String[]::new);
//				paramsGoods.setArrGoodsCd(arrGoodsCd);
//			}
//		}

		// 쿠폰발급
		// ERROR_10: 발급가능 쿠폰없음, 20: 발급완료 쿠폰, 30: 발급받은 쿠폰
		//죄송합니다. 쿠폰이 모두 소진되었습니다
		//죄송합니다. 해당 쿠폰은 다운로드가 불가합니다.
		String couponResult = goodsService.createGoodsCoupon(paramsGoods);

		result.set("status", GagaResponseStatus.SUCCESS.getCode());

		if ("ERROR_10".equals(couponResult)) {
			result.set("message", "발급가능 쿠폰이 없습니다.");
		} else if ("ERROR_20".equals(couponResult)) {
			result.set("message", "죄송합니다. 해당 쿠폰은 다운로드가 불가합니다.");
		} else if ("ERROR_30".equals(couponResult)) {
			result.set("message", "죄송합니다. 쿠폰이 모두 소진되었습니다.");
		} else {
			if (paramsGoods.getArrCpnId() != null && paramsGoods.getArrCpnId().length > 0) {
				result.set("message", couponResult + "개 쿠폰이 발급되었습니다.");
			} else {
				result.set("message", "쿠폰이 발급되었습니다.");
			}

		}
		result.set("status", "200");
		result.set("params", paramsGoods);
		result.set("goodsCouponList", couponService.getGoodsCouponList(paramsGoods));
		return result;
	}

	/**
	 * 상품 옵션1 목록
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 3. 24
	 */
	@PostMapping("/detail/compsGoods/list")
	@ResponseBody
	public GagaMap getDealCompsGoodsList(@RequestBody Goods goods) {

		GagaMap result = new GagaMap();
		goods.setSiteCd(TscConstants.Site.STYLE24.value());
		result.set("dataList", goodsService.getGoodsDealComposeList(goods));

		return result;
	}

	/**
	 * 상품 옵션1 목록
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 3. 24
	 */
	@PostMapping("/detail/option1/list")
	@ResponseBody
	public GagaMap getGoodsOption1List(@RequestBody Goods goods) {

		GagaMap result = new GagaMap();
		if (StringUtils.isEmpty(goods.getMastrGoodsCd())) {
			goods.setMastrGoodsCd(goods.getGoodsCd());
		}
		result.set("dataList", goodsService.getGoodsOption1List(goods));

		return result;
	}

	/**
	 * 상품 옵션2 목록
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021. 3. 22
	 */
	@PostMapping("/detail/option2/list")
	@ResponseBody
	public GagaMap getGoodsOption2List(@RequestBody Goods goods) {

		//log.info("goods = {}", goods);
		GagaMap result = new GagaMap();
		if (StringUtils.isEmpty(goods.getMastrGoodsCd())) {
			goods.setMastrGoodsCd(goods.getGoodsCd());
		}
		result.set("dataList", goodsService.getGoodsOption2List(goods));

		return result;
	}

	/**
	 * 최근본상품 목록
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 22
	 */
	@GetMapping("/recently/list")
	@ResponseBody
	public Collection<RecentlyGoods> getRecentlyGoodsList() {
//		// DB 처리를 하는 것으로 변경함에 따라 해당 부분 주석 처리
//		Collection<RecentlyGoods> recentlyGoodsList = new ArrayList<>();
//		RecentlyGoods recentlyGoods = new RecentlyGoods();
//		
//		String ckGoodsCds = GagaCookieUtil.getCookie(TsfSession.getHttpServletRequest(), TsfConstants.CK_PREFIX + "_today_goodsCd");
//		if (StringUtils.isNotBlank(ckGoodsCds)) {
//			String[] arrGoodsCds = ckGoodsCds.split("\\,");
//			StringBuilder sql = new StringBuilder();
//			if (arrGoodsCds.length > 0) {
//				int idx = 1;
//				for (String goodsCd : arrGoodsCds) {
//					if (!StringUtils.isBlank(goodsCd)) {
//						if (idx > 1) {
//							sql.append("UNION ALL ");
//						}
//						sql.append("SELECT '").append(goodsCd).append("' AS GOODS_CD, ").append(idx++).append(" AS DISP_ORD FROM DUAL\r\n");
//					}
//				}
//				recentlyGoods.setGoodsSql(sql.toString());
//				recentlyGoodsList = recentlyGoodsService.getRecentlyGoodsList();
//			}
//		}
//
//		return recentlyGoodsList;
		return recentlyGoodsService.getRecentlyGoodsList();
	}

	/**
	 * 딜상품상세 -  구성상품 상세정보 레이어
	 * @return
	 * @author eskim
	 * @since 2021. 3. 24
	 */
	@PostMapping("/deal/detail/layer/{goodsCd}/{compsGoodsCd}")
	public ModelAndView goodsDealDetailForm(@PathVariable String goodsCd, @PathVariable String compsGoodsCd) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(goodsCd);
		setGoods(paramsGoods);
		// 1. 딜상품코드 적용
		mav.addObject("goodsDealComposeList", goodsService.getGoodsDealComposeList(paramsGoods));

		// 2.구상상품코드 적용
		paramsGoods.setGoodsCd(compsGoodsCd);
		paramsGoods.setAdminYn("Y"); 	// 딜상세 레이어는 상품상태가 승인완료가 아니더라도 보이게 처리
		Goods goods = goodsService.getGoodsInfo(paramsGoods);
		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		GagaMap params = new GagaMap();
		params.set("goodsCd", goodsCd);
		params.set("compsGoodsCd", compsGoodsCd);
		params.set("adminYn", "Y");

		mav.addObject("params", params);

		mav.setViewName(super.getDeviceViewName("goods/GoodsDealListForm"));
		return mav;
	}

	/**
	 * 딜상품상세 -  ajax 구성상품 상세정보
	 * @return
	 * @author eskim
	 * @since 2021. 3. 24
	 */
	@PostMapping("/deal/detail/info/frame")
	public ModelAndView goodsDealDetailInfoForm(Goods paramsGoods) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(paramsGoods);

		Goods goods = goodsService.getGoodsInfo(paramsGoods);
		// 상품 상세
		goods = goodsService.getGoodsDesc(goods);

		// 조회색상이 없으면 메인컬러 설정
		if (StringUtils.isEmpty(paramsGoods.getColorCd())) {
			paramsGoods.setColorCd(goods.getMainColorCd());
			paramsGoods.setOptCd1(goods.getMainColorCd());
		}
		paramsGoods.setSelfGoodsYn(goods.getSelfGoodsYn());
		if (TscConstants.GoodsType.DEAL.value().equals(goods.getGoodsType()) || TscConstants.GoodsType.SET.value().equals(goods.getGoodsType())) {
			paramsGoods.setColorCd("XX");
		}
		// 상품 기본정보
		mav.addObject("goodsInfo", goods);
		// 상품 이미지정보
		mav.addObject("goodsImgList", goodsService.getGoodsImgList(paramsGoods));
		// 상품 동영상정보
		GoodsVideo goodsVideo = new GoodsVideo();
		goodsVideo.setGoodsCd(paramsGoods.getGoodsCd());
		goodsVideo.setMaxRownum(1);
		mav.addObject("goodsVideoList", goodsService.getVideoList(goodsVideo));
		// 상품 공지
		mav.addObject("goodsNoticeList", goodsService.getGoodsNoticeList(paramsGoods));
		// 상품 고시정보
		mav.addObject("goodsNotiList", goodsService.getGoodsNotiList(goods));
		// 상품 안전인증 정보
		mav.addObject("goodsSafeNo", goodsService.getGoodsSafeNo(goods));

		GoodsContents goodsContents = new GoodsContents();
		goodsContents.setGoodsCd(paramsGoods.getGoodsCd());
		// 상세용 동영상
		goodsContents.setGoodsContentsType("G086_1"); //동영상 -1건
		mav.addObject("goodsDescVideoList", goodsService.getGoodsContentsList(goodsContents));
		// 상세용 베너
		goodsContents.setGoodsContentsType("G086_2"); //베너 -1건
		mav.addObject("goodsDescBannerList", goodsService.getGoodsContentsList(goodsContents));

		mav.addObject("params", paramsGoods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsDealDescForm"));
		return mav;
	}

	/**
	 * 상품상세 -  ajax 구성상품 배송정보
	 * @return
	 * @author eskim
	 * @since 2021. 3. 26
	 */
	@PostMapping("/detail/delivery/frame")
	public ModelAndView goodsDetailDeliveryForm(@RequestBody Goods paramsGoods) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(paramsGoods);
		paramsGoods.setAdminYn("Y"); //20210526 soldout된 상품도 정보 조회는 가능해야함
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 배송업체명, 반품비, 교환비, 주소
		mav.addObject("deliveryInfo", goodsService.getGoodsDeliveryInfo(goods.getGoodsCd()));

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsDetailDeliveryForm"));
		return mav;
	}

	/**
	 * 상품상세 -  ajax 구성상품 문의정보
	 * @return
	 * @author eskim
	 * @since 2021. 3. 26
	 */
	@PostMapping("/detail/qna/frame")
	public ModelAndView goodsDetailQnaForm(@RequestBody Goods paramsGoods) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(paramsGoods);

		log.info("[goodsDetailQnaForm]  paramsGoods= {}", paramsGoods);
//		Goods goods = goodsService.getGoodsInfo(paramsGoods);
//
//		// 상품 기본정보
//		mav.addObject("goodsInfo", goods);

		// 상품 기본정보
		mav.addObject("goodsInfo", paramsGoods);

		mav.setViewName(super.getDeviceViewName("goods/GoodsDetailQnaForm"));
		return mav;
	}

	/**
	 * 상품상세 -  ajax 구성상품 상품평정보
	 * @return
	 * @author eskim
	 * @since 2021. 3. 26
	 */
	@PostMapping("/detail/review/frame")
	public ModelAndView goodsDetailReviewForm(@RequestBody Goods paramsGoods) {
		ModelAndView mav = new ModelAndView();
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(paramsGoods);
		paramsGoods.setAdminYn("Y"); //20210526 soldout된 상품도 정보 조회는 가능해야함
		Goods goods = goodsService.getGoodsInfo(paramsGoods);

		// 상품 기본정보
		mav.addObject("goodsInfo", goods);

		// 상품평 포인트
		GagaMap reviewPoint = new GagaMap();
		reviewPoint.set("textReviewPoint", envsetService.getTextReviewPoint(TscConstants.Site.STYLE24.value()));	//텍스트상품평포인트
		reviewPoint.set("photoReviewPoint", envsetService.getPhotoReviewPoint(TscConstants.Site.STYLE24.value()));	//포토상품평포인트
		reviewPoint.set("bestReviewPoint", envsetService.getBestReviewPoint(TscConstants.Site.STYLE24.value()));	//베스트상품평포인트
		mav.addObject("reviewPoint", reviewPoint);

		Review review = new Review();
		review.setGoodsCd(goods.getGoodsCd());
		review.setGoodsType(goods.getGoodsType());
		//log.info("review {}", review);
		mav.addObject("reviewCount", reviewService.getReviewTotalCount(review));	// 전체상품평 건수

		review.setRownum(1);
		mav.addObject("reviewList", reviewService.getReviewList(review));	// 전체상품평 유무 확인
		review.setBestYn("Y");
		review.setRownum(0);	// 전체 조회
		mav.addObject("bestReviewList", reviewService.getReviewList(review));	//베스트상품평
		review.setPhotoYn("Y");
		review.setBestYn("");
		review.setRownum(0);	// 전체 조회
		mav.addObject("photoReviewList", reviewService.getReviewList(review));	//포토상품평

		// 상품평에 등록된 사이즈 정보
		mav.addObject("reviewOptionList", reviewService.getReviewOptionList(goods));

		// 유야동: 베이비(07), 키즈여아(08), 키즈남아(09), 키즈공통(10), 주니어여야(11), 주니어남아(12), 주니어공통(13), 성인G: 유아동 제외 전체
		// 유야동 키 공통코드 G091, 성인 키 공통코드 G090
		String[] arrItem = {"07", "08", "09", "10", "11", "12", "13"};
		ArrayList<String> itemList = new ArrayList<>(Arrays.asList(arrItem));

		// 키전체 
		Collection<CommonCode> reviewHeightList = new ArrayList<CommonCode>();
		//log.info("goods.getItemkindCd().substring(0, 2) => {} ", goods.getItemkindCd().substring(0, 2));
		if (goods.getItemkindCd().length() > 1) {
			if (itemList.contains(goods.getItemkindCd().substring(0, 2))) {
				reviewHeightList = rendererService.getAvailCommonCodeList("G091");
			} else {
				reviewHeightList = rendererService.getAvailCommonCodeList("G090");
			}
		}

		// 상품평 키
		mav.addObject("reviewHeightList", reviewHeightList);

		// 유야동 몸무게 공통코드 G093, 성인 몸무게 공통코드 G092
		// 몸무게
		Collection<CommonCode> reviewWeightList = new ArrayList<CommonCode>();
		if (goods.getItemkindCd().length() > 1) {
			if (itemList.contains(goods.getItemkindCd().substring(0, 2))) {
				reviewWeightList = rendererService.getAvailCommonCodeList("G093");
			} else {
				reviewWeightList = rendererService.getAvailCommonCodeList("G092");
			}
		}

		// 상품평 몸무게
		mav.addObject("reviewWeightList", reviewWeightList);

		mav.setViewName(super.getDeviceViewName("goods/GoodsDetailReviewForm"));
		return mav;
	}

	/**
	 * 퀵메뉴 위시리스트
	 * @return
	 * @author sowon
	 * @since 2021. 4. 1
	 */
	@GetMapping("/wish/list")
	@ResponseBody
	public Collection<Goods> getWishList() {
		Collection<Goods> wishList = new ArrayList<>();
		WishList wish = new WishList();
		wish.setSiteCd(TscConstants.Site.STYLE24.value());
		wish.setFrontGb(TsfSession.getFrontGb());
		wish.setCustGb(TsfSession.getCustGb());
		wish.setQuickYn("Y");
		// 위시리스트 상품목록
		wishList = wishListService.getQuickWishList(wish);
		return wishList;
	}

	/**
	 * ep 쿠폰 목록
	 *
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2021. 4. 15
	 */
	@GetMapping("/epCoupon/list")
	@ResponseBody
	public Collection<Coupon> getEpGouponList(@RequestParam HashMap<String, String> paramMap) {
		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		Goods paramsGoods = new Goods();
		setGoods(paramsGoods);

		// 순서중요 setGoods 이후에 설정
		paramsGoods.setAfLinkCd(paramMap.get("afLinkCd"));
		paramsGoods.setGoodsCd(paramMap.get("goodsCd"));
		paramsGoods.setMaxRownum(Integer.parseInt(paramMap.get("maxRownum")));
		return couponService.getGoodsEpCouponList(paramsGoods);
	}

	/**
	 * ep쿠폰다운로드
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2021. 4. 15.
	 */
	@PostMapping(value = "/ep/coupon/download")
	@ResponseBody
	public GagaMap createEpGoodsCoupon(@RequestBody Goods goods) throws Exception {

		GagaMap result = new GagaMap();

		// 상품관련 기본값 설정(회원 등급, 앱, PC/모바일 등)
		setGoods(goods);
		log.info("createGoodsCoupon  goods {}", goods);

		// 쿠폰발급
		// ERROR_10: 발급가능 쿠폰없음, 20: 발급완료 쿠폰, 30: 발급받은 쿠폰
		//죄송합니다. 쿠폰이 모두 소진되었습니다
		//죄송합니다. 해당 쿠폰은 다운로드가 불가합니다.
		String couponResult = goodsService.createEpCoupon(goods);

		result.set("status", GagaResponseStatus.SUCCESS.getCode());

		if ("ERROR_10".equals(couponResult)) {
			result.set("message", "발급가능 쿠폰이 없습니다.");
		} else if ("ERROR_20".equals(couponResult)) {
			result.set("message", "죄송합니다. 해당 쿠폰은 다운로드가 불가합니다.");
		} else if ("ERROR_30".equals(couponResult)) {
			result.set("message", "죄송합니다. 쿠폰이 모두 소진되었습니다.");
		} else {
			if (goods.getArrCpnId() != null && goods.getArrCpnId().length > 0) {
				result.set("message", couponResult + "개 쿠폰이 발급되었습니다.");
			} else {
				result.set("message", "쿠폰이 발급되었습니다.");
			}

		}
		result.set("status", "200");
		result.set("params", goods);
		return result;
	}

	/**
	 * 상품상세 > 이 상품과 비슷한 상품
	 * @param goodsCd - 상품코드
	 * @return
	 * @author gagamel
	 * @since 2021. 5. 14
	 */
	@GetMapping("/same/category/goods/list/{goodsCd}")
	@ResponseBody
	public Collection<Result> getSameCategoryGoodsList(@PathVariable String goodsCd) {
		return eigeneaiApi.getSameCategoryRelatedGoodsList(10, goodsCd);
	}

}
