package com.zxyj.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.zxyj.entity.GuideInviteCode; import com.zxyj.mapper.GuideInviteCodeMapper; import org.springframework.stereotype.Service; import java.util.Date; import java.util.UUID; /** * 指导师邀请码服务 */ @Service public class GuideInviteCodeService extends ServiceImpl { /** * 生成邀请码 */ public GuideInviteCode generateInviteCode(Long guideId, Integer maxUseCount, Integer expireDays) { GuideInviteCode inviteCode = new GuideInviteCode(); inviteCode.setGuideId(guideId); inviteCode.setCode(generateCode()); inviteCode.setStatus("active"); inviteCode.setUseCount(0); inviteCode.setMaxUseCount(maxUseCount != null ? maxUseCount : 1); if (expireDays != null && expireDays > 0) { Date expireAt = new Date(); expireAt.setTime(expireAt.getTime() + expireDays * 24 * 60 * 60 * 1000L); inviteCode.setExpireAt(expireAt); } this.save(inviteCode); return inviteCode; } /** * 验证邀请码 */ public GuideInviteCode validateInviteCode(String code) { LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(GuideInviteCode::getCode, code) .eq(GuideInviteCode::getStatus, "active"); GuideInviteCode inviteCode = this.getOne(wrapper); if (inviteCode == null) { return null; } // 检查是否过期 if (inviteCode.getExpireAt() != null && inviteCode.getExpireAt().before(new Date())) { inviteCode.setStatus("expired"); this.updateById(inviteCode); return null; } // 检查使用次数 if (inviteCode.getUseCount() >= inviteCode.getMaxUseCount()) { inviteCode.setStatus("used"); this.updateById(inviteCode); return null; } return inviteCode; } /** * 使用邀请码 */ public boolean useInviteCode(String code, Long userId) { GuideInviteCode inviteCode = validateInviteCode(code); if (inviteCode == null) { return false; } inviteCode.setUsedByUserId(userId); inviteCode.setUsedAt(new Date()); inviteCode.setUseCount(inviteCode.getUseCount() + 1); // 如果达到最大使用次数,标记为已使用 if (inviteCode.getUseCount() >= inviteCode.getMaxUseCount()) { inviteCode.setStatus("used"); } return this.updateById(inviteCode); } /** * 获取指导师的邀请码列表 */ public java.util.List getGuideInviteCodes(Long guideId) { LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); wrapper.eq(GuideInviteCode::getGuideId, guideId) .orderByDesc(GuideInviteCode::getCreatedAt); return this.list(wrapper); } /** * 生成随机邀请码 */ private String generateCode() { return UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase(); } }