package com.ruoyi.web.work.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.work.api.util.AppUtil;
import com.ruoyi.web.work.domain.Favorite;
import com.ruoyi.web.work.mapper.FavoriteMapper;
import com.ruoyi.web.work.service.IFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lsw
 * @date 2024-06-15
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {
    @Autowired
    private FavoriteMapper favoriteMapper;

    @Override
    public List<Favorite> selectList(Favorite favorite) {
        return favoriteMapper.selectList(favorite);
    }

    @Override
    public AjaxResult add(Long id) {
        Favorite collection = favoriteMapper.check(new Favorite().setUserId(AppUtil.getUser().getId()).setPositionId(id));
        if (collection != null) {
            return AjaxResult.error("已添加收藏");
        }
        collection = new Favorite();
        collection.setUserId(AppUtil.getUser().getId());
        collection.setPositionId(id);
        if (!save(collection)) {
            throw new ServiceException("添加收藏失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult remove(Long id) {
        Favorite collection = getById(id);
        if (collection == null || !collection.getUserId().equals(AppUtil.getUser().getId())) {
            return AjaxResult.error("收藏不存在或非法操作");
        }
        if (!removeById(id)) {
            throw new ServiceException("删除收藏失败");
        }
        return AjaxResult.success();
    }
}
