刘光辉
昨天 bb638871a7fb692d80f1b7a758f991dc0879002c
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
package jnpf.limsService.impl;
 
import jnpf.base.UserInfo;
import jnpf.exception.DataException;
import jnpf.limsEntity.JianyanStatus;
import jnpf.limsEntity.LimsWendingxingFenxiBatchParam;
import jnpf.limsEntity.LimsWendingxingFenxiCompletenessRecordVo;
import jnpf.limsEntity.LimsWendingxingFenxiCompletenessVo;
import jnpf.limsEntity.LimsWendingxingFenxiDataVo;
import jnpf.limsEntity.LimsWendingxingFenxiExpectedPeriodVo;
import jnpf.limsEntity.LimsWendingxingFenxiOptionVo;
import jnpf.limsEntity.LimsWendingxingFenxiOptionsVo;
import jnpf.limsEntity.LimsWendingxingFenxiParam;
import jnpf.limsEntity.LimsWendingxingFenxiRowVo;
import jnpf.limsMapper.LimsWendingxingFenxiMapper;
import jnpf.limsService.LimsWendingxingFenxiService;
import jnpf.limsService.support.LimsWendingxingFenxiSupport;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
@Service
public class LimsWendingxingFenxiServiceImpl implements LimsWendingxingFenxiService {
 
    @Autowired
    private LimsWendingxingFenxiMapper fenxiMapper;
 
    @Override
    public LimsWendingxingFenxiOptionsVo listOptions(LimsWendingxingFenxiParam source) {
        LimsWendingxingFenxiParam param = normalize(source);
        String tenantId = currentTenantId();
        LimsWendingxingFenxiOptionsVo result = new LimsWendingxingFenxiOptionsVo();
        result.setFenleiList(fenxiMapper.selectCategories(tenantId));
        if (!StringUtils.hasText(param.getFenleiBianma())) {
            return result;
        }
        result.setYangpinList(fenxiMapper.selectProducts(tenantId, param.getFenleiBianma()));
        if (!StringUtils.hasText(param.getYangpinId())) {
            return result;
        }
        result.setXiangmuList(fenxiMapper.selectItems(
                tenantId, param.getFenleiBianma(), param.getYangpinId()));
        if (param.getXiangmuIds().isEmpty()) {
            return result;
        }
        result.setJihuaList(fenxiMapper.selectPlans(
                tenantId, param.getYangpinId(), param.getXiangmuIds()));
        result.setPihaoList(fenxiMapper.selectBatches(
                tenantId, param.getYangpinId(), param.getXiangmuIds(), param.getJihuaIds()));
        return result;
    }
 
    @Override
    public LimsWendingxingFenxiDataVo listData(LimsWendingxingFenxiParam source) {
        validateRawFilters(source);
        LimsWendingxingFenxiParam param = normalize(source);
        validateRequired(param);
        String tenantId = currentTenantId();
        validateAuthorizedOptions(tenantId, param);
 
        List<LimsWendingxingFenxiRowVo> rows = fenxiMapper.selectRows(tenantId, param);
        for (LimsWendingxingFenxiRowVo row : rows) {
            normalizeRow(row);
        }
        rows.sort(rowComparator());
 
        LimsWendingxingFenxiDataVo result = new LimsWendingxingFenxiDataVo();
        result.setRows(rows);
        List<LimsWendingxingFenxiCompletenessRecordVo> completenessRecords =
                fenxiMapper.selectCompleteness(tenantId, param);
        result.setCompleteness(buildCompleteness(completenessRecords));
        result.setExpectedPeriods(buildExpectedPeriods(completenessRecords));
        return result;
    }
 
    private void validateRawFilters(LimsWendingxingFenxiParam source) {
        if (source == null) {
            return;
        }
        validateRawIds(source.getXiangmuIds(), "检验项目");
        validateRawIds(source.getJihuaIds(), "稳定性考察编号");
        Set<String> batchKeys = new HashSet<>();
        if (source.getPihaoKeys() == null) {
            return;
        }
        for (LimsWendingxingFenxiBatchParam batch : source.getPihaoKeys()) {
            if (batch == null || !StringUtils.hasText(batch.getJihuaId())
                    || !StringUtils.hasText(batch.getPihao())) {
                throw new DataException("批号筛选项不完整");
            }
            String key = batch.getJihuaId().trim() + "::" + batch.getPihao().trim();
            if (!batchKeys.add(key)) {
                throw new DataException("批号筛选项不能重复");
            }
        }
    }
 
    private void validateRawIds(List<String> values, String label) {
        if (values == null) {
            return;
        }
        Set<String> unique = new HashSet<>();
        for (String value : values) {
            if (!StringUtils.hasText(value)) {
                throw new DataException(label + "筛选项不能为空");
            }
            if (!unique.add(value.trim())) {
                throw new DataException(label + "筛选项不能重复");
            }
        }
    }
 
