1
zj
2025-10-10 080dd1f1de81758b946c01e6db71938c008e9427
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package com.ruoyi.web.controller.user;
 
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.im.comm.Result;
import com.ruoyi.im.dto.RegisterDto;
import com.ruoyi.im.out.UserAccountOut;
import com.ruoyi.im.service.ImApiServcie;
import com.ruoyi.im.service.UserKycService;
import com.ruoyi.im.util.ConverterUtil;
import com.ruoyi.im.util.PhoneNumberValidatorUtil;
import com.ruoyi.im.util.SymmetricCryptoUtil;
import com.ruoyi.system.domain.UserAccount;
import com.ruoyi.system.domain.UserKyc;
import com.ruoyi.system.domain.vo.UserAccountUpdateVo;
import com.ruoyi.system.domain.vo.UserAccountVo;
import com.ruoyi.system.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
 
import java.util.*;
import java.util.stream.Collectors;
 
@RestController
@RequestMapping("/im/user")
@Slf4j
public class UserController extends BaseController {
 
    @Autowired
    UserAccountService userAccountService;
 
    @Autowired
    private ImApiServcie imApiServcie;
 
    @Autowired
    private UserKycService userKycService;
 
    /**
     * 获取会员列表
     */
    @GetMapping("/list")
    public TableDataInfo list(UserAccountVo vo)
    {
        // 创建查询条件包装器
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
 
        if (ObjectUtil.isNotEmpty(vo.getKeywords())) {
            String keywords = vo.getKeywords().trim();
            if (StringUtils.isNotEmpty(keywords)) {
                queryWrapper.and(wrapper -> wrapper
                        .eq(UserAccount::getInvitationCode, keywords)
                        .or()
                        // 使用右模糊匹配,可以利用索引
                        .likeRight(UserAccount::getPhoneNumber, keywords)
                        .or()
                        .likeRight(UserAccount::getAccount, keywords)
                        .or()
                        .likeRight(UserAccount::getNickname, keywords)
                );
            }
        }
 
        // 添加其他条件
        queryWrapper
                .eq(ObjectUtil.isNotEmpty(vo.getAccountType()), UserAccount::getAccountType, vo.getAccountType())
                .eq(ObjectUtil.isNotEmpty(vo.getStatus()), UserAccount::getStatus, vo.getStatus())
                .eq(ObjectUtil.isNotEmpty(vo.getPosition()), UserAccount::getPosition, vo.getPosition())
                .between(ObjectUtil.isAllNotEmpty(vo.getStartTime(), vo.getEndTime()),
                        UserAccount::getCreateTime, vo.getStartTime(), vo.getEndTime());
 
        // 默认按创建时间倒序
        queryWrapper.orderByDesc(UserAccount::getCreateTime);
        startPage();
        List<UserAccount> list = userAccountService.list(queryWrapper);
 
        List<Integer> idList = list.stream()
                .map(UserAccount::getId)
                .collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(idList)){
            List<UserKyc> kycList = userKycService.list(new LambdaQueryWrapper<UserKyc>()
                    .in(UserKyc::getUserId, idList)
            );
 
            Map<Integer, UserKyc> kycMap = kycList.stream()
                    .collect(Collectors.toMap(UserKyc::getUserId, kyc -> kyc));
 
            list.forEach(f->{
                if(ObjectUtil.isNotEmpty(kycMap.get(f.getId()))){
                    f.setName(kycMap.get(f.getId()).getName());
                    f.setIdCard(kycMap.get(f.getId()).getIdCard());
                }
            });
        }
 
        PageInfo<UserAccount> pageInfo = new PageInfo<>(list);
 
