package com.qs.mp.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qs.mp.channel.domain.ChannelCart;
import com.qs.mp.channel.domain.param.ChannelCartParam;
import com.qs.mp.channel.domain.vo.ChannelCartVO;
import com.qs.mp.channel.mapper.ChannelCartMapper;
import com.qs.mp.channel.service.IChannelCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.utils.SecurityUtils;
import java.util.List;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 经销商购物车 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-03-02
 */
@Service
public class ChannelCartServiceImpl extends ServiceImpl<ChannelCartMapper, ChannelCart> implements IChannelCartService {

  @Override
  public List<ChannelCartVO> listCartVO(Wrapper<ChannelCart> queryWrapper) {
    return getBaseMapper().listCartVO(queryWrapper);
  }

  @Override
  public boolean addToCart(ChannelCartParam param) {
    Long channelId = SecurityUtils.getLoginUser().getChannelId();
    if (null != param.getCartId() && 0 != param.getCartId()) {
      throw new ServiceException("购物清单ID不为空");
    }

    // 从盲票销售列表页面点加购
    ChannelCart channelCart = getOne(new LambdaQueryWrapper<ChannelCart>()
        .eq(ChannelCart::getBoxId, param.getBoxId()).eq(ChannelCart::getChannelId, channelId));
    if (null != channelCart) {
      // 购物车里已存在，只更新订购数量
      return refreshCart(param, channelCart);
    }

    channelCart = new ChannelCart();
    channelCart.setChannelId(channelId);
    channelCart.setBoxId(param.getBoxId());
    channelCart.setOrderNum(param.getOrderNum());
    save(channelCart);
    return true;
  }

  private boolean refreshCart(ChannelCartParam param, ChannelCart channelCart) {
    int orderNum = channelCart.getOrderNum() + param.getOrderNum();
    if (orderNum <= 0) {
      throw new ServiceException("该宝贝不能再减少了");
    }
    channelCart.setOrderNum(orderNum);
    boolean rtn = updateById(channelCart);
    return rtn;
  }
}
