package org.jeecg.modules.oroqen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.oroqen.entity.OroqenCart;
import org.jeecg.modules.oroqen.mapper.OroqenCartMapper;
import org.jeecg.modules.oroqen.service.IOroqenCartService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Description: 购物车
 * @Author: jeecg-boot
 * @Date: 2025-01-08
 * @Version: V1.0
 */
@Service
public class OroqenCartServiceImpl extends ServiceImpl<OroqenCartMapper, OroqenCart> implements IOroqenCartService {

    @Override
    public List<OroqenCart> getByUserId(String userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public void addToCart(String userId, String productId, Integer quantity) {
        OroqenCart existingCart = baseMapper.selectByUserIdAndProductId(userId, productId);
        if (existingCart != null) {
            // 如果商品已存在，更新数量
            existingCart.setQuantity(existingCart.getQuantity() + quantity);
            existingCart.setUpdateTime(new Date());
            this.updateById(existingCart);
        } else {
            // 如果商品不存在，新增
            OroqenCart cart = new OroqenCart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cart.setCreateTime(new Date());
            this.save(cart);
        }
    }

    @Override
    public void updateQuantity(String userId, String productId, Integer quantity) {
        UpdateWrapper<OroqenCart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
        updateWrapper.eq("product_id", productId);
        updateWrapper.set("quantity", quantity);
        updateWrapper.set("update_time", new Date());
        this.update(updateWrapper);
    }

    @Override
    public void removeFromCart(String userId, String productId) {
        QueryWrapper<OroqenCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_id", productId);
        this.remove(queryWrapper);
    }

    @Override
    public void clearCart(String userId) {
        QueryWrapper<OroqenCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        this.remove(queryWrapper);
    }
}