        // 转换为输出对象并递归加载下级列表(最多3级)
        List<UserAccountOut> toList = convertToUserAccountOutWithSubordinates(list, 3);
 
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(toList);
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }
 
    /**
     * 转换用户账户列表并递归加载下级用户
     * @param userAccounts 用户账户列表
     * @param maxLevel 最大递归层级
     * @return 包含下级列表的用户输出对象列表
     */
    private List<UserAccountOut> convertToUserAccountOutWithSubordinates(List<UserAccount> userAccounts, int maxLevel) {
        if (ObjectUtil.isEmpty(userAccounts) || maxLevel <= 0) {
            return new ArrayList<>();
        }
 
        // 先转换基础信息
        List<UserAccountOut> result = ConverterUtil.convertToList(userAccounts, UserAccountOut.class);
 
        // 递归加载下级用户
        loadSubordinateUsersRecursive(result, maxLevel);
 
        return result;
    }
 
    /**
     * 递归加载多级下级用户
     * @param userAccountOuts 当前层级的用户列表
     * @param remainingLevels 剩余递归层级
     */
    private void loadSubordinateUsersRecursive(List<UserAccountOut> userAccountOuts, int remainingLevels) {
        if (ObjectUtil.isEmpty(userAccountOuts) || remainingLevels <= 0) {
            return;
        }
 
        // 加载当前级别的下级用户
        loadCurrentLevelSubordinates(userAccountOuts);
 
        // 递归加载下级的下级
        for (UserAccountOut user : userAccountOuts) {
            if (ObjectUtil.isNotEmpty(user.getSubordinateList())) {
                loadSubordinateUsersRecursive(user.getSubordinateList(), remainingLevels - 1);
            }
        }
    }
 
    private void loadCurrentLevelSubordinates(List<UserAccountOut> userAccountOuts) {
        if (ObjectUtil.isEmpty(userAccountOuts)) {
            return;
        }
 
        // 收集所有用户的账号(用于查询下级)
        List<String> accounts = userAccountOuts.stream()
                .map(UserAccountOut::getAccount)
                .filter(ObjectUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
 
        if (accounts.isEmpty()) {
            userAccountOuts.forEach(user -> user.setSubordinateList(new ArrayList<>()));
            return;
        }
 
        // 批量查询所有直接下级用户
        LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserAccount::getInvitationAccount, accounts);
        List<UserAccount> allSubordinates = userAccountService.list(queryWrapper);
 
        // 转换为输出对象
        List<UserAccountOut> allSubordinateOuts = ConverterUtil.convertToList(allSubordinates, UserAccountOut.class);
 
        // 收集所有需要设置 KYC 的用户(当前层级 + 下级)
        List<UserAccountOut> allUsers = new ArrayList<>();
        allUsers.addAll(userAccountOuts);
        allUsers.addAll(allSubordinateOuts);
 
        // 一次性设置所有用户的 KYC 信息
        setKycInfoForUsers(allUsers);
 
        // 按邀请人账号分组
        Map<String, List<UserAccountOut>> subordinateMap = allSubordinateOuts.stream()
                .filter(sub -> ObjectUtil.isNotEmpty(sub.getInvitationAccount()))
                .collect(Collectors.groupingBy(UserAccountOut::getInvitationAccount));
 
        // 为每个用户设置下级列表
        for (UserAccountOut user : userAccountOuts) {
            if (ObjectUtil.isNotEmpty(user.getAccount())) {
                List<UserAccountOut> subordinates = subordinateMap.get(user.getAccount());
                user.setSubordinateList(ObjectUtil.isNotEmpty(subordinates) ? subordinates : new ArrayList<>());
            } else {
                user.setSubordinateList(new ArrayList<>());
            }
        }
    }
 
    /**
     * 为用户列表设置 KYC 信息
     */
    private void setKycInfoForUsers(List<UserAccountOut> users) {
        if (ObjectUtil.isEmpty(users)) {
            return;
        }
 
        // 收集用户ID
        List<Integer> idList = users.stream()
                .map(UserAccountOut::getId)
                .filter(ObjectUtil::isNotEmpty)
                .collect(Collectors.toList());
 
        if (idList.isEmpty()) {
            return;
        }
 
        // 批量查询 KYC 信息
        List<UserKyc> kycList = userKycService.list(new LambdaQueryWrapper<UserKyc>()
                .in(UserKyc::getUserId, idList)
        );
 
        // 转换为 Map
        Map<Integer, UserKyc> kycMap = kycList.stream()
                .collect(Collectors.toMap(UserKyc::getUserId, kyc -> kyc, (existing, replacement) -> existing));
 
        // 设置 KYC 信息
        users.forEach(user -> {
            if (ObjectUtil.isNotEmpty(user.getId()) && ObjectUtil.isNotEmpty(kycMap.get(user.getId()))) {
                UserKyc kyc = kycMap.get(user.getId());
                user.setName(kyc.getName());
                user.setIdCard(kyc.getIdCard());
            }
        });
    }
 
    /**
     * 获取用户的下级树形结构
     * @param userId 用户ID
     * @param maxLevel 最大层级深度
     * @return 用户下级树形结构
     */
    @GetMapping("/subordinateTree/{userId}")
    public AjaxResult getSubordinateTree(@PathVariable Integer userId,
                                         @RequestParam(defaultValue = "3") int maxLevel) {
        try {
            UserAccount userAccount = userAccountService.getById(userId);
            if (ObjectUtil.isEmpty(userAccount)) {
                return AjaxResult.error("用户不存在");
            }
 
            // 转换当前用户
            UserAccountOut userOut = ConverterUtil.convert(userAccount, UserAccountOut.class);
 
            // 递归加载下级树
            List<UserAccountOut> userList = new ArrayList<>();
            userList.add(userOut);
            loadSubordinateUsersRecursive(userList, maxLevel);
 
            return AjaxResult.success(userOut);
        } catch (Exception e) {
            log.error("获取用户下级树失败", e);
            return AjaxResult.error("获取下级树失败");
        }
    }
 
    /**
     * 获取用户的直接下级列表(不分页)
     */
    @GetMapping("/directSubordinates/{userId}")
    public AjaxResult getDirectSubordinates(@PathVariable Integer userId) {
        try {
            UserAccount userAccount = userAccountService.getById(userId);
            if (ObjectUtil.isEmpty(userAccount)) {
                return AjaxResult.error("用户不存在");
            }
 
            // 查询直接下级
            LambdaQueryWrapper<UserAccount> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserAccount::getInvitationAccount, userAccount.getAccount());
            List<UserAccount> subordinates = userAccountService.list(queryWrapper);
 
            List<UserAccountOut> result = ConverterUtil.convertToList(subordinates, UserAccountOut.class);
 
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("获取直接下级列表失败", e);
            return AjaxResult.error("获取下级列表失败");
        }
    }
 
 
 
 
 
    /**
     * 修改会员
     */
