陈昶聿
9 天以前 8a73ac17d717c32aa8fd97f4c682094d7b1c0654
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
package com.smartor.service.mch;
 
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.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;
        }
 
        List<MchFollowupPlan> actives = planMapper.selectActiveByArchive(
                snapshot.archiveType, snapshot.archiveId, snapshot.archiveDetailId);
        if (actives == null) {
            actives = Collections.emptyList();
        }
        for (MchFollowupPlan active : actives) {
            if (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;
    }
 
    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();
        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();
        return snapshot;
    }
 
    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;
    }
}