From 680db402517fc38cc5137c53827aceec066cb744 Mon Sep 17 00:00:00 2001
From: zj <1772600164@qq.com>
Date: Mon, 01 Sep 2025 02:30:43 +0800
Subject: [PATCH] 1

---
 ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java |  205 ++++++++++++++++++++++++++++++++-------------------
 1 files changed, 128 insertions(+), 77 deletions(-)

diff --git a/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java b/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
index c9c4066..fb95e3b 100644
--- a/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
+++ b/ruoyi-admin/src/main/java/com/ruoyi/im/service/impl/ImApiServcieImpl.java
@@ -1,9 +1,11 @@
 package com.ruoyi.im.service.impl;
 
 import cn.hutool.core.util.ObjectUtil;
+import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson2.JSON;
 import com.alibaba.fastjson2.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.netease.nim.server.sdk.core.BizName;
 import com.netease.nim.server.sdk.core.YunxinApiHttpClient;
@@ -19,12 +21,14 @@
 import com.ruoyi.im.config.*;
 import com.ruoyi.im.dto.UpdateUserBusinessDto;
 import com.ruoyi.im.service.NeteaseTeamService;
+import com.ruoyi.imenum.ErrorCodeEnum;
 import com.ruoyi.system.domain.GroupWelcomeConfig;
 import com.ruoyi.system.domain.NeteaseTeam;
 import com.ruoyi.system.domain.UserAccount;
 import com.ruoyi.im.service.ImApiServcie;
 import com.ruoyi.im.dto.RegisterDto;
 import com.ruoyi.system.domain.vo.UserAccountUpdateVo;
+import com.ruoyi.system.mapper.NeteaseTeamMapper;
 import com.ruoyi.system.service.GroupWelcomeConfigService;
 import com.ruoyi.system.service.UserAccountService;
 import com.ruoyi.im.util.SymmetricCryptoUtil;
@@ -71,6 +75,8 @@
 
     @Autowired
     private JdbcTemplate jdbcTemplate;
+    @Autowired
+    private NeteaseTeamMapper neteaseTeamMapper;
 
     @Resource
     private final YunxinApiHttpClient yunxinClient;
