liusheng
4 天以前 3d453a41ccd7c69a40bd9bfa31f8c5b159513b6b
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
package com.smartor.service.impl;
 
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserDept;
import com.ruoyi.common.core.domain.entity.SysUserRole;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.smartor.domain.*;
import com.smartor.mapper.*;
import com.smartor.service.IPatArchiveService;
import com.smartor.service.IPatMedInhospService;
import com.smartor.service.IServiceSLTDHealthcareRecordService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
 
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
@Slf4j
@Service
public class ServiceSLTDHealthcareRecordServiceImpl implements IServiceSLTDHealthcareRecordService {
 
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String APP_KEY = "ak-zUMiOWhqXiJQWPB1pCbz0pjr";
 
    @Autowired
    private IPatArchiveService patArchiveService;
 
    @Autowired
    private IPatMedInhospService patMedInhospService;
 
    @Autowired
    private PatMedOuthospMapper patMedOuthospMapper;
 
    @Autowired
    private SysUser2Mapper sysUser2Mapper;
 
    @Autowired
    private SysDept2Mapper sysDeptMapper;
 
    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;
 
    @Autowired
    private SysUserRole2Mapper sysUserRoleMapper;
 
    @Value("${sltd_pub_path}")
    private String sltdPubPath;
 
    @Value("${userPwd}")
    private String userPwd;
 
