From cc479e6a056785103996cc7ea67dbd5faa3e800e Mon Sep 17 00:00:00 2001
From: liusheng <337615773@qq.com>
Date: 星期一, 19 十月 2026 18:07:22 +0800
Subject: [PATCH] 数据采集模块

---
 smartor/src/main/java/com/smartor/service/impl/ServiceSLTDHealthcareRecordServiceImpl.java |  372 +++++++++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 335 insertions(+), 37 deletions(-)

diff --git a/smartor/src/main/java/com/smartor/service/impl/ServiceSLTDHealthcareRecordServiceImpl.java b/smartor/src/main/java/com/smartor/service/impl/ServiceSLTDHealthcareRecordServiceImpl.java
index 1ad6fc5..11638b2 100644
--- a/smartor/src/main/java/com/smartor/service/impl/ServiceSLTDHealthcareRecordServiceImpl.java
+++ b/smartor/src/main/java/com/smartor/service/impl/ServiceSLTDHealthcareRecordServiceImpl.java
@@ -8,13 +8,20 @@
 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.DateUtils;
 import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.core.service.dto.InhospPositionRecord;
 import com.smartor.common.enums.EmergencyLevelEnum;
 import com.smartor.common.enums.ImportFlagEnum;
 import com.ruoyi.common.utils.http.HttpUtils;
 import com.smartor.common.DistinctByProperty;
 import com.smartor.domain.*;
+import com.ruoyi.outpatientvisit.domain.PatMedOuthospError;
+import com.ruoyi.outpatientvisit.domain.PatMedOuthosp;
+import com.ruoyi.inhospvisit.api.InhospVisitFacade;
+import com.ruoyi.inhospvisit.domain.PatMedInhosp;
 import com.smartor.mapper.*;
+import com.ruoyi.outpatientvisit.mapper.PatMedOuthospErrorMapper;
 import com.smartor.service.IPatArchiveService;
 import com.smartor.service.IPatMedInhospService;
 import com.smartor.service.IPatMedOuthospService;
@@ -36,12 +43,33 @@
 import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
 import java.util.stream.Collectors;
