From 5ba25cb53dab2ef0f8052a93796ef67a8a2ee820 Mon Sep 17 00:00:00 2001
From: liusheng <337615773@qq.com>
Date: 星期二, 10 六月 2025 14:53:49 +0800
Subject: [PATCH] 代码提交

---
 jh-module-ecg/jh-module-ecg-biz/src/main/java/cn/lihu/jh/module/ecg/service/appointment/AppointmentServiceImpl.java |  542 ++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 522 insertions(+), 20 deletions(-)

diff --git a/jh-module-ecg/jh-module-ecg-biz/src/main/java/cn/lihu/jh/module/ecg/service/appointment/AppointmentServiceImpl.java b/jh-module-ecg/jh-module-ecg-biz/src/main/java/cn/lihu/jh/module/ecg/service/appointment/AppointmentServiceImpl.java
index c165a8a..d43196c 100644
--- a/jh-module-ecg/jh-module-ecg-biz/src/main/java/cn/lihu/jh/module/ecg/service/appointment/AppointmentServiceImpl.java
+++ b/jh-module-ecg/jh-module-ecg-biz/src/main/java/cn/lihu/jh/module/ecg/service/appointment/AppointmentServiceImpl.java
@@ -1,20 +1,37 @@
 package cn.lihu.jh.module.ecg.service.appointment;
 
+import cn.lihu.jh.framework.common.pojo.PageResult;
+import cn.lihu.jh.framework.common.util.date.DateUtils;
+import cn.lihu.jh.framework.common.util.object.BeanUtils;
+import cn.lihu.jh.module.ecg.controller.admin.appointment.vo.AppointmentConfirmReqVO;
+import cn.lihu.jh.module.ecg.controller.admin.appointment.vo.AppointmentPageReqVO;
+import cn.lihu.jh.module.ecg.controller.admin.appointment.vo.AppointmentSaveReqVO;
+import cn.lihu.jh.module.ecg.controller.admin.queue.vo.QueueSaveReqVO;
+import cn.lihu.jh.module.ecg.dal.dataobject.appointment.AppointmentDO;
+import cn.lihu.jh.module.ecg.dal.dataobject.patient.PatDetails;
+import cn.lihu.jh.module.ecg.dal.dataobject.queue.QueueDO;
+import cn.lihu.jh.module.ecg.dal.mysql.appointment.AppointmentMapper;
+import cn.lihu.jh.module.ecg.enums.HisCheckCodeEnum;
+import cn.lihu.jh.module.ecg.feign.RemoteDataService;
+import cn.lihu.jh.module.ecg.service.config.EcgConfigService;
+import cn.lihu.jh.module.ecg.service.queue.QueueService;
+import cn.lihu.jh.module.ecg.service.queuesequence.QueueSequenceService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.ibatis.annotations.Param;
+import org.springframework.dao.DuplicateKeyException;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.CollectionUtils;
 import org.springframework.validation.annotation.Validated;
 
-import cn.lihu.jh.module.ecg.controller.admin.appointment.vo.*;
-import cn.lihu.jh.module.ecg.dal.dataobject.appointment.AppointmentDO;
-import cn.lihu.jh.framework.common.pojo.PageResult;
-import cn.lihu.jh.framework.common.pojo.PageParam;
-import cn.lihu.jh.framework.common.util.object.BeanUtils;
-
-import cn.lihu.jh.module.ecg.dal.mysql.appointment.AppointmentMapper;
-
 import javax.annotation.Resource;
-
+import java.time.LocalDate;
 import java.time.LocalDateTime;
-import java.util.Date;
+import java.time.format.DateTimeFormatter;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
 
 import static cn.lihu.jh.framework.common.exception.util.ServiceExceptionUtil.exception;
 import static cn.lihu.jh.module.ecg.enums.ErrorCodeConstants.*;
@@ -26,20 +43,35 @@
  */
 @Service
 @Validated