    private void validateRequired(LimsWendingxingFenxiParam param) {
        if (!StringUtils.hasText(param.getFenleiBianma())) {
            throw new DataException("分类不能为空");
        }
        if (!StringUtils.hasText(param.getYangpinId())) {
            throw new DataException("品名不能为空");
        }
        if (param.getXiangmuIds().isEmpty()) {
            throw new DataException("检验项目不能为空");
        }
    }
 
    private void validateAuthorizedOptions(String tenantId, LimsWendingxingFenxiParam param) {
        requireContains(fenxiMapper.selectCategories(tenantId), param.getFenleiBianma(), "分类");
        requireContains(fenxiMapper.selectProducts(tenantId, param.getFenleiBianma()), param.getYangpinId(), "品名");
        requireContainsAll(fenxiMapper.selectItems(
                tenantId, param.getFenleiBianma(), param.getYangpinId()), param.getXiangmuIds(), "检验项目");
 
        List<LimsWendingxingFenxiOptionVo> planOptions = fenxiMapper.selectPlans(
                tenantId, param.getYangpinId(), param.getXiangmuIds());
        requireContainsAll(planOptions, param.getJihuaIds(), "稳定性考察编号");
 
        List<LimsWendingxingFenxiOptionVo> batchOptions = fenxiMapper.selectBatches(
                tenantId, param.getYangpinId(), param.getXiangmuIds(), param.getJihuaIds());
        Set<String> allowedBatchKeys = optionKeys(batchOptions);
        for (LimsWendingxingFenxiBatchParam batch : param.getPihaoKeys()) {
            if (!allowedBatchKeys.contains(batchKey(batch))) {
                throw new DataException("批号不属于当前筛选范围");
            }
        }
    }
 
    private void requireContains(List<LimsWendingxingFenxiOptionVo> options,
                                 String value, String label) {
        if (!optionKeys(options).contains(value)) {
            throw new DataException(label + "不属于当前租户或筛选范围");
        }
    }
 
    private void requireContainsAll(List<LimsWendingxingFenxiOptionVo> options,
                                    List<String> values, String label) {
        Set<String> allowed = optionKeys(options);
        for (String value : values) {
            if (!allowed.contains(value)) {
                throw new DataException(label + "不属于当前租户或筛选范围");
            }
        }
    }
 
    private Set<String> optionKeys(List<LimsWendingxingFenxiOptionVo> options) {
        Set<String> result = new HashSet<>();
        for (LimsWendingxingFenxiOptionVo option : options) {
            if (StringUtils.hasText(option.getKey())) {
                result.add(option.getKey());
            } else if (StringUtils.hasText(option.getId())) {
                result.add(option.getId());
            }
        }
        return result;
    }
 
    private void normalizeRow(LimsWendingxingFenxiRowVo row) {
        BigDecimal value = LimsWendingxingFenxiSupport.strictDecimal(row.getRawResult());
        BigDecimal lower = LimsWendingxingFenxiSupport.strictDecimal(row.getXiaxian());
        BigDecimal upper = LimsWendingxingFenxiSupport.strictDecimal(row.getShangxian());
        row.setNumericResult(value);
        row.setXiaxianValue(lower);
        row.setShangxianValue(upper);
        try {
            row.setZhouqiOrder(LimsWendingxingFenxiSupport.periodOrder(
                    new BigDecimal(row.getZhouqi()), row.getZhouqiDanwei()));
        } catch (RuntimeException ignored) {
            row.setZhouqiOrder(Double.MAX_VALUE);
        }
        row.setExceptionType(LimsWendingxingFenxiSupport.exceptionType(
                row.getYichangDiaochaLeixing(), row.getJianyanJielun(), value, lower, upper));
        row.setBatchKey(safe(row.getJihuaId()) + "::" + safe(row.getPihao()));
    }
 
    private Comparator<LimsWendingxingFenxiRowVo> rowComparator() {
        Comparator<String> strings = Comparator.nullsLast(String::compareTo);
        Comparator<Date> dates = Comparator.nullsLast(Date::compareTo);
        return Comparator.comparing(LimsWendingxingFenxiRowVo::getXiangmuMingcheng, strings)
                .thenComparing(LimsWendingxingFenxiRowVo::getXiangmuBianma, strings)
                .thenComparing(LimsWendingxingFenxiRowVo::getJihuaBianhao, strings)
                .thenComparing(LimsWendingxingFenxiRowVo::getJihuaId, strings)
                .thenComparing(LimsWendingxingFenxiRowVo::getPihao, strings)
                .thenComparing(LimsWendingxingFenxiRowVo::getZhouqiOrder,
                        Comparator.nullsLast(Double::compareTo))
                .thenComparing(LimsWendingxingFenxiRowVo::getJieguoLuruRiqi, dates)
                .thenComparing(LimsWendingxingFenxiRowVo::getXiangmuId, strings);
    }
 
