package com.fdkankan.platform.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.common.constant.TbStatus;
import com.fdkankan.common.user.SSOUser;
import com.fdkankan.platform.goods.entity.Cart;
import com.fdkankan.platform.goods.entity.Goods;
import com.fdkankan.platform.goods.mapper.ICartMapper;
import com.fdkankan.platform.goods.service.ICartService;
import com.fdkankan.platform.goods.service.IGoodsService;
import com.fdkankan.platform.user.request.RequestCart;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.platform.user.vo.ResponseCart;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-24
 */
@Service
public class CartServiceImpl extends ServiceImpl<ICartMapper, Cart> implements ICartService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;

    @Override
    public String addCart(RequestCart param, String token) {
        if (param.getGoodsId() == null){
           throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        SSOUser ssoUser = userService.getSSOUserByToken(token);
        Cart cartEntity = getByUserAndGoods(ssoUser.getId(), param.getGoodsId());
        if (cartEntity == null){
            cartEntity = new Cart();
            cartEntity.setUserId(ssoUser.getId());
            cartEntity.setGoodsId(param.getGoodsId());
            cartEntity.setPayStatus(0);
            cartEntity.setSkuSn(param.getSkuSn());
        }
        Integer count = cartEntity.getGoodsCount() == null ? 0 : cartEntity.getGoodsCount();
        cartEntity.setGoodsCount(count + param.getGoodsCount());
        if(!this.saveOrUpdate(cartEntity)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public List<ResponseCart> getCartList(RequestCart param, String token) {
        SSOUser ssoUser = userService.getSSOUserByToken(token);
        List<Cart> cartList = getByUser(ssoUser.getId());
        List<ResponseCart> voList = cartList.parallelStream().map(cart -> {
            ResponseCart cartVo = new ResponseCart();
            BeanUtils.copyProperties(cart, cartVo);
            Goods goods = goodsService.getById(param.getGoodsId());
            cartVo.setPrice(goods.getGoodsPrice());
            return cartVo;
        }).collect(Collectors.toList());
        return voList;
    }

    @Override
    public String removeCart(RequestCart param, String token) {
        if (param.getGoodsId() == null){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        SSOUser ssoUser = userService.getSSOUserByToken(token);
        Cart cart = this.getByUserAndGoods(ssoUser.getId(), param.getGoodsId());
        if (param.getGoodsCount() != 0){
            cart.setGoodsCount(param.getGoodsCount());
            this.updateById(cart);
        }else {
            this.removeById(cart.getId());
        }
        return ServerCode.SUCCESS.message();
    }

    @Override
    public String removeCarts(RequestCart param, String token) {
        if (StringUtils.isEmpty(param.getIds())){
            throw new BusinessException(ErrorCode.MISSING_REQUIRED_PARAMETERS);
        }
        String [] ids = param.getIds().split(",");
        List<String> idsList = new ArrayList<>(Arrays.asList(ids));
        if(!this.removeByIds(idsList)){
            throw new BusinessException(ErrorCode.ERROR_MSG);
        }
        return ServerCode.SUCCESS.message();
    }

    public List<Cart> getByUser(Long userId){
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Cart::getTbStatus, TbStatus.VALID.code());
        queryWrapper.lambda().eq(Cart::getUserId,userId);
        queryWrapper.lambda().orderByDesc(Cart::getCreateTime);
        return this.list(queryWrapper);
    }

    public Cart getByUserAndGoods(Long userId ,Long goodsId){
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Cart::getTbStatus,TbStatus.VALID.code());
        queryWrapper.lambda().eq(Cart::getUserId,userId);
        queryWrapper.lambda().eq(Cart::getGoodsId,goodsId);
        queryWrapper.lambda().last("LIMIT 1");
        List<Cart> list = this.list(queryWrapper);
        if(list == null || list.size()<=0){
            return null;
        }
        return list.get(0);
    }
}
