package com.style24.front.biz.web;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.style24.core.biz.service.TscKcpService;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.front.biz.service.TsfCartService;
import com.style24.front.biz.service.TsfCouponService;
import com.style24.front.biz.service.TsfGoodsService;
import com.style24.front.biz.service.TsfOrderService;
import com.style24.front.biz.thirdparty.EigeneaiApi;
import com.style24.front.support.controller.TsfBaseController;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.Cart;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.Login;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.eigene.Eigeneai;
import com.style24.persistence.domain.eigene.Item;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;

import javax.servlet.http.HttpServletRequest;

/**
 * 장바구니 Controller
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Controller
@RequestMapping("/cart")
@Slf4j
public class TsfCartController extends TsfBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsfCartService cartService;

	@Autowired
	private TsfGoodsService goodsService;

	@Autowired
	private TsfCouponService couponService;

	@Autowired
	private TscOrderService coreOrderService;

	@Autowired
	private TscKcpService coreKcpService;

	@Autowired
	private TsfOrderService orderService;

	@Autowired
	private EigeneaiApi eigeneaiApi;

	@Autowired
	private Environment env;

	/**
	 * 장바구니 화면
	 * @return
	 * @author xodud1202
	 * @since 2021. 01. 28
	 */
	@GetMapping("/list/form")
	public ModelAndView cartListForm() {
		ModelAndView mav = new ModelAndView();
		Cart cart = new Cart();
		if (TsfSession.isLogin()) {
			cart.setCustNo(TsfSession.getInfo().getCustNo());
		} else {
			cart.setCustNo(0);
			cart.setJsessionId(TsfSession.getSessionId());
		}

		Collection<Cart> cartList = cartService.getAllCartList(cart);
		if (cartList != null && cartList.size() > 0) {
			// 장바구니 상품이 있을 경우
			Collection<Eigeneai.Result> itemList = eigeneaiApi.getRelatedGoodsList(cartList, 20);
			mav.addObject("recomGoodsList", itemList);
			mav.addObject("cartSize", cartList.size());
		} else {
			// 장바구니 상품이 없을 경우
			Collection<Item> itemList = eigeneaiApi.getRealtimeViewGoodsList(20);
			mav.addObject("recomGoodsList", itemList);
			mav.addObject("cartSize", 0);
		}

		mav.addObject("loginCustNo", cart.getCustNo());
		mav.setViewName(super.getDeviceViewName("cart/CartListForm"));
		return mav;
	}

	/**
	 * 장바구니 등록
	 * @param param
	 * goodsCd : 상품코드 (세트 : 세트상품코드, 딜상품 : 원상품코드, 일반상품 : 상품코드)
	 * dealGoodsCd : 딜상품코드
	 * itemCd : 구성상품코드 (세트. 세트 아닐 경우 입력X)
	 * optCd : 옵션코드
	 * goodsType : 상품타입 (공통코드 G026)
	 * goodsQty : 장바구니 등록 수량
	 * cartGb : O = 바로주문, C = 장바구니
	 * afLinkCd : 제휴링크코드
	 * ithr_cd : 유입경로
	 * contents_loc : 컨텐츠 위치
	 * planDtlSq : 기획전상세번호
	 * dealGoodsCd : 딜상품코드 (딜상품코드)
	 * @return ModelAndView
	 * @author xodud1202
	 * @since 2021. 01. 28
	 */
	@ResponseBody
	@PostMapping("/save")
	public GagaMap createCart(HttpServletRequest request, @RequestBody Collection<Cart> params) {
		GagaMap result = cartService.saveCartInfo(params, request);
		String cartGb = String.valueOf(result.get("cartGb"));
		if ("C".equals(cartGb) || cartGb.equals(TscConstants.CartGb.CART.value())) {
			cartService.deleteOldCart();
		}

		return result;
	}

	// @ResponseBody
	@PostMapping("/goods/list")
	public String selectCartGoodsList(Order param, Model model) {
		// 총알배송 가능 여부 체크
		int shotCanYn = coreOrderService.getDailyDeliveryCheck(param);

		// 10시 이전에만 총알 배송 가능 여부 체크
		if (shotCanYn == 1) {
			SimpleDateFormat format = new SimpleDateFormat("MM/dd");
			Date time = new Date();

			param.setShotCanYn("Y");
			param.setShotDelvDt(format.format(time));
		} else {
			SimpleDateFormat format = new SimpleDateFormat("MM/dd");
			Date time = new Date();
			param.setShotCanYn("N");
			param.setShotDelvDt(format.format(time));
		}

		if (param.getShotDelvUseYn() == null) {
			param.setShotDelvUseYn(param.getShotCanYn());
		}

		// 장바구니 정보 조회
		Order order = cartService.getCartGoodsList(param);

		order.setShotDelvUseYn(param.getShotDelvUseYn());
		order.setShotCanYn(param.getShotCanYn());
		order.setShotDelvDt(param.getShotDelvDt());
		
		// 2021.11.08 입접업체만 있는경우 총알배송 선택여부 미노출
		if (order.getShotCartList().size() < 1) {
			order.setShotCanYn("N");
		}

		model.addAttribute("loginInfo", TsfSession.getInfo());
		model.addAttribute("order", order);
		model.addAttribute("IMG_PATH", env.getProperty("upload.goods.view"));

		return super.getDeviceViewName("cart/CartListAjaxForm");
	}

	@PostMapping("/delv/fee/save/goods/list")
	public ModelAndView selectCartAddGoodsList(Order param) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("goodsList", cartService.getDelvFeeSaveGoodsList(param));
		mav.setViewName(super.getDeviceViewName("cart/CartDelvFeeSaveGoodsPopup"));
		return mav;
	}

	@PostMapping("/tmtb/sales/goods/list")
	public ModelAndView selectTmtbSalesGoodsList(@RequestBody Goods param) {
		ModelAndView mav = new ModelAndView();
		param.setFrontGb(TsfSession.getFrontGb());
		param.setSiteCd(TscConstants.Site.STYLE24.value());
		param.setMaxRownum(20);

		// 회원 구분
		if (TsfSession.getInfo() != null) {
			param.setCustGb(TsfSession.getInfo().getCustGb());
			param.setCustNo(TsfSession.getInfo().getCustNo());
		} else {
			param.setCustGb(TsfSession.getCustGb());
			param.setCustNo(0);
		}

		// 수량 및 금액 다다익선 최소 조건 조회
		DecimalFormat format = new DecimalFormat("###,###");
		List<Order> tmtbSalesValueList = (ArrayList<Order>)cartService.selectTmtbSalesValueList(param);
		// 조건 멘트 적용
		List<StringBuilder> tmtbDcDescList = new ArrayList<StringBuilder>();
		for (Order tmtbDcValue : tmtbSalesValueList) {
			if (!StringUtils.isEmpty(tmtbDcValue.getDefaultYn()) && "Y".equals(tmtbDcValue.getDefaultYn())) {
				StringBuilder tmtbDcDesc = new StringBuilder();
				if (TscConstants.ApplyGb.QTY.value().equals(tmtbDcValue.getSectionGb())) {
					tmtbDcDesc.append(tmtbDcValue.getSectionVal()).append("개 이상 구매시 ");
				} else if (TscConstants.ApplyGb.AMT.value().equals(tmtbDcValue.getSectionGb())) {
					tmtbDcDesc.append(format.format(tmtbDcValue.getSectionVal())).append("원 이상 구매시 ");
				}

				if (TscConstants.DcWay.AMT.value().equals(tmtbDcValue.getDcWay())) {
					tmtbDcDesc.append(format.format(tmtbDcValue.getDcVal())).append("원 할인");
				} else if (TscConstants.DcWay.RATE.value().equals(tmtbDcValue.getDcWay())) {
					tmtbDcDesc.append(tmtbDcValue.getDcVal()).append("% 할인");
				}

				tmtbDcDescList.add(tmtbDcDesc);
			}
		}

		// 다다익선 조건
		mav.addObject("tmtbDcDescList", tmtbDcDescList);

		// 다다익선 상품 조회 (수량, 금액 섞어서)
		Collection<Goods> goodsList = goodsService.getTmtbGoodsList(param);
		goodsList.removeIf(goods -> !TscConstants.GoodsType.NORMAL.value().equals(goods.getGoodsType()));

		mav.addObject("goodsList", goodsList);

		mav.setViewName(super.getDeviceViewName("cart/CartTmtbSalesGoodsPopup"));
		return mav;
	}

	/**
	 * 장바구니 로그인 정보 조회
	 * @param param
	 * @return
	 */
	@ResponseBody
	@PostMapping("/login/info")
	public Login selectLoginInfo(Order param) {
		Login result = new Login();
		if (TsfSession.isLogin()) {
			result = TsfSession.getInfo();
		} else {
			result.setCustNo(0);
		}

		return result;
	}

	/**
	 * 장바구니 체크박스 change시에 계산로직 진행
	 * @param param
	 * @return
	 */
	@ResponseBody
	@PostMapping("/change/goods/list")
	public Order selectCartGoodsJsonList(@RequestBody Order param) {
		Order order = cartService.getCartGoodsList(param);
		order.setImgPath1(env.getProperty("upload.goods.view"));
		return order;
	}

	/**
	 * 프로모션 할인 쿠폰 조회
	 * @param param
	 * rdCpnNm : 시리얼쿠폰명
	 * cartSqArr[] : 장바구니 번호 배열
	 * @return GagaMap
	 * @author xodud1202
	 * @since 2021. 02. 17
	 */
	@ResponseBody
	@PostMapping("/list/serialCpnApply")
	public GagaMap serialCpnApply(@RequestBody Coupon param) {
		GagaMap result = new GagaMap();

		// 시리얼 쿠폰 정보 조회 및 쿠폰 지급 미대상인 경우 쿠폰 지급
		Coupon useSerial = couponService.serialCpnApplyInfo(param);

		result.put("serialCpnInfo", useSerial);

		return result;
	}

	/**
	 * 장바구니 삭제
	 * @param param
	 * @return GagaMap
	 * @author xodud1202
	 * @since 2021. 02. 23
	 */
	@ResponseBody
	@PostMapping("/deleteCart")
	public GagaMap deleteCart(@RequestBody Cart param) {
		cartService.deleteCart(param);
		return new GagaMap();
	}

	/**
	 * 장바구니 옵션변경 팝업
	 * @param param
	 * @return String
	 * @author xodud1202
	 * @since 2021. 02. 23
	 */
	// @ResponseBody
	@PostMapping("/goods/info")
	public String getCartGoodsInfo(Cart param, Model model) {
		Cart cart = cartService.getCartGoodsInfo(param);

		model.addAttribute("cart", cart);
		model.addAttribute("setType", TscConstants.GoodsType.SET.value());
		return super.getDeviceViewName("cart/CartChangeOptionPopup");
	}

	/**
	 * 장바구니 옵션 변경
	 * @param param
	 * @return GagaMap
	 * @author xodud1202
	 * @since 2021. 02. 23
	 */
	@ResponseBody
	@PostMapping("/change/option")
	public GagaMap updateCartOption(@RequestBody Cart param) {
		GagaMap result = new GagaMap();

		result = cartService.updateCartOption(param);

		if ("SUCCESS".equals(result.get("status"))) {
			result.put("message", message.getMessage("SUCC_0009"));
		}

		return result;
	}

	/**
	 * 장바구니 주문하기 시점 재고 및 상태 체크
	 * @param param
	 * @return
	 * @author xodud1202
	 * @since 2021. 04. 02
	 */
	@ResponseBody
	@PostMapping("/order/list/check")
	public Collection<Order> selectOrderListCheck(@RequestBody Order param) {
		return cartService.getOrderListConditionCheck(param);
	}

	/**
	 * 장바구니 최소 주문 수량으로 변경
	 * @param param
	 * @return
	 * @author xodud1202
	 * @since 2021. 04. 02
	 */
	@ResponseBody
	@PostMapping("/update/goodsQty")
	public Order updateCartGoodsQty(@RequestBody Cart param) {
		return cartService.updateCartGoodsQty(param);
	}

	/**
	 * 퀵메뉴 장바구니 리스트
	 * @return
	 * @author xodud1202
	 * @since 2021. 04. 02
	 */
	@GetMapping("/quick/cart/list")
	@ResponseBody
	public GagaMap getCartList() {
		GagaMap result = new GagaMap();
		Order cart = new Order();

		// 장바구니 상품목록
		cart = cartService.getCartGoodsList(cart);
		cart.setImgPath1(env.getProperty("upload.goods.view"));

		// 현재 주문 가능 수량순으로 정렬
		Collections.sort((ArrayList<Order>)cart.getDelvAllCartList(), new Comparator<Order>() {
			@Override
			public int compare(Order c1, Order c2) {
				return c1.getOrdCanQty() - c2.getOrdCanQty();
				// return c2.getQtyTmtbSq() - c1.getQtyTmtbSq(); //역순 정렬
			}
		});

		List<Order> cartList = new ArrayList<>();
		for (Order oneData : cart.getDelvAllCartList()) {
			if (oneData.getOrdCanQty() < 6 && oneData.getOrdCanQty() > 0) {
				cartList.add(oneData);
			}
		}

		// 장바구니 등록 최신순 정렬
		Collections.sort((ArrayList<Order>)cart.getDelvAllCartList(), new Comparator<Order>() {
			@Override
			public int compare(Order c1, Order c2) {
				return c2.getCartSq() - c1.getCartSq();	//역순 정렬
			}
		});

		for (Order oneData : cart.getDelvAllCartList()) {
			if (oneData.getOrdCanQty() > 5) {
				cartList.add(oneData);
			}
		}

		for (Order oneData : cart.getDelvAllCartList()) {
			if (oneData.getOrdCanQty() < 1) {
				cartList.add(oneData);
			}
		}

		cart.setDelvAllCartList(cartList);

		if(cart.getTotCartCnt() < 1) {
			// 장바구니 상품이 없을 경우
			Collection<Item> itemList = eigeneaiApi.getRealtimeViewGoodsList(20);
			result.put("itemList", itemList);
		}

		result.put("order", cart);

		return result;
	}

	/**
	 * 장바구니 수량 조회(모바일 헤더)
	 * @return
	 * @author xodud1202
	 * @since 2021. 05. 04
	 */
	@ResponseBody
	@GetMapping("/goods/not/soldout/cnt")
	public Order getCartNotSoldoutCnt() {
		return cartService.getCartNotSoldoutCnt();
	}

	/**
	 * 상품 품절 제외 옵션 조회
	 * @param param
	 * @return
	 */
	@ResponseBody
	@PostMapping("/tmtb/sales/goods/optcd")
	public Goods selectTmtbSalesGoodsOptCd(@RequestBody Goods param) {
		Collection<Goods> goodsList = cartService.selectTmtbSalesGoodsOptCd(param);
		Goods result = new Goods();
		for (Goods goods : goodsList) {
			result = goods;		// goodsList는 상품정보 1라인만 조회됨
		}

		return result;
	}
}