+@Slf4j
 public class AppointmentServiceImpl implements AppointmentService {
+
+    @Resource
+    private EcgConfigService ecgConfigService;
+
+    @Resource
+    private RemoteDataService remoteDataService;
+
+    @Resource
+    private QueueSequenceService queueSequenceService;
+
+    @Resource
+    private QueueService queueService;
 
     @Resource
     private AppointmentMapper appointmentMapper;
 
     @Override
-    public Integer createAppointment(AppointmentSaveReqVO createReqVO) {
+    public Long createAppointment(AppointmentSaveReqVO createReqVO) {
         // 鎻掑叆
         AppointmentDO appointment = BeanUtils.toBean(createReqVO, AppointmentDO.class);
 
-        appointment.setBookTime( LocalDateTime.now() );
-        appointment.setBookSrc( 0 );
+        try {
+            appointmentMapper.insert(appointment);
+        } catch (DuplicateKeyException e) {
+            throw exception(APPOINTMENT_EXIST_TODAY);
+        }
 
-        appointmentMapper.insert(appointment);
         // 杩斿洖
         return appointment.getId();
     }
@@ -54,27 +86,72 @@
     }
 
     @Override
-    public void deleteAppointment(Integer id) {
+    public void deleteAppointment(Long id) {
         // 鏍¢獙瀛樺湪
         validateAppointmentExists(id);
         // 鍒犻櫎
         appointmentMapper.deleteById(id);
     }
 
-    private void validateAppointmentExists(Integer id) {
+    private void validateAppointmentExists(Long id) {
         if (appointmentMapper.selectById(id) == null) {
             throw exception(APPOINTMENT_NOT_EXISTS);
         }
     }
 
     @Override
-    public AppointmentDO getAppointment(Integer id) {
+    public AppointmentDO getAppointment(Long id) {
         return appointmentMapper.selectById(id);
     }
 
     @Override
-    public AppointmentDO getAppointmentByPatId(String patId) {
-        return appointmentMapper.getByPatId( patId );
+    public AppointmentDO getCurAppointmentByPatIdAndCheckType(String patId, Integer checkType) {
+        AppointmentDO appointmentDO = appointmentMapper.getByPatAndCheckTypeAndBookDate(patId, checkType);
+        return appointmentDO;
+    }
+
+    /**
+     * @param patCode 缂栧彿 : !!! 涓嶄竴瀹氬氨鏄湰绯荤粺鐨� 鎮h�呯紪鍙�(patID), 鏍规簮鍦ㄤ簬 妫�鏌ュ崟鎵弿鍑烘潵鐨勭紪鍙� 涓嶄竴瀹氭槸 鏈郴缁熺殑 鎮h�呯紪鍙�(patID)
+     * @return
+     */
+    @Override
+    public List<AppointmentDO> queryAndCreateAppointmentByPatId(String patCode) {
+        // 浠庡尰闄㈠钩鍙版煡璇�
+        List<AppointmentDO> appointmentExtermalList = getAppointmentExtermal(patCode);
+
+        for (int appointmentIndex = 0; appointmentIndex < appointmentExtermalList.size(); appointmentIndex++) {
+            AppointmentDO appointmentExtermal = appointmentExtermalList.get(appointmentIndex);
+            if (null == appointmentExtermal) continue;
+
+            // 浠嶥B鏌ヨ棰勭害锛屾槸鍚﹀凡缁忓瓨鍦�
+            AppointmentDO appointmentDO = appointmentMapper.getByEpisodeIdAndApplyNo(appointmentExtermal.getEpisodeId(), appointmentExtermal.getApplyNo());
+            if (null == appointmentDO) {
+                appointmentMapper.insert(appointmentExtermal);
+            } else {
+                appointmentExtermal.setId(appointmentDO.getId()); // 纭繚 杩斿洖鍊煎寘鍚� appointment id
+
+                // 澶勭悊绗竴娆$‘璁ゆ椂杩樻病鏈夐绾︽椂闂达紝鍐嶆潵纭鏃跺凡鏈夐绾︽椂闂寸殑鎯呭喌
+                if (appointmentDO.getBookDate() != appointmentExtermal.getBookDate()) {
+                    appointmentMapper.updateById(appointmentExtermal);
+                }
+            }
+        }
+
+        // 鏌ヨ[queue琛╙琛ュ厖 book_seq_num 鍒拌繑鍥炲�间腑
+        if (!appointmentExtermalList.isEmpty()) {
+            List<Long> appointIdlist = appointmentExtermalList.stream().map(appointmentDO -> appointmentDO.getId()).toList();
+            List<QueueDO> simpleQueueDOList = queueService.selectBookSeqNumByAppointIdList(appointIdlist);
+            if (!simpleQueueDOList.isEmpty()) {
+                Map<Long, Integer> mapAppointIdVsBookSeqNo = simpleQueueDOList.stream().collect(Collectors.toMap(QueueDO::getAppointId, QueueDO::getBookSeqNum));
+                appointmentExtermalList.forEach(appointmentExterma -> appointmentExterma.setBookSeqNum(mapAppointIdVsBookSeqNo.get(appointmentExterma.getId())));
+            }
+        }
+
+        // 涓嶄粠DB鏌ヨ
+        //List<AppointmentDO> appointmentDOList = appointmentMapper.getCurrentPatId( patCode );
+        //return 0 == appointmentDOList.size() ? null : appointmentDOList.get(0);
+
+        return appointmentExtermalList;
     }
 
     @Override
@@ -82,4 +159,429 @@
         return appointmentMapper.selectPage(pageReqVO);
     }
 
-}
\ No newline at end of file
+    @Override
+    public List<AppointmentDO> getAppointmentExtermal(String patId) {
+        return appointmentMapper.getCurrentPatId(patId);
+    }
+
+//    @Override
+//    public List<AppointmentDO> getAppointmentExtermal(String patId) {
+//        List<AppointmentDO> curAppointDOList = new ArrayList<AppointmentDO>();
+//
+//        RestApiReqBodyVo reqBodyVo = new RestApiReqBodyVo();
+//        if (18 == patId.length()) {
+//            reqBodyVo.setSfzh( patId );
+//        } else {
+//            reqBodyVo.setMzzyh(patId);
+//        }
+//
+//        // QueryRisReportList   queryEcgRequest
+//        RestApiResult<AppointmentExternal> result = remoteDataService.httpApi("queryEcgRequest", "ECG", "ECG", reqBodyVo);
+//        if (0 == result.getRow().size()) {
+//            return curAppointDOList;
+//        }
+//
+//        for (int appointIndex=0; appointIndex < result.getRow().size(); appointIndex++ ) {
+//            AppointmentExternal appointmentExternal = result.getRow().get( appointIndex );
+//
+//            AppointmentDO appointmentDO = BeanUtils.toBean(appointmentExternal, AppointmentDO.class);
+//            appointmentDO.setApplyNo( appointmentExternal.getReqIdeApplyno() );
+//            appointmentDO.setEpisodeId( appointmentExternal.getEpisodeID() );
+//            appointmentDO.setPatSrc( getCorrespondingPatientSource(appointmentExternal.getAdmTypeCode()) );
+//            appointmentDO.setPatId(appointmentExternal.getPatientID()); // 鍐呭涓� 韬唤璇佸彿 鎴� 闂ㄨ瘖浣忛櫌鍙�
+//            appointmentDO.setPatName(appointmentExternal.getPatName());
+//            appointmentDO.setPatGender(Byte.valueOf(appointmentExternal.getPatgender()));
+//            appointmentDO.setPatBirthday(DateUtils.ofUTC(appointmentExternal.getEncPatBirthDate()).toLocalDate());
+//            appointmentDO.setPatIdentityId(appointmentExternal.getIdentityID());
+//            appointmentDO.setPatAddr(appointmentExternal.getAddress());
+//            appointmentDO.setPatDeptCode(appointmentExternal.getPatLocDeptCode());
+//            appointmentDO.setPatDeptDesc(appointmentExternal.getPatLocDeptDesc());
+//            appointmentDO.setPatWardCode(appointmentExternal.getPatLocWardCode());
+//            appointmentDO.setPatWardDesc(appointmentExternal.getPatLocWardDesc());
+//            appointmentDO.setPatMobile(appointmentExternal.getPhone());
+//            appointmentDO.setPatBedNo(appointmentExternal.getEnBedno());
+//            appointmentDO.setBookCheckType(getCorrespondingCheckType(appointmentExternal.getPlanDefItemList().getPlanDefItem().getPlanDefItemcode()));
+//            appointmentDO.setBookTime(DateUtils.ofUTC(appointmentExternal.getReqAuthoredOn()));  // 寮�鍗曟椂闂�
+//            appointmentDO.setBookSrc( 0 );
+//
+//            // 鍏夊紑鍗曠殑鎯呭喌锛屾病鏈夐绾︽椂闂�
+//            if (null != appointmentExternal.getReqExtBooktime() ) {
+//                appointmentDO.setBookDate(DateUtils.ofUTC(appointmentExternal.getReqExtBooktime()).toLocalDate());
+//                LocalDateTime bookStartTime = DateUtils.ofUTC(appointmentExternal.getReqExtBooktime());
+//                LocalDateTime bookEndTime = bookStartTime.plusMinutes( ecgConfigService.getTimeslotLength());
+//                appointmentDO.setBookTimeslot((bookStartTime.getHour() * 100 + bookStartTime.getMinute()) * 10000 + bookEndTime.getHour() * 100 + bookEndTime.getMinute());
+//            }
+//
+//            appointmentDO.setPaid( 0 );
+//
+//            curAppointDOList.add( appointmentDO );
+//        }
+//
+//        return curAppointDOList;
+//    }
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public Integer appoitmentConfirm(AppointmentConfirmReqVO confirmReqVO) {
+        AppointmentDO appointment = getAppointment(confirmReqVO.getId());
+        if (null == appointment) throw exception(PATIENT_NOT_EXISTS);
+
+        // 鎵嬪姩棰勭害锛岀洿鎺ヨ缃绾︽棩鏈熶负褰撳ぉ
+        if (confirmReqVO.getIsVip() == 1) {
+            appointment.setBookDate(LocalDate.now());
+        }
+
+        if (!DateUtils.isToday(appointment.getBookDate())) throw exception(APPOINTMENT_NOT_TODAY);
+
+
+        Integer newSeqNo = null;
+        if (confirmReqVO.getIsVip() == 0) {
+            newSeqNo = queueSequenceService.distributeSeqNo(confirmReqVO.getBookCheckType(), confirmReqVO.getBookTimeslot());
+        } else {
+            newSeqNo = queueSequenceService.distributeVipSeqNo(confirmReqVO.getBookCheckType(), confirmReqVO.getBookTimeslot());
+        }
+
+        try {
+            QueueSaveReqVO queueSaveReqVO = new QueueSaveReqVO();
+            queueSaveReqVO.setApplyNo(appointment.getApplyNo());
+            queueSaveReqVO.setEpisodeId(appointment.getEpisodeId());
+            queueSaveReqVO.setAppointId(appointment.getId());
+            queueSaveReqVO.setPatId(appointment.getPatId());
+            queueSaveReqVO.setPatName(appointment.getPatName());
+            queueSaveReqVO.setPatGender(appointment.getPatGender());
+            queueSaveReqVO.setBookDate(appointment.getBookDate());
+            queueSaveReqVO.setBookTimeslot(confirmReqVO.getBookTimeslot()); /*appointment.getBookTimeslot()*/
+            queueSaveReqVO.setBookCheckType(appointment.getBookCheckType());
+            queueSaveReqVO.setBookSeqNum(newSeqNo);
+            queueSaveReqVO.setIsVip(confirmReqVO.getIsVip());
+            queueSaveReqVO.setPassed((byte) 0);
+            queueSaveReqVO.setExpired((byte) 0);
+            queueSaveReqVO.setPatDetails(getPatDetails(appointment));
+            queueService.queue(queueSaveReqVO);
+        } catch (DuplicateKeyException duplicateKeyException) {
+            throw exception(APPOINTMENT_HAVE_QUEUED);
+        }
+
+        return newSeqNo;
+    }
+
+    private PatDetails getPatDetails(AppointmentDO appointment) {
+        PatDetails patDetails = new PatDetails();
+        patDetails.setAppointmentId(appointment.getId());
+        patDetails.setId(appointment.getPatId());
+        patDetails.setName(appointment.getPatName());
+        patDetails.setMobile(appointment.getPatMobile());
+        patDetails.setDeptCode(appointment.getPatDeptCode());
+        patDetails.setDeptDesc(appointment.getPatDeptDesc());
+        patDetails.setWardCode(appointment.getPatWardCode());
+        patDetails.setWardDesc(appointment.getPatWardDesc());
+        patDetails.setBedNo(appointment.getPatBedNo());
+        patDetails.setSource(appointment.getPatSrc());
+        return patDetails;
+    }
+
+    @Override
+    public Long handleAppointmentCreate(Map<String, Object> dataMap) {
+        if (dataMap == null) {
+            throw exception(APPOINTMENT_CREATE_FAIL);
+        }
+
+        try {
+            // 鍒涘缓AppointmentDO瀵硅薄
+            AppointmentDO appointment = new AppointmentDO();
+
+            // 浠巇ataMap涓彁鍙栨暟鎹�
+            Map<String, Object> encounter = extractEncounter(dataMap);
+            if (encounter == null) {
+                throw exception(APPOINTMENT_CREATE_FAIL);
+            }
+
+            // 璁剧疆灏辫瘖娴佹按鍙�
+            Optional.ofNullable(encounter.get("id")).map(id -> (Map<String, Object>) id).map(id -> (List<?>) id.get("item")).filter(items -> items.size() > 1).map(items -> (Map<String, Object>) items.get(1)).map(item -> (String) item.get("extension")).ifPresent(appointment::setEpisodeId);
+
+            Optional.ofNullable(encounter.get("location")).map(location -> (Map<String, Object>) location).map(location -> (Map<String, Object>) location.get("serviceDeliveryLocation")).map(serviceDeliveryLocation -> (Map<String, Object>) serviceDeliveryLocation.get("location")).map(location -> (Map<String, Object>) location.get("id")).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(appointment::setPatBedNo);
+
+
+            // 璁剧疆鎮h�呮潵婧愮被鍨�
+            Optional.ofNullable(encounter.get("code")).map(code -> (Map<String, Object>) code).map(code -> (String) code.get("code")).map(Integer::parseInt).ifPresent(appointment::setPatSrc);
+
+            // 璁剧疆鎮h�呬俊鎭�
+            Optional.ofNullable(encounter.get("subject")).map(subject -> (Map<String, Object>) subject).map(subject -> (Map<String, Object>) subject.get("patient")).map(patient -> (Map<String, Object>) patient.get("patientPerson")).ifPresent(patientPerson -> {
+                // 璁剧疆鎮h�匢D
+                Optional.ofNullable(encounter.get("subject")).map(subject -> (Map<String, Object>) subject).map(subject -> (Map<String, Object>) subject.get("patient")).map(patient -> (Map<String, Object>) patient.get("id")).map(id -> (Map<String, Object>) id).map(id -> (List<?>) id.get("item")).filter(items -> items.size() > 1).map(items -> (Map<String, Object>) items.get(1)).map(item -> (String) item.get("extension")).ifPresent(appointment::setPatId);
+
+                // 璁剧疆鎮h�呭鍚�
+                Optional.ofNullable(patientPerson.get("name")).map(name -> (Map<String, Object>) name).map(name -> (Map<String, Object>) name.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(appointment::setPatName);
+
+                // 璁剧疆鎮h�呮墜鏈哄拰鐢佃瘽
+                Optional.ofNullable(patientPerson.get("telecom")).map(telecom -> (Map<String, Object>) telecom).map(telecom -> (Map<String, Object>) telecom.get("item")).map(item -> (String) item.get("value")).ifPresent(phone -> {
+                    appointment.setPatMobile(phone);
+                    appointment.setPatPhone(phone);
+                });
+
+                // 璁剧疆鎮h�呮�у埆
+                Optional.ofNullable(patientPerson.get("administrativeGenderCode")).map(genderCode -> (Map<String, Object>) genderCode).map(genderCode -> (String) genderCode.get("code")).map(Byte::parseByte).ifPresent(appointment::setPatGender);
+
+                // 璁剧疆鎮h�呯敓鏃�
+                Optional.ofNullable(patientPerson.get("birthTime")).map(birthTime -> (Map<String, Object>) birthTime).map(birthTime -> (String) birthTime.get("value")).map(birthdayStr -> LocalDate.parse(birthdayStr, DateTimeFormatter.ofPattern("yyyyMMdd"))).ifPresent(appointment::setPatBirthday);
+
+                // 璁剧疆鎮h�呭湴鍧�
+                Optional.ofNullable(patientPerson.get("addr")).map(addr -> (Map<String, Object>) addr).map(addr -> (Map<String, Object>) addr.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(appointment::setPatAddr);
+
+                // 璁剧疆鎮h�呰韩浠借瘉鍙�
+                Optional.ofNullable(patientPerson.get("id")).map(id -> (Map<String, Object>) id).map(id -> (List<?>) id.get("item")).filter(items -> !items.isEmpty()).map(items -> (Map<String, Object>) items.get(0)).map(item -> (String) item.get("extension")).ifPresent(appointment::setPatIdentityId);
+            });
+
+            // 璁剧疆绉戝鍜岀梾鍖轰俊鎭�
+            Optional.ofNullable(encounter.get("location")).map(location -> (Map<String, Object>) location).map(location -> (Map<String, Object>) location.get("serviceDeliveryLocation")).map(location -> (Map<String, Object>) location.get("serviceProviderOrganization")).ifPresent(org -> {
+                // 璁剧疆绉戝浠g爜鍜屽悕绉�
+                Optional.ofNullable(org.get("id")).map(id -> (Map<String, Object>) id).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(appointment::setPatDeptCode);
+
+                Optional.ofNullable(org.get("name")).map(name -> (Map<String, Object>) name).map(name -> (Map<String, Object>) name.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(appointment::setPatDeptDesc);
+
+                // 璁剧疆鐥呭尯浠g爜鍜屽悕绉�
+                Optional.ofNullable(org.get("asOrganizationPartOf")).map(wardOrg -> (Map<String, Object>) wardOrg).map(wardOrg -> (Map<String, Object>) wardOrg.get("wholeOrganization")).ifPresent(wardOrg -> {
+                    Optional.ofNullable(wardOrg.get("id")).map(id -> (Map<String, Object>) id).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(appointment::setPatWardCode);
+
+                    Optional.ofNullable(wardOrg.get("name")).map(name -> (Map<String, Object>) name).map(name -> (Map<String, Object>) name.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(appointment::setPatWardDesc);
+                });
+            });
+
+            // 璁剧疆鏀粯鐘舵��
+            Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("zdy")).map(zdy -> {
+                Object payStatus = zdy.get("PayStatus");
+                if (payStatus != null) {
+                    try {
+                        return Integer.parseInt(payStatus.toString());
+                    } catch (NumberFormatException e) {
+                        log.warn("PayStatus杞崲澶辫触: {}", payStatus);
+                        return null;
+                    }
+                }
+                return null;
+            }).ifPresent(appointment::setPaid);
+            // 璁剧疆鐢宠鍗曞彿
+            Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("id")).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(appointment::setApplyNo);
+
+            //璁剧疆妫�鏌ョ被鍨�
+//            String checkType = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("component2")).map(component2 -> (Map<String, Object>) component2.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("code")).map(code -> (String) code.get("code")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+            String checkType = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("component2")).map(component2 -> (Map<String, Object>) component2.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("code")).map(code -> (String) code.get("code")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+            if (checkType != null || checkType != "")
+                appointment.setBookCheckType(Integer.valueOf(HisCheckCodeEnum.getByCode(checkType.substring(1))));
+
+            // 灏咥ppointmentDO杞崲涓篈ppointmentSaveReqVO骞朵繚瀛�
+            AppointmentSaveReqVO saveReqVO = BeanUtils.toBean(appointment, AppointmentSaveReqVO.class);
+            saveReqVO.setStatus("1");
+            return createAppointment(saveReqVO);
+        } catch (Exception e) {
+            log.error("[handleAppointmentCreate][澶勭悊棰勭害鍒涘缓澶辫触 dataMap({})]", dataMap, e);
+            throw exception(APPOINTMENT_CREATE_FAIL);
+        }
+    }
+
+    @Override
+    public void handleAppointmentUpdate(Map<String, Object> dataMap) {
+        if (dataMap == null) {
+            throw exception(APPOINTMENT_UPDATE_FAIL);
+        }
+
+        try {
+            // 浠巇ataMap涓彁鍙栫敵璇峰崟鍙�
+            String applyNo = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("id")).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+
+            // 鏌ヨ鐜版湁棰勭害璁板綍
+            AppointmentDO existingAppointment = appointmentMapper.getByApplyNo(applyNo);
+
+            // 濡傛灉璁板綍涓嶅瓨鍦紝鍒欒皟鐢╤andleAppointmentCreate杩涜鏂板
+            if (existingAppointment == null) {
+                handleAppointmentCreate(dataMap);
+                return;
+            }
+
+            // 浠巇ataMap涓彁鍙栨暟鎹�
+            Map<String, Object> encounter = extractEncounter(dataMap);
+            if (encounter == null) {
+                throw exception(APPOINTMENT_CREATE_FAIL);
+            }
+
+            // 鏇存柊灏辫瘖娴佹按鍙�
+            Optional.ofNullable(encounter.get("id")).map(id -> (Map<String, Object>) id).map(id -> (List<?>) id.get("item")).filter(items -> items.size() > 1).map(items -> (Map<String, Object>) items.get(1)).map(item -> (String) item.get("extension")).ifPresent(existingAppointment::setEpisodeId);
+
+            // 璁剧疆搴婁綅鍙�
+            Optional.ofNullable(encounter.get("location")).map(location -> (Map<String, Object>) location).map(location -> (Map<String, Object>) location.get("serviceDeliveryLocation")).map(serviceDeliveryLocation -> (Map<String, Object>) serviceDeliveryLocation.get("location")).map(location -> (Map<String, Object>) location.get("id")).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(existingAppointment::setPatBedNo);
+
+
+            // 鏇存柊鎮h�呮潵婧愮被鍨�
+            Optional.ofNullable(encounter.get("code")).map(code -> (Map<String, Object>) code).map(code -> (String) code.get("code")).map(Integer::parseInt).ifPresent(existingAppointment::setPatSrc);
+
+            // 鏇存柊鎮h�呬俊鎭�
+            Optional.ofNullable(encounter.get("subject")).map(subject -> (Map<String, Object>) subject).map(subject -> (Map<String, Object>) subject.get("patient")).map(patient -> (Map<String, Object>) patient.get("patientPerson")).ifPresent(patientPerson -> {
+                // 鏇存柊鎮h�匢D
+                Optional.ofNullable(encounter.get("subject")).map(subject -> (Map<String, Object>) subject).map(subject -> (Map<String, Object>) subject.get("patient")).map(patient -> (Map<String, Object>) patient.get("id")).map(id -> (Map<String, Object>) id).map(id -> (List<?>) id.get("item")).filter(items -> items.size() > 1).map(items -> (Map<String, Object>) items.get(1)).map(item -> (String) item.get("extension")).ifPresent(existingAppointment::setPatId);
+
+                // 鏇存柊鎮h�呭鍚�
+                Optional.ofNullable(patientPerson.get("name")).map(name -> (Map<String, Object>) name).map(name -> (Map<String, Object>) name.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(existingAppointment::setPatName);
+
+                // 鏇存柊鎮h�呮墜鏈哄拰鐢佃瘽
+                Optional.ofNullable(patientPerson.get("telecom")).map(telecom -> (Map<String, Object>) telecom).map(telecom -> (Map<String, Object>) telecom.get("item")).map(item -> (String) item.get("value")).ifPresent(phone -> {
+                    existingAppointment.setPatMobile(phone);
+                    existingAppointment.setPatPhone(phone);
+                });
+
+                // 鏇存柊鎮h�呮�у埆
+                Optional.ofNullable(patientPerson.get("administrativeGenderCode")).map(genderCode -> (Map<String, Object>) genderCode).map(genderCode -> (String) genderCode.get("code")).map(Byte::parseByte).ifPresent(existingAppointment::setPatGender);
+
+                // 鏇存柊鎮h�呯敓鏃�
+                Optional.ofNullable(patientPerson.get("birthTime")).map(birthTime -> (Map<String, Object>) birthTime).map(birthTime -> (String) birthTime.get("value")).map(birthdayStr -> LocalDate.parse(birthdayStr, DateTimeFormatter.ofPattern("yyyyMMdd"))).ifPresent(existingAppointment::setPatBirthday);
+
+                // 鏇存柊鎮h�呭湴鍧�
+                Optional.ofNullable(patientPerson.get("addr")).map(addr -> (Map<String, Object>) addr).map(addr -> (Map<String, Object>) addr.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(existingAppointment::setPatAddr);
+
+                // 鏇存柊鎮h�呰韩浠借瘉鍙�
+                Optional.ofNullable(patientPerson.get("id")).map(id -> (Map<String, Object>) id).map(id -> (List<?>) id.get("item")).filter(items -> !items.isEmpty()).map(items -> (Map<String, Object>) items.get(0)).map(item -> (String) item.get("extension")).ifPresent(existingAppointment::setPatIdentityId);
+            });
+
+            // 鏇存柊绉戝鍜岀梾鍖轰俊鎭�
+            Optional.ofNullable(encounter.get("location")).map(location -> (Map<String, Object>) location).map(location -> (Map<String, Object>) location.get("serviceDeliveryLocation")).map(location -> (Map<String, Object>) location.get("serviceProviderOrganization")).ifPresent(org -> {
+                // 鏇存柊绉戝浠g爜鍜屽悕绉�
+                Optional.ofNullable(org.get("id")).map(id -> (Map<String, Object>) id).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(existingAppointment::setPatDeptCode);
+
+                Optional.ofNullable(org.get("name")).map(name -> (Map<String, Object>) name).map(name -> (Map<String, Object>) name.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(existingAppointment::setPatDeptDesc);
+
+                // 鏇存柊鐥呭尯浠g爜鍜屽悕绉�
+                Optional.ofNullable(org.get("asOrganizationPartOf")).map(wardOrg -> (Map<String, Object>) wardOrg).map(wardOrg -> (Map<String, Object>) wardOrg.get("wholeOrganization")).ifPresent(wardOrg -> {
+                    Optional.ofNullable(wardOrg.get("id")).map(id -> (Map<String, Object>) id).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).ifPresent(existingAppointment::setPatWardCode);
+
+                    Optional.ofNullable(wardOrg.get("name")).map(name -> (Map<String, Object>) name).map(name -> (Map<String, Object>) name.get("item")).map(item -> (Map<String, Object>) item.get("part")).map(part -> (String) part.get("value")).ifPresent(existingAppointment::setPatWardDesc);
+                });
+            });
+
+            // 鏇存柊鏀粯鐘舵��
+            Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("zdy")).map(zdy -> {
+                Object payStatus = zdy.get("PayStatus");
+                if (payStatus != null) {
+                    try {
+                        return Integer.parseInt(payStatus.toString());
+                    } catch (NumberFormatException e) {
+                        log.warn("PayStatus杞崲澶辫触: {}", payStatus);
+                        return null;
+                    }
+                }
+                return null;
+            }).ifPresent(existingAppointment::setPaid);
+            //璁剧疆妫�鏌ョ被鍨�
+            String checkType = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("component2")).map(component2 -> (Map<String, Object>) component2.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("code")).map(code -> (String) code.get("code")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+            if (checkType != null || checkType != "")
+                existingAppointment.setBookCheckType(Integer.valueOf(HisCheckCodeEnum.getByCode(checkType.substring(1))));
+
+            // 灏咥ppointmentDO杞崲涓篈ppointmentSaveReqVO骞舵洿鏂�
+            AppointmentSaveReqVO updateReqVO = BeanUtils.toBean(existingAppointment, AppointmentSaveReqVO.class);
+            updateAppointment(updateReqVO);
+        } catch (Exception e) {
+            log.error("[handleAppointmentUpdate][鐢宠鍗曟洿鏂板け璐� dataMap({})]", dataMap, e);
+            throw exception(APPOINTMENT_UPDATE_FAIL);
+        }
+    }
+
+    @Override
+    public void handleAppointmentStateUpdate(Map<String, Object> dataMap) {
+        if (dataMap == null) {
+            throw exception(APPOINTMENT_STATUS_UPDATE_FAIL);
+        }
+        // 浠巇ataMap涓彁鍙栫敵璇峰崟鍙�
+        String applyNo = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("placerGroup")).map(placerGroup -> (Map<String, Object>) placerGroup.get("component2")).map(component2 -> (Map<String, Object>) component2.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("id")).map(id -> (Map<String, Object>) id.get("item")).map(item -> (String) item.get("extension")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+
+        // 鏌ヨ鐜版湁棰勭害璁板綍
+        AppointmentDO existingAppointment = appointmentMapper.getByApplyNo(applyNo);
+
+        // 濡傛灉璁板綍涓嶅瓨鍦紝鍒欒皟鐢╤andleAppointmentCreate杩涜鏂板
+        if (existingAppointment == null) {
+            handleAppointmentCreate(dataMap);
+            return;
+        }
+
+
+        // 浠巇ataMap涓彁鍙栫敵璇峰崟鍙�
+//        String status = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("placerGroup")).map(placerGroup -> (Map<String, Object>) placerGroup.get("component2")).map(component2 -> (Map<String, Object>) component2.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("component1")).map(component1 -> (Map<String, Object>) component1.get("processStep")).map(processStep -> (Map<String, Object>) processStep.get("code")).map(code -> (Map<String, Object>) code.get("displayName")).map(displayName -> (String) displayName.get("value")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+        String status = Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("placerGroup")).map(placerGroup -> (Map<String, Object>) placerGroup.get("component2")).map(component2 -> (Map<String, Object>) component2.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("component1")).map(component1 -> (Map<String, Object>) component1.get("processStep")).map(processStep -> (Map<String, Object>) processStep.get("code")).map(code -> (String) code.get("code")).orElseThrow(() -> exception(APPOINTMENT_CREATE_FAIL));
+
+        existingAppointment.setStatus(status);
+        // 灏咥ppointmentDO杞崲涓篈ppointmentSaveReqVO骞舵洿鏂�
+        AppointmentSaveReqVO updateReqVO = BeanUtils.toBean(existingAppointment, AppointmentSaveReqVO.class);
+        updateAppointment(updateReqVO);
+    }
+
+
+    /**
+     * 浠巇ataMap涓彁鍙杄ncounter鏁版嵁
+     */
+    private Map<String, Object> extractEncounter(Map<String, Object> dataMap) {
+        return Optional.ofNullable(dataMap.get("controlActProcess")).map(controlActProcess -> (Map<String, Object>) controlActProcess).map(controlActProcess -> (Map<String, Object>) controlActProcess.get("subject")).map(subject -> (Map<String, Object>) subject.get("observationRequest")).map(observationRequest -> (Map<String, Object>) observationRequest.get("componentOf1")).map(componentOf1 -> (Map<String, Object>) componentOf1.get("encounter")).orElse(null);
+    }
+
+    @Override
+    public void handleCheckAppointmentUpdate(Map<String, Object> dataMap) {
+        // 浠巇ataMap涓幏鍙朿ontrolActProcess
+        Map<String, Object> controlActProcess = (Map<String, Object>) dataMap.get("controlActProcess");
+        Map<String, Object> subject = (Map<String, Object>) controlActProcess.get("subject");
+        Map<String, Object> actAppointment = (Map<String, Object>) subject.get("actAppointment");
+
+        // 鑾峰彇鐢宠缂栧彿
+        List<Map<String, Object>> referencedOrders = (List<Map<String, Object>>) actAppointment.get("referencedOrder");
+        String applyNo = null;
+        if (!CollectionUtils.isEmpty(referencedOrders)) {
+            Map<String, Object> actOrder = (Map<String, Object>) referencedOrders.get(0).get("actOrder");
+            Map<String, Object> id = (Map<String, Object>) actOrder.get("id");
+            applyNo = (String) id.get("extension");
+        }
+
+        if (applyNo == null) {
+            log.warn("[handleCheckAppointmentUpdate][鏈壘鍒扮敵璇风紪鍙穄");
+            return;
+        }
+
+        // 鏍规嵁applyNo鏌ヨ棰勭害璁板綍
+        AppointmentDO appointment = appointmentMapper.getByApplyNo(applyNo);
+        if (appointment == null) {
+            log.warn("[handleCheckAppointmentUpdate][鏈壘鍒伴绾﹁褰� applyNo({})]", applyNo);
+            return;
+        }
+
+        // 鑾峰彇棰勭害鏃堕棿
+        Map<String, Object> effectiveTime = (Map<String, Object>) actAppointment.get("effectiveTime");
+        Map<String, Object> any = (Map<String, Object>) effectiveTime.get("any");
+        String bookTimeStr = (String) any.get("value");
+
+        // 鑾峰彇棰勭害鏉ユ簮
+        Map<String, Object> code = (Map<String, Object>) actAppointment.get("code");
+        String bookSrc = (String) code.get("code");
+
+        // 瑙f瀽棰勭害鏃堕棿
+        LocalDateTime bookTime = LocalDateTime.parse(bookTimeStr, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
+        LocalDate bookDate = bookTime.toLocalDate();
+
+        // 鑾峰彇鏃堕棿娈�
+        String timeRange = (String) ((Map<String, Object>) actAppointment.get("ZDY")).get("time");
+        String[] time1 = timeRange.split(" ");
+        String[] times = time1[1].split("-");
+        String startTime = times[0].trim();
+        String endTime = times[1].trim();
+
+        // 杞崲鏃堕棿娈垫牸寮忎负hhmmhhmm
+        int bookTimeslot = Integer.parseInt(startTime.replace(":", "")) * 10000 + Integer.parseInt(endTime.replace(":", ""));
+
+        // 鏇存柊棰勭害淇℃伅
+        appointment.setBookDate(bookDate);
+        appointment.setBookTimeslot(bookTimeslot);
+        appointment.setBookTime(bookTime);
+        appointment.setBookSrc(Integer.parseInt(bookSrc));
+
+        // 淇濆瓨鏇存柊
+        appointmentMapper.updateById(appointment);
+    }
+
+    public AppointmentDO getByApplyNo(String applyNo) {
+        return appointmentMapper.getByApplyNo(applyNo);
+    }
+}
+

--
Gitblit v1.9.3