package com.gree.mall.miniapp.logic.order;

import com.gree.mall.miniapp.logic.promotion.PromotionFullPieceLogic;
import org.apache.commons.lang3.StringUtils;
import com.gree.mall.miniapp.bean.order.BuyGood;
import com.gree.mall.miniapp.bean.order.ShoppingCartBean;
import com.gree.mall.miniapp.bean.order.ShoppingCartDetail;
import com.gree.mall.miniapp.bean.order.ShoppingCartList;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.commonmapper.AppMapper;
import com.gree.mall.miniapp.enums.UserTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.promotion.PromotionGroupLogic;
import com.gree.mall.miniapp.logic.seckill.SecKillLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ShoppingCartLogic {

    @Autowired
    SecKillLogic secKillLogic;
    @Autowired
    PromotionGroupLogic promotionGroupLogic;
    @Autowired
    AppMapper appMapper;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    MiniNoticeService miniNoticeService;
    @Autowired
    UserService userService;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    PromotionFullPieceLogic promotionFullPieceLogic;

    /**
     * 查询购物车商品数量
     */
    public Integer total(String userId){
        try {
            List<ShoppingCartList> shoppingCartLists = this.queryShoppingCart(userId).getShoppingCartLists();
            if (shoppingCartLists.size() == 0) {
                return 0;
            }
            Integer sum = shoppingCartLists.stream().collect(Collectors.summingInt(x -> x.getNum()));
            return sum;
        }catch(Exception e){
            log.error("【查询购物车商品数量失败】",e);
            return 0;
        }
    }

    /**
     * 查询购物车
     */
    public ShoppingCartDetail queryShoppingCart(String userId) throws InterruptedException {

        List<ShoppingCartList> list = appMapper.queryShoppingCartList(userId);
        User user = userService.getById(userId);
        String promotionGroupUserId = user.getPromotionGroupUserId();
        if(user.getPromotionGroupLeader()){
            promotionGroupUserId = user.getUserId();
        }
        int totalNum = 0;
        BigDecimal totalAmount = new BigDecimal(0);
        for(ShoppingCartList shoppingCart : list){
            String promotionGroupId = shoppingCart.getPromotionGroupId();
            String secKillId = shoppingCart.getSecKillId();
            String goodsSpecId = shoppingCart.getGoodsSpecId();
            //团购活动商品
            if(StringUtils.isNotBlank(promotionGroupId)){
                PromotionGroupSpecUser promotionGroupSpecUser = null;
                try {
                    promotionGroupSpecUser = promotionGroupLogic.getStock(promotionGroupUserId, goodsSpecId, 0);
                }catch(Exception e){}
                if(promotionGroupSpecUser != null) {
                    shoppingCart.setPrice(promotionGroupSpecUser.getGroupPrice());
                    shoppingCart.setOrgPrice(promotionGroupSpecUser.getOrgGoodsPrice());
                }
            }
            //秒杀活动商品
            if(StringUtils.isNotBlank(secKillId)){
                SecKillActivitySpec stock = null;
                try {
                    stock = secKillLogic.getStock(secKillId, goodsSpecId, 0);
                }catch(Exception e){}
                if(stock != null) {
                    shoppingCart.setPrice(stock.getPrice());
                    shoppingCart.setOrgPrice(stock.getGoodsPrice());
                }
            }
            totalNum += shoppingCart.getNum();
            totalAmount = totalAmount.add(shoppingCart.getPrice());
        }

        ShoppingCartDetail shoppingCartDetail = new ShoppingCartDetail();
        shoppingCartDetail.setTotalAmount(totalAmount);
        shoppingCartDetail.setTotalNum(totalNum);
        shoppingCartDetail.setShoppingCartLists(list);
        //当前有效的满件打折活动
        List<PromotionFullPieceItem> items = promotionFullPieceLogic.getItems();
        shoppingCartDetail.setPromotionFullPieceItems(items);
        return shoppingCartDetail;
    }

    /**
     * 添加商品到购物车
     */
    public ShoppingCartDetail addShoppingCart(HttpServletRequest request , ShoppingCartBean shoppingCartBean) throws RemoteServiceException, InterruptedException {
        String userId = shoppingCartBean.getUserId();
        //先清空
        this.clearShoppingCart(userId);
        User user = userService.getById(userId);
        List<BuyGood> buyGoods = shoppingCartBean.getBuyGoods();
        if(buyGoods == null || buyGoods.size() == 0){
           return null;
        }
        long count = buyGoods.stream().filter(v -> v.getNum() <= 0).count();
        if(count > 0){
            throw new RemoteServiceException("请求失败存在数量小于0的请求数据");
        }
        if(!this.checkDist(buyGoods)){
            throw new RemoteServiceException("有重复数据请重新请求");
        }
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);

        //增加
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for(BuyGood buyGood : buyGoods){
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setCreateTime(new Date());
            shoppingCart.setGoodsId(buyGood.getGoodsId());
            shoppingCart.setGoodsSpecId(buyGood.getGoodsSpecId());
            shoppingCart.setNum(buyGood.getNum());
            shoppingCart.setUserId(userId);
            shoppingCart.setPromotionGroupId(buyGood.getPromotionGroupId());
            shoppingCart.setSecKillId(buyGood.getSecKillId());
            if(user.getType().equals(UserTypeEnum.GENERAL.toString())) {
                shoppingCart.setWxSceneId(buyGood.getWxSceneId());
            }
            shoppingCart.setCompanyWechatId(currentCompanyWechat.getCurrentCompanyWechatId());
            shoppingCart.setCompanyName(currentCompanyWechat.getCurrentCompanyName());
            shoppingCarts.add(shoppingCart);
        }
        shoppingCartService.saveBatch(shoppingCarts);

        return this.queryShoppingCart(userId);
    }


    /**
     * 添加一条商品到购物车
     * @param shoppingCartBean
     * @return
     * @throws RemoteServiceException
     */
    public ShoppingCartDetail addOne(HttpServletRequest request,ShoppingCartBean shoppingCartBean) throws RemoteServiceException, InterruptedException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);

        String userId = shoppingCartBean.getUserId();
        User user = userService.getById(userId);

        List<BuyGood> buyGoods = shoppingCartBean.getBuyGoods();
        if(buyGoods == null || buyGoods.size() == 0 || buyGoods .size() > 1){
            return null;
        }
        BuyGood buyGood = buyGoods.get(0);
        if(buyGood.getNum() == 0){
            throw new RemoteServiceException("请求失败存在数量小于0的请求数据");
        }
        String goodsId = buyGood.getGoodsId();
        String goodsSpecId = buyGood.getGoodsSpecId();
        ShoppingCart shoppingCart = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getGoodsId, goodsId)
                .eq(ShoppingCart::getGoodsSpecId, goodsSpecId)
                .eq(ShoppingCart::getUserId, userId)
                .one();
        if(shoppingCart == null){
            ShoppingCart bean = new ShoppingCart();
            bean.setCreateTime(new Date());
            bean.setGoodsId(buyGood.getGoodsId());
            bean.setGoodsSpecId(buyGood.getGoodsSpecId());
            bean.setNum(buyGood.getNum());
            bean.setUserId(userId);
            bean.setPromotionGroupId(buyGood.getPromotionGroupId());
            bean.setSecKillId(buyGood.getSecKillId());
            if(user.getType().equals(UserTypeEnum.GENERAL.toString())) {
                bean.setWxSceneId(buyGood.getWxSceneId());
            }
            bean.setCompanyWechatId(currentCompanyWechat.getCurrentCompanyWechatId());
            bean.setCompanyName(currentCompanyWechat.getCurrentCompanyName());
            bean.insert();
        }else{
            shoppingCart.setNum(shoppingCart.getNum()+buyGood.getNum());
            shoppingCart.updateById();
        }
        return this.queryShoppingCart(userId);
    }

    /**
     * 清空购物车
     */
    public void clearShoppingCart(String userId){
        shoppingCartService.lambdaUpdate().eq(ShoppingCart::getUserId,userId).remove();
    }

    /**
     * 判断是否重复
     */
    public Boolean checkDist(List<BuyGood> buyGoods){

        Set<String> set = new HashSet<>();
        for(BuyGood buyGood : buyGoods){
            set.add(buyGood.getGoodsId()+""+buyGood.getGoodsSpecId());
        }
        if(set.size() != buyGoods.size()){
            return false;
        }
        return true;
    }

    /**
     * 删除选中的商品
     */
    public ShoppingCartDetail remove(String userId,List<String> shoppingCartIds) throws InterruptedException {
        shoppingCartService.lambdaUpdate().in(ShoppingCart::getShoppingCartId,shoppingCartIds).remove();
        return this.queryShoppingCart(userId);
    }

    /**
     * 消息通知
     */
    public String miniNotice(HttpServletRequest request){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);

        List<MiniNotice> list = miniNoticeService.lambdaQuery()
                .eq(MiniNotice::getStatus, true)
                .eq(MiniNotice::getCompanyWechatId , currentCompanyWechat.getCurrentCompanyWechatId())
                .list();
        if(list.size() > 0){
            return list.get(0).getNoticeContent();
        }
        return "";
    }


}