+import com.ruoyi.common.core.domain.entity.PatArchive;
+import com.ruoyi.task.domain.ServiceSubtask;
+import com.ruoyi.task.mapper.ServiceSubtaskMapper;
+import com.ruoyi.task.service.impl.ServiceSubtaskServiceImpl;
 
 @Slf4j
 @Service
 public class ServiceSLTDHealthcareRecordServiceImpl implements IServiceSLTDHealthcareRecordService {
 
     private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
+
+    /**
+     * 鍦ㄩ櫌鎮h�呭綋鍓嶄綅缃煡璇㈠湴鍧�锛堢綉鍏虫牴璺緞 {@code sltd_pub_path} + 鍥哄畾鍚庣紑锛夈��
+     * <p>
+     * 涓�"鍏ラ櫌閲囬泦"鏄�<b>鍚屼竴涓帴鍙�</b>锛坽@code queryHealthcareRecordList} 鐢ㄧ殑涔熸槸瀹冿級锛�
+     * 鍖哄埆鍙槸鏈柟娉曟寜 {@code healthcareRecordNo} 鍗曟煡銆佸彧鍙栦綅缃瓧娈点�佷笉钀藉簱銆�
+     */
+    private static final String INHOSP_POSITION_PATH =
+            "/osj/hbos-thirdparty-integration/standard/common/healthcareRecord/dtcQueryHealthcareRecordList";
+
+    /**
+     * 褰撳墠浣嶇疆鏌ヨ鐨勮繛鎺�/璇昏秴鏃讹細涓�杞鎸夋偅鑰呰皟鐢ㄥ嚑鍗冩锛�
+     * 涓嶈兘璁╀竴娆℃棤鍝嶅簲鎶婇噰闆嗙嚎绋嬫棤闄愭湡鎸備綇锛坽@code HttpUtils} 鑰佹柟娉曟病鏈夎秴鏃讹級
+     */
+    private static final int INHOSP_POSITION_CONNECT_TIMEOUT_MS = 5000;
+
+    private static final int INHOSP_POSITION_READ_TIMEOUT_MS = 15000;
 
     @Autowired
     private IPatArchiveService patArchiveService;
@@ -85,6 +113,15 @@
 
     @Value("${spring.profiles.active}")
     private String active;
+    @Autowired
+    private ServiceSubtaskServiceImpl serviceSubtaskServiceImpl;
+    @Autowired
+    private ServiceSubtaskMapper serviceSubtaskMapper;
+    @Autowired
+    private InhospVisitFacade inhospVisitFacade;
+
+    @Autowired
+    private PatMedOuthospErrorMapper patMedOuthospErrorMapper;
 
     @Override
     public List<ServiceSLTDInhospResDTO> queryHealthcareRecordList(ServiceSLTDInhospReqVO reqVO) {
@@ -407,6 +444,47 @@
         return true;
     }
 
+    @Override
+    public List<InhospPositionRecord> queryInhospPosition(ServiceSLTDInhospReqVO reqVO) {
+        // 涓�"鍏ラ櫌閲囬泦"鍏辩敤鍚屼竴濂楀叆鍙傛瀯閫狅細orgId + campusIds + statusList + healthcareRecordNo
+        Map<String, Object> requestParams = buildRequestParams(reqVO);
+        Map<String, String> headers = buildRequestHeaders();
+        String url = sltdPubPath + INHOSP_POSITION_PATH;
+        String result = HttpUtils.sendPostByHeader(url, new Gson().toJson(requestParams), headers,
+                INHOSP_POSITION_CONNECT_TIMEOUT_MS, INHOSP_POSITION_READ_TIMEOUT_MS);
+        if (StringUtils.isEmpty(result)) {
+            // sendPostByHeader 鎶婂紓甯稿悶鎺夊悗杩斿洖绌轰覆锛氳繖閲岀粷涓嶈兘褰撴垚"璇ユ偅鑰呭凡涓嶅湪闄�"锛�
+            // 鍚﹀垯鎺ュ彛鏁翠綋涓嶅彲鐢ㄦ椂浼氳璁版垚"鍑犲崈涓偅鑰呴兘鍑洪櫌浜�"锛屼笌鐪熺浉鍙嶃��
+            throw new RuntimeException("鏌ヨ鍦ㄩ櫌鎮h�呭綋鍓嶄綅缃帴鍙f棤鍝嶅簲锛宧ealthcareRecordNo=" + reqVO.getHealthcareRecordNo());
+        }
+        // getDataList 鍦ㄨ繑鍥炵爜闈� 200 鏃舵姏 RuntimeException锛沝ata 涓� []锛堣鎮h�呭凡涓嶅湪鍏ラ櫌鐘舵�侊級鏃惰繑鍥炵┖鍒楄〃
+        List<Map<String, Object>> dataList = getDataList(result, 1);
+        List<InhospPositionRecord> records = new ArrayList<>(dataList.size());
+        for (Map<String, Object> dataItem : dataList) {
+            records.add(convertToInhospPosition(dataItem));
+        }
+        return records;
+    }
+
+    /**
+     * 鍋ュ悍璁板綍 JSON 鈫� 濂戠害 DTO 鐨勯�愬瓧娈垫惉杩愶紙鍙彇"褰撳墠浣嶇疆"瑕佺敤鐨勫瓧娈碉級銆�
+     * <p>
+     * 涓�寰嬭蛋 {@code getStringValue} / {@code getLongValue}锛氭帴鍙e绌哄�煎彲鑳借繑鍥� {@code null}銆�
+     * {@code ""} 鐢氳嚦缂哄瓧娈碉紝鐩存帴璁� Gson 鍙嶅簭鍒楀寲鍒� Long 瀛楁浼氬湪绌轰覆涓婃姏 NumberFormatException銆�
+     */
+    private InhospPositionRecord convertToInhospPosition(Map<String, Object> dataItem) {
+        InhospPositionRecord record = new InhospPositionRecord();
+        record.setHealthcareRecordNo(getStringValue(dataItem, "healthcareRecordNo"));
+        record.setPatientName(getStringValue(dataItem, "patientName"));
+        record.setDeptId(getLongValue(dataItem, "deptId"));
+        record.setDeptName(getStringValue(dataItem, "deptName"));
+        record.setAreaId(getLongValue(dataItem, "areaId"));
+        record.setAreaName(getStringValue(dataItem, "areaName"));
+        record.setBedNumber(getStringValue(dataItem, "bedNumber"));
+        record.setHealthcareRecordStatus(getStringValue(dataItem, "healthcareRecordStatus"));
+        return record;
+    }
+
     private String determineCry(ServiceSLTDInhospReqVO reqVO) {
         if (CollectionUtils.isEmpty(reqVO.getStatusList()) && CollectionUtils.isEmpty(reqVO.getHealthcareRecordTypeList()))
             return null;
@@ -496,7 +574,12 @@
             log.info("銆恜arseResponseData銆戞垚鍔熻В鏋恉ataList:{}鏉″仴搴疯褰曟暟鎹�", dataList.size());
             List<ServiceSLTDInhospResDTO> resultList = new ArrayList<>();
             for (Map<String, Object> dataItem : dataList) {
-                resultList.add(convertToDTO(dataItem));
+                try {
+                    resultList.add(convertToDTO(dataItem));
+                } catch (Exception e) {
+                    // 鍗曟潯鏁版嵁杞崲澶辫触涓嶅啀璁╂暣椤靛け璐ワ細鍐欓敊璇〃浜ょ粰浜哄伐澶勭悊锛屽叾浣欒褰曠収甯稿叆搴�
+                    saveOuthospError(dataItem, "CONVERT", e.getMessage(), new Gson().toJson(dataItem), e);
+                }
             }
             log.info("銆恜arseResponseData銆戞垚鍔熻В鏋恟esultList:{}鏉″仴搴疯褰曟暟鎹�", resultList.size());
 
@@ -606,34 +689,184 @@
     }
 
     private Boolean outHospitalDate(List<ServiceSLTDInhospResDTO> resultList) {
-        List<PatMedOuthosp> batchList = new ArrayList<>();
-
+        // 闂ㄦ�ヨ瘖鍦� HIS 渚у彧鑳芥寜澶╂煡锛岄噰闆嗕换鍔℃瘡鍗婂皬鏃堕兘浼氭妸褰撳ぉ涓婁竾涓瘖鐤楄褰曢噸鏂版媺涓�閬嶏紝
+        // 鍏朵腑缁濆ぇ澶氭暟涓婁竴杞凡缁忓叆搴撱�傝繖閲屽厛鏁撮〉鎵归噺鏌ラ噸锛屾妸宸插叆搴撶殑鐩存帴璺宠繃锛�
+        // 鍙鏂板璁板綍鍋�"妗f澶勭悊 + 鍏ュ簱"锛屽惁鍒欐瘡鏉¢噸澶嶆暟鎹兘瑕佽蛋涓�閬�
+        // Redis鍔犻攣 + 妗f鏌ラ噸 + 妗f鏇存柊 + countBySerialnum + insert锛屼竴涓囨潯灏辨槸鍑犱竾娆� SQL锛屽崐灏忔椂璺戜笉瀹屻��
+        Set<String> pageSerialnums = new HashSet<>();
+        List<ServiceSLTDInhospResDTO> uniqueList = new ArrayList<>();
+        List<ServiceSLTDInhospResDTO> noSerialnumList = new ArrayList<>();
+        Map<String, List<String>> serialnumsByDate = new LinkedHashMap<>();
         for (ServiceSLTDInhospResDTO dto : resultList) {
             if (Objects.isNull(dto)) {
                 continue;
             }
-            PatArchive patArchive = processPatientArchive(dto);
-            PatMedOuthosp patMedOuthosp = buildPatMedOuthosp(dto, patArchive);
-            batchList.add(patMedOuthosp);
+            String serialnum = dto.getHealthcareRecordNo();
+            if (StringUtils.isEmpty(serialnum)) {
+                // 娌℃湁璇婄枟璁板綍鍙峰氨娌℃硶鏌ラ噸锛屼繚鎸佸師鏈夎涓虹収甯稿鐞嗭紙鍏ュ簱鐜妭杩樹細鍐嶅厹涓�娆★級
+                log.warn("銆恛utHospitalDate銆戣瘖鐤楄褰曞彿涓虹┖锛屾棤娉曟煡閲嶏紝鎸夋柊澧炲鐞嗭細patientName={}", dto.getPatientName());
+                noSerialnumList.add(dto);
+                continue;
+            }
+            if (!pageSerialnums.add(serialnum)) {
+                // 鍚屼竴椤靛唴閲嶅鐨勮褰曪紝鍙鐞嗕竴鏉�
+                continue;
+            }
+            uniqueList.add(dto);
+            // 鎸夊氨璇婃棩鏈熷垎缁勶紙璺ㄩ浂鐐规椂鏈�澶氫袱涓棩鏈燂級锛屼繚璇佹煡閲嶇殑鍒嗚〃鍜屽叆搴撴椂鍒嗚〃璺敱涓�鑷�
+            String admitDateStr = formatAdmitDate(dto.getLastEncounterTime());
+            serialnumsByDate.computeIfAbsent(admitDateStr == null ? "" : admitDateStr, k -> new ArrayList<>()).add(serialnum);
         }
+
+        // 涓�娆� SQL 鏌ュ嚭杩欎竴椤甸噷宸茬粡鍏ュ簱鐨� serialnum锛堝彇浠i�愭潯 countBySerialnum锛�
+        Set<String> existingSerialnums = new HashSet<>();
+        for (Map.Entry<String, List<String>> entry : serialnumsByDate.entrySet()) {
+            try {
+                existingSerialnums.addAll(patMedOuthospService.selectExistingSerialnums(entry.getKey(), entry.getValue()));
+            } catch (Exception e) {
+                // 鎵归噺鏌ラ噸澶辫触涓嶅奖鍝嶆纭�э細涓嬮潰鍏ュ簱鏃舵瘡鏉¤繕浼氬啀鏌ヤ竴娆¢噸锛屽彧鏄參涓�浜�
+                log.error("銆恛utHospitalDate銆戞壒閲忔煡閲嶅け璐ワ紝閫�鍖栦负閫愭潯鏌ラ噸锛屽氨璇婃棩鏈燂細{}", entry.getKey(), e);
+            }
+        }
+
+        List<PatMedOuthosp> batchList = new ArrayList<>();
+        int existSkipCount = 0;
+        for (ServiceSLTDInhospResDTO dto : uniqueList) {
+            if (existingSerialnums.contains(dto.getHealthcareRecordNo())) {
+                existSkipCount++;
+                continue;
+            }
+            PatMedOuthosp patMedOuthosp = buildNewOuthosp(dto);
+            if (patMedOuthosp != null) {
+                batchList.add(patMedOuthosp);
+            }
+        }
+        for (ServiceSLTDInhospResDTO dto : noSerialnumList) {
+            PatMedOuthosp patMedOuthosp = buildNewOuthosp(dto);
+            if (patMedOuthosp != null) {
+                batchList.add(patMedOuthosp);
+            }
+        }
+        log.info("銆恛utHospitalDate銆戞湰椤祘}鏉★紝鍘婚噸鍚巤}鏉★紝宸插叆搴撹烦杩噞}鏉★紝寰呭叆搴搟}鏉�",
+                resultList.size(), uniqueList.size(), existSkipCount, batchList.size());
 
         // 鎵归噺鎻掑叆锛岃嚜鍔ㄥ拷鐣ラ噸澶�
         if (CollectionUtils.isNotEmpty(batchList)) {
-            try {
-                //杩欓噷鐢ㄨ嚜鍔ㄥ拷鐣ラ噸澶嶄細鏈夐棶棰橈紝濡傛灉琛ㄩ噸鏂板缓锛宻erialnum绱㈠紩浼氫涪澶便�傚氨鏃犳硶鍘婚噸锛屾墍浠ヨ繕鏄渶瑕佸唴瀛橀噷鍘婚噸
-                batchList = DistinctByProperty.distinctByProperty(batchList, PatMedOuthosp::getSerialnum);
-                Integer insertCount = 0;
-                for (PatMedOuthosp patMedOuthosp : batchList) {
-                    insertCount += patMedOuthospService.insertPatMedOuthosp(patMedOuthosp);
+            //杩欓噷鐢ㄨ嚜鍔ㄥ拷鐣ラ噸澶嶄細鏈夐棶棰橈紝濡傛灉琛ㄩ噸鏂板缓锛宻erialnum绱㈠紩浼氫涪澶便�傚氨鏃犳硶鍘婚噸锛屾墍浠ヨ繕鏄渶瑕佸唴瀛橀噷鍘婚噸
+            batchList = DistinctByProperty.distinctByProperty(batchList, PatMedOuthosp::getSerialnum);
+            int insertCount = 0;
+            int skipCount = 0;
+            List<String> failSerialnums = new ArrayList<>();
+            for (PatMedOuthosp patMedOuthosp : batchList) {
+                try {
+                    int inserted = patMedOuthospService.insertPatMedOuthosp(patMedOuthosp);
+                    if (inserted > 0) {
+                        insertCount += inserted;
+                    } else {
+                        // 杩斿洖0琛ㄧず宸插瓨鍦紙閲嶅閲囬泦锛夋垨灏辫瘖鏃堕棿涓虹┖锛屽睘浜庢甯歌烦杩囷紝涓嶇畻澶辫触
+                        skipCount++;
+                    }
+                } catch (Exception e) {
+                    // 鍗曟潯鍏ュ簱澶辫触涓嶅啀涓柇閲囬泦锛氳惤閿欒琛ㄤ氦缁欎汉宸ュ鐞嗭紝閲囬泦鏂偣鐓у父鎺ㄨ繘
+                    failSerialnums.add(patMedOuthosp.getSerialnum());
+                    saveOuthospError(null, patMedOuthosp, "INSERT", e.getMessage(), new Gson().toJson(patMedOuthosp), e);
                 }
+            }
+            log.info("鎵归噺鎻掑叆闂ㄦ�ヨ瘖璁板綍锛屾�绘暟锛歿}, 瀹為檯鎻掑叆锛歿}, 璺宠繃锛堝凡瀛樺湪/鏃犲氨璇婃椂闂达級锛歿}, 钀介敊璇〃锛歿}",
+                    batchList.size(), insertCount, skipCount, failSerialnums.size());
 
-                log.info("鎵归噺鎻掑叆闂ㄦ�ヨ瘖璁板綍锛屾�绘暟锛歿}, 瀹為檯鎻掑叆锛歿}", batchList.size(), insertCount);
-
-            } catch (Exception e) {
-                log.error("鎵归噺鎻掑叆闂ㄦ�ヨ瘖璁板綍澶辫触", e);
+            if (!failSerialnums.isEmpty()) {
+                // 澶辫触鏄庣粏宸查�愭潯鍐欒繘 pat_med_outhosp_error锛岃繖閲屽彧鎻愮ず锛屼笉鍐嶆姏寮傚父闃绘柇閲囬泦
+                log.error("闂ㄦ�ヨ瘖璁板綍鍏ュ簱澶辫触 {} 鏉★紝宸插啓鍏� pat_med_outhosp_error 绛変汉宸ュ鐞嗭紝serialnum锛歿}",
+                        failSerialnums.size(), failSerialnums);
             }
         }
         return true;
+    }
+
+    /**
+     * 澶勭悊鍗曟潯鏂板璁板綍鐨勬偅鑰呮。妗堝苟鏋勫缓闂ㄦ�ヨ瘖璁板綍锛�
+     * 澶辫触鏃跺啓閿欒琛ㄤ氦缁欎汉宸ュ鐞嗗苟杩斿洖 null锛屼笉褰卞搷鍚屼竴椤甸噷鍏朵粬璁板綍
+     */
+    private PatMedOuthosp buildNewOuthosp(ServiceSLTDInhospResDTO dto) {
+        try {
+            PatArchive patArchive = processPatientArchive(dto);
+            return buildPatMedOuthosp(dto, patArchive);
+        } catch (Exception e) {
+            saveOuthospError(dto, null, "ARCHIVE", e.getMessage(), new Gson().toJson(dto), e);
+            return null;
+        }
+    }
+
+    /** 閲囬泦澶辫触鐨勫師濮嬭褰曟潵鑷帴鍙h繑鍥炵殑 Map锛堟暟鎹浆鎹㈠け璐ユ椂杩樻病鏈� DTO锛� */
+    private void saveOuthospError(Map<String, Object> dataItem, String errorType, String errorMsg,
+                                  String rawData, Throwable cause) {
+        PatMedOuthospError error = new PatMedOuthospError();
+        error.setSerialnum(getStringValue(dataItem, "healthcareRecordNo"));
+        error.setOuthospno(getStringValue(dataItem, "healthcareRecordNo"));
+        error.setPatname(getStringValue(dataItem, "patientName"));
+        error.setPatno(getStringValue(dataItem, "medicalRecordNo"));
+        error.setCampusid(getStringValue(dataItem, "campusId"));
+        error.setOrgid(getStringValue(dataItem, "orgId"));
+        doSaveOuthospError(error, errorType, errorMsg, rawData, cause);
+    }
+
+    /** 閲囬泦澶辫触鐨勫師濮嬭褰曟潵鑷� DTO / 寰呭叆搴撶殑 PatMedOuthosp */
+    private void saveOuthospError(ServiceSLTDInhospResDTO dto, PatMedOuthosp patMedOuthosp, String errorType,
+                                  String errorMsg, String rawData, Throwable cause) {
+        PatMedOuthospError error = new PatMedOuthospError();
+        if (dto != null) {
+            error.setSerialnum(dto.getHealthcareRecordNo());
+            error.setOuthospno(dto.getHealthcareRecordNo());
+            error.setPatname(dto.getPatientName());
+            error.setPatno(dto.getMedicalRecordNo());
+            error.setCampusid(dto.getCampusId());
+            error.setOrgid(dto.getOrgId());
+            error.setAdmitdate(parseDate(dto.getLastEncounterTime()));
+        }
+        if (patMedOuthosp != null) {
+            if (StringUtils.isEmpty(error.getSerialnum())) {
+                error.setSerialnum(patMedOuthosp.getSerialnum());
+            }
+            error.setOuthospno(patMedOuthosp.getOuthospno());
+            error.setPatname(patMedOuthosp.getPatname());
+            error.setPatno(patMedOuthosp.getPatno());
+            error.setCampusid(patMedOuthosp.getCampusid());
+            error.setOrgid(patMedOuthosp.getOrgid());
+            error.setAdmitdate(patMedOuthosp.getAdmitdate());
+        }
+        doSaveOuthospError(error, errorType, errorMsg, rawData, cause);
+    }
+
+    /**
+     * 鍐欓棬鎬ヨ瘖閲囬泦澶辫触璁板綍琛紝浜ょ粰浜哄伐澶勭悊銆�
+     * 杩欓噷鍏滀綇涓�鍒囧紓甯革細杩為敊璇〃閮藉啓涓嶈繘鍘绘椂鍙墦鏃ュ織锛堝甫鍘熷鏁版嵁锛夛紝缁濅笉鍥犱负鍐欓敊璇〃澶辫触鑰屼腑鏂噰闆�
+     */
+    private void doSaveOuthospError(PatMedOuthospError error, String errorType, String errorMsg,
+                                    String rawData, Throwable cause) {
+        error.setErrorType(errorType);
+        error.setErrorMsg(truncate(errorMsg == null || errorMsg.isEmpty() ? String.valueOf(cause) : errorMsg, 1000));
+        error.setRawData(rawData);
+        error.setFailCount(1);
+        error.setHandleStatus("0");
+        error.setGatherDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
+        error.setCreateTime(DateUtils.getNowDate());
+        try {
+            patMedOuthospErrorMapper.insertPatMedOuthospError(error);
+            log.error("銆愰棬鎬ヨ瘖閲囬泦銆憑} 澶辫触锛屽凡鍐欏叆 pat_med_outhosp_error 绛変汉宸ュ鐞嗭紝serialnum={}锛屾偅鑰�={}锛屽師鍥�={}",
+                    errorType, error.getSerialnum(), error.getPatname(), error.getErrorMsg(), cause);
+        } catch (Exception ex) {
+            log.error("銆愰棬鎬ヨ瘖閲囬泦銆憑} 澶辫触锛屼笖鍐欏叆閿欒琛ㄤ篃澶辫触锛宻erialnum={}锛屽師濮嬫暟鎹細{}",
+                    errorType, error.getSerialnum(), rawData, ex);
+        }
+    }
+
+    /** 鎴柇瓒呴暱鏂囨湰锛岄伩鍏嶈秴鍑洪敊璇〃瀛楁闀垮害瀵艰嚧钀借〃澶辫触 */
+    private String truncate(String text, int maxLength) {
+        if (text == null) {
+            return null;
+        }
+        return text.length() <= maxLength ? text : text.substring(0, maxLength);
     }
 
     private PatMedOuthosp buildPatMedOuthosp(ServiceSLTDInhospResDTO dto, PatArchive patArchive) {
@@ -674,11 +907,35 @@
         }
     }
 
+    /**
+     * 鍙栧氨璇婃棩鏈熺殑 yyyy-MM-dd 閮ㄥ垎锛屼笌 buildPatMedOuthosp 閲岀殑 admitdate 淇濇寔瀹屽叏涓�鑷寸殑瑙f瀽瑙勫垯锛�
+     * 淇濊瘉鎵归噺鏌ラ噸鐢ㄧ殑鍒嗚〃鍜屽叆搴撴椂璺敱鍒扮殑鍒嗚〃鏄悓涓�寮�
+     */
+    private String formatAdmitDate(String lastEncounterTime) {
+        Date admitDate = parseDate(lastEncounterTime);
+        if (admitDate == null) {
+            return null;
+        }
+        return new SimpleDateFormat("yyyy-MM-dd").format(admitDate);
+    }
+
     private Boolean inHospitalDate(List<ServiceSLTDInhospResDTO> resultList, String cry) {
+        int failCount = 0;
         for (ServiceSLTDInhospResDTO dto : resultList) {
             if (Objects.isNull(dto)) continue;
-            PatArchive patArchive = processPatientArchive(dto);
-            processPatientInhospInfo(dto, patArchive, cry);
+            try {
+                PatArchive patArchive = processPatientArchive(dto);
+                processPatientInhospInfo(dto, patArchive, cry);
+            } catch (Exception e) {
+                failCount++;
+                log.error("銆恑nHospitalDate銆戝崟鏉¤褰曞鐞嗗け璐ワ紝宸茶烦杩囩户缁噰闆嗐�俿tate={}, serialnum={}, patname={}, patno={}, orgid={}, campusId={}",
+                        cry, dto.getHealthcareRecordNo(), dto.getPatientName(), dto.getMedicalRecordNo(),
+                        dto.getOrgId(), dto.getCampusId(), e);
+            }
+        }
+        if (failCount > 0) {
+            log.warn("銆恑nHospitalDate銆戞湰椤靛叡{}鏉★紝澶辫触{}鏉″凡璺宠繃锛屽叾浣檣}鏉″鐞嗗畬鎴愶紝state={}",
+                    resultList.size(), failCount, resultList.size() - failCount, cry);
         }
         return true;
     }
@@ -690,7 +947,7 @@
         queryInhosp.setSerialnum(StringUtils.trim(patMedInhosp.getSerialnum()));
         queryInhosp.setOrgid(StringUtils.trim(dto.getOrgId()));
         queryInhosp.setInhospstate(cry);
-        log.info("----------------杩欓噷鐨勫叆鍙備负锛歿},{}", queryInhosp.getPatno(), queryInhosp.getSerialnum());
+//        log.info("----------------杩欓噷鐨勫叆鍙備负锛歿},{}", queryInhosp.getPatno(), queryInhosp.getSerialnum());
         List<PatMedInhosp> existingInhosps = patMedInhospService.selectPatMedInhosp(queryInhosp);
 
         if (cry.equals("0")) {
@@ -709,6 +966,44 @@
                     queryInhosp.setInhospstate("1");
                     patMedInhospList = patMedInhospService.selectPatMedInhosp(queryInhosp);
                     if (CollectionUtils.isNotEmpty(patMedInhospList)) {
+                        //濡傛灉涓嶄负绌猴紝鍒欏皢鍏ラ櫌鏃堕棿杩涜鏇存柊
+                        PatMedInhosp pmOut = patMedInhospList.get(0);
+                        //鏈鍏ラ櫌鏁版嵁锛堣繖閲� existingInhosps 蹇呬负绌猴紝鍙� existingInhosps.get(0) 浼氫笅鏍囪秺鐣岋級
+                        PatMedInhosp pmIn = patMedInhosp;
+                        pmOut.setStarttime(pmIn.getStarttime());
+                        pmOut.setUpdateTime(new Date());
+                        patMedInhospService.updatePatMedInhosp(pmOut);
+                        //鐪佺珛鍚屽痉闇�瑕佸皢寮�濮嬫棩鏈熶笌鍏ラ櫌鏃ユ湡鐩哥瓑鐨勪换鍔★紝鏀规垚涓嶆墽琛�
+                        try {
+                            if ("sltd".equals(active) && DateUtils.isSameDay(pmOut.getStarttime(), pmIn.getEndtime())) {
+                                ServiceSubtask serviceSubtask = new ServiceSubtask();
+                                serviceSubtask.setInhospid(pmOut.getInhospid());
+                                serviceSubtask.setSendstate(4L);
+                                serviceSubtaskMapper.updateServiceSubtaskByCondition(serviceSubtask);
+                            }
+                            //閫氳繃鍏ラ櫌鏃堕棿锛屽拰鎮h�呯殑缂栧彿鍘绘煡涓�涓嬪嚭闄㈡椂闂达紝鏄惁瀛樺湪锛屽鏋滃瓨鍦紝鍒欒鎮h�呮槸鍐嶅叆闄㈢殑锛岄渶瑕佹敼鎴愪笉鎵ц
+                            //鍑洪櫌鏃堕棿鍙瘮杈冨埌澶╋紝涓嶆瘮杈冩椂鍒嗙
+                            if (pmIn.getStarttime() != null) {
+                                Date dayStart = DateUtils.truncate(pmIn.getStarttime(), Calendar.DAY_OF_MONTH);
+                                Date dayEnd = DateUtils.addDays(dayStart, 1);
+                                List<PatMedInhosp> outInhosps = inhospVisitFacade.selectOutInhospByPatnoAndOutDate(
+                                        StringUtils.trim(pmIn.getPatno()), dayStart, dayEnd);
+                                if (CollectionUtils.isNotEmpty(outInhosps)) {
+                                    //瀛樺湪鍑洪櫌璁板綍锛岃鏄庤鎮h�呮槸鍐嶅叆闄紝鎶婁笂涓�娆″嚭闄骇鐢熺殑瀛愪换鍔℃敼鎴愪笉鎵ц
+                                    ServiceSubtask outSubtask = new ServiceSubtask();
+                                    outSubtask.setInhospid(outInhosps.get(0).getInhospid());
+                                    outSubtask.setSendstate(4L);
+                                    outSubtask.setRemark("鎮h�呭啀鍏ラ櫌");
+                                    outSubtask.setUpdateTime(new Date());
+                                    serviceSubtaskMapper.updateServiceSubtaskByCondition(outSubtask);
+                                    log.info("鎮h�呭啀鍏ラ櫌锛屽皢涓婃鍑洪櫌璁板綍鐨勫瓙浠诲姟鏀逛负涓嶆墽琛岋細patno={}, 鍑洪櫌inhospid={}, 鍑洪櫌鏃堕棿={}, 鏈鍏ラ櫌鏃堕棿={}",
+                                            pmIn.getPatno(), outInhosps.get(0).getInhospid(), outInhosps.get(0).getEndtime(), pmIn.getStarttime());
+                                }
+                            }
+
+                        } catch (Exception e) {
+                            log.error("灏嗗嚭闄㈡椂闂寸瓑浜庡叆闄㈡椂闂寸殑inhospid鐨勪换鍔℃洿鏂板け璐ヤ簡, inhospid={}", pmOut.getInhospid(), e);
+                        }
                         return;
                     }
                 }
@@ -733,7 +1028,7 @@
             } else {
                 // 涓嶅瓨鍦ㄥ嚭闄㈣褰曪紝鍏堟煡棰勫叆闄紙state=3锛夛紝鍐嶆煡鍏ラ櫌锛坰tate=0锛�
                 queryInhosp.setInhospstate("3");
-                log.info("-----鏌ヨ棰勫叆闄㈣褰曪紝鍏ュ弬涓猴細{}", queryInhosp);
+//                log.info("-----鏌ヨ棰勫叆闄㈣褰曪紝鍏ュ弬涓猴細{}", queryInhosp);
                 List<PatMedInhosp> patMedInhospList = patMedInhospService.selectPatMedInhosp(queryInhosp);
                 log.info("----棰勫叆闄㈡煡璇㈢粨鏋滐細{}", CollectionUtils.isEmpty(patMedInhospList) ? "绌�" : patMedInhospList.get(0).getSerialnum());
                 if (CollectionUtils.isNotEmpty(patMedInhospList)) {
@@ -786,13 +1081,14 @@
                     if (CollectionUtils.isEmpty(patMedInhospList3)) {
                         try {
                             //鑾峰彇涓�涓嬪叆闄㈢敵璇峰崟
-                            Map<String, String> headers = buildRequestHeaders();
-                            Map<String, Object> requestParams = new HashMap<>();
-                            requestParams.put("orgId", "20001001");
-                            requestParams.put("20001001", patArchive.getPatidHis());
-                            String result = HttpUtils.sendPostByHeader(sltdPubPath + "/hospitalizedApply/query", new Gson().toJson(requestParams), headers);
-
-
+                            //鏍规嵁 encounterSourceId 鑾峰彇 importanceFlagCode   emergencyLevelCode
+                            if (active.equals("sltd")) {
+                                Map<String, String> applyInfo = hospitalizedApply(dto.getEncounterSourceId(), dto.getOrgId());
+                                if (ObjectUtils.isNotEmpty(applyInfo)) {
+                                    patMedInhosp.setImportanceFlagCode(applyInfo.get("importanceFlagCode"));
+                                    patMedInhosp.setEmergencyLevelCode(applyInfo.get("emergencyLevelCode"));
+                                }
+                            }
                             patMedInhospService.insertPatMedInhosp(patMedInhosp);
                             log.debug("鎴愬姛鎻掑叆棰勫叆闄㈣褰曪細serialnum={}", patMedInhosp.getSerialnum());
                         } catch (Exception e) {
@@ -842,7 +1138,7 @@
         if ("1".equals(cry)) {
             patMedInhosp.setInhospstate("1");
             ServiceSLTDDiagnosisResDTO mainDischargeDiagnosis = dto.getMainDischargeDiagnosis();
-            log.info("-----------mainDischargeDiagnosis鐨勫�兼湁浜嗗悧?{}", mainDischargeDiagnosis);
+//            log.info("-----------mainDischargeDiagnosis鐨勫�兼湁浜嗗悧?{}", mainDischargeDiagnosis);
             if (!Objects.isNull(mainDischargeDiagnosis)) {
                 if (mainDischargeDiagnosis.getIsMainDiagnosis() == 1) {
                     patMedInhosp.setLeavediagname(StringUtils.defaultString(mainDischargeDiagnosis.getDiagnosisDictName(), ""));
@@ -871,11 +1167,13 @@
         } else {
             setAdmissionInfo(patMedInhosp, dto);
             patMedInhosp.setEncounterSourceId(dto.getEncounterSourceId() == null ? "" : dto.getEncounterSourceId());
-            if (StringUtils.isNotEmpty(dto.getEncounterSourceId())) {
+            if (StringUtils.isNotEmpty(dto.getEncounterSourceId()) && active.equals("sltd")) {
                 //鏍规嵁 encounterSourceId 鑾峰彇 importanceFlagCode   emergencyLevelCode
                 Map<String, String> applyInfo = hospitalizedApply(dto.getEncounterSourceId(), dto.getOrgId());
-                patMedInhosp.setImportanceFlagCode(applyInfo.get("importanceFlagCode"));
-                patMedInhosp.setEmergencyLevelCode(applyInfo.get("emergencyLevelCode"));
+                if (!Objects.isNull(applyInfo)) {
+                    patMedInhosp.setImportanceFlagCode(applyInfo.get("importanceFlagCode"));
+                    patMedInhosp.setEmergencyLevelCode(applyInfo.get("emergencyLevelCode"));
+                }
             }
         }
 
@@ -897,13 +1195,13 @@
             }
         }
 
-        if (active.equals("nhfy") || active.equals("sltd")) {
+        //鐩墠鍙湁鐪佺珛鍚屽痉
+        if (active.equals("sltd")) {
             Map<String, String> drugInfoMap = queryMedicalOrders(dto);
             if (drugInfoMap != null && !drugInfoMap.isEmpty()) {
                 patMedInhosp.setMedicalName(drugInfoMap.get("drugItemNames"));
                 patMedInhosp.setMedicalCode(drugInfoMap.get("drugItemIds"));
                 patMedInhosp.setMedicalCompany(drugInfoMap.get("drugManufacturerNames"));
-
                 log.info("鑾峰彇鑽搧淇℃伅鎴愬姛锛氬悕绉�={}, 缂栫爜={}, 鍘傚={}", drugInfoMap.get("drugItemNames"), drugInfoMap.get("drugItemIds"), drugInfoMap.get("drugManufacturerNames"));
             }
         }
@@ -958,7 +1256,7 @@
                 String code = BigDecimal.valueOf(((Number) codeObj).longValue()).toPlainString();
                 if (!"200".equals(code)) {
                     log.error("銆恞ueryMedicalOrders銆戞帴鍙h繑鍥炲け璐ワ紝code={}, message={}", code, responseMap.get("message"));
-                    return result;
+                    return null;
                 }
             }
 
@@ -969,7 +1267,7 @@
 
                 // 閬嶅巻鍖诲槺鍒楄〃锛屾彁鍙栬嵂鍝佷俊鎭�
                 Set<String> processedItemIds = new HashSet<>(); // 鐢ㄤ簬鍘婚噸锛堝彧鏍规嵁 itemId 鍘婚噸锛�
-                
+
                 for (Object item : dataList) {
                     if (item instanceof Map) {
                         Map<String, Object> itemMap = (Map<String, Object>) item;
@@ -995,7 +1293,7 @@
 
                         // 鑷冲皯鏈変竴涓湁鍊硷紝澶勭悊姣忎釜瀛楁
                         String itemName = (itemNameObj != null && StringUtils.isNotEmpty(itemNameObj.toString())) ? itemNameObj.toString() : "";
-                        
+
                         // itemId 鐗规畩澶勭悊锛氶伩鍏嶇瀛﹁鏁版硶锛圙son 鍙兘灏嗘暟瀛楄В鏋愪负 Double锛�
                         String itemId = "";
                         if (itemIdObj != null && StringUtils.isNotEmpty(itemIdObj.toString())) {
@@ -1006,7 +1304,7 @@
                                 itemId = itemIdObj.toString();
                             }
                         }
-                        
+
                         String manufacturerName = (manufacturerNameObj != null && StringUtils.isNotEmpty(manufacturerNameObj.toString())) ? manufacturerNameObj.toString() : "";
 
                         // 鍙牴鎹� itemId 鍘婚噸锛堝悓涓�缂栫爜鐨勮嵂鍝佸彧淇濈暀涓�涓級

--
Gitblit v1.9.3