    @Override
    public List<ServiceSLTDInhospResDTO> queryHealthcareRecordList(ServiceSLTDInhospReqVO reqVO) {
        try {
            log.info("【queryHealthcareRecordList】开始调用省立同德健康记录查询接口,请求参数:{}", reqVO);
            Map<String, Object> requestParams = buildRequestParams(reqVO);
            Map<String, String> headers = buildRequestHeaders();
 
            String result = HttpUtils.sendPostByHeader(sltdPubPath + "osj/hbos-thirdparty-integration/standard/common/healthcareRecord/dtcQueryHealthcareRecordList", new Gson().toJson(requestParams), headers);
            log.info("【queryHealthcareRecordList】接口响应结果:{}", result);
 
            String cry = determineCry(reqVO);
            return parseResponseData(result, reqVO.getHealthcareRecordTypeList(), cry, reqVO.getCampusId());
        } catch (Exception e) {
            log.error("【queryHealthcareRecordList】调用省立同德健康记录查询接口异常,请求参数:{}", reqVO, e);
            throw new RuntimeException("调用省立同德健康记录查询接口失败", e);
        }
    }
 
 
    /**
     * 采集科室病区信息
     *
     * @param serviceSLTDDeptReqVO
     * @return 参考
     * {
     * "orgId": 20001001,
     * "campusIds": 30001002,
     * "unitIds": null,
     * "relationType": null,
     * "searchText": null,
     * "status": 1
     * }
     */
    @Override
    public Boolean queryDeptWardAreaInfoList(ServiceSLTDDeptReqVO serviceSLTDDeptReqVO) {
        log.info("【queryDeptWardAreaInfoList】开始调用省立同德科室病区查询接口,请求参数:{}", serviceSLTDDeptReqVO);
        try {
            Map<String, Object> params = new HashMap<>();
            if (serviceSLTDDeptReqVO.getOrgId() != null) {
                params.put("orgId", Long.parseLong(serviceSLTDDeptReqVO.getOrgId()));
            }
            if (serviceSLTDDeptReqVO.getCampusIds() != null) {
                params.put("campusIds", serviceSLTDDeptReqVO.getCampusIds());
            }
            params.put("subjectCode", serviceSLTDDeptReqVO.getSubjectCode());
            params.put("orgSubjectCode", serviceSLTDDeptReqVO.getOrgSubjectCode());
 
            params.put("deptDimensions", serviceSLTDDeptReqVO.getDeptDimensions());
 
            params.put("serviceScopes", serviceSLTDDeptReqVO.getServiceScopes());
            params.put("inpatientArea", serviceSLTDDeptReqVO.getInpatientArea());
            params.put("status", serviceSLTDDeptReqVO.getStatus());
 
 
            Map<String, String> headers = buildRequestHeaders();
            String result = HttpUtils.sendPostByHeader(sltdPubPath + "/osj/hbos-thirdparty-integration/standard/common/dept/queryDeptList", new Gson().toJson(params), headers);
            log.info("【queryDeptWardAreaInfoList】接口响应结果:{}", result);
            List<Map<String, Object>> dataList = getDataList(result);
            log.info("-----------dataList接口响应结果:{}", dataList.size());
            for (Map<String, Object> dataItem : dataList) {
                SysDept sysDept = new SysDept();
                sysDept.setOrgid("" + serviceSLTDDeptReqVO.getCampusIds().get(0));
                sysDept.setHisDeptId("" + getLongValue(dataItem, "deptId"));
                sysDept.setHisParentId(getStringValue(dataItem, "parentDeptId"));
                //通过his的父科室ID去找到科室ID,填充parentId
                if (StringUtils.isNotEmpty(getStringValue(dataItem, "parentDeptId"))) {
                    SysDept sd = new SysDept();
                    sd.setHisDeptId(getStringValue(dataItem, "parentDeptId"));
                    sd.setOrgid(getStringValue(dataItem, "orgId"));
                    List<SysDept> sysDepts = sysDeptMapper.selectDeptList(sd);
                    if (CollectionUtils.isNotEmpty(sysDepts)) {
                        SysDept sysDept1 = sysDepts.get(0);
                        sysDept.setParentId(sysDept1.getDeptId());
                        sysDept.setParentName(sysDept1.getDeptName());
                    }
                }
                sysDept.setDeptName(getStringValue(dataItem, "deptName"));
                Integer inpatientArea = getIntegerValue(dataItem, "inpatientArea");
                if (inpatientArea != null && inpatientArea == 0) sysDept.setDeptType("1");
                else if (inpatientArea != null && inpatientArea == 1) sysDept.setDeptType("2");
                sysDept.setLeader("");
                Integer status = getIntegerValue(dataItem, "status");
                if (status != null & status == 0) sysDept.setStatus("1");
                if (status != null & status == 1) sysDept.setStatus("0");
                sysDept.setType("");
                sysDept.setDeptCode("" + getLongValue(dataItem, "deptId"));
                sysDept.setCreateBy(null);
                sysDept.setCreateTime(new Date());
                sysDept.setUpdateTime(new Date());
                sysDept.setUpdateBy(null);
 
                SysDept sysDept1 = sysDeptMapper.selectDeptByCode(sysDept.getDeptCode(), sysDept.getOrgid());
                if (Objects.isNull(sysDept1)) {
                    int i = sysDeptMapper.insertDept(sysDept);
                    log.info("ServiceExternalServiceImpl---addDeptInfo是否新增成功:{}", i);
                } else {
                    sysDept.setDeptId(sysDept1.getDeptId());
                    int i = sysDeptMapper.updateDept(sysDept);
                    log.info("ServiceExternalServiceImpl---addDeptInfo是否修改成功04:{}", i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
 
 
    /**
     * 采集医院用户信息
     *
     * @param reqVO
     * @return
     */
    @Override
    public Boolean queryHospUserInfoList(ServiceSLTDInhospReqVO reqVO) {
        Map<String, Object> requestParams = buildRequestParams(reqVO);
        Map<String, String> headers = buildRequestHeaders();
        String result = HttpUtils.sendPostByHeader(sltdPubPath + "/osj/hbos-thirdparty-integration/standard/common/staff/queryStaffList", new Gson().toJson(requestParams), headers);
        log.info("【queryHealthcareRecordList】接口响应结果:{}", result);
        List<Map<String, Object>> dataList = getDataList(result);
        for (Map<String, Object> dataItem : dataList) {
            SysUser sysUser = new SysUser();
            if (StringUtils.isEmpty(getStringValue(dataItem, "accountNo"))) {
                continue;
            }
            sysUser.setUserName(getStringValue(dataItem, "accountNo"));
            sysUser.setNickName(getStringValue(dataItem, "name"));
            List diagnosisObjList = (List<?>) dataItem.get("qualifications");
            if (CollectionUtils.isNotEmpty(diagnosisObjList)) {
                for (Object diagnosis : diagnosisObjList) {
                    if (diagnosis instanceof Map) {
                        Map<String, Object> diagnosisMap = (Map<String, Object>) diagnosis;
                        String professionalTitleName = getStringValue(diagnosisMap, "professionalTitleName");
                        if (professionalTitleName.contains("医师")) {
                            sysUser.setUserType("医生");
                            sysUser.setSearchscope("1");
                        }
                        if (professionalTitleName.contains("护")) {
                            sysUser.setUserType("护士");
                            sysUser.setSearchscope("2");
                        }
                        sysUser.setTitle(getStringValue(diagnosisMap, "professionalTitleName"));
                    }
                }
            }
 
            sysUser.setPhonenumber(getStringValue(dataItem, "telephone"));
            sysUser.setUserCode(getStringValue(dataItem, "jobNumber"));
            //设置性别
            String genderName = getStringValue(dataItem, "genderName");
            if ("男".equals(genderName)) sysUser.setSex("0");
            else if ("女".equals(genderName)) sysUser.setSex("1");
            else sysUser.setSex("2");
 
            sysUser.setCreateTime(new Date());
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateBy("admin");
            sysUser.setCreateBy("admin");
            sysUser.setCreateBy("admin");
            sysUser.setOrgid(reqVO.getCampusId().toString());
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            sysUser.setPassword(passwordEncoder.encode(userPwd));
 
            sysUser2Mapper.insertUser(sysUser);
 
            // 处理用户与部门的关系
            List personnelDepts = (List<?>) dataItem.get("personnelDepts");
            if (CollectionUtils.isEmpty(personnelDepts)) {
                continue;
            }
 
            List<List<String>> deptInfoList = new ArrayList<>();
            List<List<String>> hospInfoList = new ArrayList<>();
            for (Object personnelDept : personnelDepts) {
                if (personnelDept instanceof Map) {
                    Map<String, Object> personnelDeptMap = (Map<String, Object>) personnelDept;
//                    Long hisDeptId = (Long) personnelDeptMap.get("deptId");
                    String hisDeptId = getStringValue(personnelDeptMap, "deptId");
                    //在这里,hisDeptId就是deptCode
                    SysDept sysDept = sysDeptMapper.selectDeptByCode(hisDeptId, reqVO.getCampusId().toString());
                    if (Objects.isNull(sysDept)) continue;
                    SysUserDept sysUserDept = new SysUserDept();
                    sysUserDept.setUserId(sysUser.getUserId());
                    sysUserDept.setDeptType(sysDept.getDeptType());
                    sysUserDept.setDeptId(sysDept.getDeptId());
                    sysUserDept.setDeptCode(sysDept.getDeptCode());
                    sysUserDept.setDeptName(sysDept.getDeptName());
                    sysUserDept.setOrgid(sysDept.getOrgid());
                    sysUserDept.setCreateTime(new Date());
                    sysUserDept.setDelFlag(0L);
                    sysUserDeptMapper.insertSysUserDept(sysUserDept);
                    if (StringUtils.isNotEmpty(sysDept.getDeptType()) && sysDept.getDeptType().equals("1")) {
                        hospInfoList.add(Arrays.asList(sysDept.getDeptCode()));
                    } else if (StringUtils.isNotEmpty(sysDept.getDeptType()) && sysDept.getDeptType().equals("2")) {
                        deptInfoList.add(Arrays.asList(sysDept.getDeptCode()));
                    }
                }
            }
            //将部门我病区放到指定字段中
            Gson gson = new Gson();
            sysUser.setHospInfo(gson.toJson(hospInfoList));
            sysUser.setDeptInfo(gson.toJson(deptInfoList));
            sysUser2Mapper.updateUser(sysUser);
 
            //设置一个默认角色(医生角色)
            List<SysUserRole> userRoleList = new ArrayList();
            SysUserRole sur = new SysUserRole();
            sur.setUserId(sysUser.getUserId());
            sur.setRoleId(3L);
            sur.setOrgid(sysUser.getOrgid());
            userRoleList.add(sur);
            sysUserRoleMapper.batchUserRole(userRoleList);
 
        }
 
        return true;
    }
 
    private String determineCry(ServiceSLTDInhospReqVO reqVO) {
        if (reqVO.getHealthcareRecordTypeList().contains("FH0108.02")) {
            if (reqVO.getStartHeadTime() != null && reqVO.getStartTailTime() != null) {
                return "0";
            } else if (StringUtils.isNotEmpty(reqVO.getPreOutHospitalHeadDate()) && StringUtils.isNotEmpty(reqVO.getPreOutHospitalTailDate())) {
                return "1";
            }
        }
        return null;
    }
 
    private Map<String, Object> buildRequestParams(ServiceSLTDInhospReqVO reqVO) {
        Map<String, Object> params = new HashMap<>();
        if (reqVO.getOrgId() != null) {
            params.put("orgId", Long.parseLong(reqVO.getOrgId()));
        }
        if (reqVO.getCampusId() != null) {
            params.put("campusId", reqVO.getCampusId());
        }
        if (reqVO.getStartHeadTime() != null) {
            params.put("startHeadTime", reqVO.getStartHeadTime());
        }
        if (reqVO.getStartTailTime() != null) {
            params.put("startTailTime", reqVO.getStartTailTime());
        }
        if (reqVO.getEncounterTimeStart() != null) {
            params.put("encounterTimeStart", reqVO.getEncounterTimeStart());
        }
        if (reqVO.getEncounterTimeEnd() != null) {
            params.put("encounterTimeEnd", reqVO.getEncounterTimeEnd());
        }
        if (reqVO.getPreOutHospitalHeadDate() != null) {
            params.put("preOutHospitalHeadDate", reqVO.getPreOutHospitalHeadDate());
        }
        if (reqVO.getPreOutHospitalTailDate() != null) {
            params.put("preOutHospitalTailDate", reqVO.getPreOutHospitalTailDate());
        }
        if (reqVO.getHealthcareRecordTypeList() != null && !reqVO.getHealthcareRecordTypeList().isEmpty()) {
            params.put("healthcareRecordTypeList", reqVO.getHealthcareRecordTypeList());
        }
        params.put("subjectCode", reqVO.getPatientName());
        params.put("healthcareRecordNo", reqVO.getHealthcareRecordNo());
        params.put("orgSubjectCode", reqVO.getIdCardNo());
        if (reqVO.getDeptIdList() != null && !reqVO.getDeptIdList().isEmpty()) {
            params.put("deptDimensions", reqVO.getDeptIdList());
        }
        params.put("serviceScopes", null);
        params.put("inpatientArea", null);
        params.put("status", reqVO.getStatusList() != null && !reqVO.getStatusList().isEmpty() ? reqVO.getStatusList().get(0) : null);
        return params;
    }
 
    private Map<String, String> buildRequestHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("app-key", APP_KEY);
        return headers;
    }
 
    private List<ServiceSLTDInhospResDTO> parseResponseData(String result, List<String> types, String cry, Long orgid) {
        try {
 
            List<Map<String, Object>> dataList = getDataList(result);
            List<ServiceSLTDInhospResDTO> resultList = new ArrayList<>();
            for (Map<String, Object> dataItem : dataList) {
                resultList.add(convertToDTO(dataItem));
            }
            log.info("【parseResponseData】成功解析{}条健康记录数据", resultList.size());
 
            processResultList(resultList, types, cry, orgid);
            return resultList;
        } catch (Exception e) {
            log.error("【parseResponseData】解析响应数据异常,响应内容:{}", result, e);
            throw new RuntimeException("解析响应数据失败", e);
        }
    }
 
    public List<Map<String, Object>> getDataList(String result) {
        Gson gson = new Gson();
        Type mapType = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> responseMap = gson.fromJson(result, mapType);
        Number codeNum = (Number) responseMap.get("code");
        String code = BigDecimal.valueOf(codeNum.longValue()).toPlainString();
        if (StringUtils.isEmpty(code) || !code.equals("200")) {
            log.error("【parseResponseData】接口返回失败,响应码:{},响应内容:{}", code, result);
            throw new RuntimeException("接口调用失败,响应码:" + code);
        }
 
        Object dataObj = responseMap.get("data");
        if (dataObj == null) {
            log.info("【parseResponseData】接口返回数据为空");
            return new ArrayList<>();
        }
 
        String dataJson = gson.toJson(dataObj);
        Type listType = new TypeToken<List<Map<String, Object>>>() {
        }.getType();
        List<Map<String, Object>> dataList = gson.fromJson(dataJson, listType);
        return dataList;
    }
 
    private void processResultList(List<ServiceSLTDInhospResDTO> resultList, List<String> types, String cry, Long orgid) {
        for (String type : types)
            switch (type) {
                case "FH0108.01":
                    log.info("【parseResponseData】解析门诊数据");
                    outHospitalDate(resultList, orgid);
                    break;
                case "FH0108.02":
                    log.info("【parseResponseData】解析住院数据");
                    inHospitalDate(resultList, cry, orgid);
                    break;
                case "FH0108.03":
                    log.info("【parseResponseData】解析急诊数据");
                    outHospitalDate(resultList, orgid);
                    break;
                default:
                    log.warn("【parseResponseData】未知的数据类型:{}", type);
                    break;
            }
    }
 
    private Boolean outHospitalDate(List<ServiceSLTDInhospResDTO> resultList, Long orgid) {
        for (ServiceSLTDInhospResDTO dto : resultList) {
            if (Objects.isNull(dto)) continue;
            PatArchive patArchive = processPatientArchive(dto, orgid);
            PatMedOuthosp patMedOuthosp = buildPatMedOuthosp(dto, patArchive, orgid);
            patMedOuthospMapper.insertPatMedOuthosp(patMedOuthosp);
        }
        return true;
    }
 
    private PatMedOuthosp buildPatMedOuthosp(ServiceSLTDInhospResDTO dto, PatArchive patArchive, Long orgid) {
        PatMedOuthosp patMedOuthosp = new PatMedOuthosp();
        patMedOuthosp.setOuthospno(dto.getHealthcareRecordNo());
        patMedOuthosp.setSerialnum(dto.getHealthcareRecordNo());
        patMedOuthosp.setPatid(patArchive.getId());
        patMedOuthosp.setPatname(patArchive.getName());
        patMedOuthosp.setPatno(patArchive.getPatientno());
        patMedOuthosp.setDeptcode("" + dto.getDeptId());
        patMedOuthosp.setDeptname(dto.getDeptName());
        patMedOuthosp.setDiagname(dto.getDiagnosisName());
        patMedOuthosp.setIcd10code(dto.getDiagnosisCode());
        patMedOuthosp.setDrcode("" + dto.getDoctorId());
        patMedOuthosp.setDrname(dto.getDoctorName());
        patMedOuthosp.setAdmitdate(parseDate(dto.getLastEncounterTime()));
        patMedOuthosp.setSchemestatus(1L);
        patMedOuthosp.setMainsuit(dto.getDiagnosisName());
        patMedOuthosp.setHpi(null);
        patMedOuthosp.setCreateTime(new Date());
        patMedOuthosp.setOrgid("" + orgid);
        return patMedOuthosp;
    }
 
    private Date parseDate(String dateStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        try {
            return new SimpleDateFormat(DATE_FORMAT).parse(dateStr);
        } catch (ParseException e) {
            log.warn("【parseDate】解析日期失败:{}", dateStr, e);
            return null;
        }
    }
 
    private Boolean inHospitalDate(List<ServiceSLTDInhospResDTO> resultList, String cry, Long orgid) {
        for (ServiceSLTDInhospResDTO dto : resultList) {
            if (Objects.isNull(dto)) continue;
            PatArchive patArchive = processPatientArchive(dto, orgid);
            processPatientInhospInfo(dto, patArchive, cry, orgid);
        }
        return true;
    }
 
    private void processPatientInhospInfo(ServiceSLTDInhospResDTO dto, PatArchive patArchive, String cry, Long orgid) {
        PatMedInhosp patMedInhosp = buildPatientInhospInfo(dto, patArchive, cry, orgid);
        PatMedInhosp queryInhosp = new PatMedInhosp();
        queryInhosp.setPatno(patArchive.getPatientno());
        queryInhosp.setSerialnum(patMedInhosp.getSerialnum());
        queryInhosp.setOrgid("" + orgid);
        log.info("----------------这里的入参为:{}", queryInhosp);
        List<PatMedInhosp> existingInhosps = patMedInhospService.selectPatMedInhospList(queryInhosp);
 
        log.info("----------------这里的返参为:{}", existingInhosps);
        if (CollectionUtils.isNotEmpty(existingInhosps)) {
            patMedInhosp.setInhospid(existingInhosps.get(0).getInhospid());
            patMedInhospService.updatePatMedInhosp(patMedInhosp);
            log.debug("【processPatientInhospInfo】更新住院信息,患者编号:{},流水号:{}", patArchive.getPatientno(), patMedInhosp.getSerialnum());
        } else {
            patMedInhospService.insertPatMedInhosp(patMedInhosp);
            log.debug("【processPatientInhospInfo】新增住院信息,患者编号:{},流水号:{}", patArchive.getPatientno(), patMedInhosp.getSerialnum());
        }
    }
 
    private PatMedInhosp buildPatientInhospInfo(ServiceSLTDInhospResDTO dto, PatArchive patArchive, String cry, Long orgid) {
        log.info("----------------buildPatientInhospInfo这里进来了吗?{}", cry);
        PatMedInhosp patMedInhosp = new PatMedInhosp();
        patMedInhosp.setPatid(patArchive.getId());
        patMedInhosp.setPatno(patArchive.getPatientno());
        patMedInhosp.setPatname(patArchive.getName());
        patMedInhosp.setNurseId(dto.getChiefNurseId() == null ? "" : dto.getChiefNurseId().toString());
        patMedInhosp.setNurseName(dto.getChiefNurseName());
        patMedInhosp.setSerialnum(dto.getHealthcareRecordNo());
        patMedInhosp.setFuflag("1");
        if ("0".equals(cry)) patMedInhosp.setInhospstate("0");
        if ("1".equals(cry)) patMedInhosp.setInhospstate("1");
        patMedInhosp.setHospitalcode(dto.getOrgId());
        patMedInhosp.setBedNo(dto.getBedNumber());
        patMedInhosp.setStarttime(parseDate(dto.getStartTime()));
        patMedInhosp.setEndtime(parseDate(dto.getPreOutHospitalDate()));
 
        if ("1".equals(cry)) {
            setDischargeInfo(patMedInhosp, dto);
        } else {
            setAdmissionInfo(patMedInhosp, dto);
        }
 
        patMedInhosp.setDrname(dto.getDoctorName());
        patMedInhosp.setDrcode("" + dto.getDoctorId());
        patMedInhosp.setSchemestatus("0".equals(cry) ? 1L : 2L);
        patMedInhosp.setDelFlag("0");
        patMedInhosp.setOrgid("" + orgid);
        return patMedInhosp;
    }
 
    private void setDischargeInfo(PatMedInhosp patMedInhosp, ServiceSLTDInhospResDTO dto) {
        patMedInhosp.setLeaveldeptcode("" + dto.getDeptId());
        patMedInhosp.setLeaveldeptname(dto.getDeptName());
        patMedInhosp.setLeavediagname(dto.getMainDischargeDiagnosis() == null ? null : dto.getMainDischargeDiagnosis().getDiagnosisDictName());
        patMedInhosp.setLeaveicd10code(dto.getMainDischargeDiagnosis() == null ? null : dto.getMainDischargeDiagnosis().getDiagnosisDictCode());
        patMedInhosp.setOutWayId(null);
        patMedInhosp.setOutWayName(null);
        patMedInhosp.setLeavehospitaldistrictid("" + dto.getAreaId());
        patMedInhosp.setLeavehospitaldistrictcode("" + dto.getAreaId());
        patMedInhosp.setLeavehospitaldistrictname(dto.getAreaName());
        patMedInhosp.setLeaveldeptid("" + dto.getDeptId());
    }
 
    private void setAdmissionInfo(PatMedInhosp patMedInhosp, ServiceSLTDInhospResDTO dto) {
        patMedInhosp.setDeptcode("" + dto.getDeptId());
        patMedInhosp.setDeptname(dto.getDeptName());
        patMedInhosp.setDiagname(dto.getAdmissionDiagnosisName());
        patMedInhosp.setIcd10code(dto.getAdmissionDiagnosisCode());
        patMedInhosp.setHospitaldistrictid("" + dto.getAreaId());
        patMedInhosp.setHospitaldistrictcode("" + dto.getAreaId());
        patMedInhosp.setHospitaldistrictname(dto.getAreaName());
    }
 
    private PatArchive processPatientArchive(ServiceSLTDInhospResDTO dto, Long orgid) {
        PatArchive queryArchive = new PatArchive();
        queryArchive.setIdcardno(StringUtils.isEmpty(dto.getIdCardNo()) ? "" + dto.getMedicalCardId() : dto.getIdCardNo().trim());
        List<PatArchive> existingArchives = patArchiveService.selectPatArchiveList(queryArchive);
 
        PatArchive patArchive = buildPatientArchive(dto, orgid);
 
        if (CollectionUtils.isEmpty(existingArchives)) {
            patArchiveService.insertPatArchive(patArchive);
            log.debug("【processPatientArchive】新增患者档案,患者编号:{}", patArchive.getPatientno());
        } else {
            patArchive.setId(existingArchives.get(0).getId());
            patArchiveService.updateArchive(patArchive);
            log.debug("【processPatientArchive】更新患者档案,患者编号:{}", patArchive.getPatientno());
        }
 
        return patArchive;
    }
 
    private PatArchive buildPatientArchive(ServiceSLTDInhospResDTO dto, Long orgid) {
        PatArchive patArchive = new PatArchive();
        patArchive.setPatientno("" + dto.getPatientId());
        patArchive.setIdcardno(StringUtils.isEmpty(dto.getIdCardNo()) ? "" + dto.getMedicalCardId() : dto.getIdCardNo().trim());
        patArchive.setName(dto.getPatientName());
        patArchive.setSourcefrom(2);
        patArchive.setPattype("2");
        patArchive.setSex("男".equals(dto.getGender()) ? 1L : 2L);
        patArchive.setNation(dto.getNation());
        patArchive.setNativePlace(dto.getNativePlace());
        patArchive.setPlaceOfResidence(dto.getAddress());
        patArchive.setBirthdate(parseDate(dto.getBirthday()));
        patArchive.setTelcode(dto.getPhone());
        if (CollectionUtils.isNotEmpty(dto.getResidentContactInfos())) {
            patArchive.setRelativetelcode(dto.getResidentContactInfos().get(0).getTelecom());
        }
        patArchive.setDelFlag("0");
        patArchive.setCreateTime(new Date());
        patArchive.setUpdateTime(new Date());
        patArchive.setOrgid("" + orgid);
        return patArchive;
    }
 
    private ServiceSLTDInhospResDTO convertToDTO(Map<String, Object> dataItem) {
        ServiceSLTDInhospResDTO dto = new ServiceSLTDInhospResDTO();
        dto.setOrgId(getStringValue(dataItem, "orgId"));
        dto.setHealthcareRecordId(getLongValue(dataItem, "healthcareRecordId"));
        dto.setHealthcareRecordNo(getStringValue(dataItem, "healthcareRecordNo"));
        dto.setPatientId(getLongValue(dataItem, "patientId"));
        dto.setPatientName(getStringValue(dataItem, "patientName"));
        dto.setPinyin(getStringValue(dataItem, "pinyin"));
        dto.setNation(getStringValue(dataItem, "nation"));
        dto.setIdCardNo(getStringValue(dataItem, "idCardNo"));
        dto.setHealthcareRecordTimes(getIntegerValue(dataItem, "healthcareRecordTimes"));
        dto.setHospitalizationNumber(getIntegerValue(dataItem, "hospitalizationNumber"));
        dto.setMedicalCardId(getLongValue(dataItem, "medicalCardId"));
        dto.setMedicalCardType(getStringValue(dataItem, "medicalCardType"));
        dto.setMedicalCardTypeName(getStringValue(dataItem, "medicalCardTypeName"));
        dto.setMedicalCardNo(getStringValue(dataItem, "medicalCardNo"));
        dto.setMedicalRecordNo(getStringValue(dataItem, "medicalRecordNo"));
        dto.setGender(getStringValue(dataItem, "gender"));
        dto.setGenderCode(getStringValue(dataItem, "genderCode"));
        dto.setAge(getStringValue(dataItem, "age"));
        dto.setBirthday(getStringValue(dataItem, "birthday"));
        dto.setPhone(getStringValue(dataItem, "phone"));
        dto.setEducation(getStringValue(dataItem, "education"));
        dto.setEducationCode(getStringValue(dataItem, "educationCode"));
        dto.setNeonatal(getBooleanValue(dataItem, "neonatal"));
        dto.setMarriage(getStringValue(dataItem, "marriage"));
        dto.setMarriageCode(getStringValue(dataItem, "marriageCode"));
        dto.setOccupationType(getStringValue(dataItem, "occupationType"));
        dto.setOccupationTypeCode(getStringValue(dataItem, "occupationTypeCode"));
        dto.setNativePlace(getStringValue(dataItem, "nativePlace"));
        dto.setAreaId(getLongValue(dataItem, "areaId"));
        dto.setAreaName(getStringValue(dataItem, "areaName"));
        dto.setRoomId(getLongValue(dataItem, "roomId"));
        dto.setRoomNumber(getStringValue(dataItem, "roomNumber"));
        dto.setBedId(getLongValue(dataItem, "bedId"));
        dto.setBedNumber(getStringValue(dataItem, "bedNumber"));
        dto.setEncounterTime(getStringValue(dataItem, "encounterTime"));
        dto.setStartTime(getStringValue(dataItem, "startTime"));
        dto.setPreOutHospitalDate(getStringValue(dataItem, "preOutHospitalDate"));
        dto.setLastEncounterTime(getStringValue(dataItem, "lastEncounterTime"));
        dto.setDiagnosisCode(getStringValue(dataItem, "diagnosisCode"));
        dto.setDiagnosisName(getStringValue(dataItem, "diagnosisName"));
        dto.setHealthcareRecordStatus(getStringValue(dataItem, "healthcareRecordStatus"));
        dto.setHealthcareType(getStringValue(dataItem, "healthcareType"));
        dto.setDeptId(getLongValue(dataItem, "deptId"));
        dto.setDeptName(getStringValue(dataItem, "deptName"));
        dto.setDoctorId(getLongValue(dataItem, "doctorId"));
        dto.setDoctorName(getStringValue(dataItem, "doctorName"));
        dto.setHealthcarePeriodId(getLongValue(dataItem, "healthcarePeriodId"));
        dto.setChiefNurseId(getLongValue(dataItem, "chiefNurseId"));
        dto.setChiefNurseName(getStringValue(dataItem, "chiefNurseName"));
        dto.setCostCategoryName(getStringValue(dataItem, "costCategoryName"));
        dto.setCostCategoryCode(getStringValue(dataItem, "costCategoryCode"));
        dto.setCostNatureName(getStringValue(dataItem, "costNatureName"));
        dto.setCostNatureCode(getStringValue(dataItem, "costNatureCode"));
        dto.setFurtherConsultationStatus(getIntegerValue(dataItem, "furtherConsultationStatus"));
 
        Object contactsObj = dataItem.get("residentContactInfos");
        if (contactsObj instanceof List) {
            dto.setResidentContactInfos(parseContacts((List<?>) contactsObj));
        }
 
        Object diagnosisObj = dataItem.get("diagnosisList");
        if (diagnosisObj instanceof List) {
            dto.setDiagnosisList(parseDiagnosis((List<?>) diagnosisObj));
        }
 
        return dto;
    }
 
    private List<ServiceSLTDContactsResDTO> parseContacts(List<?> contactsList) {
        List<ServiceSLTDContactsResDTO> contacts = new ArrayList<>();
        for (Object contactObj : contactsList) {
            if (contactObj instanceof Map) {
                Map<String, Object> contactMap = (Map<String, Object>) contactObj;
                ServiceSLTDContactsResDTO contact = new ServiceSLTDContactsResDTO();
                contact.setName(getStringValue(contactMap, "name"));
                contact.setRelationshipCode(getStringValue(contactMap, "relationshipCode"));
                contact.setRelationship(getStringValue(contactMap, "relationship"));
                contact.setTelecom(getStringValue(contactMap, "telecom"));
                contact.setCurrentAddress(getStringValue(contactMap, "currentAddress"));
                contacts.add(contact);
            }
        }
        return contacts;
    }
 
    private List<ServiceSLTDDiagnosisResDTO> parseDiagnosis(List<?> diagnosisList) {
        List<ServiceSLTDDiagnosisResDTO> diagnosis = new ArrayList<>();
        for (Object diagnosisObj : diagnosisList) {
            if (diagnosisObj instanceof Map) {
                Map<String, Object> diagnosisMap = (Map<String, Object>) diagnosisObj;
                ServiceSLTDDiagnosisResDTO diag = new ServiceSLTDDiagnosisResDTO();
                diag.setDiagnosisDictCode(getStringValue(diagnosisMap, "diagnosisDictCode"));
                diag.setDiagnosisDictName(getStringValue(diagnosisMap, "diagnosisDictName"));
                diag.setDiagnosisCategory(getStringValue(diagnosisMap, "diagnosisCategory"));
                diag.setRecordType(getIntegerValue(diagnosisMap, "recordType"));
                diag.setIsMainDiagnosis(getIntegerValue(diagnosisMap, "isMainDiagnosis"));
                diagnosis.add(diag);
            }
        }
        return diagnosis;
    }
 
    private String getStringValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
 
        // 只处理数字类型,避免科学计数法
        return value instanceof Number ? new BigDecimal(value.toString()).toPlainString() : value.toString();
    }
 
    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private Integer getIntegerValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private Boolean getBooleanValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Boolean) {
            return (Boolean) value;
        }
        return Boolean.parseBoolean(value.toString());
    }
}