1
zj
2025-10-12 84d42b6997ae87fa64b75ae085fce11d05a6ca5a
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package com.ruoyi.im;
 
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.im.comm.Result;
import com.ruoyi.im.config.IpUtils;
import com.ruoyi.im.dto.UpdateUserBusinessDto;
import com.ruoyi.im.service.*;
import com.ruoyi.im.dto.RegisterDto;
import com.ruoyi.im.service.impl.InsurancePositionServiceImpl;
import com.ruoyi.im.util.PayService;
import com.ruoyi.im.util.SimplePayUtil;
import com.ruoyi.im.util.UserPolicyUtils;
import com.ruoyi.im.util.ValidatorUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.SubordinateInformationDto;
import com.ruoyi.system.domain.out.UserOut;
import com.ruoyi.system.domain.out.UserTeamAndPositionOut;
import com.ruoyi.system.domain.vo.UserAccountUpdateVo;
import com.ruoyi.system.service.GroupWelcomeConfigService;
import com.ruoyi.system.service.IpBlacklistService;
import com.ruoyi.system.service.PaymentRecordService;
import com.ruoyi.system.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.*;
import java.util.stream.Collectors;
 
@RestController
@RequestMapping("/im/api")
@Slf4j
public class ImApiController {
 
    @Autowired
    private ImApiServcie imApiServcie;
 
    @Autowired
    IpBlacklistService ipBlacklistService;
 
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    GroupWelcomeConfigService groupWelcomeConfigService;
 
    @Autowired
    InsuranceProductService insuranceProductService;
 
    @Autowired
    MedicalInsuranceAccountService medicalInsuranceAccountService;
 
    @Autowired
    UserPolicyService userPolicyService;
 
    @Autowired
    InsurancePositionServiceImpl insurancePositionService;
 
    @Autowired
    UserKycService userKycService;
 
    @Autowired
    InsuranceFeatureService insuranceFeatureService;
 
 
 
    @Value("${file.upload-dir}")
    private String uploadDir;
 
