刘光辉
7 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
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
450
451
452
453
454
455
456
457
458
459
package jnpf.tmsService.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jnpf.base.UserInfo;
import jnpf.exception.DataException;
import jnpf.permission.OrganizeApi;
import jnpf.permission.PositionApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.OrganizeEntity;
import jnpf.permission.entity.PositionEntity;
import jnpf.permission.entity.UserEntity;
import jnpf.tmsEntity.TmsPersonFileEntity;
import jnpf.tmsEntity.TmsPersonTrainEntity;
import jnpf.tmsEntity.TmsPersonWorkEntity;
import jnpf.tmsEntity.archive.TmsTrainArchiveCatalogVO;
import jnpf.tmsEntity.archive.TmsTrainArchiveDetailVO;
import jnpf.tmsEntity.archive.TmsTrainArchiveProfileVO;
import jnpf.tmsEntity.archive.TmsTrainArchiveWorkVO;
import jnpf.tmsMapper.TmsPersonFileMapper;
import jnpf.tmsMapper.TmsPersonTrainMapper;
import jnpf.tmsMapper.TmsPersonWorkMapper;
import jnpf.tmsService.TmsTrainArchiveService;
import jnpf.tmsEntity.enums.TmsPassFlag;
import jnpf.tmsEntity.enums.TmsTaskSourceType;
import jnpf.tmsEntity.enums.TmsTrainMode;
import jnpf.tmsEntity.enums.TmsTaskCategory;
import jnpf.tmsEntity.enums.TmsEvalMode;
import jnpf.tmsEntity.enums.TmsValidRevoked;
import jnpf.util.DateUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
 
