package com.style24.front.biz.service;

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

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

import com.gagaframework.web.util.GagaDateUtil;
import com.style24.core.biz.dao.TscCouponDao;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.env.TscConstants;
import com.style24.front.biz.dao.TsfCouponDao;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.CustCoupon;
import com.style24.persistence.domain.CustGrade;
import com.style24.persistence.domain.Customer;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.Login;
import com.style24.persistence.domain.Order;

import lombok.extern.slf4j.Slf4j;

/**
 * 쿠폰 Service
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Service
@Slf4j
public class TsfCouponService {

	@Autowired
	private TsfCouponDao couponDao;

	@Autowired
	private TscCouponDao coreCouponDao;

	@Autowired
	private TscOrderService coreOrderService;

	@Autowired
	private TsfOrderService orderService;

	@Autowired
	private TsfCustomerService customerService;

	/**
	 * 시리얼 쿠폰 지급 정보 조회
	 * @param param
	 * @return
	 * @author xodud1202
	 * @since 2021. 02. 16
	 */
	public Coupon getSerialCpnUseInfo(Coupon param) {
		return couponDao.getSerialCpnUseInfo(param);
	}

	/**
	 * 시리얼 쿠폰 적용
	 * @param param
	 * @return
	 * @author xodud1202
	 * @since 2021. 02. 16
	 */
	public Coupon serialCpnApplyInfo(Coupon param) {
		if (TsfSession.isLogin()) {
			Login login = TsfSession.getInfo();
			param.setCustNo(login.getCustNo());
			param.setRegNo(login.getCustNo());
			param.setUpdNo(login.getCustNo());
		} else {
			throw new IllegalStateException("로그인을 해야합니다.");
		}

		param.setFrontGb(TsfSession.getFrontGb());

		// 시리얼키의 쿠폰이 다운로드 가능한지 확인
		Coupon cpn = couponDao.getSearchSerialCpnInfo(param);

		// 다운로드 받을 수 있는 쿠폰이 있으면
		if (cpn != null && cpn.getCpnId() > 0) {
			// 다운 받을 수 있는 쿠폰ID를 내가 받은 이력이 있는지 확인
			cpn.setCustNo(param.getCustNo());
			Coupon myCpn = couponDao.getSerialCpnUseInfo(cpn);

			// 다운로드 받은 쿠폰이 있는 경우
			if (myCpn != null && myCpn.getCpnId() > 0) {
				// 이미 다운 받았고, 사용 한 쿠폰이 있을 경우 종료
				if (!StringUtils.isEmpty(myCpn.getUsedDt())) {
					cpn.setResult("해당 쿠폰은 이미 사용하신 쿠폰입니다.");
					return cpn;
				} else if ("N".equals(myCpn.getAvailYn())) {
					cpn.setResult("지급 받으신 쿠폰의 유효기간이 아닙니다.");
					return cpn;
				} else if (!StringUtils.isEmpty(myCpn.getRdCpnNm()) && myCpn.getCnt() < 1) {
					cpn.setResult("동일 쿠폰을 " + myCpn.getRdCpnNm() + "으로 지급 받으셨습니다.<br/>해당 쿠폰을 사용해주세요.");
					return cpn;
				}
			} else {
				/* 다운받은 쿠폰이 아닐 경우 (tb_cust_coupon insert) */
				// 랜덤쿠폰 할당 및 쿠폰 지급
				cpn.setRegNo(param.getRegNo());
				cpn.setUpdNo(param.getUpdNo());
				updateGiveRandomCpnInfo(cpn);
				cpn.setDownloadCnt(1);
			}
		} else {
			// 다운로드 받을 수 있는 쿠폰이 존재하지 않음.
			cpn = new Coupon();
			cpn.setResult("할인코드가 일치하지 않습니다. 정확히 입력해주세요.");
			return cpn;
		}

		Coupon cpnInfo = couponDao.getSerialCpnUseInfo(cpn);

		cpn.setAvailStdtTime(cpnInfo.getAvailStdtTime());
		cpn.setAvailEddtTime(cpnInfo.getAvailEddtTime());
		cpn.setAvailStdt(cpnInfo.getAvailStdt());
		cpn.setAvailEddt(cpnInfo.getAvailEddt());
		cpn.setBuyLimitAmt(cpnInfo.getBuyLimitAmt());
		cpn.setMaxDcAmt(cpnInfo.getMaxDcAmt());
		cpn.setCpnNm(cpnInfo.getCpnNm());
		cpn.setCustPubLimitQty(cpnInfo.getCustPubLimitQty());
		cpn.setApplyScope(cpnInfo.getApplyScope());

		// 쿠폰 적용 대상조건명 및 조건별 수량 조회
		if (TscConstants.ApplyScope.INDIVIDUAL.value().equals(cpn.getApplyScope())) {
			Collection<Coupon> cpnRefInfo = couponDao.getCpnRefName(cpn);

			for (Coupon ref : cpnRefInfo) {
				if (TscConstants.CpnTarget.GOODS.value().equals(ref.getCpnTarget())) {
					cpn.setRefGoodsNm(ref.getRefVal());
					cpn.setRefGoodsCnt(ref.getCnt());
				} else if (TscConstants.CpnTarget.BRAND.value().equals(ref.getCpnTarget())) {
					if (ref.getCnt() > 1) {
						cpn.setRefBrandNm(ref.getRefVal() + " / " + ref.getSecondRefVal());
					} else {
						cpn.setRefBrandNm(ref.getRefVal());
					}
					cpn.setRefBrandCnt(ref.getCnt());
				} else if (TscConstants.CpnTarget.COMP.value().equals(ref.getCpnTarget())) {
					cpn.setRefSupplyCompNm(ref.getRefVal());
					cpn.setRefSupplyCompCnt(ref.getCnt());
				} else if (TscConstants.CpnTarget.CATE.value().equals(ref.getCpnTarget())) {
					cpn.setRefCateNm(ref.getRefVal());
					cpn.setRefCateCnt(ref.getCnt());
				}
			}
		}

		// 2021.03.03 장바구니 시퀀스 없음 jsh77b 
		// 장바구니쿠폰 토탈 할인 금액 계산
		if (param.getCartSqArr() != null) {
			param.setCpnId(cpn.getCpnId());
			cpn.setDcAmt(getCartCpnApplyTotalAmt(param));
		} else {
			Order order = new Order();

			/*
			// 3. 할인구간정보조회
			// 3.2 상품쿠폰, 장바구니쿠폰 목록 조회
			GagaMap goodsCartCpnMap = coreOrderService.getGoodsCartCpnApplyGoodsList(order);
			
			Collection<Order> goodsCpnList 	= (Collection<Order>) goodsCartCpnMap.get("goodsCpnList");
			Collection<Order> cartCpnList 	= (Collection<Order>) goodsCartCpnMap.get("cartCpnList");
			
			// 3.2.1 상품기준 ---> 상품쿠폰 적용된 상품 목록
			Collection<Order> goodsApplyCpnList = coreOrderService.getGoodsCpnApplyList(tmtbGoodsApplyList, goodsCpnList);
			
			// 3.2.2 장바구니쿠폰기준 ---> 상품목록
			cartCpnList = coreOrderService.getCartCpnApplyList(tmtbGoodsApplyList, cartCpnList);
			*/

		}

		cpn.setResult("SUCCESS");

		return cpn;
	}

	// 장바구니쿠폰 토탈 할인 금액 계산
	public int getCartCpnApplyTotalAmt(Coupon param) {
		// 쿠폰 할당 금액 세팅
		Order order = new Order();
		order.setCustNo(param.getCustNo());
		order.setCartSqArr(param.getCartSqArr());
		order.setCpnId(param.getCpnId());
		order.setFrontGb(TsfSession.getFrontGb());

		// 장바구니에 등록된 상품 중 적용 상품 조회
		int totDcAmt = 0;
		int totCurrPrice = 0;
		int maxDcAmt = 0;
		int buyLimitAmt = 0;
		if (param != null && param.getCartSqArr().length > 0) {
			Collection<Order> serialGoodsList = coreOrderService.getSerialCpnApplyGoodsList(order);
			for (int i = 0; i < param.getCartSqArr().length; i++) {
				for (Order cpnInfo : serialGoodsList) {
					if ("A".equals(cpnInfo.getApplyScope()) || param.getCartSqArr()[i] == cpnInfo.getCartSq()) {
						cpnInfo.setCurrPrice(param.getCurrPrices()[i]);
					}
				}
			}

			// 각 필요 데이터 세팅
			for (Order info : serialGoodsList) {
				totCurrPrice = totCurrPrice + info.getCurrPrice();					// 적용 상품 구매 금액 합계((즉시할인쿠폰 + 옵션추가) * 수량)
				maxDcAmt = info.getMaxDcAmt();										// 최대할인율과 최소주문금액은 한 쿠폰에 값이 동일
				buyLimitAmt = info.getBuyLimitAmt();								// 최대할인율과 최소주문금액은 한 쿠폰에 값이 동일
				if (TscConstants.DcWay.RATE.value().equals(info.getDcWay())) {		// 할인방식이 할인율이면 각 상품별 할인금액을 따로 계산해야함
					int dcAmt = (int)(info.getCurrPrice() * (info.getDcVal() / 100.0));		// 해당상품 할인금
					totDcAmt = totDcAmt + dcAmt;									// 적용 상품 총 할인금액
				} else {															// 할인 방식이 금액일 경우
					totDcAmt = info.getDcVal();
				}
			}

			if (totCurrPrice < totDcAmt) {
				totDcAmt = totCurrPrice;
			}

			// 최대 할인 금액 요건 확인 (0은 제한 없음. 최대 할인 금액보다 할인금액이 크다면 최대할인금액만큼만 할인)
			if (maxDcAmt > 0 && maxDcAmt < totDcAmt) {
				totDcAmt = maxDcAmt;
			}

			// 주문 최소 금액 요건 확인 (최소 주문 금액보다 총 상품 금액이 적으면 0원으로 세팅)
			if (buyLimitAmt > totCurrPrice) {
				totDcAmt = 0;
			}
		}

		return totDcAmt;
	}

	@Transactional("shopTxnManager")
	public void updateGiveRandomCpnInfo(Coupon param) {
		// 랜덤쿠폰 할당 및 쿠폰 지급
		CustCoupon custCoupon = new CustCoupon();
		custCoupon.setCustNo(param.getCustNo());
		custCoupon.setRegNo(param.getRegNo());
		custCoupon.setUpdNo(param.getUpdNo());
		custCoupon.setCpnId(param.getCpnId());
		custCoupon.setRdCpnId(param.getRdCpnId());
		custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
		custCoupon.setAvailStdt(param.getAvailStdt());
		custCoupon.setAvailEddt(param.getAvailEddt());
		custCoupon.setPubReason("G068_60");		// 쿠폰 발행사유 (랜덤쿠폰등록)
		custCoupon.setPubReasonDtl(param.getRdCpnNm() + " 쿠폰 등록");

		// 트랜잭션을 묶기 위해 dao 직접 호출
		coreCouponDao.updateGiveRandomCoupon(custCoupon);		// 랜덤쿠폰 CUST_NO UPDATE
		coreCouponDao.saveCouponCustPub(custCoupon);			// 랜덤쿠폰 고객 지급
	}

	/**
	 * 마이페이지 등급쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return Collection<Coupon>
	 * @author card007
	 * @since 2021.02.25
	 */
	@Transactional("shopTxnManager")
	public int createCustGradeAllCoupon(Coupon coupon) {
		int count = 0;

		Collection<Coupon> couponList = couponDao.getCustGradeCouponInfo(coupon);

		for (Coupon tmpCoupon : couponList) {
			int downloadCnt = tmpCoupon.getDownloadCnt();
			for (int i = 0; i < downloadCnt; i++) {
				CustCoupon custCoupon = new CustCoupon();
				custCoupon.setCustNo(tmpCoupon.getCustNo());
				custCoupon.setCpnId(tmpCoupon.getCpnId());
				custCoupon.setAvailStdt(tmpCoupon.getAvailStdt());
				custCoupon.setAvailEddt(tmpCoupon.getAvailEddt());
				custCoupon.setPubReason(TscConstants.PubReason.DOWNLOAD.value());
				custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
				custCoupon.setRegNo(tmpCoupon.getCustNo());
				custCoupon.setUpdNo(tmpCoupon.getCustNo());

				coreCouponDao.saveCouponCustPub(custCoupon);

				count++;
			}
		}

		return count;
	}

	/**
	 * 회원가입시 혜택 쿠폰지급
	 *
	 * @param coupon - 쿠폰정보
	 * @author jsshin
	 * @since 2021.03.03
	 */
	@Transactional("shopTxnManager")
	public void saveJoinCoupon(Coupon coupon) {
		Coupon joinCoupon = couponDao.getJoinCoupon(coupon);
		if (joinCoupon != null) {
			CustCoupon custCoupon = new CustCoupon();
			custCoupon.setCustNo(coupon.getCustNo());
			custCoupon.setCpnId(joinCoupon.getCpnId());
			custCoupon.setAvailStdt(joinCoupon.getAvailStdt());
			custCoupon.setAvailEddt(joinCoupon.getAvailEddt());
			custCoupon.setPubReason(TscConstants.PubReason.JOIN.value());
			custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
			custCoupon.setUpdNo(coupon.getCustNo());
			custCoupon.setRegNo(coupon.getCustNo());
			coreCouponDao.saveCouponCustPub(custCoupon);
		}
	}

	/**
	 * 상품 쿠폰 조회
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021.03.11
	 */
	public Collection<Coupon> getGoodsCouponList(Goods goods) {
		return couponDao.getGoodsCouponList(goods);
	}

	/**
	 * 딜상품 쿠폰 조회
	 * @param Goods
	 * @return Collection<Coupon>
	 * @author card007
	 * @since 2021. 08. 24
	 */
	public Collection<Coupon> getGoodsDealCouponList(Goods goods) {
		Collection<Coupon> couponList = new ArrayList<>();
		List<Integer> cpnIdList = new ArrayList<>();

		for (Coupon coupon : couponDao.getGoodsCouponList(goods)) {
			Integer cpnId = coupon.getCpnId();

			if(!cpnIdList.contains(cpnId)) {
				cpnIdList.add(cpnId);
				couponList.add(coupon);
			}
		}

		return couponList;
	}

	/**
	 * 상품 즉시할인 쿠폰 조회
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021.05.01
	 */
	public Collection<Coupon> getGoodsCoupon1List(Goods goods) {
		return couponDao.getGoodsCoupon1List(goods);
	}

	/**
	 * ep 쿠폰 조회
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2021.04.15
	 */
	public Collection<Coupon> getGoodsEpCouponList(Goods goods) {
		return couponDao.getGoodsEpCouponList(goods);
	}

	/**
	 * 상품 쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return int
	 * @author eskim
	 * @since 2021.03.12
	 */
	@Transactional("shopTxnManager")
	public String createGoodsCoupon(Goods parmsGoods) {
		String result = "SUCESS";
		
		log.info("상품쿠폰 발급전 정보 goods {}", parmsGoods);
		
		// 쿠폰 모두 받기
		if (parmsGoods.getArrGoodsCd() != null && parmsGoods.getArrGoodsCd().length > 0) {
			
			int idx = 0;
			int couponCnt = 0; 
			for (String goodsCd : parmsGoods.getArrGoodsCd()) {
				Goods goods = new Goods();
				goods.setGoodsCd(goodsCd);
				goods.setCpnId(parmsGoods.getArrCpnId()[idx]);
				goods.setCpnAllDownYn(parmsGoods.getCpnAllDownYn());
				goods.setSiteCd(parmsGoods.getSiteCd());
				goods.setCustGb(parmsGoods.getCustGb());
				goods.setFrontGb(parmsGoods.getFrontGb());
				goods.setPointUnit(parmsGoods.getPointUnit());
				goods.setCustGrade(parmsGoods.getCustGrade());
				goods.setCustNo(parmsGoods.getCustNo());
				
				result =  createCoupon(goods);
				
				if (result.indexOf("ERROR") < 0) {
					couponCnt += Integer.parseInt(result);
				}
				
				idx++;
			}
			
			if (couponCnt > 0) {
				result = Integer.toString(couponCnt);	
			}else {
				result = "ERROR_10";
			}
			
		}else {
			result =  createCoupon(parmsGoods);
		
		}

		return result;
	}

	private String createCoupon(Goods goods) {
		
		String result = "";
		int downloadCnt = 1; 	// 쿠폰당 다운 받을수
		int custPubLimitQty = 1;
		int onePubQty = 1;
		Collection<Coupon> goodsCouponList = couponDao.getGoodsCouponList(goods);
		
		if (goodsCouponList == null || goodsCouponList.isEmpty()) {
			result = "ERROR_10";
			return result;
		}

		Coupon coupon = goodsCouponList.iterator().next();
		onePubQty = coupon.getOnePubQty();	// 1회 발급당 발행수량 설정

		//log.info("상품쿠폰 쿠폰정보  coupon {}", coupon);

		// 고객당 발급수량 확인
		if (coupon.getCustPubLimitQty() > 0) {
			int tempCustCouponCnt = coupon.getCustPubLimitQty() * onePubQty;
			//if (coupon.getCustPubLimitQty() <= coupon.getCustCouponCnt()) {
			if (tempCustCouponCnt <= coupon.getCustCouponCnt()) {
				//log.info("상품쿠폰 다운  skip: 쿠폰발급수 : {}, 회원발급수 : {}", coupon.getCustPubLimitQty(), coupon.getCustCouponCnt());
				result = "ERROR_30";
				return result;
			}
		}
		
		// 발급수 확인
		if (coupon.getTotPubLimitQty() > 0) {
			if (coupon.getTotPubLimitQty() <= coupon.getTotCouponCnt()) {
				//log.info("상품쿠폰 다운  skip: 쿠폰총발급제한수 : {}, 전체발급수 : {}", coupon.getTotPubLimitQty(), coupon.getTotCouponCnt());
				result = "ERROR_30";
				return result;
			}
		}

		// 회원정보 확인 - 발급등급,첫구매, 신규회원, 제휴링크

		// 회원등급 USABLE_CUST_GRADE
		if (coupon.getUsableCustGrade().indexOf(goods.getCustGrade()) < 0) {
			//log.info("상품쿠폰 다운  skip: 쿠폰등급 : {}, 회원등급 : {}", coupon.getUsableCustGrade(), goods.getCustGrade());
			result = "ERROR_20";
			return result;
		}

		// 첫구매여부 (Y:구매이력이없음 | N:구매이력있음) - 구매기간일자 해당기간에 구매이력이 없으면 다운로드 가능
		if ("Y".equals(coupon.getFirstOrdYn())) {
			int firstOrdcnt = orderService.getCustFirstOrderCount(coupon);
			if (firstOrdcnt > 0) {
				//log.info("상품쿠폰 다운  skip: 쿠폰첫구매정보 : {}, {} ~ {} ", coupon.getFirstOrdYn(), coupon.getBuyStdt(), coupon.getBuyEddt());
				result = "ERROR_20";
				return result;
			}
		}

		//총발급수량
		downloadCnt = custPubLimitQty * onePubQty;
		
		// 신규회원 NEW_CUST_YN
		if ("Y".equals(coupon.getNewCustYn())) {
			Customer customer = customerService.getCustomerFindByCustNo(goods.getCustNo());
			if (customer == null || StringUtils.isEmpty(customer.getJoinDt())) {
				//log.info("상품쿠폰 다운  skip: 쿠폰 신규회원정보 : {} 회원정보 없음", coupon.getCustNo());
				result = "ERROR_20";
				return result;
			}
			//log.info("고객정보 customer {}", customer);
			if (Long.parseLong(customer.getJoinDt()) < Long.parseLong(coupon.getCustJoinStdt()) ||
				Long.parseLong(customer.getJoinDt()) > Long.parseLong(coupon.getCustJoinEddt())) {
				//log.info("상품쿠폰 다운  skip: 쿠폰 신규회원정보 : {}, {} ~ {} ", customer.getJoinDt(), coupon.getCustJoinStdt(), coupon.getCustJoinEddt());
				result = "ERROR_20";
				return result;
			}
		}

		int count = 0;
		for (Coupon tmpCoupon : goodsCouponList) {

			for (int i = 0; i < downloadCnt; i++) {
				CustCoupon custCoupon = new CustCoupon();
				custCoupon.setCustNo(TsfSession.getInfo().getCustNo());
				custCoupon.setCpnId(tmpCoupon.getCpnId());
				custCoupon.setAvailStdt(tmpCoupon.getAvailStdt());
				custCoupon.setAvailEddt(tmpCoupon.getAvailEddt());
				custCoupon.setPubReason(TscConstants.PubReason.DOWNLOAD.value());
				custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
				custCoupon.setRegNo(TsfSession.getInfo().getCustNo());
				custCoupon.setUpdNo(TsfSession.getInfo().getCustNo());

				//log.info("상품쿠폰 고객 다운로드 custCoupon {}", custCoupon);
				coreCouponDao.saveCouponCustPub(custCoupon);

				count++;
			}
		}
		result = Integer.toString(count);	// 다운받은 쿠폰수
		
		return result;
		
	}

	/**
	 * 마이페이지 쿠폰 조회
	 * @param coupon
	 * @return
	 * @author sowon
	 * @since 2021.03.16
	 */
	public Collection<Coupon> getMypageCouponList(Coupon coupon) {
		coupon.setCustNo(TsfSession.getInfo().getCustNo());
		coupon.setFrontGb(TsfSession.getFrontGb());
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		return couponDao.getMypageCouponList(coupon);
	}

	/**
	 * 마이페이지 (사용가능,만료예정)쿠폰 수 조회
	 * @param param
	 * @return
	 * @author sowon
	 * @since 2021. 03. 16
	 */
	public Coupon getMypageCouponInfo(Coupon param) {
		param.setCustNo(TsfSession.getInfo().getCustNo());
		param.setFrontGb(TsfSession.getFrontGb());
		param.setSiteCd(TscConstants.Site.STYLE24.value());
		return couponDao.getMypageCouponInfo(param);
	}

	/**
	 * 마이페이지 쿠폰 디테일 정보
	 * @param cpnId
	 * @return
	 * @author sowon
	 * @since 2021. 03. 16
	 */
	public Coupon getCouponDetailInfo(Coupon coupon) {
		if (TsfSession.isLogin()) {
			coupon.setCustNo(TsfSession.getInfo().getCustNo());
		}
		coupon.setFrontGb(TsfSession.getFrontGb());
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		return couponDao.getCouponDetailInfo(coupon);
	}

	/**
	 * 기획전 쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return Collection<Coupon>
	 * @author sowon
	 * @since 2021.02.25
	 */
	@Transactional("shopTxnManager")
	public String getPlanCouponInfo(Coupon coupon) {
		int downloadCnt = 1; 	// 쿠폰당 다운 받을수
		int custPubLimitQty = 1;
		int onePubQty = 1;

		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		coupon.setFrontGb(TsfSession.getFrontGb());
		coupon.setCustGb(TsfSession.getCustGb());
		coupon.setCustNo(TsfSession.getInfo().getCustNo());
		coupon.setCustGrade(TsfSession.getInfo().getCustGrade());
		String result = "SUCESS";
		Collection<Coupon> couponList = couponDao.getPlanCouponInfo(coupon);
		
		
		if (couponList == null || couponList.isEmpty()) {
			result = "ERROR_10";
			return result;
		}
		Coupon temp = couponList.iterator().next();
		temp.setCustNo(TsfSession.getInfo().getCustNo());
		onePubQty = temp.getOnePubQty();	// 1회 발급당 발행수량 설정

		log.info("기획전 쿠폰정보  temp {}", temp);

		// 고객당 발급수량 확인
		if (temp.getCustPubLimitQty() > 0) {
			int tempCustCouponCnt = temp.getCustPubLimitQty() * onePubQty;
			//if (coupon.getCustPubLimitQty() <= coupon.getCustCouponCnt()) {
			log.info("기획전쿠폰 다운  skip: tempCustCouponCnt : {}, temp.getCustPubLimitQty() : {} , onePubQty : {}", tempCustCouponCnt, temp.getCustPubLimitQty(), onePubQty);
			if (tempCustCouponCnt <= temp.getCustCouponCnt()) {
				log.info("기획전쿠폰 다운  skip: 쿠폰발급수 : {}, 회원발급수 : {}", temp.getCustPubLimitQty(), temp.getCustCouponCnt());
				result = "ERROR_30";
				return result;
			}
		}

		log.info("기획전쿠폰 다운 쿠폰총발급제한수  skip: temp.getTotPubLimitQty() : {}, temp.getTotCouponCnt() : {} ", temp.getTotPubLimitQty(), temp.getTotCouponCnt());
		// 발급수 확인
		if (temp.getTotPubLimitQty() > 0) {
			if (temp.getTotPubLimitQty() <= temp.getTotCouponCnt()) {
				log.info("기획전쿠폰 다운  skip: 쿠폰총발급제한수 : {}, 전체발급수 : {}", temp.getTotPubLimitQty(), temp.getTotCouponCnt());
				result = "ERROR_40";
				return result;
			}
		}
		
//		if (temp.getTotPubLimitQty() > 0) {
//			if (temp.getCustPubLimitQty() <= temp.getCustCouponCnt()) {
//				result = "ERROR_30";
//				return result;
//			}
//		}

		// 첫구매여부 (Y:구매이력이없음 | N:구매이력있음) - 구매기간일자 해당기간에 구매이력이 없으면 다운로드 가능
		if ("Y".equals(temp.getFirstOrdYn())) {
			int firstOrdcnt = orderService.getCustFirstOrderCount(temp);
			if (firstOrdcnt > 0) {
				//log.info("상품쿠폰 다운  skip: 쿠폰첫구매정보 : {}, {} ~ {} ", coupon.getFirstOrdYn(), coupon.getBuyStdt(), coupon.getBuyEddt());
				result = "ERROR_20";
				return result;
			}
		}

		for (Coupon tmpCoupon : couponList) {
			//int downloadCnt = tmpCoupon.getDownloadCnt();
			for (int i = 0; i < couponList.size(); i++) {
				if (couponList.iterator().next().getOwnCoupon() == 0) {
					CustCoupon custCoupon = new CustCoupon();
					custCoupon.setCustNo(TsfSession.getInfo().getCustNo());
					custCoupon.setCpnId(tmpCoupon.getCpnId());
					custCoupon.setAvailStdt(tmpCoupon.getAvailStdt());
					custCoupon.setAvailEddt(tmpCoupon.getAvailEddt());
					custCoupon.setPubReason(TscConstants.PubReason.DOWNLOAD.value());
					custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
					custCoupon.setRegNo(TsfSession.getInfo().getCustNo());
					custCoupon.setUpdNo(TsfSession.getInfo().getCustNo());

					coreCouponDao.saveCouponCustPub(custCoupon);
				}
			}
		}
		return result;
	}

	/*
	 * 정책 등급쿠폰 발급
	 *
	 * @param  custGrade - 고객번호
	 * @return int : 받은 쿠폰 수량
	 * @author jsshin
	 * @since 2021. 04. 06
	 */
	@Transactional("shopTxnManager")
	public int downloadCustGradeCoupon(Integer custNo) {

		if (custNo == null || custNo == 0) {
			throw new IllegalStateException("고객정보가 없습니다. 다시 로그인 하시기 바랍니다.");
		}

		// 1. 고객정보 조회
		Customer custInfo = customerService.getCustomerFindByCustNo(custNo);

		// 2. 등급쿠폰 조회
		CustGrade params = new CustGrade();
		params.setCustNo(custInfo.getCustNo());
		params.setSiteCd(custInfo.getSiteCd());
		params.setGradeCd(custInfo.getCustGrade());
		List<CustGrade> custGradeCollection = (List<CustGrade>)customerService.getCustGradePolicy(params);
		CustGrade custGradePolicy = custGradeCollection.get(0);

		// 3.WELCOME 등급 - 첫번째 쿠폰은 회원 가입시 지급
		if (TscConstants.CustGrade.WELCOME.value().equals(custGradePolicy.getGradeCd())) {
			custGradePolicy.setGradeCpnId1("0");
		}

		String frontGb = TsfSession.getFrontGb();
		// 4. 회원등급 정책 쿠폰1 발급
		Coupon couponFirst = new Coupon();
		couponFirst.setCustNo(custNo);
		couponFirst.setCpnId(Integer.parseInt(custGradePolicy.getGradeCpnId1()));
		couponFirst.setFrontGb(frontGb);
		couponFirst.setPubReason(TscConstants.PubReason.CHANGE_CUSTOMER_GRADE.value());
		int custGradeCpnFirst = saveCustGradeCoupon(couponFirst);

		// 5. 회원등급 정책 쿠폰2 발급
		Coupon couponSecond = new Coupon();
		couponSecond.setCustNo(custNo);
		couponSecond.setCpnId(Integer.parseInt(custGradePolicy.getGradeCpnId2()));
		couponSecond.setFrontGb(frontGb);
		couponSecond.setPubReason(TscConstants.PubReason.CHANGE_CUSTOMER_GRADE.value());
		int custGradeCpnSecond = saveCustGradeCoupon(couponSecond);

		// 6. 회원등급 정책 쿠폰3 발급(생일쿠폰)
		int birthCpn = 0;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(custInfo.getBirthYmd()) && custInfo.getBirthYmd().length() > 7) {
			String currentMonth = GagaDateUtil.getToday().substring(4, 6);
			String birthMonth = custInfo.getBirthYmd().substring(4, 6);
			log.info("currentMonth ===> {}, birthMonth ===> {}", currentMonth, birthMonth);
			if (currentMonth.equals(birthMonth)) {
				Coupon couponThird = new Coupon();
				couponThird.setCustNo(custNo);
				couponThird.setCpnId(Integer.parseInt(custGradePolicy.getGradeCpnId3()));
				couponThird.setFrontGb(frontGb);
				couponThird.setPubReason(TscConstants.PubReason.BIRTHDAY.value());
				birthCpn = saveCustGradeCoupon(couponThird);
			}
		}
		return custGradeCpnFirst + custGradeCpnSecond + birthCpn;
	}

	/**
	 * 등급쿠폰 발급
	 *
	 * @param coupon - 쿠폰 아이디, 고객번호
	 * @return int - 결과
	 * @author jsshin
	 * @since 2021.04.08
	 */
	@Transactional("shopTxnManager")
	public int saveCustGradeCoupon(Coupon coupon) {
		int resultCnt = 0;
		if (coupon.getCpnId() > 0) {
			Coupon custGradeCoupon = couponDao.getCustGradePolicyCoupon(coupon);
			if (custGradeCoupon != null) {
				CustCoupon custCoupon = new CustCoupon();
				custCoupon.setCustNo(coupon.getCustNo());
				custCoupon.setCpnId(custGradeCoupon.getCpnId());
				custCoupon.setAvailStdt(custGradeCoupon.getAvailStdt());
				custCoupon.setAvailEddt(custGradeCoupon.getAvailEddt());
				custCoupon.setPubReason(coupon.getPubReason());
				custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
				custCoupon.setUpdNo(coupon.getCustNo());
				custCoupon.setRegNo(coupon.getCustNo());
				resultCnt = coreCouponDao.saveCouponCustPub(custCoupon);
			}
		}
		return resultCnt;
	}

	/**
	
	 * EP 쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return int
	 * @author eskim
	 * @since 2021.03.12
	 */
	@Transactional("shopTxnManager")
	public String createEpCoupon(Goods goods) {
		String result = "SUCESS";
		int downloadCnt = 1; 	// 쿠폰당 다운 받을수

		Collection<Coupon> goodsCouponList = couponDao.getGoodsEpCouponList(goods);
		if (goodsCouponList == null || goodsCouponList.isEmpty()) {
			result = "ERROR_10";
			return result;
		}

		Coupon coupon = goodsCouponList.iterator().next();

		// 발급수 확인 -- 필요없나?
		if (coupon.getTotPubLimitQty() > 0) {
			if (coupon.getTotPubLimitQty() <= coupon.getCustCouponCnt()) {
				result = "ERROR_30";
				return result;
			}
		}

		// 회원정보 확인 - 발급등급,첫구매, 신규회원, 제휴링크

		// 회원등급 USABLE_CUST_GRADE
		if (coupon.getUsableCustGrade().indexOf(goods.getCustGrade()) < 0) {
			result = "ERROR_20";
			return result;
		}

		// 첫구매여부 (Y:구매이력이없음 | N:구매이력있음) - 구매기간일자 해당기간에 구매이력이 없으면 다운로드 가능
		if ("Y".equals(coupon.getFirstOrdYn())) {
			int firstOrdcnt = orderService.getCustFirstOrderCount(coupon);
			if (firstOrdcnt > 0) {
				result = "ERROR_20";
				return result;
			}
		}

		// 신규회원 NEW_CUST_YN
		if ("Y".equals(coupon.getNewCustYn())) {
			Customer customer = customerService.getCustomerFindByCustNo(goods.getCustNo());
			if (customer == null || StringUtils.isEmpty(customer.getJoinDt())) {
				result = "ERROR_20";
				return result;
			}
			if (Integer.parseInt(customer.getJoinDt()) < Integer.parseInt(coupon.getCustJoinStdt()) ||
				Integer.parseInt(customer.getJoinDt()) > Integer.parseInt(coupon.getCustJoinEddt())) {
				result = "ERROR_20";
				return result;
			}
		}

		int count = 0;
		for (Coupon tmpCoupon : goodsCouponList) {
			for (int i = 0; i < downloadCnt; i++) {
				CustCoupon custCoupon = new CustCoupon();
				custCoupon.setCustNo(TsfSession.getInfo().getCustNo());
				custCoupon.setCpnId(tmpCoupon.getCpnId());
				custCoupon.setAvailStdt(tmpCoupon.getAvailStdt());
				custCoupon.setAvailEddt(tmpCoupon.getAvailEddt());
				custCoupon.setPubReason(TscConstants.PubReason.DOWNLOAD.value());
				custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
				custCoupon.setRegNo(TsfSession.getInfo().getCustNo());
				custCoupon.setUpdNo(TsfSession.getInfo().getCustNo());

				coreCouponDao.saveCouponCustPub(custCoupon);

				count++;
			}
		}
		result = Integer.toString(count);	// 다운받은 쿠폰수

		return result;
	}

	/* 출석체크 쿠폰  정보
	* @param coupon - 쿠폰정보
	* @return Coupon
	* @author sowon
	* @since 2021. 04. 15
	*/
	public CustCoupon getAttendCouponInfo(CustCoupon coupon) {
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		coupon.setFrontGb(TsfSession.getFrontGb());
		return couponDao.getAttendCouponInfo(coupon);
	}

	/**
	 * 퀵메뉴 다운가능 쿠폰 리스트
	 * 
	 * @param coupon
	 * @return Collection<Coupon>
	 * @author sowon
	 * @since 2021.04.23
	 */
	public Collection<Coupon> getQuickCouponDownList(Coupon coupon) {
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		coupon.setFrontGb(TsfSession.getFrontGb());
		coupon.setCustGb(TsfSession.getCustGb());
		coupon.setCustNo(TsfSession.getInfo().getCustNo());
		coupon.setCustGrade(TsfSession.getInfo().getCustGrade());
		return couponDao.getQuickCouponDownList(coupon);
	}

	/**
	 * 퀵메뉴 쿠폰 다운
	 *
	 * @param coupon - 쿠폰 아이디, 고객번호
	 * @return int - 결과
	 * @author sowon
	 * @since 2021.04.23
	 */
	@Transactional("shopTxnManager")
	public String saveQuickCoupon(Coupon coupon) {
		//String result = "SUCESS";
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		coupon.setFrontGb(TsfSession.getFrontGb());
		coupon.setCustGb(TsfSession.getCustGb());
		coupon.setCustNo(TsfSession.getInfo().getCustNo());
		coupon.setCustGrade(TsfSession.getInfo().getCustGrade());
		Collection<Coupon> quickCouponList = couponDao.getQuickCouponDownList(coupon);
		
		Coupon temp = quickCouponList.iterator().next();
		String result = "SUCESS";

		if (quickCouponList == null || quickCouponList.isEmpty()) {
			result = "ERROR_10";
			return result;
		}
		
		if (temp.getTotPubLimitQty() > 0) {
			if (temp.getCustPubLimitQty() <= temp.getCustCouponCnt()) {
				result = "ERROR_30";
				return result;
			}
		}
		// 첫구매여부 (Y:구매이력이없음 | N:구매이력있음) - 구매기간일자 해당기간에 구매이력이 없으면 다운로드 가능
		if ("Y".equals(temp.getFirstOrdYn())) {
			int firstOrdcnt = orderService.getCustFirstOrderCount(temp);
			if (firstOrdcnt > 0) {
				//log.info("상품쿠폰 다운  skip: 쿠폰첫구매정보 : {}, {} ~ {} ", coupon.getFirstOrdYn(), coupon.getBuyStdt(), coupon.getBuyEddt());
				result = "ERROR_20";
				return result;
			}
		}

		if (coupon.getCpnId() > 0) {
			for (Coupon quickCoupon : quickCouponList) {
				if (quickCoupon != null) {
					CustCoupon custCoupon = new CustCoupon();
					custCoupon.setCustNo(coupon.getCustNo());
					custCoupon.setCpnId(quickCoupon.getCpnId());
					custCoupon.setAvailStdt(quickCoupon.getAvailStdt());
					custCoupon.setAvailEddt(quickCoupon.getAvailEddt());
					custCoupon.setPubReason(TscConstants.PubReason.DOWNLOAD.value());
					custCoupon.setEndAlimSendYn("N");		// 알림 발송 여부(발송되면 Y)
					custCoupon.setUpdNo(coupon.getCustNo());
					custCoupon.setRegNo(coupon.getCustNo());
					coreCouponDao.saveCouponCustPub(custCoupon);
				}
			}
		}
		//result = Integer.toString(count);	// 다운받은 쿠폰수

		return result;
	}

	/**
	 * 회원가입 쿠폰 정보 조회
	 *
	 *
	 * @return Coupon
	 * @author jsshin
	 * @since 2021. 05. 27
	 */
	public Coupon getJoinCouponInfo() {
		Coupon coupon = new Coupon();
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		coupon.setCustGrade(TscConstants.CustGrade.WELCOME.value());
		coupon.setFrontGb(TsfSession.getFrontGb());
		return couponDao.getJoinCoupon(coupon);
	}

	/**
	 * 기획전 쿠폰 디테일 정보
	 * @param cpnId
	 * @return
	 * @author bin2107
	 * @since 2021. 07. 07
	 */
	public Coupon getPlanCouponDetailInfo(Coupon coupon) {
		coupon.setFrontGb(TsfSession.getFrontGb());
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		return couponDao.getPlanCouponDetailInfo(coupon);
	}

}
