package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.entity.ActivityRegistration;
import com.zhentao.mapper.ActivityRegistrationMapper;
import com.zhentao.service.ActivityRegistrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动报名服务实现类
 */
@Slf4j
@Service
public class ActivityRegistrationServiceImpl implements ActivityRegistrationService {
    
    private final ActivityRegistrationMapper activityRegistrationMapper;
    
    public ActivityRegistrationServiceImpl(ActivityRegistrationMapper activityRegistrationMapper) {
        this.activityRegistrationMapper = activityRegistrationMapper;
    }
    
    @Override
    public List<ActivityRegistration> getUserRegistrations(Integer userId, Integer status) {
        try {
            if (status != null) {
                // 查询特定状态的记录
                return activityRegistrationMapper.selectUserRegistrations(userId, status);
            } else {
                // 查询所有记录
                return activityRegistrationMapper.selectAllUserRegistrations(userId);
            }
        } catch (Exception e) {
            log.error("查询用户活动报名记录失败: userId={}, status={}", userId, status, e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean cancelRegistration(Long id, Integer userId) {
        try {
            // 验证记录是否属于该用户
            QueryWrapper<ActivityRegistration> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id).eq("user_id", userId).eq("status", 1);
            
            ActivityRegistration registration = activityRegistrationMapper.selectOne(wrapper);
            if (registration == null) {
                log.warn("报名记录不存在或已取消: id={}, userId={}", id, userId);
                return false;
            }
            
            // 更新状态为已取消
            registration.setStatus(2);
            registration.setUpdatedTime(LocalDateTime.now());
            
            return activityRegistrationMapper.updateById(registration) > 0;
        } catch (Exception e) {
            log.error("取消报名失败: id={}, userId={}", id, userId, e);
            return false;
        }
    }
}