    private LimsWendingxingFenxiCompletenessVo buildCompleteness(
            List<LimsWendingxingFenxiCompletenessRecordVo> records) {
        Map<String, Integer> states = new LinkedHashMap<>();
        for (LimsWendingxingFenxiCompletenessRecordVo record : records) {
            int state = record.getJianyanZhuangtai() == null ? 0
                    : JianyanStatus.AUDITED.getCode().equals(record.getJianyanZhuangtai()) ? 2 : 1;
            states.merge(record.getExpectedKey(), state, Math::max);
        }
        LimsWendingxingFenxiCompletenessVo result = new LimsWendingxingFenxiCompletenessVo();
        result.setExpectedCount(states.size());
        for (Integer state : states.values()) {
            if (state == 2) {
                result.setAuditedCount(result.getAuditedCount() + 1);
            } else if (state == 1) {
                result.setPendingCount(result.getPendingCount() + 1);
            } else {
                result.setMissingCount(result.getMissingCount() + 1);
            }
        }
        return result;
    }
 
    private List<LimsWendingxingFenxiExpectedPeriodVo> buildExpectedPeriods(
            List<LimsWendingxingFenxiCompletenessRecordVo> records) {
        Map<String, LimsWendingxingFenxiExpectedPeriodVo> periods = new LinkedHashMap<>();
        for (LimsWendingxingFenxiCompletenessRecordVo record : records) {
            String key = safe(record.getXiangmuId()) + "::" + safe(record.getZhouqi())
                    + "::" + safe(record.getZhouqiDanwei());
            if (periods.containsKey(key)) {
                continue;
            }
            LimsWendingxingFenxiExpectedPeriodVo period =
                    new LimsWendingxingFenxiExpectedPeriodVo();
            period.setXiangmuId(record.getXiangmuId());
            period.setZhouqi(record.getZhouqi());
            period.setZhouqiDanwei(record.getZhouqiDanwei());
            try {
                period.setZhouqiOrder(LimsWendingxingFenxiSupport.periodOrder(
                        new BigDecimal(record.getZhouqi()), record.getZhouqiDanwei()));
            } catch (RuntimeException ignored) {
                period.setZhouqiOrder(Double.MAX_VALUE);
            }
            periods.put(key, period);
        }
        List<LimsWendingxingFenxiExpectedPeriodVo> result =
                new ArrayList<>(periods.values());
        result.sort(Comparator.comparing(
                LimsWendingxingFenxiExpectedPeriodVo::getZhouqiOrder,
                Comparator.nullsLast(Double::compareTo)));
        return result;
    }
 
    private LimsWendingxingFenxiParam normalize(LimsWendingxingFenxiParam source) {
        LimsWendingxingFenxiParam result = source == null
                ? new LimsWendingxingFenxiParam() : source;
        result.setFenleiBianma(trimToNull(result.getFenleiBianma()));
        result.setYangpinId(trimToNull(result.getYangpinId()));
        result.setXiangmuIds(LimsWendingxingFenxiSupport.normalizeIds(result.getXiangmuIds()));
        result.setJihuaIds(LimsWendingxingFenxiSupport.normalizeIds(result.getJihuaIds()));
 
        Map<String, LimsWendingxingFenxiBatchParam> batches = new LinkedHashMap<>();
        if (result.getPihaoKeys() != null) {
            for (LimsWendingxingFenxiBatchParam batch : result.getPihaoKeys()) {
                if (batch == null) {
                    continue;
                }
                batch.setJihuaId(trimToNull(batch.getJihuaId()));
                batch.setPihao(trimToNull(batch.getPihao()));
                if (batch.getJihuaId() != null && batch.getPihao() != null) {
                    batches.putIfAbsent(batchKey(batch), batch);
                }
            }
        }
        result.setPihaoKeys(new ArrayList<>(batches.values()));
        return result;
    }
 
    private String batchKey(LimsWendingxingFenxiBatchParam batch) {
        return safe(batch.getJihuaId()) + "::" + safe(batch.getPihao());
    }
 
    private String safe(String value) {
        return value == null ? "" : value;
    }
 
    private String trimToNull(String value) {
        return StringUtils.hasText(value) ? value.trim() : null;
    }
 
    private String currentTenantId() {
        UserInfo user = UserProvider.getUser();
        return user == null || !StringUtils.hasText(user.getTenantId())
                ? "0" : user.getTenantId();
    }
}