package shop.alien.gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.UserPoint;
import shop.alien.gateway.service.UserPointService;
import shop.alien.mapper.UserPointMapper;

import java.util.List;

/**
 * 签到类型活动服务
 *
 * @author zhangchen
 * @since 2025-9-8
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserPointServiceImpl extends ServiceImpl<UserPointMapper, UserPoint> implements UserPointService {

    private final UserPointMapper userPointMapper;

    @Override
    public UserPoint addPoint(Integer userId, Integer point) {
        UserPoint userPoint = new UserPoint();
        if (userId != null && point != null) {
            LambdaQueryWrapper<UserPoint> userPointLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userPointLambdaQueryWrapper.eq(UserPoint::getUserId, userId);
            userPointLambdaQueryWrapper.eq(UserPoint::getDeleteFlag, 0);
            List<UserPoint> userPointList = userPointMapper.selectList(userPointLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(userPointList)) {
                userPoint = userPointList.get(0);
                int totalPoint = point + userPoint.getUserPoint();
                userPoint.setUserPoint(totalPoint);
                userPointMapper.updateById(userPoint);
            } else {
                userPoint.setUserId(userId);
                userPoint.setUserPoint(point);
                userPointMapper.insert(userPoint);
            }
        }
        return userPoint;
    }

}
