package com.style24.front.biz.web;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import com.style24.persistence.domain.CustGrade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
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.GagaResponseStatus;
import com.style24.core.biz.service.TscCouponService;
import com.style24.core.biz.service.TscCustomerService;
import com.style24.core.biz.service.TscPointService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.front.biz.service.TsfCouponService;
import com.style24.front.biz.service.TsfCustomerService;
import com.style24.front.biz.service.TsfDisplayService;
import com.style24.front.biz.service.TsfPlanningService;
import com.style24.front.biz.service.TsfReviewService;
import com.style24.front.support.controller.TsfBaseController;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.CustCoupon;
import com.style24.persistence.domain.CustDeliveryAddr;
import com.style24.persistence.domain.Customer;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.Plan;
import com.style24.persistence.domain.Point;
import com.style24.persistence.domain.Poll;
import com.style24.persistence.domain.Review;

import lombok.extern.slf4j.Slf4j;

/**
 * 기획전 Controller
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Controller
@RequestMapping("/planning")
@Slf4j
public class TsfPlanningController extends TsfBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsfPlanningService planningService;

	@Autowired
	private TscCustomerService coreCustomerService;

	@Autowired
	private TsfCouponService couponService;

	@Autowired
	private TscCouponService coreCouponService;

	@Autowired
	private TsfCustomerService customerService;

	@Autowired
	private TsfDisplayService displayService;

	@Autowired
	private TscPointService corePointService;

	@Autowired
	private TsfReviewService reviewService;

	/**
	 * 기획전 메인 화면
	 * @param cateNo - 카테고리번호
	 * @return
	 * @author sowon
	 * @since 2021. 3. 5
	 */
	@GetMapping("/main/form")
	public ModelAndView planningMainForm(@RequestParam(value = "cateNo", required = false) Integer cateNo, @RequestParam(value = "brandGroupNo", required = false) Integer brandGroupNo) {
		ModelAndView mav = new ModelAndView(super.getDeviceViewName("planning/PlanningMainForm"));

		Plan plan = new Plan();
		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setFrontGb(TsfSession.getFrontGb());

		// 기획전 카테고리 목록
		mav.addObject("cateList", planningService.getPlanningCategoryList(plan));

		mav.addObject("cateNo", cateNo);
		mav.addObject("brandGroupNo", brandGroupNo);
		if(!"".equals(brandGroupNo)){
			mav.addObject("brandGroupInfo", displayService.getGnbBrandGroup(brandGroupNo));
		}else{
			mav.addObject("brandGroupInfo", null);
		}

		return mav;
	}

	/**
	 * 기획전 메인 목록
	 * @param plan - 기획전 정보
	 * @param device - 디바이스 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 29
	 */
	@GetMapping("/main/list")
	@ResponseBody
	public Collection<Plan> getPlanningMainList(Plan plan, Device device) {
		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setFrontGb(TsfSession.getFrontGb());
		plan.setCustGb(TsfSession.getCustGb());
		plan.setCustNo(TsfSession.isLogin() ? TsfSession.getInfo().getCustNo() : 0);

		if (device.isNormal()) {
			plan.setMaxRow(2); // PC웹은 2개
		} else {
			plan.setMaxRow(3); // 모바일은 3개
		}

		return planningService.getPlanningMainList(plan);
	}

	/**
	 * 기획전 / 이벤트 상세화면
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 3. 9
	 */
	@GetMapping("/detail/form")
	public ModelAndView PlanningDetailForm(Plan plan) {
		ModelAndView mav = new ModelAndView();
		plan.setFrontGb(TsfSession.getFrontGb());
		// 접근 불가능한 기획전 메시지 조회
		String inaccessibleMsg = planningService.getInaccessiblePlanningMessage(plan);

		if (StringUtils.isNotBlank(inaccessibleMsg)) {
			if (!TsfSession.isLogin()) {
				mav.addObject("loginYn", "N");
			}else {
				mav.addObject("loginYn", "Y");
			}
			mav.addObject("inaccessibleMsg", inaccessibleMsg);
			mav.setViewName(super.getDeviceViewName("error/Inaccess"));
			return mav;
		}

		Review review = new Review();
		Coupon coupon = new Coupon();

		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setCustGb(TsfSession.getCustGb());
		review.setFrontGb(TsfSession.getFrontGb());
		review.setCustGb(TsfSession.getCustGb());
		if (TsfSession.isLogin()) {
			plan.setCustNo(TsfSession.getInfo().getCustNo());
		}

		// 기본 set
		plan.setExceptPlanSq(plan.getPlanSq());
		plan.setPlanSq(plan.getPlanSq());
		review.setPlanSq(plan.getPlanSq());
		coupon.setPlanSq(plan.getPlanSq());
		coupon.setSiteCd(TscConstants.Site.STYLE24.value());
		coupon.setFrontGb(TsfSession.getFrontGb());
		plan.setFrontGb(TsfSession.getFrontGb());

		Plan planInfo = planningService.getPlanDetailInfo(plan);
		String planGb = planInfo.getPlanGb();
		mav.addObject("planInfo", planInfo);

		mav.addObject("planCount", planningService.getPlanAllCount(plan));
		// 템플릿 순서
		mav.addObject("templateOrd", planningService.templateDispOrdInfo(plan));

		// 상단소스
		plan.setFrontGb("T");
		mav.addObject("fsrcInfoTop", planningService.getPlanFsrcInfo(plan));

		// 하단소스
		plan.setFrontGb("B");
		mav.addObject("fsrcInfoBtm", planningService.getPlanFsrcInfo(plan));

		// 리뷰
		plan.setTmplType("G082_10");
		mav.addObject("reviewInfo", planningService.getPlanReviewInfo(review));
		mav.addObject("reviewContent", planningService.getPlanContentInfo(plan));

		// 쿠폰
		plan.setTmplType("G082_20");
		plan.setAfLinkCd(TsfSession.getAttribute("afLinkCd"));
		mav.addObject("couponInfo", planningService.getPlanCouponInfo(coupon));
		mav.addObject("couponContent", planningService.getPlanContentInfo(plan));

		// 이미지
		mav.addObject("imageInfo", planningService.getPlanImageInfo(plan));

		// 유의사항
		mav.addObject("noticeInfo", planningService.getPlanNoticeInfo(plan));

		plan.setFrontGb(TsfSession.getFrontGb());
		// 상품1열 전시
		plan.setTmplType("G082_50");
		mav.addObject("goods1Info", planningService.getPlanGoodsDisplayList(plan));
		mav.addObject("goods1Content", planningService.getPlanContentInfo(plan));

		// 상품2열 전시
		plan.setTmplType("G082_51");
		mav.addObject("goods2Info", planningService.getPlanGoodsDisplayList(plan));
		mav.addObject("goods2Content", planningService.getPlanContentInfo(plan));

		// 상품4열 전시
		plan.setTmplType("G082_52");
		mav.addObject("goods4Info", planningService.getPlanGoodsDisplayList(plan));
		mav.addObject("goods4Content", planningService.getPlanContentInfo(plan));

		// 코너 목록
		mav.addObject("planCornerList", planningService.getPlanCornerList(plan));
		// 코너 상품
		mav.addObject("planCornerGoodsList", planningService.getPlanningCornerGoodsList(plan));

		// Popup Parameter
		mav.addObject("preview", plan.getPreview());
		mav.addObject("viewDt", plan.getViewDt());
		mav.addObject("viewPage", "G037_40");
		mav.addObject("popupPlanSq", plan.getPlanSq());

		if (planGb.equals("P")) {
			// 다른기획전 보기
			mav.addObject("planList", planningService.getPlanningList(plan));
			mav.addObject("listSize", planningService.getPlanningList(plan).size());
		}
		else if(planGb.equals("E")){
			// 다른이벤트 보기
			mav.addObject("planList", planningService.getPlanEventList(plan));
			mav.addObject("listSize", planningService.getPlanEventList(plan).size());
		}else if(planGb.equals("C")) {
			// 출석체크
			mav.addObject("planList", planningService.getPlanEventList(plan));
			mav.addObject("listSize", planningService.getPlanEventList(plan).size());
			mav.addObject("month", planningService.getAttendMonth(planInfo));
			mav.addObject("benefitList", planningService.getAttendBenefitList(plan));

			if (TsfSession.isLogin()) {
				mav.addObject("custAttendList",planningService.getCustAttendEntryList(plan));
			}
			mav.setViewName(super.getDeviceViewName("planning/PlanningEventAttendForm"));
			return mav;
		}

		// 브랜드그룹 정보 : 브랜드메인 링크에 설정된 기획전으로 들어올때 GNB 변경때문에 사용
		mav.addObject("brandGroupInfo", displayService.getGnbBrandGroup(plan.getBrandGroupNo()));

		mav.setViewName(super.getDeviceViewName("planning/PlanningDetailForm"));
		return mav;
	}

	/**
	 * 모바일 상품 2열 전시 더보기
	 * @param plan
	 * @return
	 * @author sowon
	 * @since 2021. 05. 14
	 */
	@PostMapping("/goods/list")
	@ResponseBody
	public GagaMap getPlanningGoodsList(@RequestBody Plan plan) {

		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		if (TsfSession.isLogin()) {
			plan.setCustNo(TsfSession.getInfo().getCustNo());
		}
		plan.setFrontGb(TsfSession.getFrontGb());
		GagaMap result = new GagaMap();
		plan.setTmplType("G082_51");
		plan.setPlanStat("Y");
		result.set("planGoods2List", planningService.getPlanGoodsDisplayList(plan).size());

		TscPageRequest pageable = new TscPageRequest((plan.getPageNo2() > 0 ? plan.getPageNo2() - 1 : 0), plan.getPageSize2(), plan.getPageUnit2());
		int totalCnt = planningService.getPlanGoodsDisplayList(plan).size();

		pageable.setTotalCount(totalCnt);
		plan.setPageable2(pageable);
		result.set("paging1", plan);
		result.set("totalCnt", totalCnt);
		result.set("endRow", pageable.getEndRow());
		result.set("dataList", planningService.getPlanGoodsDisplayList(plan));

		return result;
	}


	/**
	 * 기획전 쿠폰 상세보기 팝업
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 04. 14
	 */
	@PostMapping(value = "/coupon/detailpop")
	public ModelAndView planningCouponDetailPop(@RequestBody Coupon coupon) {
		ModelAndView mav = new ModelAndView();

		// 쿠폰 - 기본정보
		mav.addObject("couponDetailInfo", couponService.getPlanCouponDetailInfo(coupon));

		mav.setViewName(super.getDeviceViewName("planning/PlanningCouponDetailForm"));
		return mav;
	}

	/**
	 * 댓글이미지상세 -  댓글 상세 레이어
	 * @return
	 * @author sowon
	 * @since 2021. 5. 15
	 */
	@PostMapping("/reply/detail/layer")
	public ModelAndView planReplyDetailForm(Plan plan) {
		ModelAndView mav = new ModelAndView();

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

		mav.addObject("replyAttachList",planningService.getEntryReplyAttachList(plan));
		mav.addObject("replyList",planningService.getReplyList(plan));
		mav.setViewName(super.getDeviceViewName("planning/PlanningReplyPhotoForm"));
		return mav;
	}

	/**
	 * 기획전/이벤트 댓글 리스트
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 04. 08
	 */
	@PostMapping("/reply/list")
	@ResponseBody
	public GagaMap getReplyList(@RequestBody Plan plan) {
		GagaMap result = new GagaMap();
		if (TsfSession.isLogin()) {
			result.set("custNo",TsfSession.getInfo().getCustNo());
		}
		TscPageRequest pageable = new TscPageRequest((plan.getPageNo() > 0 ? plan.getPageNo() - 1 : 0), plan.getPageSize(), plan.getPageUnit());
		pageable.setTotalCount(planningService.getEntryReplyCount(plan));
		plan.setPageable(pageable);
		log.info("pageable: {}", pageable);
		log.info("totalCount {}", pageable.getTotalCount());
		result.set("paging", plan);
		result.set("replyList",planningService.getReplyList(plan));
		result.set("replyCount",planningService.getEntryReplyCount(plan));
		result.set("replyAttachList",planningService.getEntryReplyAttachList(plan));
		return result;
	}

	/**
	 * 기획전/이벤트 댓글 저장
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 04. 13
	 */
	@PostMapping("/reply/save")
	@ResponseBody
	public GagaMap saveEntryReply(@RequestBody Plan plan) {
		GagaMap result = new GagaMap();
		planningService.saveEntryReply(plan);
		return result;
	}

	/**
	 * 기획전/이벤트 댓글 삭제
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 04. 13
	 */
	@PostMapping("/reply/delete")
	@ResponseBody
	public GagaMap deleteEntryReply(@RequestBody Plan plan) {
		GagaMap result = new GagaMap();
		planningService.deleteEntryReply(plan);
		return result;
	}


	/**
	 * 기획전 쿠폰 상세보기 모달
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 04. 01
	 */
	@GetMapping(value = "/coupon/detail")
	public ModelAndView mypageCouponDetailPop(@RequestBody Coupon coupon) {
		ModelAndView mav = new ModelAndView();

		// 쿠폰 - 기본정보
		coupon.setPlanCouponStat("Y");
		mav.addObject("couponDetailInfo", couponService.getCouponDetailInfo(coupon));
		mav.setViewName(super.getDeviceViewName("planning/PlanningCouponDetailForm"));
		return mav;
	}

	/**
	 * 기획전 쿠폰 다운로드. 고객이 상품쿠폰 다운로드 시 발급됨.
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 * @author sowon
	 * @since 2021. 3. 24.
	 */
	@PostMapping(value = "/coupon/download")
	@ResponseBody
	public GagaMap createPlanCoupon(@RequestBody Coupon coupon) throws Exception {

		GagaMap result = new GagaMap();

		// 고객정보 조회
		Customer customer = new Customer();
		customer.setSiteCd(TscConstants.Site.STYLE24.value());
		customer.setCustNo(TsfSession.getInfo().getCustNo());
		customer.setCustStat(TscConstants.CustStat.ACTIVE.value());
		customer = coreCustomerService.getCustomerInfo(customer);

		// 고객정보 설정
		coupon.setCustGb(customer.getCustGb());
		coupon.setCustGrade(customer.getCustGrade());
		coupon.setCustNo(customer.getCustNo());
		// 등급쿠폰 다운 처리
		String couponResult = planningService.getPlanCouponDownInfo(coupon);

		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("ERROR_40".equals(couponResult)){
			result.set("message", "발급 가능 쿠폰 수량이 모두 소진되었습니다.");
		}else {
			result.set("message", "쿠폰이 발급되었습니다.");
		}

		result.set("couponList", planningService.getPlanCouponInfo(coupon));
		return result;
	}

	/**
	 * 이벤트 메인 화면
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 3. 8
	 */
	@GetMapping("/event/main/form")
	public ModelAndView PlanningEventMainForm(Plan plan) throws Exception {
		ModelAndView mav = new ModelAndView();

		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setFrontGb(TsfSession.getFrontGb());

		mav.setViewName(super.getDeviceViewName("planning/PlanningEventMainForm"));
		return mav;
	}

	/**
	 * 이벤트 메인 목록
	 * @param plan - 이벤트 정보
	 * @return
	 * @author sowon
	 * @since 2021. 3. 29
	 */
	@GetMapping("/event/main/list")
	@ResponseBody
	public Collection<Plan> getPlanningEventMainList(Plan plan, Device device) {
		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setFrontGb(TsfSession.getFrontGb());
		plan.setCustGb(TsfSession.getCustGb());
		plan.setCustNo(TsfSession.isLogin() ? TsfSession.getInfo().getCustNo() : 0);

		return planningService.getPlanEventList(plan);
	}

	/**
	 * 이벤트 설문조사 화면
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 4. 2
	 */
	@GetMapping("/event/poll/form")
	public ModelAndView planningEventPollSave(Plan plan) {
		ModelAndView mav = new ModelAndView();
		// 로그인 안 한 경우
		if (!TsfSession.isLogin()) {
			mav.addObject("inaccessibleMsg", "로그인 후 참여 가능합니다.");
			mav.setViewName(super.getDeviceViewName("error/Inaccess"));
			return mav;
		}

		Poll poll = new Poll();
		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setCustNo(TsfSession.getInfo().getCustNo());
		plan.setFrontGb(TsfSession.getFrontGb());
		poll = planningService.getPollQuestionInfo(plan);
		String partYn = poll.getDupPartiYn();
		String comYn = poll.getFstComYn();
		int partiCnt = poll.getPartiCnt();

		// 중복참여가 아닌경우
		if(partYn.equals("N")) {
			int count = planningService.getCustAnswerCount(plan);
			if (count>0) {
				mav.addObject("inaccessibleMsg", "이미 응모하셨습니다.");
				mav.setViewName(super.getDeviceViewName("error/Inaccess"));
				return mav;
			}
		}
		if (comYn.equals("Y")) {
			int count = planningService.getCustAnswerPartiCount(poll);
			if (count>=partiCnt) {
				mav.addObject("inaccessibleMsg", "선착순 응모가 마감되었습니다.");
				mav.setViewName(super.getDeviceViewName("error/Inaccess"));
				return mav;
			}
		}

		mav.addObject("pollInfo", planningService.getPollQuestionInfo(plan));
		mav.addObject("pollList", planningService.getPollQuestionList(plan));
		mav.setViewName(super.getDeviceViewName("planning/PlanningEventPollForm"));
		return mav;
	}



	/**
	 * 이벤트 설문조사 저장
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 4. 2
	 */
	@PostMapping("/event/poll/save")
	@ResponseBody
	public GagaMap planningEventPollForm(@RequestBody Poll poll) {
		GagaMap result = new GagaMap();
		planningService.savePollCustAnswer(poll);
		return result;
	}


	/**
	 * 총알배송 메인 화면
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 3. 30
	 */
	@GetMapping("/shot/delivery/guide/form")
	public ModelAndView planningShotDeliveryForm(Plan plan) throws Exception {
		ModelAndView mav = new ModelAndView();
		Integer planSq = planningService.getShotPlanSq(plan);
		plan.setPlanSq(planSq);

		CustDeliveryAddr addr = new CustDeliveryAddr();
		Integer custNo = null;
		if (TsfSession.isLogin()) {
			custNo = TsfSession.getInfo().getCustNo();
			plan.setCustNo(custNo);
			// 고객정보 조회
			Customer customer = new Customer();
			customer.setSiteCd(TscConstants.Site.STYLE24.value());
			customer.setCustNo(custNo);
			customer.setCustStat(TscConstants.CustStat.ACTIVE.value());
			customer = coreCustomerService.getCustomerInfo(customer);
			mav.addObject("customerInfo", customer);
		}
		plan.setFrontGb(TsfSession.getFrontGb());
		plan.setSiteCd(TscConstants.Site.STYLE24.value());
		plan.setCustGb(TsfSession.getCustGb());
		// 코너 목록
		mav.addObject("shotBrandList", planningService.getShotBrandList());
		// 코너 상품
		mav.addObject("shotBrandGoodsList", planningService.getShotDeliveryGoodsList(plan));

		addr.setCustNo(custNo);


		mav.addObject("custAddr", planningService.getCustAddrInfo(addr));
		mav.addObject("shotHtmlTop", planningService.getShotDeliveryHtmlTop(plan));
		mav.addObject("shotHtmlBtm", planningService.getShotDeliveryHtmlBtm(plan));
		mav.setViewName(super.getDeviceViewName("planning/PlanningShotGuideForm"));
		return mav;
	}


	/**
	 * 총알배송 / 일반배송 확인
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 4. 5
	 */
	@GetMapping("shot/delivery/confirm")
	@ResponseBody
	public GagaMap planningShotDeliveryConfirm(@RequestParam(value="recipZipcode") String recipZipcode) throws Exception {
		GagaMap result = new GagaMap();
		result.set("shotYn", planningService.getCustAddrShotConfirm(recipZipcode));
		return result;
	}


	/**
	 * 회원등급 혜택
	 *
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 04. 06
	 */
	@GetMapping("/event/custgrade/benefit/form")
	public ModelAndView getCustGradeBenefitForm() {
		ModelAndView mav = new ModelAndView();
		boolean isLogin = TsfSession.isLogin();
		mav.addObject("isLogin", isLogin);

		if (isLogin) {
			Customer customer = new Customer();
			customer.setSiteCd(TscConstants.Site.STYLE24.value());
			customer.setCustNo(TsfSession.getInfo().getCustNo());
			customer.setCustStat(TscConstants.CustStat.ACTIVE.value());

			mav.addObject("exptCustGradeMap", customerService.getExpectedCustGrde(customer));
			mav.addObject("customerInfo", coreCustomerService.getCustomerInfo(customer));
		}

		mav.setViewName(super.getDeviceViewName("planning/PlanningCustGradeBenefitForm"));
		return mav;
	}



	@GetMapping("/next/custgrade/info/{nextGradeCd}")
	@ResponseBody
	public GagaMap getNextCustGradeInfo(@PathVariable String nextGradeCd) {
		boolean isLogin = TsfSession.isLogin();
		if (!isLogin) {
			throw new IllegalStateException("로그인 하시기 바랍니다.");
		}
		CustGrade custGrade = new CustGrade();
		custGrade.setSiteCd(TscConstants.Site.STYLE24.value());
		custGrade.setCustNo(TsfSession.getInfo().getCustNo());
		custGrade.setGradeCd(nextGradeCd);
		return customerService.getNextCustGradeInfo(custGrade);
	}

	/**
	 * 회원등급 쿠폰 다운로드
	 *
	 * @return GagaMap
	 * @author jsshin
	 * @since 2021. 04. 08
	 */
	@PostMapping("/event/custgrade/coupon/down")
	@ResponseBody
	public GagaMap downCustGradeCoupon() {
		GagaMap result = new GagaMap();
		Integer custNo = TsfSession.getInfo().getCustNo();

		int downloadCnt = couponService.downloadCustGradeCoupon(custNo);

		//2021-09-10 금 시작  추가 요청자:CS요청 받을 쿠폰이 없습니다. 1건 구매 하시고 다음달 등급 쿠폰을 받아보세요! --WELCOME 등급의 경우 해당 메세지 출력(G110_50)
		if(downloadCnt == 0 && "G110_50".equals(TsfSession.getInfo().getCustGrade())) {
			throw new IllegalStateException("받을 쿠폰이 없습니다. 1건 구매 하시고 다음달 등급 쿠폰을 받아보세요!");
		}
		//2021-09-10 금  끝

		boolean isDownload = downloadCnt > 0;
		result.setBoolean("isDownload", isDownload);
		result.setInt("downloadCnt", downloadCnt);
		return result;
	}


	/**
	 * 출석체크
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 4. 7
	 */
	@PostMapping("/event/attend/entry")
	@ResponseBody
	public GagaMap planningAttendEntry(@RequestBody Plan plan) throws Exception {
		GagaMap result = new GagaMap();
		plan.setEntryAllYn("N");
		int count = planningService.getAttendEntryCount(plan);
		if (count > 0) {
			result.set("msg", "이미 출석체크 되었습니다.");
		}else {
			planningService.saveAttendEntry(plan);

			// 총 출석일 수 구해보장..
			Collection<Plan> benefitList = planningService.getAttendBenefitList(plan);
			plan.setEntryAllYn("Y");
			count = planningService.getAttendEntryCount(plan);
			String msg = "출석체크 되었습니다.";
			for (Plan tPlan : benefitList) {
				if (tPlan.getBasDays() == count) {
					// 지급 방식이 포인트일 경우
					if (tPlan.getBenefitGb().equals("P")) {
						Point point = new Point();
						int pointAmt = tPlan.getPntAmt();
						point.setRegNo(TsfSession.getInfo().getCustNo());
						point.setUpdNo(TsfSession.getInfo().getCustNo());
						point.setCustNo(TsfSession.getInfo().getCustNo());
						point.setPntUploadStat(TscConstants.PntUploadStat.APPLY_COMPLETE.value());
						point.setGvPntAmt(pointAmt);
						point.setRmPntAmt(pointAmt);
						point.setPntAmt(pointAmt);
						point.setOccurDtlDesc("출석체크이벤트");
						point.setOccurGb("G069_37"); //출석체크 이벤트
						Calendar cal = Calendar.getInstance();
				        cal.setTime(new Date());
				        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				        int usableDay = tPlan.getPntUsableDay();
				        cal.add(Calendar.DATE, +usableDay);
				        point.setExpBeDt(df.format(cal.getTime()));
				        point.setSignGb("+");
						corePointService.saveCustomerPoint(point);
						msg =  "축하합니다. " + toNumFormat(pointAmt) + " 포인트가 지급 되었습니다!";
//						result.set("msg", msg);
						break;
					}
					else if(tPlan.getBenefitGb().equals("C")) {
						CustCoupon coupon = new CustCoupon();
						coupon.setCpnId(tPlan.getCpnId());
						coupon = couponService.getAttendCouponInfo(coupon);
						coupon.setCustNo(TsfSession.getInfo().getCustNo());
						coupon.setRegNo(TsfSession.getInfo().getCustNo());
						coupon.setUpdNo(TsfSession.getInfo().getCustNo());
						// 이거 공통코드 변경예정.. 밑에
						coupon.setPubReason("G068_60");
						coupon.setPubReasonDtl("이벤트출석체크");
						coupon.setEndAlimSendYn("N");
						coreCouponService.saveCouponIssue(coupon);
						msg =  "축하합니다. " + toNumFormat(coupon.getDcVal()) +coupon.getDcWay() + " 할인쿠폰이 지급 되었습니다!";
//						result.set("msg", msg);
						break;
					}
					else if(tPlan.getBenefitGb().equals("A")) {
						Point point = new Point();
						int pointAmt = tPlan.getPntAmt();
						point.setRegNo(TsfSession.getInfo().getCustNo());
						point.setUpdNo(TsfSession.getInfo().getCustNo());
						point.setCustNo(TsfSession.getInfo().getCustNo());
						point.setPntUploadStat(TscConstants.PntUploadStat.APPLY_COMPLETE.value());
						point.setGvPntAmt(pointAmt);
						point.setRmPntAmt(pointAmt);
						point.setPntAmt(pointAmt);
						point.setOccurDtlDesc("출석체크이벤트");
						point.setOccurGb("G069_37"); //출석체크 이벤트
						Calendar cal = Calendar.getInstance();
				        cal.setTime(new Date());
				        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				        int usableDay = tPlan.getPntUsableDay();
				        cal.add(Calendar.DATE, +usableDay);
				        point.setExpBeDt(df.format(cal.getTime()));
				        point.setSignGb("+");
						corePointService.saveCustomerPoint(point);

						CustCoupon coupon = new CustCoupon();
						coupon.setCpnId(tPlan.getCpnId());
						coupon = couponService.getAttendCouponInfo(coupon);
						coupon.setCustNo(TsfSession.getInfo().getCustNo());
						coupon.setRegNo(TsfSession.getInfo().getCustNo());
						coupon.setUpdNo(TsfSession.getInfo().getCustNo());
						// 이거 공통코드 변경예정.. 밑에
						coupon.setPubReason("G068_91");
						coupon.setPubReasonDtl("출석체크");
						coupon.setEndAlimSendYn("N");
						coreCouponService.saveCouponIssue(coupon);
						msg =  "축하합니다. " + toNumFormat(pointAmt) + " 포인트와 " + toNumFormat(coupon.getDcVal()) +coupon.getDcWay() + " 할인쿠폰이 지급 되었습니다!";
//						result.set("msg", msg);
						break;
					}

				}else {
//					result.set("msg", "출석체크 되었습니다.");
					break;
				}
			}
			result.set("msg", msg);
		}

		result.set("custAttendList",planningService.getCustAttendEntryList(plan));
		return result;
	}

	/**
	 * 기획전 리뷰 상세 -  리뷰 상세 레이어
	 * @return
	 * @author sowon
	 * @since 2021. 6. 18
	 */
	@PostMapping("/review/detail/layer")
	public ModelAndView planningReviewDetailForm(Review review) {
		ModelAndView mav = new ModelAndView();
		Goods paramsGoods = new Goods();
		paramsGoods.setGoodsCd(review.getGoodsCd());

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

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

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

		mav.setViewName(super.getDeviceViewName("planning/PlanningReviewDetailForm"));
		return mav;
	}


	/**
	 * 기획전 리뷰 상세 -  리뷰 상세 레이어
	 * @return
	 * @author sowon
	 * @since 2021. 6. 18
	 */
	@PostMapping("/review/detail/list")
	@ResponseBody
	public GagaMap getReviewDetailList(@RequestBody Review review) {
		GagaMap result = new GagaMap();
		result.set("reviewList", reviewService.getReviewList(review));
		return result;
	}


	// 컴마
	 public static String toNumFormat(int num) {
		  DecimalFormat df = new DecimalFormat("#,###");
		  return df.format(num);
	 }


}