@@ -105,30 +111,48 @@
     @Override
     @Transactional(rollbackFor = Exception.class)
     public Result register(RegisterDto dto) {
+        // 验证手机号是否已存在
+        List<UserAccount> accounts = userAccountService.list(
+                new LambdaQueryWrapper<>(UserAccount.class)
+                        .eq(UserAccount::getAccount, dto.getAccount())
+        );
+
+        if (!CollectionUtils.isEmpty(accounts)) {
+            return Result.error("账号已被注册!");
+        }
+
+        if(dto.getAccountType() == 0 && StringUtils.isEmpty(dto.getInvitationCode())){
+            return Result.error("邀请码不能为空!");
+        }
+
+        String invitationCode = getInvitationCode();
+        UserAccount user = new UserAccount();
+        if(dto.getAccountType() == 0 && StringUtils.isNotEmpty(dto.getInvitationCode()) &&  !dto.getInvitationCode().equals("000000")){
+            user = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
+                    .eq(UserAccount::getInvitationCode, dto.getInvitationCode()).last(" limit 1"));
+            if(ObjectUtil.isEmpty(user)){
+                return Result.error("邀请码错误");
+            }
+        }
+
+        // 创建本地用户账户记录
+        UserAccount userAccount = new UserAccount();
+        userAccount.setAccount(dto.getAccount());
+        userAccount.setPhoneNumber(dto.getAccount());
+        userAccount.setCloudMessageAccount(dto.getAccount());
+        userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(dto.getPassword()));
+        userAccount.setCreateTime(new Date());
+        userAccount.setNickname(dto.getNickname());
+        userAccount.setCreateTime(new Date());
+        userAccount.setUpdateTime(new Date());
+        userAccount.setInvitationCode(invitationCode);
+        userAccount.setInvitationAccount(ObjectUtil.isNotEmpty(user.getAccount()) ? user.getAccount() : "");
+
+        if (!userAccountService.save(userAccount)) {
+            throw new RuntimeException("保存用户账户失败");
+        }
+
         try {
-            // 验证手机号是否已存在
-            List<UserAccount> accounts = userAccountService.list(
-                    new LambdaQueryWrapper<>(UserAccount.class)
-                            .eq(UserAccount::getAccount, dto.getAccount())
-            );
-
-            if (!CollectionUtils.isEmpty(accounts)) {
-                return Result.error("账号已被注册!");
-            }
-
-            // 创建本地用户账户记录
-            UserAccount userAccount = new UserAccount();
-            userAccount.setAccount(dto.getAccount());
-            userAccount.setPhoneNumber(dto.getAccount());
-            userAccount.setCloudMessageAccount(dto.getAccount());
-            userAccount.setPassword(SymmetricCryptoUtil.encryptPassword(dto.getPassword()));
-            userAccount.setCreateTime(new Date());
-            userAccount.setNickname(dto.getNickname());
-
-            if (!userAccountService.save(userAccount)) {
-                throw new RuntimeException("保存用户账户失败"); // 改为抛出异常
-            }
-
             // 注册云信账号(远程调用)
             Map<String, String> paramMap = new HashMap<>();
             paramMap.put("accid", dto.getAccount());
@@ -144,33 +168,72 @@
             JSONObject json = JSONObject.parseObject(data);
             int code = json.getIntValue("code");
 
-            if (code == 200) {
-                GroupWelcomeConfig groupWelcomeConfig = groupWelcomeConfigService.getOne(new LambdaQueryWrapper<>(GroupWelcomeConfig.class)
-                        .eq(GroupWelcomeConfig::getConfigurationName, "IM-BASICS").last(" limit 1"));
-                if(ObjectUtil.isNotEmpty(groupWelcomeConfig)){
-                    //添加默认好友
-                    addFriends(userAccount.getAccount(),groupWelcomeConfig.getUserAccid());
-                    //加入默认群聊
-                    List<String> accountList = new ArrayList<>();
-                    accountList.add(userAccount.getAccount());
-                    AddTeamMembersRequest request = new AddTeamMembersRequest();
-                    request.setInviteAccountIds(accountList);
-                    request.setOperatorId(groupWelcomeConfig.getUserAccid());
-                    neteaseTeamService.inviteTeamMembers(request);
+            if (code != 200) {
+                String errorMsg = "";
+                if(code == 102405){
+                    errorMsg = "用户已存在";
                 }
-                return Result.success("注册成功");
-            } else {
-                // 所有非200状态码都抛出异常触发回滚
-                throw new RuntimeException("云信注册失败,错误码: " + code + ", 响应: " + data);
+                log.error("-----------注册账号异常:"+ErrorCodeEnum.getByCode(code).getComment()+"----im信息:"+ErrorCodeEnum.getByCode(code).getDesc());
+                throw new RuntimeException(errorMsg);
             }
+
+            // 注册成功后的其他操作
+            GroupWelcomeConfig groupWelcomeConfig = groupWelcomeConfigService.getOne(new LambdaQueryWrapper<>(GroupWelcomeConfig.class)
+                    .eq(GroupWelcomeConfig::getConfigurationName, "IM-BASICS").last(" limit 1"));
+
+            NeteaseTeam neteaseTeam = neteaseTeamMapper.selectOne(new LambdaQueryWrapper<NeteaseTeam>().eq(NeteaseTeam::getTid,groupWelcomeConfig.getGroupId()));
+            if(ObjectUtil.isNotEmpty(groupWelcomeConfig) &&  ObjectUtil.isNotEmpty(groupWelcomeConfig.getUserAccid())){
+                addFriends(userAccount.getAccount(),groupWelcomeConfig.getUserAccid());
+            }
+            if(ObjectUtil.isNotEmpty(groupWelcomeConfig) &&  ObjectUtil.isNotEmpty(groupWelcomeConfig.getGroupId()) && ObjectUtil.isNotEmpty(neteaseTeam)){
+                List<String> accountList = new ArrayList<>();
+                accountList.add(userAccount.getAccount());
+                AddTeamMembersRequest request = new AddTeamMembersRequest();
+                request.setInviteAccountIds(accountList);
+                request.setGroupId(ObjectUtil.isNotEmpty(neteaseTeam.getId().toString()) ? neteaseTeam.getId().toString() : null);
+                neteaseTeamService.inviteTeamMembers(request);
+            }
+            return Result.success("注册成功");
+
         } catch (Exception e) {
-            // 记录异常日志
             log.error("注册过程发生异常", e);
-            // 重新抛出异常以确保事务回滚
-            throw new RuntimeException("注册失败: " + e.getMessage(), e);
+            // 将异常包装为Result并抛出RuntimeException触发回滚
+            throw new RuntimeException(Result.error("注册失败: " + e.getMessage()).toString(), e);
         }
     }
 
+    private String getInvitationCode() {
+        String invitationCode = null;
+        int maxAttempts = 100; // 最大尝试次数
+        int attempts = 0;
+
+        while (attempts < maxAttempts) {
+            invitationCode = generateInvitationCode();
+            long count = userAccountService.count(new LambdaQueryWrapper<UserAccount>()
+                    .eq(UserAccount::getInvitationCode, invitationCode));
+            if(count <= 0){
+                break;
+            }
+            attempts++;
+        }
+
+        if (attempts >= maxAttempts) {
+            log.error("生成邀请码已超最大尝试次数!");
+            throw new RuntimeException("无法生成唯一的邀请码,请稍后重试");
+        }
+        return invitationCode;
+    }
+
+
+    /**
+     * 生成邀请码
+     * @return
+     */
+    public static String generateInvitationCode() {
+        Random random = new Random();
+        int code = 100000 + random.nextInt(900000);
+        return String.valueOf(code);
+    }
 
     /**
      * 优化的账号生成方法,使用雪花算法变体提高并发性能
@@ -263,25 +326,9 @@
             httpPatch.setHeader("CurTime", curTime);
             httpPatch.setHeader("CheckSum", checkSum);
 
-            // 构建请求体
-//            UpdateUserInfoRequest builder = new UpdateUserInfoRequest();
-//            if(StringUtils.isNotEmpty(dto.getMobile())){
-//                builder.setMobile(dto.getMobile());
-//            }
-//            if(StringUtils.isNotEmpty(dto.getName())){
-//                builder.setName(dto.getName());
-//            }
-//            if(StringUtils.isNotEmpty(dto.getSign())){
-//                builder.setSign(dto.getSign());
-//            }
-//            if(StringUtils.isNotEmpty(dto.getAvatar())){
-//                builder.setAvatar(dto.getAvatar());
-//            }
-//            String body = builder.build();
             UpdateUserInfoRequest requestBody = new UpdateUserInfoRequest(dto.getAvatar(),
-                    dto.getName(),dto.getSign(),dto.getEmail(),dto.getMobile());
+                    dto.getName(),dto.getSign(),dto.getEmail(),dto.getMobile(),dto.getGender());
             String jsonBody = objectMapper.writeValueAsString(requestBody);
-//            String jsonBody = objectMapper.writeValueAsString(body);
             httpPatch.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
 
             // 执行请求
@@ -334,6 +381,9 @@
         if(StringUtils.isNotEmpty(vo.getSignature())){
             dto.setSign(vo.getSignature());
         }
+        if(ObjectUtil.isNotEmpty(vo.getGender())){
+            dto.setGender(vo.getGender());
+        }
         Map<String, Object> map = updateUserAvatar(vo.getAccountId(), dto);
         //更新用户属性 状态 密码
         if ((Boolean) map.get("success")) {
@@ -359,6 +409,7 @@
                 if (StringUtils.isNotBlank(vo.getSignature())) {
                     userAccount.setSignature(vo.getSignature());
                 }
+                userAccount.setStatus(vo.getStatus());
                 userAccount.setUpdateTime(new Date());
                 userAccountService.updateById(userAccount);
             }else{
@@ -399,16 +450,14 @@
 
             // 创建构建器实例
             DynamicRequestBodyBuilder builder = new DynamicRequestBodyBuilder();
-            if(null != vo.getStatus() && vo.getStatus() == 0){
+            if(null != vo.getStatus() && vo.getStatus() == 1){
                 builder.setEnabled(false);
                 builder.setNeedKick(true);
-            }
-            if(StringUtils.isNotEmpty(vo.getPassword())){
+            }else if(StringUtils.isNotEmpty(vo.getPassword())){
                 builder.setToken(vo.getPassword());
             }
             // 只设置需要的字段
-            String body = builder.build();
-            String jsonBody = objectMapper.writeValueAsString(body);
+            String jsonBody = builder.build();
             httpPatch.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
 
             // 执行请求
@@ -441,6 +490,7 @@
     @Override
     @Transactional(rollbackFor = Exception.class)
     public Result batchRegister(RegisterDto dto) {
+        dto.setAccountType(1);
         if(dto.getType() == 2){
             return register(dto);
         }else{
@@ -474,7 +524,7 @@
                 return yunxinResult;
             }
 
-            return Result.success("成功批量注册 " + count + " 个账号");
+            return Result.success("成功批量注册 " + count + " 个账号",yunxinResult.getData());
 
         } catch (Exception e) {
             // 其他异常,触发回滚
@@ -493,7 +543,7 @@
         List<UserAccount> accounts = new ArrayList<>(count);
         Set<String> generatedAccounts = new HashSet<>(count); // 用于内存中去重
         Random random = new Random();
-
+        String invitationCode = getInvitationCode();
         for (int i = 0; i < count; i++) {
             String account;
             do {
@@ -511,7 +561,7 @@
             userAccount.setCreateTime(new Date());
             userAccount.setNickname("用户_" + account.substring(7)); // 简单生成昵称
             userAccount.setAccountType(1); // 设置账号类型为1
-
+            userAccount.setInvitationCode(invitationCode);
             accounts.add(userAccount);
         }
         return accounts;
@@ -566,21 +616,22 @@
                 .map(CompletableFuture::join)
                 .collect(Collectors.toList());
 
+        List<String> acccountList = new ArrayList<>();
         // 检查所有响应结果
         for (YunxinApiResponse response : responses) {
             String data = response.getData();
             JSONObject json = JSONObject.parseObject(data);
             int code = json.getIntValue("code");
-            if (code != 200) {
-                // 记录具体的错误信息
-                String errorAccid = json.getString("accid"); // 如果返回了accid
-                log.error("云信账号注册失败,accid: {}, 响应: {}, traceId: {}", errorAccid, data, response.getTraceId());
-                // 返回第一个遇到的错误
-                return Result.error("云信注册失败,错误码: " + code + (errorAccid != null ? ", 账号: " + errorAccid : ""));
-            }
-        }
+            JSONObject info = json.getJSONObject("info");
+            String accid = info.getString("accid");
 
-        return Result.success("所有云信账号注册成功");
+            if (code != 200) {
+                log.error("-----------云信账号注册失败:"+ ErrorCodeEnum.getByCode(code).getComment()+"----im信息:"+ErrorCodeEnum.getByCode(code).getDesc());
+                return Result.error("云信注册失败:"+ErrorCodeEnum.getByCode(code).getComment());
+            }
+            acccountList.add(accid);
+        }
+        return Result.success(acccountList);
     }
 
 

--
Gitblit v1.9.3