puzhibing
2026-02-28 9821e05e90ef31f2f2dce4128a7cd1adf032a60c
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package com.xiaopeng.account.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaopeng.account.constant.I18nKeyConstant;
import com.xiaopeng.account.mapper.SysRoleMapper;
import com.xiaopeng.account.mapper.XpOperationsRoleMapper;
import com.xiaopeng.account.mapper.XpOperationsUserMapper;
import com.xiaopeng.account.model.dto.EnableDisableDTO;
import com.xiaopeng.account.model.dto.RePasswordDTO;
import com.xiaopeng.account.model.dto.XpOperationsUserAddDTO;
import com.xiaopeng.account.model.dto.XpOperationsUserDTO;
import com.xiaopeng.account.model.query.XpOperationsUserPageQuery;
import com.xiaopeng.account.model.query.XpOperationsUserQuery;
import com.xiaopeng.account.service.ISysRoleService;
import com.xiaopeng.account.service.IXpOperationsRoleService;
import com.xiaopeng.account.service.IXpOperationsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaopeng.account.service.IXpQualificationAuditService;
import com.xiaopeng.api.feignClient.maintenance.XpClockInClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.XpFleetClient;
import com.xiaopeng.api.feignClient.vehicleConvoy.XpFleetOperationsClient;
import com.xiaopeng.api.model.account.*;
import com.xiaopeng.api.model.vehicleConvoy.XpFleet;
import com.xiaopeng.api.vo.account.*;
import com.xiaopeng.common.core.domain.R;
import com.xiaopeng.common.core.exception.ServiceException;
import com.xiaopeng.common.core.utils.poi.ExcelUtil;
import com.xiaopeng.common.core.web.page.PageInfo;
import com.xiaopeng.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 运维人员 服务实现类
 * </p>
 *
 * @author mitao
 * @since 2026-02-03
 */
@Slf4j
@Service
public class XpOperationsUserServiceImpl extends ServiceImpl<XpOperationsUserMapper, XpOperationsUser> implements IXpOperationsUserService {
 
    @Autowired
    private XpFleetOperationsClient xpFleetOperationsClient;
 
    @Autowired
    private XpFleetClient xpFleetClient;
 
    @Autowired
    private XpOperationsRoleMapper xpOperationsRoleMapper;
    @Autowired
    private IXpOperationsRoleService xpOperationsRoleService;
 
    @Autowired
    private XpClockInClient xpClockInClient;
 
    @Autowired
    private IXpQualificationAuditService xpQualificationAuditService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private ISysRoleService iSysRoleService;
 
    @Override
    public List<XpOperationsUser> listByName(String nickName) {
        if (StringUtils.isBlank(nickName)) {
            return Collections.emptyList();
        }
        return lambdaQuery().like(XpOperationsUser::getNickName, nickName).list();
    }
 
    @Override
    public PageInfo<XpOperationsUserWithRoleVO> selectUserPageByConditions(XpOperationsUserPageQuery query) {
        Page<XpOperationsUserWithRoleVO> page = baseMapper.selectUserPageByConditions(new Page<>(query.getPageNum(), query.getPageSize()), query);
        PageInfo<XpOperationsUserWithRoleVO> pageInfo = new PageInfo<>();
        pageInfo.setRecords(page.getRecords());
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }
 