//    @PreAuthorize("@ss.hasPermi('im:user:updateUserAccount')")
    @PostMapping("/updateUserAccount")
    public AjaxResult updateUserAccount(UserAccountUpdateVo vo) {
 
        try {
            UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
                    .eq(UserAccount::getAccount,vo.getAccount())
            );
            if(ObjectUtil.isEmpty(userAccount)){
                return AjaxResult.error("会员不存在!");
            }
            if(StringUtils.isNotEmpty(vo.getPhoneNumber())){
                PhoneNumberValidatorUtil.ValidationResult result = PhoneNumberValidatorUtil.validatePhoneNumber(vo.getPhoneNumber());
                if(!result.isValid()){
                    return AjaxResult.error("手机号格式不正确!");
                }
            }
            if(StringUtils.isNotEmpty(vo.getPassword()) && StringUtils.isEmpty(vo.getOldPassword())){
                return AjaxResult.error("旧密码不能为空!");
            }
            if(StringUtils.isNotEmpty(vo.getPassword())){
                String s = SymmetricCryptoUtil.decryptPassword(userAccount.getPassword());
                if(!vo.getOldPassword().equals(s)){
                    return AjaxResult.error("旧密码不正确!");
                }
            }
            vo.setAccount(userAccount.getCloudMessageAccount());
            return imApiServcie.updateUserAccount(vo);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("修改会员失败!");
        }
        return AjaxResult.success();
    }
 
    /**
     * 创建会员
     */
    @PostMapping("/batchRegister")
    public Result batchRegister(@Validated RegisterDto dto){
        try {
            if(null == dto.getType()){
                return Result.error("类型不能为空");
            }else if(dto.getType() == 2){
                if(StringUtils.isEmpty(dto.getAccount())){
                    return Result.error("账号不能为空");
                }
                if(StringUtils.isEmpty(dto.getPassword())){
                    return Result.error("密码不能为空");
                }
                if(StringUtils.isEmpty(dto.getNikeName())){
                    return Result.error("昵称不能为空");
                }
            }else if (dto.getType() == 1){
                if(dto.getNumber() <= 0){
                    return Result.error("数量不能为空");
                }else if(dto.getNumber() > 100){
                    return Result.error("批量注册最多一次100");
                }
            }
            return imApiServcie.batchRegister(dto);
        }catch (Exception e){
            e.printStackTrace();
            log.error("-----------批量注册报错------------");
            return Result.error("注册失败,请稍后再试!");
        }
    }
 
}