陈昶聿
3 天以前 3acf9415fce2dd21c0fd5d67805b72a8bde24a81
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
package com.smartor.service.mch;
 
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.smartor.common.MchFollowupConstants;
import com.smartor.common.SpecificArchiveConstants;
import com.smartor.domain.MchFollowupArchiveCandidate;
import com.smartor.domain.MchFollowupNode;
import com.smartor.domain.MchFollowupPlan;
import com.smartor.domain.MchFollowupPlanItem;
import com.smartor.domain.MchFollowupTaskQuery;
import com.smartor.domain.MchFollowupTaskVO;
import com.smartor.domain.PatChildArchiveDetail;
import com.smartor.domain.PatMaternityArchiveDetail;
import com.smartor.mapper.MchFollowupPlanItemMapper;
import com.smartor.mapper.MchFollowupPlanMapper;
import com.smartor.mapper.PatChildArchiveDetailMapper;
import com.smartor.mapper.PatMaternityArchiveDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.Collections;
import java.util.Date;
import java.util.List;
 
/**
 * 妇幼随访计划服务实现。
 *
 * <p>只处理丽水市妇幼保健院。计划生成不发送消息,发送由
 * {@link IMchFollowupSendService} 独立完成。</p>
 */
@Slf4j
@Service
public class MchFollowupPlanServiceImpl implements IMchFollowupPlanService {
 
    @Autowired
    private MchFollowupPlanMapper planMapper;
 
    @Autowired
    private MchFollowupPlanItemMapper itemMapper;
 
    @Autowired
    private PatMaternityArchiveDetailMapper maternityDetailMapper;
 
    @Autowired
    private PatChildArchiveDetailMapper childDetailMapper;
 
    @Autowired
    private MchFollowupPeriodParser periodParser;
 
    @Autowired
    private MchFollowupPlanAssembler planAssembler;
 