    @Override
    public XpOperationsUserProfileVO getUserProfile(Long userId) {
        // 1. 查询运维人员基础信息
        XpOperationsUser user = this.getById(userId);
        if (user == null) {
            throw new ServiceException("运维人员不存在");
        }
 
        XpOperationsUserProfileVO vo = new XpOperationsUserProfileVO();
        BeanUtils.copyProperties(user, vo);
 
        // 2. 查询关联的车队ID列表(一个运维人员只能关联一个车队)
        R<List<Long>> fleetIdsResult = xpFleetOperationsClient.getFleetIdsByUserId(userId);
        List<Long> fleetIds = fleetIdsResult.getData();
 
        if (!CollectionUtils.isEmpty(fleetIds)) {
            // 3. 获取第一个车队ID(因为只能关联一个车队)
            Long fleetId = fleetIds.get(0);
 
            // 4. 查询车队信息
            R<List<XpFleet>> fleetsResult = xpFleetClient.listByIds(Collections.singletonList(fleetId));
            List<XpFleet> fleets = fleetsResult.getData();
 
            if (!CollectionUtils.isEmpty(fleets)) {
                XpFleet fleet = fleets.get(0);
 
                // 5. 组装车队信息VO
                FleetInfoVO fleetVO = new FleetInfoVO();
                fleetVO.setFleetId(fleet.getId());
                fleetVO.setFleetName(fleet.getFleetName());
                fleetVO.setProvinceName(fleet.getProvinceName());
                fleetVO.setCityName(fleet.getCityName());
                fleetVO.setDistrictName(fleet.getDistrictName());
 
                // 6. 查询并填充车队队长信息
                if (fleet.getOperationsUserId() != null) {
                    XpOperationsUser captain = this.getById(fleet.getOperationsUserId());
                    if (captain != null) {
                        fleetVO.setCaptainId(captain.getId());
                        fleetVO.setFleetLeaderName(captain.getNickName());
                        fleetVO.setFleetLeaderAvatar(captain.getAvatar());
                    }
                }
 
                vo.setFleet(fleetVO);
            }
        }
 
        // 7. 查询是否上班中
        try {
            R<Boolean> workStatusResult = xpClockInClient.checkWorkStatus(userId);
            if (workStatusResult != null && workStatusResult.getCode() == 200) {
                vo.setWorkFlag(workStatusResult.getData());
            } else {
                // 调用失败,默认 false
                vo.setWorkFlag(false);
                log.warn("查询用户上班状态失败, userId={}, result={}", userId, workStatusResult);
            }
        } catch (Exception e) {
            // 异常情况,默认 false
            vo.setWorkFlag(false);
            log.error("查询用户上班状态异常, userId={}", userId, e);
        }
 
        // 8. 查询角色信息
        List<XpOperationsUserWithRoleVO> userWithRoles = xpOperationsRoleMapper.selectUsersWithRoleByIds(Collections.singletonList(userId));
        XpOperationsUserWithRoleVO operationsUserWithRoleVO = userWithRoles.get(0);
        if (CollUtil.isNotEmpty(operationsUserWithRoleVO.getRoles())) {
            List<XpOperationsUserProfileVO.RoleInfoVO> roleVOs = operationsUserWithRoleVO.getRoles().stream()
                    .map(item -> BeanUtil.copyProperties(item, XpOperationsUserProfileVO.RoleInfoVO.class))
                    .collect(Collectors.toList());
            vo.setRoles(roleVOs);
        }
        return vo;
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveCertificate(XpOperationsUserDTO dto) {
        XpOperationsUser xpOperationsUser = BeanUtil.copyProperties(dto, XpOperationsUser.class);
        updateById(xpOperationsUser);
        //保存审核记录
        XpQualificationAudit xpQualificationAudit = BeanUtil.copyProperties(dto, XpQualificationAudit.class, "id");
        xpQualificationAudit.setAuditStatus(1);
        xpQualificationAuditService.save(xpQualificationAudit);
    }
 
    @Override
    public PageInfo<XpOperationsUserVO> pageList(XpOperationsUserQuery query) {
        PageInfo<XpOperationsUserVO> pageInfo = new PageInfo<>(query.getPageNum(), query.getPageSize());
        List<XpOperationsUserVO> list = this.baseMapper.pageList(pageInfo, query);
 
        if(CollectionUtils.isEmpty(list)){
            return pageInfo;
        }
 
        // 查询角色名称
        List<Long> operationsUserIds = list.stream().map(XpOperationsUserVO::getId).collect(Collectors.toList());
 
        // 查询用户信息
        List<XpOperationsRole> xpOperationsRoles = xpOperationsRoleMapper.selectList(Wrappers.lambdaQuery(XpOperationsRole.class)
                .in(XpOperationsRole::getOperationsUserId, operationsUserIds));
 
        if(!CollectionUtils.isEmpty(xpOperationsRoles)){
            List<Long> roleIds = xpOperationsRoles.stream().map(XpOperationsRole::getRoleId).distinct().collect(Collectors.toList());
            // 查询列表关联的所有角色
            List<SysRole> sysRoles = sysRoleMapper.selectList(Wrappers.lambdaQuery(SysRole.class)
                    .in(SysRole::getId, roleIds));
            if(!CollectionUtils.isEmpty(sysRoles)){
 
                // 角色匹配账号id
                Map<Long, List<SysRole>> map = new HashMap<>();
                for (XpOperationsRole xpOperationsRole : xpOperationsRoles) {
                    List<SysRole> sysRoleList = sysRoles.stream().filter(sysRole -> sysRole.getId().equals(xpOperationsRole.getRoleId())).collect(Collectors.toList());
                    List<SysRole> roleList = map.get(xpOperationsRole.getOperationsUserId());
                    if(!CollectionUtils.isEmpty(roleList)){
                        sysRoleList.addAll(roleList);
                    }
                    map.put(xpOperationsRole.getOperationsUserId(), sysRoleList);
                }
                // 角色名称匹配
                for (XpOperationsUserVO xpOperationsUserVO : list) {
                    xpOperationsUserVO.setSysRoles(map.get(xpOperationsUserVO.getId()));
                }
            }
        }
        pageInfo.setRecords(list);
        return pageInfo;
    }
 
    @Override
    public R<String> addOperationsUser(XpOperationsUserAddDTO dto) {
        long userCount = this.count(Wrappers.lambdaQuery(XpOperationsUser.class)
                .eq(XpOperationsUser::getPhoneNumber, dto.getPhoneNumber()));
        if (StringUtils.isNotBlank(dto.getPhoneNumber()) && userCount>0) {
            throw new ServiceException("登录账号重复", I18nKeyConstant.ACCOUNT_DUPLICATE);
        }
        //校验编号是否唯一
        long numberCount = this.count(Wrappers.lambdaQuery(XpOperationsUser.class)
                .eq(XpOperationsUser::getUniqueNumber, dto.getUniqueNumber()));
        if (numberCount > 0) {
            throw new ServiceException("用户编号已存在", I18nKeyConstant.ACCOUNT_UNIQUE_NUMBER_DUPLICATE);
        }
        // 密码加密
        dto.setPassword(SecurityUtils.encryptPassword(dto.getPassword()));
        // 保存
        this.save(dto);
        // 存储角色
        List<Long> roleIds = dto.getRoleIds();
        if(!CollectionUtils.isEmpty(roleIds)){
            List<XpOperationsRole> xpOperationsRoles = roleIds.stream().map(roleId -> {
                XpOperationsRole xpOperationsRole = new XpOperationsRole();
                xpOperationsRole.setOperationsUserId(dto.getId());
                xpOperationsRole.setRoleId(roleId);
                return xpOperationsRole;
            }).collect(Collectors.toList());
            xpOperationsRoleService.saveBatch(xpOperationsRoles);
        }
        return R.ok();
    }
 
    @Override
    public R<String> editOperationsUser(XpOperationsUserAddDTO dto) {
        XpOperationsUser operationsUser = this.getOne(Wrappers.lambdaQuery(XpOperationsUser.class)
                .eq(XpOperationsUser::getPhoneNumber, dto.getPhoneNumber())
                .last("LIMIT 1"));
 
        if (StringUtils.isNotBlank(dto.getPhoneNumber()) && (Objects.nonNull(operationsUser) && !dto.getId().equals(operationsUser.getId()) )) {
            throw new ServiceException("手机号已开通账号", I18nKeyConstant.ACCOUNT_PHONE_DUPLICATE);
        }
        if (dto.getPassword() != null && !dto.getPassword().isEmpty()) {
            dto.setPassword(null);
        }
        this.updateById(dto);
 
        //删除旧的角色数据,添加新的角色
        xpOperationsRoleService.remove(new LambdaQueryWrapper<XpOperationsRole>().eq(XpOperationsRole::getOperationsUserId, dto.getId()));
        // 存储角色
        List<Long> roleIds = dto.getRoleIds();
        if(!CollectionUtils.isEmpty(roleIds)){
            List<XpOperationsRole> xpOperationsRoles = roleIds.stream().map(roleId -> {
                XpOperationsRole xpOperationsRole = new XpOperationsRole();
                xpOperationsRole.setOperationsUserId(dto.getId());
                xpOperationsRole.setRoleId(roleId);
                return xpOperationsRole;
            }).collect(Collectors.toList());
            xpOperationsRoleService.saveBatch(xpOperationsRoles);
        }
        return R.ok();
    }
 
    @Override
    public void enableDisableById(EnableDisableDTO dto) {
        XpOperationsUser operationsUser = this.getById(dto.getId());
        operationsUser.setStatus(dto.getStatus());
        this.updateById(operationsUser);
    }
 
    @Override
    public void rePassword(RePasswordDTO dto) {
        XpOperationsUser operationsUser = this.getById(dto.getId());
        // 密码加密
        operationsUser.setPassword(SecurityUtils.encryptPassword(dto.getNewPassword()));
        this.updateById(operationsUser);
    }
 
    @Override
    public XpOperationsUserVO detailById(Long id) {
        // 查询用户信息
        XpOperationsUser xpOperationsUser = this.getById(id);
        XpOperationsUserVO xpOperationsUserVO = new XpOperationsUserVO();
        BeanUtils.copyProperties(xpOperationsUser, xpOperationsUserVO);
        // 查询角色
        List<XpOperationsRole> xpOperationsRoles = xpOperationsRoleMapper.selectList(Wrappers.lambdaQuery(XpOperationsRole.class)
                .eq(XpOperationsRole::getOperationsUserId, id));
        if(!CollectionUtils.isEmpty(xpOperationsRoles)){
            List<Long> roleIds = xpOperationsRoles.stream().map(XpOperationsRole::getRoleId).collect(Collectors.toList());
            List<SysRole> sysRoles = sysRoleMapper.selectList(Wrappers.lambdaQuery(SysRole.class)
                    .in(SysRole::getId, roleIds));
            xpOperationsUserVO.setSysRoles(sysRoles);
        }
        return xpOperationsUserVO;
    }
 
 
    /**
     * 导出运维人员列表
     * @param query
     */
    @Override
    public void exportOperationsUser(XpOperationsUserQuery query, HttpServletResponse response) {
        List<ExportOperationsUserVo> list = this.baseMapper.exportOperationsUser(query);
        ExcelUtil<ExportOperationsUserVo> util = new ExcelUtil<ExportOperationsUserVo>(ExportOperationsUserVo.class);
        util.exportExcel(response, list, "运维人员管理列表");
    }
 
 
    /**
     * 导入运维人员数据
     * @param file
     */
    @Override
    public void importOperationsUser(MultipartFile file) {
        ExcelUtil<ExportOperationsUserVo> util = new ExcelUtil<ExportOperationsUserVo>(ExportOperationsUserVo.class);
        try {
            List<ExportOperationsUserVo> list = util.importExcel(file.getInputStream());
            for (ExportOperationsUserVo exportOperationsUserVo : list) {
                XpOperationsUser xpOperationsUser = new XpOperationsUser();
                xpOperationsUser.setNickName(exportOperationsUserVo.getNickName());
                xpOperationsUser.setUniqueNumber(exportOperationsUserVo.getUniqueNumber());
                xpOperationsUser.setAvatar(exportOperationsUserVo.getAvatar());
                xpOperationsUser.setPhoneNumber(exportOperationsUserVo.getPhoneNumber());
                xpOperationsUser.setRemarks(exportOperationsUserVo.getRemarks());
                xpOperationsUser.setStatus(true);
                xpOperationsUser.setIdCardFront(exportOperationsUserVo.getIdCardFront());
                xpOperationsUser.setIdCardBack(exportOperationsUserVo.getIdCardBack());
                xpOperationsUser.setDriverLicense(exportOperationsUserVo.getDriverLicense());
                xpOperationsUser.setCertificateOfNoCriminalRecord(exportOperationsUserVo.getCertificateOfNoCriminalRecord());
                xpOperationsUser.setTrainingGraduationCertificate(exportOperationsUserVo.getTrainingGraduationCertificate());
                xpOperationsUser.setDeleted(false);
                xpOperationsUser.setCreateTime(LocalDateTime.now());
                xpOperationsUser.setUpdateTime(LocalDateTime.now());
                this.save(xpOperationsUser);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
 
    /**
     * 导出模板
     * @param response
     */
    @Override
    public void exportTemplate(HttpServletResponse response) {
        ExcelUtil<ExportOperationsUserVo> util = new ExcelUtil<ExportOperationsUserVo>(ExportOperationsUserVo.class);
        util.importTemplateExcel(response, "运维人员管理列表");
    }
 
    @Override
    public List<XpOperationsUserWithRoleVO> selectUsersWithRoleByIds(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
 
        List<XpOperationsUser> operationsUsers = listByIds(ids);
        if (CollUtil.isEmpty(operationsUsers)) {
            return Collections.emptyList();
        }
 
        // 查询用户角色信息
        List<Long> userIds = operationsUsers.stream()
                .map(XpOperationsUser::getId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
 
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
 
        // 获取关联角色ids
        List<XpOperationsRole> operationsRoles = xpOperationsRoleMapper.selectList(
                Wrappers.lambdaQuery(XpOperationsRole.class)
                        .in(XpOperationsRole::getOperationsUserId, userIds)
        );
 
        // userId -> 该用户关联的 roleId 列表
        Map<Long, List<Long>> userRoleIdsMap = CollUtil.isNotEmpty(operationsRoles)
                ? operationsRoles.stream()
                .filter(r -> r.getOperationsUserId() != null && r.getRoleId() != null)
                .collect(Collectors.groupingBy(
                        XpOperationsRole::getOperationsUserId,
                        Collectors.mapping(XpOperationsRole::getRoleId,
                                Collectors.collectingAndThen(Collectors.toList(),
                                        list -> list.stream().distinct().collect(Collectors.toList())))
                ))
                : Collections.emptyMap();
 
        // 一次性查出所有角色
        List<Long> roleIds = userRoleIdsMap.values().stream()
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());
 
        Map<Long, SysRole> roleMap = CollUtil.isNotEmpty(roleIds)
                ? iSysRoleService.listByIds(roleIds).stream()
                .collect(Collectors.toMap(SysRole::getId, Function.identity(), (a, b) -> a))
                : Collections.emptyMap();
 
        // 组装 VO:每个用户对应角色列表
        return operationsUsers.stream().map(u -> {
            Long uid = u.getId();
 
            List<Long> roleIdList = userRoleIdsMap.getOrDefault(uid, Collections.emptyList());
            List<SysRole> roles = roleIdList.stream()
                    .map(roleMap::get)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
 
            // 根据你的 VO 字段调整
            XpOperationsUserWithRoleVO vo = BeanUtil.copyProperties(u, XpOperationsUserWithRoleVO.class);
            vo.setRoles(roles);
 
            return vo;
        }).collect(Collectors.toList());
    }
}