package com.style24.front.biz.service;

import java.util.Collection;

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

import com.style24.front.biz.dao.TsfRecentlyGoodsDao;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.RecentlyGoods;

import lombok.extern.slf4j.Slf4j;

/**
 * 최근본상품 Service
 *
 * @author gagamel
 * @since 2021. 5. 13
 */
@Service
@Slf4j
public class TsfRecentlyGoodsService {

	@Autowired
	private TsfRecentlyGoodsDao recentlyGoodsDao;

	/**
	 * 최근본상품 저장
	 * @param goodsCd - 상품코드
	 * @author gagamel
	 * @since 2021. 5. 13
	 */
	@Transactional("shopTxnManager")
	public void createRecentlyGoods(String goodsCd) {
		RecentlyGoods recentlyGoods = new RecentlyGoods();
		recentlyGoods.setGoodsCd(goodsCd);
		recentlyGoods.setJsessionId(TsfSession.getSessionId());

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

		// 최근본상품 건수
		int totCnt = recentlyGoodsDao.getRecentlyGoodsTotalCount(recentlyGoods);

		if (totCnt > 50) {
			// 맨 처음 등록된 상품 삭제
			recentlyGoodsDao.deleteRecentlyFirstGoods(recentlyGoods);
		}
		
		// 등록 여부 
		int ownCnt = recentlyGoodsDao.getRecentlyGoodsOwnCount(recentlyGoods);
		if (ownCnt > 0) {
			recentlyGoodsDao.updateRecentlyGoods(recentlyGoods);
		}else {
			// 최근본상품 생성
			recentlyGoodsDao.createRecentlyGoods(recentlyGoods);
		}
	}

	/**
	 * 로그인 후 최근본상품 Update
	 * 		회원 로그인 후 호출됨으로 세션 정보 있음
	 * @param custNo - 고객번호
	 * @author gagamel
	 * @since 2021. 5. 13
	 */
	@Transactional("shopTxnManager")
	public void updateRecentlyGoodsAfterLogin(Integer custNo) {
		RecentlyGoods recentlyGoods = new RecentlyGoods();
		recentlyGoods.setJsessionId(TsfSession.getSessionId());
		recentlyGoods.setCustNo(custNo);
		recentlyGoodsDao.updateRecentlyGoodsAfterLogin(recentlyGoods);
	}

	/**
	 * 최근본상품 목록
	 * @return
	 * @author gagamel
	 * @date 2021. 3. 22
	 */
	public Collection<RecentlyGoods> getRecentlyGoodsList() {
		RecentlyGoods recentlyGoods = new RecentlyGoods();
		recentlyGoods.setJsessionId(TsfSession.getSessionId());

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

		return recentlyGoodsDao.getRecentlyGoodsList(recentlyGoods);
	}

}