    @Autowired
    private ISysConfigService configService;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int rebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId) {
        try {
            return doRebuildForArchive(archiveType, archiveId, archiveDetailId);
        } catch (Exception e) {
            // 计划生成失败不能影响档案主流程,异常在事务边界内消化
            log.error("【妇幼随访】计划重建异常,archiveType={},archiveId={},detailId={}",
                    archiveType, archiveId, archiveDetailId, e);
            return 0;
        }
    }
 
    private int doRebuildForArchive(String archiveType, Long archiveId, Long archiveDetailId) {
        if (!isEnabled()) {
            return 0;
        }
        ArchiveSnapshot snapshot = loadSnapshot(archiveType, archiveId, archiveDetailId);
        if (snapshot == null) {
            return 0;
        }
        if (snapshot.archiveId == null || snapshot.archiveDetailId == null) {
            log.warn("【妇幼随访】档案主键或详情主键为空,跳过计划重建,archiveType={},archiveId={},detailId={}",
                    archiveType, archiveId, archiveDetailId);
            return 0;
        }
        if (!SpecificArchiveConstants.LISHUI_MCH_ORG_ID.equals(snapshot.orgid)) {
            return 0;
        }
        // 档案必须经过人工保存/确认后才允许生成计划;接诊完成自动建档只是草稿。
        if (!isFollowupActive(snapshot.followupStatus)) {
            log.debug("【妇幼随访】档案未确认随访,跳过计划重建,archiveType={},archiveId={},detailId={},followupStatus={}",
                    snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId, snapshot.followupStatus);
            return 0;
        }
 
        List<MchFollowupPlan> actives = planMapper.selectActiveByArchive(
                snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId);
        if (actives == null) {
            actives = Collections.emptyList();
        }
        for (MchFollowupPlan active : actives) {
            // 只有“有效”计划才做幂等判断;待补充计划即使日期/周期字符串相同,
            // 也可能是因为之前配置非法而挂起,人工确认后必须重新解析并生成节点。
            if (MchFollowupConstants.PLAN_STATUS_ACTIVE.equals(active.getPlanStatus())
                    && sameTime(active.getPlannedFollowTime(), snapshot.plannedFollowTime)
                    && StringUtils.equals(active.getFollowupPeriod(), snapshot.followupPeriod)) {
                MchFollowupPlan contactUpdate = new MchFollowupPlan();
                contactUpdate.setId(active.getId());
                contactUpdate.setCampusid(snapshot.campusid);
                contactUpdate.setSourceBizNo(snapshot.sourceBizNo);
                contactUpdate.setPatname(snapshot.patname);
                contactUpdate.setPhone(snapshot.phone);
                contactUpdate.setIdcardno(snapshot.idcardno);
                contactUpdate.setUpdateTime(DateUtils.getNowDate());
                planMapper.updateMchFollowupPlan(contactUpdate);
                log.debug("【妇幼随访】计划未变化,仅刷新联系人信息,archiveType={},archiveId={},detailId={}",
                        snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId);
                return 0;
            }
        }
 
        Date now = DateUtils.getNowDate();
        for (MchFollowupPlan active : actives) {
            itemMapper.cancelPendingByPlanId(active.getId(), now);
            planMapper.cancelById(active.getId(), now);
        }
 
        MchFollowupPlan plan = new MchFollowupPlan();
        plan.setOrgid(snapshot.orgid);
        plan.setCampusid(snapshot.campusid);
        plan.setArchiveType(snapshot.archiveType);
        plan.setArchiveId(snapshot.archiveId);
        plan.setArchiveDetailId(snapshot.archiveDetailId);
        plan.setSourceType(snapshot.sourceType);
        plan.setSourceBizNo(snapshot.sourceBizNo);
        plan.setPatid(snapshot.patid);
        plan.setPatname(snapshot.patname);
        plan.setPhone(snapshot.phone);
        plan.setIdcardno(snapshot.idcardno);
        plan.setPlannedFollowTime(snapshot.plannedFollowTime);
        plan.setFollowupPeriod(snapshot.followupPeriod);
        plan.setCreateTime(now);
        plan.setUpdateTime(now);
 
        if (snapshot.plannedFollowTime == null) {
            plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_WAITING);
            plan.setRemark("拟随访时间为空,待补充");
            planMapper.insertMchFollowupPlan(plan);
            log.warn("【妇幼随访】拟随访时间为空,生成待补充计划,archiveType={},detailId={}",
                    snapshot.archiveType, snapshot.archiveDetailId);
            return 0;
        }
 
        List<MchFollowupNode> nodes;
        try {
            nodes = periodParser.parse(snapshot.followupPeriod, snapshot.followupCycleTimes);
        } catch (Exception e) {
            plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_WAITING);
            plan.setRemark("随访周期JSON解析失败:" + truncate(e.getMessage(), 200));
            planMapper.insertMchFollowupPlan(plan);
            log.error("【妇幼随访】随访周期解析失败,archiveType={},detailId={},period={}",
                    snapshot.archiveType, snapshot.archiveDetailId, snapshot.followupPeriod, e);
            return 0;
        }
        if (nodes.isEmpty()) {
            plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_WAITING);
            plan.setRemark("随访周期未配置发送节点");
            planMapper.insertMchFollowupPlan(plan);
            return 0;
        }
 
        plan.setPlanStatus(MchFollowupConstants.PLAN_STATUS_ACTIVE);
        planMapper.insertMchFollowupPlan(plan);
        List<MchFollowupPlanItem> items = planAssembler.assemble(plan.getId(), snapshot.plannedFollowTime, nodes);
        for (MchFollowupPlanItem item : items) {
            itemMapper.insertMchFollowupPlanItem(item);
        }
        log.info("【妇幼随访】计划重建完成,archiveType={},archiveId={},detailId={},节点数={}",
                snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId, items.size());
        return items.size();
    }
 
    @Override
    public int rebuildAll(int limit) {
        if (!isEnabled()) {
            return 0;
        }
        int batch = limit <= 0 ? MchFollowupConstants.DEFAULT_BATCH_SIZE : limit;
        List<MchFollowupArchiveCandidate> candidates =
                planMapper.selectCandidates(SpecificArchiveConstants.LISHUI_MCH_ORG_ID, batch);
        if (candidates == null || candidates.isEmpty()) {
            return 0;
        }
        int generated = 0;
        for (MchFollowupArchiveCandidate candidate : candidates) {
            try {
                generated += rebuildForArchive(candidate.getArchiveType(),
                        candidate.getArchiveId(), candidate.getArchiveDetailId());
            } catch (Exception e) {
                log.error("【妇幼随访】补建计划失败,archiveType={},archiveId={},detailId={}",
                        candidate.getArchiveType(), candidate.getArchiveId(),
                        candidate.getArchiveDetailId(), e);
            }
        }
        return generated;
    }
 
    @Override
    public int updateItemFollowupResult(MchFollowupPlanItem item) {
        if (item == null || item.getId() == null) {
            throw new BaseException("随访节点ID不能为空");
        }
        String followupStatus = item.getFollowupStatus();
        if (StringUtils.isEmpty(followupStatus)) {
            throw new BaseException("随访状态不能为空");
        }
        if (!isValidItemFollowupStatus(followupStatus)) {
            throw new BaseException("不支持的随访状态:" + followupStatus);
        }
        MchFollowupPlanItem existing = itemMapper.selectMchFollowupPlanItemById(item.getId());
        if (existing == null) {
            throw new BaseException("随访节点不存在:" + item.getId());
        }
        item.setUpdateTime(DateUtils.getNowDate());
        return itemMapper.updateFollowupResult(item);
    }
 
    @Override
    public List<MchFollowupPlanItem> listItems(Long planId) {
        if (planId == null) {
            throw new BaseException("计划ID不能为空");
        }
        return itemMapper.selectByPlanId(planId);
    }
 
    @Override
    public List<MchFollowupTaskVO> listTasks(MchFollowupTaskQuery query) {
        if (query == null || StringUtils.isEmpty(query.getOrgid())) {
            throw new BaseException("机构ID不能为空");
        }
        return itemMapper.selectTaskList(query);
    }
 
    private boolean isValidItemFollowupStatus(String status) {
        return MchFollowupConstants.ITEM_FOLLOWUP_STATUS_PENDING.equals(status)
                || MchFollowupConstants.ITEM_FOLLOWUP_STATUS_DONE.equals(status)
                || MchFollowupConstants.ITEM_FOLLOWUP_STATUS_LOST.equals(status)
                || MchFollowupConstants.ITEM_FOLLOWUP_STATUS_REFUSED.equals(status)
                || MchFollowupConstants.ITEM_FOLLOWUP_STATUS_BAD_NUMBER.equals(status);
    }
 
    private ArchiveSnapshot loadSnapshot(String archiveType, Long archiveId, Long archiveDetailId) {
        if (MchFollowupConstants.ARCHIVE_TYPE_MATERNITY.equals(archiveType)) {
            return loadMaternitySnapshot(archiveId, archiveDetailId);
        }
        if (MchFollowupConstants.ARCHIVE_TYPE_CHILD.equals(archiveType)) {
            return loadChildSnapshot(archiveId, archiveDetailId);
        }
        log.warn("【妇幼随访】未知档案类型:{}", archiveType);
        return null;
    }
 
    private ArchiveSnapshot loadMaternitySnapshot(Long archiveId, Long archiveDetailId) {
        PatMaternityArchiveDetail detail = null;
        if (archiveDetailId != null) {
            detail = maternityDetailMapper.selectPatMaternityArchiveDetailById(archiveDetailId);
        }
        if (detail == null && archiveId != null) {
            PatMaternityArchiveDetail query = new PatMaternityArchiveDetail();
            query.setArchiveid(archiveId);
            List<PatMaternityArchiveDetail> list =
                    maternityDetailMapper.selectPatMaternityArchiveDetailList(query);
            if (list != null && !list.isEmpty()) {
                detail = list.get(0);
            }
        }
        if (detail == null) {
            return null;
        }
        ArchiveSnapshot snapshot = new ArchiveSnapshot();
        snapshot.archiveType = MchFollowupConstants.ARCHIVE_TYPE_MATERNITY;
        snapshot.archiveId = detail.getArchiveid() == null ? archiveId : detail.getArchiveid();
        snapshot.archiveDetailId = detail.getId();
        snapshot.orgid = detail.getOrgid();
        snapshot.campusid = detail.getCampusid();
        snapshot.sourceType = detail.getSourceType();
        snapshot.sourceBizNo = detail.getSourceBizNo();
        snapshot.patid = detail.getPatid();
        snapshot.patname = detail.getPatname();
        snapshot.phone = detail.getPhone();
        snapshot.idcardno = detail.getIdcardno();
        snapshot.plannedFollowTime = detail.getPlannedFollowTime();
        snapshot.followupPeriod = detail.getFollowupPeriod();
        snapshot.followupCycleTimes = detail.getFollowupCycleTimes();
        snapshot.followupStatus = detail.getFollowupStatus();
        return snapshot;
    }
 
    private ArchiveSnapshot loadChildSnapshot(Long archiveId, Long archiveDetailId) {
        PatChildArchiveDetail detail = null;
        if (archiveDetailId != null) {
            detail = childDetailMapper.selectPatChildArchiveDetailById(archiveDetailId);
        }
        if (detail == null && archiveId != null) {
            PatChildArchiveDetail query = new PatChildArchiveDetail();
            query.setArchiveid(archiveId);
            List<PatChildArchiveDetail> list =
                    childDetailMapper.selectPatChildArchiveDetailList(query);
            if (list != null && !list.isEmpty()) {
                detail = list.get(0);
            }
        }
        if (detail == null) {
            return null;
        }
        ArchiveSnapshot snapshot = new ArchiveSnapshot();
        snapshot.archiveType = MchFollowupConstants.ARCHIVE_TYPE_CHILD;
        snapshot.archiveId = detail.getArchiveid() == null ? archiveId : detail.getArchiveid();
        snapshot.archiveDetailId = detail.getId();
        snapshot.orgid = detail.getOrgid();
        snapshot.campusid = detail.getCampusid();
        snapshot.sourceType = detail.getSourceType();
        snapshot.sourceBizNo = detail.getSourceBizNo();
        snapshot.patid = detail.getPatid();
        snapshot.patname = detail.getPatname();
        snapshot.phone = firstNotBlank(detail.getParentPhone(), detail.getPhone());
        snapshot.idcardno = detail.getIdcardno();
        snapshot.plannedFollowTime = detail.getPlannedFollowTime();
        snapshot.followupPeriod = detail.getFollowupPeriod();
        snapshot.followupStatus = detail.getFollowupStatus();
        return snapshot;
    }
 
    /**
     * 历史数据没有状态时按已确认处理,保证已有档案的计划不受影响。
     */
    private boolean isFollowupActive(String followupStatus) {
        return StringUtils.isEmpty(followupStatus)
                || MchFollowupConstants.FOLLOWUP_STATUS_ACTIVE.equals(followupStatus);
    }
 
    private boolean isEnabled() {
        try {
            String value = configService.selectConfigByKey(MchFollowupConstants.CONFIG_ENABLED);
            return value == null || !"false".equalsIgnoreCase(value.trim());
        } catch (Exception e) {
            log.warn("【妇幼随访】读取启用开关失败,按启用处理:{}", e.getMessage());
            return true;
        }
    }
 
    private static boolean sameTime(Date left, Date right) {
        if (left == null || right == null) {
            return left == right;
        }
        return Math.abs(left.getTime() - right.getTime()) < 1000L;
    }
 
    private static String firstNotBlank(String first, String second) {
        return StringUtils.isNotBlank(first) ? first : second;
    }
 
    private static String truncate(String text, int maxLength) {
        if (text == null || text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength);
    }
 
    private static class ArchiveSnapshot {
        private String archiveType;
        private Long archiveId;
        private Long archiveDetailId;
        private String orgid;
        private String campusid;
        private String sourceType;
        private String sourceBizNo;
        private Long patid;
        private String patname;
        private String phone;
        private String idcardno;
        private Date plannedFollowTime;
        private String followupPeriod;
        private String followupCycleTimes;
        private String followupStatus;
    }
}