package com.ruoyi.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.mall.domain.Product;
import com.ruoyi.mall.domain.UserFavorite;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class UserFavoriteServiceImpl  extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {



    @Autowired
    private ProductServiceImpl productService;

    /**
     * 收藏商品
     */
    @Override
    public Boolean addFavorite(Long productId) {
       Long userId= SecurityUtils.getAppLoginUser().getAppUserId();
        // 检查商品是否存在
        if (ObjectUtil.isEmpty(productService.selectById(productId))) {
            throw new RuntimeException("商品不存在: " + productId);
        }

        // 检查是否已收藏
        if (existsByUserIdAndProductId(userId, productId)) {
            throw new RuntimeException("您已收藏该商品");
        }

        // 创建收藏记录
        UserFavorite favorite = new UserFavorite();
        favorite.setUserId(userId);
        favorite.setProductId(productId);
        this.save(favorite);
        return true;
    }


    /**
     * 检查用户是否收藏了某商品
     */
    @Override
    public boolean existsByUserIdAndProductId(Long userId, Long productId){
        UserFavorite userFavorite= this.getOne(new QueryWrapper<UserFavorite>().eq("user_id",userId).eq("product_id",productId));
        return ObjectUtil.isNotEmpty(userFavorite);
    }
    /**
     * 取消收藏
     */
    @Override
    public boolean removeFavorite(Long userId, Long productId) {
        // 检查收藏记录是否存在
        if (!existsByUserIdAndProductId(userId, productId)) {
            throw new RuntimeException("收藏记录不存在");
        }

        // 删除收藏记录
       return this.remove(new QueryWrapper<UserFavorite>().eq("user_id",userId).eq("product_id",productId));
    }


    /**
     * 获取用户的收藏列表
     */
    @Override
    public List<Product> getUserFavorites() {
        Long userId= SecurityUtils.getAppLoginUser().getAppUserId();;
       List<Product> list= baseMapper.getFavoriteList(userId,null);
        return list;
    }


    /**
     * 获取用户的收藏数量
     */
    @Override
    public long getUserFavoriteCount() {
        Long userId= SecurityUtils.getAppLoginUser().getAppUserId();;
        return this.count(new QueryWrapper<UserFavorite>().eq("user_id",userId));
    }
}