    @Value("${file.upload-prefix}")
    private String prefix;
 
 
 
 
    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@Validated RegisterDto dto){
        try {
            // 验证手机号
            boolean isPhoneValid = ValidatorUtil.isValidPhone(dto.getAccount());
            if(!isPhoneValid){
                return Result.error("手机号格式不正确");
            }
            return imApiServcie.register(dto);
        } catch (RuntimeException e) {
            // 从异常消息中解析Result对象
            return JSON.parseObject(e.getMessage(), Result.class);
        }
    }
 
    /**
     * 获取二维码链接和邀请码
     */
    @GetMapping("/getUserCodeAndUrl")
    public Result getUserCodeAndUrl(@RequestParam("account") String account){
        try {
            GroupWelcomeConfig groupWelcomeConfig = groupWelcomeConfigService.getOne(new LambdaQueryWrapper<>(GroupWelcomeConfig.class)
                    .eq(GroupWelcomeConfig::getConfigurationName, "IM-BASICS").last(" limit 1"));
            UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getAccount, account));
            Map<String,String> map = new HashMap<>();
            map.put("url",ObjectUtil.isNotEmpty(groupWelcomeConfig.getCodeUrl()) ? groupWelcomeConfig.getCodeUrl() : "");
            map.put("code",userAccount.getInvitationCode());
            return Result.success(map);
        } catch (RuntimeException e) {
            // 从异常消息中解析Result对象
            return JSON.parseObject(e.getMessage(), Result.class);
        }
    }
 
    /**
     * 修改用户信息只有数据库
     * @return
     */
    @PostMapping("/updateUser")
    public Result updateUser(UserAccountUpdateVo vo){
        try {
            UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getAccount,vo.getAccount()));
 
            if (StringUtils.isNotBlank(vo.getNickname())) {
                userAccount.setNickname(vo.getNickname());
            }
 
            if (StringUtils.isNotBlank(vo.getSignature())) {
                userAccount.setSignature(vo.getSignature());
            }
 
            userAccount.setUpdateTime(new Date());
            userAccountService.updateById(userAccount);
            return Result.success();
        } catch (RuntimeException e) {
            e.printStackTrace();
            log.error("修改用户数据库信息失败");
            return Result.error("修改失败!");
        }
    }
 
    /**
     * 获取ip地址并判断是否在黑名单
     */
    @GetMapping("/blacklist")
    public Result blacklist(HttpServletRequest request,@RequestParam("account") String account){
        try {
            String clientIp = IpUtils.getClientIp(request);
            if(StringUtils.isEmpty(clientIp)){
                return Result.success();
            }
            long count = ipBlacklistService.count(new LambdaQueryWrapper<IpBlacklist>().eq(IpBlacklist::getIpAddress, clientIp));
            if(count > 0){
                return Result.error("账号异常,禁止登录!");
            }
            UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<>(UserAccount.class).eq(UserAccount::getCloudMessageAccount, account));
            if(ObjectUtil.isEmpty(userAccount)){
                return Result.error("账号不存在!");
            }
            userAccount.setLoginIp(clientIp);
            userAccount.setLoginTime(new Date());
            userAccountService.updateById(userAccount);
            return Result.success();
        }catch (Exception e){
            log.error("登录错误:",e);
            return Result.error("登录错误,请稍后再试!");
        }
    }
 
 
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("accountId") String accountId) {
        try {
 
            // 1. 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null ||
                    (!contentType.equals("image/jpeg") &&
                            !contentType.equals("image/png") &&
                            !contentType.equals("image/gif"))) {
 
                return Result.error("只支持JPEG、PNG和GIF格式的图片!");
            }
 
            // 确保上传目录存在
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
                // 设置目录权限为755 (rwxr-xr-x)
                setPermissions(directory, "rwxr-xr-x");
            }
 
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(uploadDir, fileName);
 
            // 保存文件
            Files.write(filePath, file.getBytes());
 
            // 设置文件权限为644 (rw-r--r--)
            setPermissions(filePath.toFile(), "rw-r--r--");
 
            // 5. 调用网易云信API更新头像
            fileName = prefix+"/"+fileName;
            UpdateUserBusinessDto dto = new UpdateUserBusinessDto();
            dto.setAvatar(fileName);
            Map<String, Object> result = imApiServcie.updateUserAvatar(accountId,dto);
            if ((Boolean) result.get("success")) {
                return Result.success("文件上传成功");
            } else {
                return Result.error("上传失败!");
            }
        } catch (IOException e) {
            return Result.error("文件上传失败");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("设置文件权限失败!");
        }
        return Result.success();
    }
 
    /**
     * 设置文件/目录权限
     * @param file 文件或目录对象
     * @param perm 权限字符串,如 "rw-r--r--"
     */
    private void setPermissions(File file, String perm) throws IOException {
        // 获取当前操作系统
        String os = System.getProperty("os.name").toLowerCase();
 
        // 只有在Unix/Linux系统上才能设置POSIX权限
        if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(perm);
            Files.setPosixFilePermissions(file.toPath(), permissions);
        } else {
            // Windows系统不支持POSIX权限,可以设置基本权限
            file.setReadable(true, false);    // 所有用户可读
            if (perm.startsWith("rw")) {
                file.setWritable(true, false); // 所有用户可写(如果权限字符串以rw开头)
            } else {
                file.setWritable(false, false);
            }
 
            // 如果是目录且包含执行权限,设置可执行
            if (file.isDirectory() && perm.contains("x")) {
                file.setExecutable(true, false);
            }
        }
    }
 
    /**
     * 产品信息列表
     */
    @GetMapping("/list")
    public Result list() {
        LambdaQueryWrapper<InsuranceProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InsuranceProduct::getStatus, "ACTIVE");
        // 按创建时间倒序排列
        wrapper.orderByDesc(InsuranceProduct::getCreatedAt);
 
        List<InsuranceProduct> list = insuranceProductService.list(wrapper);
        return Result.success(list);
    }
    /**
     * 获取用户详情
     */
    @GetMapping("/getUserByAccount")
    public Result getUserByAccount(HttpServletRequest request,@RequestParam("account") String account){
        try {
            String clientIp = IpUtils.getClientIp(request);
            if(StringUtils.isEmpty(clientIp)){
                return Result.success();
            }
            UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<>(UserAccount.class).eq(UserAccount::getCloudMessageAccount, account));
            if(ObjectUtil.isEmpty(userAccount)){
                return Result.error("账号不存在!");
            }
 
            GroupWelcomeConfig groupWelcomeConfig = groupWelcomeConfigService.getOne(new LambdaQueryWrapper<>(GroupWelcomeConfig.class)
                    .eq(GroupWelcomeConfig::getConfigurationName, "IM-BASICS").last(" limit 1"));
 
            UserOut user = new UserOut();
            if(ObjectUtil.isNotEmpty(groupWelcomeConfig)){
                user.setCustomerServiceUrl(groupWelcomeConfig.getCustomerServiceUrl());
                user.setAboutUs(groupWelcomeConfig.getAboutUs());
            }
            user.setBalance(userAccount.getBalance());
 
            MedicalInsuranceAccount insuranceAccount = medicalInsuranceAccountService.getOne(new LambdaQueryWrapper<>(MedicalInsuranceAccount.class)
                    .eq(MedicalInsuranceAccount::getUserId, userAccount.getId())
                    .eq(MedicalInsuranceAccount::getAccountStatus, MedicalInsuranceAccount.AccountStatus.ACTIVE)
            );
            user.setKycStatus(userAccount.getKycStatus());
            user.setGroupPermissions(userAccount.getGroupPermissions());
            user.setAddFriend(userAccount.getAddFriend());
            if(ObjectUtil.isEmpty(insuranceAccount)){
                return Result.success(user);
            }
            user.setAmountClaimed(insuranceAccount.getAmountClaimed());
            user.setAlreadyReceived(insuranceAccount.getAlreadyReceived());
            return Result.success(user);
        }catch (Exception e){
            log.error("获取失败:",e);
            return Result.error("获取失败,请稍后再试!");
        }
    }
 
 
    /**
     * 获取用户团队和职位
     */
    @GetMapping("/getUserTeamAndPosition")
    public Result getUserTeamAndPosition(@RequestParam("account") String account) {
        UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<>(UserAccount.class).eq(UserAccount::getCloudMessageAccount, account));
        if(ObjectUtil.isEmpty(userAccount)){
            return Result.error("账号不存在!");
        }
        //查询当前用户的下级
        List<UserAccount> userAccountList = userAccountService.list(new LambdaQueryWrapper<UserAccount>()
                .eq(UserAccount::getInvitationAccount, userAccount.getAccount())
        );
        UserTeamAndPositionOut userTeamAndPositionOut = new UserTeamAndPositionOut();
 
        List<InsurancePosition> positions = insurancePositionService.list();
 
        if(CollectionUtils.isEmpty(userAccountList)){
            userTeamAndPositionOut.setInsurancePosition(positions);
            return Result.success(userTeamAndPositionOut);
        }
        List<Integer> idList = userAccountList.stream()
                .map(UserAccount::getId)
                .collect(Collectors.toList());
 
        List<UserPolicy> userPolicyList = userPolicyService.list(new LambdaQueryWrapper<>(UserPolicy.class)
                .in(UserPolicy::getUserId, idList)
        );
 
        List<SubordinateInformationDto> informationDtos = new ArrayList<>();
        userAccountList.forEach(f->{
            userTeamAndPositionOut.setSubordinateNumber(userAccountList.size());
            SubordinateInformationDto subordinateInformationDto = new SubordinateInformationDto();
            subordinateInformationDto.setName(StringUtils.isEmpty(f.getNickname()) ? f.getAccount() : f.getNickname());
            subordinateInformationDto.setPhone(f.getAccount());
            subordinateInformationDto.setKycStatus(f.getKycStatus());
            subordinateInformationDto.setIsActivate(UserPolicyUtils.hasActivePolicyForUser(userPolicyList,f.getId()));
            informationDtos.add(subordinateInformationDto);
        });
 
        long activeNumber = UserPolicyUtils.countActivePolicies(userPolicyList);
        userTeamAndPositionOut.setInsureNumber(activeNumber);
 
        positions.forEach(f->{
            if(activeNumber >= f.getNumberPeople()){
                userTeamAndPositionOut.setPosition(f.getPosition());
                userTeamAndPositionOut.setSalary(f.getSalary());
            }
        });
        userTeamAndPositionOut.setInsurancePosition(positions);
        userTeamAndPositionOut.setSubordinateInformation(informationDtos);
        return Result.success(userTeamAndPositionOut);
    }
 
    /**
     * 获取用户实名认证
     */
    @GetMapping("/getUserKyc")
    public Result getUserKyc(@RequestParam("account") String account) {
        UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<>(UserAccount.class).eq(UserAccount::getCloudMessageAccount, account));
        if(ObjectUtil.isEmpty(userAccount)){
            return Result.error("账号不存在!");
        }
        UserKyc userKyc = userKycService.getOne(new LambdaQueryWrapper<>(UserKyc.class)
                .eq(UserKyc::getUserId, userAccount.getId())
        );
        return Result.success(userKyc);
    }
 
    /**
     * 产品信息列表
     */
    @GetMapping("/getProduct")
    public Result getProduct(@RequestParam("account") String account) {
        UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<>(UserAccount.class).eq(UserAccount::getCloudMessageAccount, account));
        if(ObjectUtil.isEmpty(userAccount)){
            return Result.error("账号不存在!");
        }
        LambdaQueryWrapper<InsuranceProduct> wrapper = new LambdaQueryWrapper<>();
        // 按创建时间倒序排列
        wrapper.orderByDesc(InsuranceProduct::getCreatedAt);
        List<InsuranceProduct> list = insuranceProductService.list(wrapper);
        list.forEach(f->{
            long count = userPolicyService.count(new LambdaQueryWrapper<>(UserPolicy.class)
                    .eq(UserPolicy::getUserId, userAccount.getId())
                    .eq(UserPolicy::getProductId,f.getId())
                    .and(a->a.ne(UserPolicy::getPayStatus,2).or().ne(UserPolicy::getPayStatus,1))
                    .ne(UserPolicy::getApprovalStatus,2)
            );
            if(count > 0){
                f.setIsBuy(true);
            }
            List<InsuranceFeature> features = insuranceFeatureService.list(new LambdaQueryWrapper<InsuranceFeature>()
                    .eq(InsuranceFeature::getProductId, f.getId()));
            f.setProductFeature(features);
        });
        return Result.success(list);
    }
}