package com.xuqm.im.service; import com.xuqm.common.exception.BusinessException; import com.xuqm.common.security.JwtUtil; import com.xuqm.im.entity.ImAccountEntity; import com.xuqm.im.repository.ImAccountRepository; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.Map; import java.util.UUID; @Service public class ImAccountService { private final ImAccountRepository accountRepository; private final JwtUtil jwtUtil; public ImAccountService(ImAccountRepository accountRepository, JwtUtil jwtUtil) { this.accountRepository = accountRepository; this.jwtUtil = jwtUtil; } public String loginOrRegister(String appId, String userId, String nickname, String avatar) { ImAccountEntity account = accountRepository.findByAppIdAndUserId(appId, userId) .orElseGet(() -> { ImAccountEntity e = new ImAccountEntity(); e.setId(UUID.randomUUID().toString()); e.setAppId(appId); e.setUserId(userId); e.setNickname(nickname); e.setAvatar(avatar); e.setGender(ImAccountEntity.Gender.UNKNOWN); e.setStatus(ImAccountEntity.Status.ACTIVE); e.setCreatedAt(LocalDateTime.now()); return accountRepository.save(e); }); if (account.getStatus() == ImAccountEntity.Status.BANNED) { throw new BusinessException(403, "账号已被封禁"); } return jwtUtil.generate(userId, Map.of("appId", appId, "role", "USER")); } public ImAccountEntity getAccount(String appId, String userId) { return accountRepository.findByAppIdAndUserId(appId, userId) .orElseThrow(() -> new BusinessException(404, "账号不存在")); } public ImAccountEntity updateAccount(String appId, String userId, String nickname, String avatar, ImAccountEntity.Gender gender) { ImAccountEntity account = getAccount(appId, userId); if (nickname != null) account.setNickname(nickname); if (avatar != null) account.setAvatar(avatar); if (gender != null) account.setGender(gender); return accountRepository.save(account); } }