/**
 * 学员「我的个人培训档案」:主档 {@code tms_person_file} + 履历 + 培训目录。
 *
 * <p>培训目录 {@code catalogList} 只读 {@code tms_person_train},
 * 数据来自培训记录归档({@link TmsRecordServiceImpl#upsertPersonTrain}),非实时学习写入。</p>
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TmsTrainArchiveServiceImpl implements TmsTrainArchiveService {
 
    private final TmsPersonFileMapper personFileMapper;
    private final TmsPersonWorkMapper personWorkMapper;
    private final TmsPersonTrainMapper personTrainMapper;
    private final OrganizeApi organizeApi;
    private final PositionApi positionApi;
    private final UserApi userApi;
 
    /**
     * 当前登录人档案;无主档则自动建档。
     * catalogList ← {@link #loadCatalogList} ← tms_person_train。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public TmsTrainArchiveDetailVO getMine() {
        UserInfo user = UserProvider.getUser();
        if (user == null || StringUtil.isEmpty(user.getUserId())) {
            throw new DataException("未获取到登录用户");
        }
        String userId = user.getUserId();
        TmsPersonFileEntity file = findByUserId(userId);
        if (file == null) {
            file = createArchive(user);
        }
 
        TmsTrainArchiveDetailVO detail = new TmsTrainArchiveDetailVO();
        detail.setProfile(toProfile(file, user));
        detail.setWorkList(loadWorkList(file.getId()));
        detail.setCatalogList(loadCatalogList(file.getId(), userId));
        return detail;
    }
 
    /**
     * 按用户 ID 查找档案主档
     */
    private TmsPersonFileEntity findByUserId(String userId) {
        LambdaQueryWrapper<TmsPersonFileEntity> qw = new LambdaQueryWrapper<>();
        qw.eq(TmsPersonFileEntity::getUserId, userId);
        qw.last("LIMIT 1");
        return personFileMapper.selectOne(qw);
    }
 
    /**
     * 创建个人培训档案主档
     */
    private TmsPersonFileEntity createArchive(UserInfo user) {
        Date now = new Date();
        TmsPersonFileEntity entity = new TmsPersonFileEntity();
        entity.setId(RandomUtil.uuId());
        entity.setArchiveNo(nextArchiveNo());
        entity.setArchiveDate(now);
        entity.setUserId(user.getUserId());
        entity.setUserName(user.getUserName());
        entity.setDeptId(user.getOrganizeId());
        List<String> positionIds = normalizeIds(user.getPositionIds());
        if (!positionIds.isEmpty()) {
            entity.setMainPostId(positionIds.get(0));
            if (positionIds.size() > 1) {
                entity.setPartPostId(positionIds.get(1));
            }
        }
        entity.setBizStatus(TmsValidRevoked.VALID.getCode());
        entity.setCreatorUserId(user.getUserId());
        entity.setCreatorTime(now);
        personFileMapper.insert(entity);
        return entity;
    }
 
    /**
     * 规范化 ID 列表
     */
    private List<String> normalizeIds(Object raw) {
        if (raw == null) {
            return Collections.emptyList();
        }
        if (raw instanceof List) {
            List<?> list = (List<?>) raw;
            List<String> out = new ArrayList<>();
            for (Object o : list) {
                if (o != null && StringUtil.isNotEmpty(String.valueOf(o))) {
                    out.add(String.valueOf(o));
                }
            }
            return out;
        }
        if (raw instanceof String[]) {
            List<String> out = new ArrayList<>();
            for (String s : (String[]) raw) {
                if (StringUtil.isNotEmpty(s)) {
                    out.add(s);
                }
            }
            return out;
        }
        if (raw instanceof String && StringUtil.isNotEmpty((String) raw)) {
            return Collections.singletonList((String) raw);
        }
        return Collections.emptyList();
    }
 
    /** 档案编号:AR + 年份 + 4 位流水 */
    private String nextArchiveNo() {
        int year = Calendar.getInstance().get(Calendar.YEAR);
        String prefix = "AR" + year;
        LambdaQueryWrapper<TmsPersonFileEntity> qw = new LambdaQueryWrapper<>();
        qw.likeRight(TmsPersonFileEntity::getArchiveNo, prefix);
        qw.orderByDesc(TmsPersonFileEntity::getArchiveNo);
        qw.last("LIMIT 1");
        TmsPersonFileEntity last = personFileMapper.selectOne(qw);
        int seq = 1;
        if (last != null && StringUtil.isNotEmpty(last.getArchiveNo()) && last.getArchiveNo().length() >= prefix.length() + 4) {
            try {
                seq = Integer.parseInt(last.getArchiveNo().substring(prefix.length())) + 1;
            } catch (NumberFormatException ignored) {
                seq = 1;
            }
        }
        return prefix + String.format("%04d", Math.min(seq, 9999));
    }
 
    /**
     * 转为档案基本信息 VO
     */
    private TmsTrainArchiveProfileVO toProfile(TmsPersonFileEntity file, UserInfo user) {
        TmsTrainArchiveProfileVO vo = new TmsTrainArchiveProfileVO();
        vo.setId(file.getId());
        vo.setArchiveNo(file.getArchiveNo());
        vo.setArchiveDate(file.getArchiveDate() == null ? null : DateUtil.dateToString(file.getArchiveDate(), "yyyy-MM-dd"));
        vo.setUserId(file.getUserId());
        vo.setUserName(StringUtil.isNotEmpty(file.getUserName()) ? file.getUserName() : user.getUserName());
        vo.setDeptName(resolveDeptName(file.getDeptId(), user));
        vo.setMainPostName(resolvePostName(file.getMainPostId(), user, true));
        vo.setPartPostName(resolvePostName(file.getPartPostId(), user, false));
        return vo;
    }
 
    /**
     * 解析部门名称
     */
    private String resolveDeptName(String deptId, UserInfo user) {
        if (StringUtil.isNotEmpty(deptId)) {
            try {
                OrganizeEntity org = organizeApi.getInfoById(deptId);
                if (org != null && StringUtil.isNotEmpty(org.getFullName())) {
                    return org.getFullName();
                }
            } catch (Exception e) {
                log.debug("resolve dept name failed: {}", e.getMessage());
            }
        }
        if (user != null && StringUtil.isNotEmpty(user.getOrganize())) {
            return user.getOrganize();
        }
        return "无";
    }
 
    /**
     * 解析岗位名称
     */
    private String resolvePostName(String postId, UserInfo user, boolean main) {
        if (StringUtil.isNotEmpty(postId)) {
            try {
                PositionEntity pos = positionApi.queryInfoById(postId);
                if (pos != null && StringUtil.isNotEmpty(pos.getFullName())) {
                    return pos.getFullName();
                }
            } catch (Exception e) {
                log.debug("resolve post name failed: {}", e.getMessage());
            }
        }
        if (main && user != null) {
            List<String> positionIds = normalizeIds(user.getPositionIds());
            if (!positionIds.isEmpty()) {
                try {
                    List<PositionEntity> list = positionApi.getListByIds(positionIds);
                    if (list != null && !list.isEmpty() && StringUtil.isNotEmpty(list.get(0).getFullName())) {
                        return list.get(0).getFullName();
                    }
                } catch (Exception e) {
                    log.debug("resolve main post from user failed: {}", e.getMessage());
                }
            }
        }
        return "无";
    }
 
        /**
         * 加载工作履历
         */
        private List<TmsTrainArchiveWorkVO> loadWorkList(String archiveId) {
        LambdaQueryWrapper<TmsPersonWorkEntity> qw = new LambdaQueryWrapper<>();
        qw.eq(TmsPersonWorkEntity::getForeignId, archiveId);
        qw.orderByAsc(TmsPersonWorkEntity::getHireDate);
        List<TmsPersonWorkEntity> rows = personWorkMapper.selectList(qw);
        if (rows == null || rows.isEmpty()) {
            return Collections.emptyList();
        }
        List<TmsTrainArchiveWorkVO> list = new ArrayList<>(rows.size());
        for (TmsPersonWorkEntity row : rows) {
            TmsTrainArchiveWorkVO vo = new TmsTrainArchiveWorkVO();
            vo.setId(row.getId());
            vo.setCompanyName(row.getCompanyName());
            vo.setPostName(row.getPostName());
            vo.setHireDate(row.getHireDate() == null ? null : DateUtil.dateToString(row.getHireDate(), "yyyy-MM-dd"));
            vo.setLeaveDate(row.getLeaveDate() == null ? null : DateUtil.dateToString(row.getLeaveDate(), "yyyy-MM-dd"));
            list.add(vo);
        }
        return list;
    }
 
    /** 按档案/用户加载培训目录(已归档写入的 person_train)。 */
    private List<TmsTrainArchiveCatalogVO> loadCatalogList(String archiveId, String userId) {
        LambdaQueryWrapper<TmsPersonTrainEntity> qw = new LambdaQueryWrapper<>();
        qw.and(w -> w.eq(TmsPersonTrainEntity::getArchiveId, archiveId)
                .or()
                .eq(TmsPersonTrainEntity::getUserId, userId));
        qw.orderByDesc(TmsPersonTrainEntity::getStartTime);
        List<TmsPersonTrainEntity> rows = personTrainMapper.selectList(qw);
        if (rows == null || rows.isEmpty()) {
            return Collections.emptyList();
        }
        // 去重:同一 id 只保留一条
        List<TmsPersonTrainEntity> distinct = new ArrayList<>(rows.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(TmsPersonTrainEntity::getId, r -> r, (a, b) -> a, LinkedHashMap::new))
                .values());
        distinct.sort((a, b) -> {
            Date ta = a.getStartTime();
            Date tb = b.getStartTime();
            if (ta == null && tb == null) return 0;
            if (ta == null) return 1;
            if (tb == null) return -1;
            return tb.compareTo(ta);
        });
 
        Set<String> teacherIds = new HashSet<>();
        for (TmsPersonTrainEntity row : distinct) {
            teacherIds.addAll(splitIds(row.getTeacherId()));
        }
        Map<String, String> teacherNames = loadUserNames(teacherIds);
 
        List<TmsTrainArchiveCatalogVO> list = new ArrayList<>(distinct.size());
        for (TmsPersonTrainEntity row : distinct) {
            list.add(toCatalog(row, teacherNames));
        }
        return list;
    }
 
    /**
     * 转为档案目录项 VO
     */
    private TmsTrainArchiveCatalogVO toCatalog(TmsPersonTrainEntity row, Map<String, String> teacherNames) {
        TmsTrainArchiveCatalogVO vo = new TmsTrainArchiveCatalogVO();
        vo.setId(row.getId());
        vo.setRecordNo(row.getRecordNo());
        vo.setTrainType(labelCategory(row.getCategory()));
        vo.setTrainContent(row.getSubject());
        vo.setTrainMode(labelTrainMode(row.getTrainMode()));
        vo.setTrainerName(resolveTeacherNames(row.getTeacherId(), teacherNames));
        vo.setEvalMode(labelEvalMode(row.getEvalMode()));
        vo.setPassFlag(normalizePassFlag(row.getPassFlag()));
        vo.setTrainStart(row.getStartTime() == null ? null : DateUtil.dateToString(row.getStartTime(), "yyyy-MM-dd HH:mm"));
        vo.setTrainEnd(row.getEndTime() == null ? null : DateUtil.dateToString(row.getEndTime(), "yyyy-MM-dd HH:mm"));
        return vo;
    }
 
    /**
     * 批量加载用户姓名
     */
    private Map<String, String> loadUserNames(Set<String> userIds) {
        Map<String, String> map = new HashMap<>();
        if (userIds == null || userIds.isEmpty()) {
            return map;
        }
        try {
            List<UserEntity> users = userApi.getUserName(new ArrayList<>(userIds));
            if (users != null) {
                for (UserEntity u : users) {
                    if (u != null && StringUtil.isNotEmpty(u.getId())) {
                        map.put(u.getId(), StringUtil.isNotEmpty(u.getRealName()) ? u.getRealName() : u.getId());
                    }
                }
            }
        } catch (Exception e) {
            log.debug("resolve users failed: {}", e.getMessage());
        }
        return map;
    }
 
    /**
     * 解析讲师姓名(可多人)
     */
    private String resolveTeacherNames(String teacherId, Map<String, String> nameMap) {
        if (StringUtil.isEmpty(teacherId)) {
            return "";
        }
        List<String> ids = splitIds(teacherId);
        if (ids.isEmpty()) {
            return teacherId;
        }
        List<String> names = new ArrayList<>();
        for (String id : ids) {
            names.add(nameMap.getOrDefault(id, id));
        }
        return String.join("、", names);
    }
 
    /**
     * 拆分 ID 字符串
     */
    private List<String> splitIds(String raw) {
        if (StringUtil.isEmpty(raw)) {
            return Collections.emptyList();
        }
        String[] parts = raw.split("[,,;;\\s]+");
        List<String> out = new ArrayList<>();
        for (String p : parts) {
            if (StringUtil.isNotEmpty(p)) {
                out.add(p.trim());
            }
        }
        return out;
    }
 
    /** 归一为 tmsPassFlag:pass/fail/absent/na;兼容历史 1/0 */
    private String normalizePassFlag(String raw) {
        String n = TmsPassFlag.normalize(raw);
        return n == null ? "" : n;
    }
 
    /**
     * 培训类别标签
     */
    private String labelCategory(String code) {
        if (StringUtil.isEmpty(code)) {
            return "";
        }
        TmsTaskCategory category = TmsTaskCategory.of(code);
        if (category != null) {
            return category == TmsTaskCategory.OUT_TRAIN ? "外派培训" : category.getLabel();
        }
        TmsTaskSourceType source = TmsTaskSourceType.of(code);
        if (source != null) {
            return source.getLabel();
        }
        if ("temporary".equals(code)) {
            return TmsTaskCategory.TEMP.getLabel();
        }
        return code;
    }
 
    /**
     * 培训方式标签
     */
    private String labelTrainMode(String code) {
        if (StringUtil.isEmpty(code)) {
            return "";
        }
        TmsTrainMode mode = TmsTrainMode.of(code.toLowerCase());
        if (mode == null) {
            return code;
        }
        switch (mode) {
            case ONLINE:
                return "在线学习";
            case ONSITE:
                return "集中授课";
            case PRACTICE:
                return "操作授课";
            default:
                return mode.getLabel();
        }
    }
 
    /**
     * 评估方式标签
     */
    private String labelEvalMode(String code) {
        if (StringUtil.isEmpty(code)) {
            return "";
        }
        TmsEvalMode mode = TmsEvalMode.of(code.toLowerCase());
        if (mode == null) {
            return code;
        }
        switch (mode) {
            case EXAM:
                return "在线考试";
            case NONE:
                return "无需考核";
            case QUIZ:
                return "现场提问";
            case PRACTICE:
                return "实操考核";
            default:
                return mode.getLabel();
        }
    }
}