A17404李放 3 lat temu
rodzic
commit
2177b10423
26 zmienionych plików z 762 dodań i 447 usunięć
  1. 1 0
      coffee-common/src/main/java/com/coffee/common/config/websocket/DefaultMessageListener.java
  2. 1 1
      coffee-framework/src/main/java/com/coffee/framework/web/exception/GlobalExceptionHandler.java
  3. 17 0
      coffee-system/src/main/java/com/coffee/bus/controller/BusHospitalConfigController.java
  4. 46 5
      coffee-system/src/main/java/com/coffee/bus/controller/BusPatientController.java
  5. 3 1
      coffee-system/src/main/java/com/coffee/bus/entity/BusDeviceRunningEntity.java
  6. 1 8
      coffee-system/src/main/java/com/coffee/bus/entity/BusHospitalConfigEntity.java
  7. 12 0
      coffee-system/src/main/java/com/coffee/bus/enums/ConfigEnum.java
  8. 13 0
      coffee-system/src/main/java/com/coffee/bus/enums/PatientAlarmEnum.java
  9. 4 2
      coffee-system/src/main/java/com/coffee/bus/hospital/HospitalManager.java
  10. 2 2
      coffee-system/src/main/java/com/coffee/bus/hospital/config/HospitalFinishMonitorConfigHandler.java
  11. 1 1
      coffee-system/src/main/java/com/coffee/bus/hospital/config/bean/FunctionOtherConfig.java
  12. 4 0
      coffee-system/src/main/java/com/coffee/bus/mapper/BusPatientMapper.java
  13. 2 0
      coffee-system/src/main/java/com/coffee/bus/registry/constant/DeviceKeyConstant.java
  14. 10 0
      coffee-system/src/main/java/com/coffee/bus/registry/device/ClusterDeviceOperator.java
  15. 12 0
      coffee-system/src/main/java/com/coffee/bus/registry/device/DeviceOperator.java
  16. 1 1
      coffee-system/src/main/java/com/coffee/bus/registry/patient/ClusterPatientRegistry.java
  17. 4 1
      coffee-system/src/main/java/com/coffee/bus/script/PythonParse.java
  18. 1 1
      coffee-system/src/main/java/com/coffee/bus/service/LocalBusDeviceRunningService.java
  19. 134 0
      coffee-system/src/main/java/com/coffee/bus/service/LocalBusHospitalConfigService.java
  20. 32 9
      coffee-system/src/main/java/com/coffee/bus/service/LocalBusHospitalService.java
  21. 18 0
      coffee-system/src/main/java/com/coffee/bus/service/LocalBusPatientService.java
  22. 3 1
      coffee-system/src/main/java/com/coffee/bus/service/dto/ManualUndoConfig.java
  23. 9 9
      coffee-system/src/main/java/com/coffee/bus/utils/WsPublishUtils.java
  24. 2 2
      coffee-system/src/main/java/com/coffee/bus/websocket/WebSocketCloseHandler.java
  25. 57 49
      coffee-system/src/main/java/com/coffee/bus/websocket/listener/DeviceInfoListener.java
  26. 372 354
      coffee-system/src/main/resources/mapper/bus/BusPatientMapper.xml

+ 1 - 0
coffee-common/src/main/java/com/coffee/common/config/websocket/DefaultMessageListener.java

@@ -43,6 +43,7 @@ public class DefaultMessageListener implements PatternMessageListener<TopicMessa
                 log.error("ws消息订阅,解析失败,message:【】", JSONUtil.toJsonStr(msg));
             }
         }else {
+            channelContext.setClosed(true);
             rPatternTopic.removeListener(this);
         }
     }

+ 1 - 1
coffee-framework/src/main/java/com/coffee/framework/web/exception/GlobalExceptionHandler.java

@@ -39,7 +39,7 @@ public class GlobalExceptionHandler {
     @ExceptionHandler(NotLoginException.class)
     public R handleNotLoginException(NotLoginException e) {
         log.error(e.getMessage(), e);
-        return R.result(ResultCode.UN_AUTHORIZED);
+        return R.result(ResultCode.TOKEN_ERROR);
     }
 
     @ExceptionHandler(NotRoleException.class)

+ 17 - 0
coffee-system/src/main/java/com/coffee/bus/controller/BusHospitalConfigController.java

@@ -1,11 +1,16 @@
 package com.coffee.bus.controller;
 
+import cn.dev33.satoken.annotation.SaCheckPermission;
 import com.baomidou.mybatisplus.core.mapper.Mapper;
 import com.coffee.bus.entity.BusHospitalConfigEntity;
+import com.coffee.bus.enums.ConfigEnum;
 import com.coffee.bus.service.LocalBusHospitalConfigService;
 import com.coffee.common.crud.BaseService;
 import com.coffee.common.crud.controller.BaseCrudController;
+import com.coffee.common.exception.CustomException;
+import com.coffee.common.result.R;
 import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
 import lombok.AllArgsConstructor;
 import org.springframework.web.bind.annotation.*;
 
@@ -33,6 +38,18 @@ public class BusHospitalConfigController extends BaseCrudController<BusHospitalC
         return "hospital:config";
     }
 
+    @PostMapping("/reset/{type}")
+    @SaCheckPermission("hospital:config:edit")
+    @ApiOperation(value = "将某一功能项改为默认配置",notes = "权限【hospital:config:edit】")
+    public R<Boolean> reset(@RequestAttribute("tenantId")String tenantId,@PathVariable("type") int type){
+        ConfigEnum configEnum = ConfigEnum.valueOf(type);
+        if(configEnum==null){
+            throw new CustomException("无此配置项");
+        }
+        hospitalConfigService.setDefaultConfig(tenantId,configEnum);
+         return R.success(true);
+    }
+
     @Override
     public BaseService<? extends Mapper<BusHospitalConfigEntity>, BusHospitalConfigEntity, String> getService() {
         return hospitalConfigService;

+ 46 - 5
coffee-system/src/main/java/com/coffee/bus/controller/BusPatientController.java

@@ -26,6 +26,7 @@ import com.coffee.common.exception.CustomException;
 import com.coffee.common.result.R;
 import io.swagger.annotations.*;
 import lombok.AllArgsConstructor;
+import org.springframework.validation.annotation.Validated;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.context.request.async.DeferredResult;
 
@@ -133,7 +134,16 @@ public class BusPatientController  implements BaseQueryController<BusPatientEnti
     private R<Boolean> monitorFinished(MonitorFinishedVo monitorFinishedVo, String tenantId){
         List<String> patientCodes = monitorFinishedVo.getPatientCodes();
         if(CollectionUtil.isEmpty(patientCodes)){
-            throw new CustomException("请选择一个病患");
+            List<String> clinicIds = monitorFinishedVo.getClinicIds();
+            if (CollectionUtil.isEmpty(clinicIds)) {
+                throw new CustomException("未选择临床信息");
+            }
+            patientCodes=clinicService.list(new QueryWrapper<BusClinicEntity>().lambda()
+                    .in(BusClinicEntity::getId,clinicIds))
+                    .stream().map(BusClinicEntity::getPatientCode).collect(Collectors.toList());
+            if (CollectionUtil.isEmpty(patientCodes)) {
+                throw new CustomException("临床信息不存在");
+            }
         }
         List<PatientOperator<PatientCacheInfo>> patientOperators = patientCodes.stream().map(code -> patientRegistry.getOperator(tenantId, code)).collect(Collectors.toList());
 
@@ -181,15 +191,28 @@ public class BusPatientController  implements BaseQueryController<BusPatientEnti
     @SaCheckPermission("device:patient:edit")
     @ApiOperation(value = "病人当前监控时间重启",notes = "当结束临床后有新的输注信息产生,那么病人监控会重新显示,此时监控时间不会重新计算,需先调用该接口,权限标识为【device:patient:edit】")
     public R reset(@ApiParam("临床id")@PathVariable("clinicId")String clinicId){
-        return R.success(clinicService.update(new UpdateWrapper<BusClinicEntity>().lambda().eq(BusClinicEntity::getId,clinicId)
-                .set(BusClinicEntity::getFinished,false)));
+        R<Boolean> result = R.success(clinicService.update(new UpdateWrapper<BusClinicEntity>().lambda().eq(BusClinicEntity::getId, clinicId)
+                .set(BusClinicEntity::getEndTime, null)));
+        BusClinicEntity clinic = clinicService.getById(clinicId);
+        wsPublishUtils.publishPatientMonitor(clinic.getPatientCode(),clinic.getTenantId());
+        return result;
     }
 
+    @PostMapping("/{alarm}/_count")
+    @SaCheckPermission("device:patient:query")
+    @ApiOperation(value = "病人报警数量统计",notes = "病人报警数量统计 0、未报警 1、泵重复 2、无泵,权限标识为【device:patient:query】")
+    public R<Long> alarmCount(@PathVariable("alarm") int alarm){
+        PatientAlarmEnum alarmEnum = PatientAlarmEnum.of(alarm);
+        if(alarmEnum==null){
+            return R.success(0L);
+        }
+        return R.success(patientService.patientAlarmCount(alarmEnum));
+    }
 
     @PostMapping("/shift")
     @SaCheckPermission("device:patient:shift")
     @ApiOperation(value = "主泵切换的操作,只切换,不结束",notes = "当出现泵重复状态时,若用户想要进行主泵的切换,调用该接口进行操作,主泵切换完成后,会将副泵自动撤泵,权限标识为【device:patient:shift】")
-    public R shift(@RequestBody DeviceShiftConfig shiftConfig){
+    public R shift(@RequestBody@Validated DeviceShiftConfig shiftConfig){
         deviceRunningService.shift(shiftConfig);
         wsPublishUtils.publishPatientMonitor(shiftConfig.getPatientCode(),shiftConfig.getTenantId());
         return R.success();
@@ -198,7 +221,8 @@ public class BusPatientController  implements BaseQueryController<BusPatientEnti
     @PostMapping("/undo")
     @SaCheckPermission("device:patient:undo")
     @ApiOperation(value = "批量撤泵,只撤泵,不切换",notes = "当出现泵重复状态时,若用户想要取消对其他副泵的监控,则调用此接口进行撤泵操作,权限标识为【device:patient:undo】")
-    public R shift(@RequestBody ManualUndoConfig undoConfig){
+    public R shift(@RequestBody@Validated ManualUndoConfig undoConfig, @RequestAttribute("tenantId")@ApiParam(hidden = true) String tenantId){
+        undoConfig.setTenantId(tenantId);
         //泵切换完成后,对病号报警解除
         deviceRunningService.undo(undoConfig,false);
         //判断当前病号下是否还存在副泵
@@ -221,6 +245,9 @@ public class BusPatientController  implements BaseQueryController<BusPatientEnti
                 .eq(BusPatientEntity::getCode,undoConfig.getPatientCode())
                 .eq(BusPatientEntity::getTenantId,undoConfig.getTenantId())
                 .set(BusPatientEntity::getAlarm, PatientAlarmEnum.NONE));
+
+        wsPublishUtils.publishPatientMonitor(undoConfig.getPatientCode(),undoConfig.getTenantId());
+        wsPublishUtils.publishDeviceRepeat(undoConfig.getTenantId());
         return R.success();
     }
 
@@ -283,6 +310,20 @@ public class BusPatientController  implements BaseQueryController<BusPatientEnti
         return patientService.getPatientInfoFromHis(tenantId,vo.getPatientCode(),vo.getTimeout(),false);
     }
 
+
+    @SaCheckPermission("device:patient:query")
+    @ApiOperation(value = "泵重复绑定数量",notes = "权限标识为【bus:patient:query】")
+    @PostMapping("/_count/repeat")
+    public R<Integer> repeatCount(){
+        return R.success(CollectionUtil.size(patientService.repeatDevice()));
+    }
+
+    @SaCheckPermission("device:patient:query")
+    @ApiOperation(value = "无泵数量",notes = "权限标识为【bus:patient:query】")
+    @PostMapping("/_count/none")
+    public R<Integer> noneCount(){
+        return R.success(CollectionUtil.size(patientService.repeatDevice()));
+    }
     /**
      * 描述:
      * @author lifang

+ 3 - 1
coffee-system/src/main/java/com/coffee/bus/entity/BusDeviceRunningEntity.java

@@ -83,7 +83,9 @@ public class BusDeviceRunningEntity extends CommonDeviceParam<String,String> {
     @JsonIgnoreProperties
     private String infusionModifyId;
 
-
+    @TableField(exist = false)
+    @JsonIgnoreProperties
+    private Date modifyTime;
     /**
      * 当前运行状态是否开启了新的输注,只在设备上传解析过程中使用,其他地方无用处
      */

+ 1 - 8
coffee-system/src/main/java/com/coffee/bus/entity/BusHospitalConfigEntity.java

@@ -1,20 +1,13 @@
 package com.coffee.bus.entity;
 
-import com.baomidou.mybatisplus.annotation.FieldFill;
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
 import com.coffee.bus.enums.ConfigEnum;
-import com.coffee.common.config.mybatis.DateToBigIntHandler;
-import com.coffee.common.entity.RecordCreationEntity;
-import com.coffee.common.entity.RecordModifierEntity;
 import com.coffee.common.entity.TenantGenericEntity;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
-import org.apache.ibatis.type.EnumTypeHandler;
-
-import java.util.Date;
 import java.util.Map;
 
 /**
@@ -30,7 +23,7 @@ import java.util.Map;
 public class BusHospitalConfigEntity extends TenantGenericEntity<String,String>  {
 
 
-    @ApiModelProperty(value = "配置类型",example = "eval:评价配置,other:其他设置,undo:撤泵配置",allowableValues = "eval:评价配置,other:其他设置,undo:撤泵配置")
+    @ApiModelProperty(value = "配置类型",example = "eval:评价配置,extra:其他设置,undo:撤泵配置",allowableValues = "eval:评价配置,extra:其他设置,undo:撤泵配置")
     private ConfigEnum type;
 
     @TableField(typeHandler = FastjsonTypeHandler.class,javaType = true)

+ 12 - 0
coffee-system/src/main/java/com/coffee/bus/enums/ConfigEnum.java

@@ -20,4 +20,16 @@ public enum  ConfigEnum implements IEnum<Integer> {
 
     private Integer value;
     private String text;
+
+    public static ConfigEnum valueOf(Integer value){
+        switch (value){
+            case 0:
+                return undo;
+            case 1:
+                return eval;
+            case 2:
+                return other;
+            default:return null;
+        }
+    }
 }

+ 13 - 0
coffee-system/src/main/java/com/coffee/bus/enums/PatientAlarmEnum.java

@@ -22,4 +22,17 @@ public enum PatientAlarmEnum implements IEnum<Integer> {
 
     private Integer value;
     private String text;
+
+    public static PatientAlarmEnum of(int value){
+        switch (value){
+            case 0:
+                return NONE;
+            case 1:
+                return DEVICE_REPEAT;
+            case 2:
+                return DEVICE_NONE;
+            default:break;
+        }
+        return null;
+    }
 }

+ 4 - 2
coffee-system/src/main/java/com/coffee/bus/hospital/HospitalManager.java

@@ -2,6 +2,7 @@ package com.coffee.bus.hospital;
 
 import cn.hutool.json.JSONUtil;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.coffee.bus.bean.Script;
 import com.coffee.bus.entity.BusDeviceRunningEntity;
 import com.coffee.bus.entity.BusHospitalConfigEntity;
 import com.coffee.bus.entity.BusHospitalEntity;
@@ -24,6 +25,7 @@ import lombok.Data;
 
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 
 /**
  * @author lifang
@@ -133,7 +135,7 @@ public class HospitalManager {
                     FunctionAnalConfig anal = otherConfig.getAnal();
                     analConfigHandler.setConfig(anal);
                     //其他
-                    FunctionExtraConfig extraConfig = otherConfig.getOther();
+                    FunctionExtraConfig extraConfig = otherConfig.getExtra();
                     extraConfigHandler.setConfig(extraConfig);
                     break;
                 default:break;
@@ -160,7 +162,7 @@ public class HospitalManager {
     public void refreshScript(){
         BusHospitalEntity hospital = hospitalService.getById(hospitalId);
         ScriptParse scriptParse = scriptManager.getById(hospitalId);
-        scriptManager.resetScript(hospitalId,scriptParse.getId(),hospital.getScript().getContent());
+        scriptManager.resetScript(hospitalId,scriptParse.getId(), Optional.ofNullable(hospital.getScript()).orElse(new Script()).getContent());
     }
 
 }

+ 2 - 2
coffee-system/src/main/java/com/coffee/bus/hospital/config/HospitalFinishMonitorConfigHandler.java

@@ -78,7 +78,7 @@ public class HospitalFinishMonitorConfigHandler extends AbstractHospitalConfigHa
                 .patientCode(patientCode)
                 .config(undoDeviceConfig)
                 .timeout(config.getNoSignalInterval())
-                .unit(TimeUnit.MINUTES)
+                .unit(TimeUnit.DAYS)
                 .tenantId(tenantId)
                 .timestamp(new Date())
                 .build();
@@ -109,7 +109,7 @@ public class HospitalFinishMonitorConfigHandler extends AbstractHospitalConfigHa
                     .patientCode(source.getPatientCode())
                     .config(undoDeviceConfig)
                     .timeout(config.getShutDownInterval())
-                    .unit(TimeUnit.MINUTES)
+                    .unit(TimeUnit.DAYS)
                     .tenantId(source.getTenantId())
                     .timestamp(new Date())
                     .build();

+ 1 - 1
coffee-system/src/main/java/com/coffee/bus/hospital/config/bean/FunctionOtherConfig.java

@@ -17,7 +17,7 @@ import java.io.Serializable;
 @ApiModel("其他配置")
 public class FunctionOtherConfig implements Serializable {
     @ApiModelProperty("其他配置")
-    private FunctionExtraConfig other;
+    private FunctionExtraConfig extra;
     @ApiModelProperty("镇痛不足配置")
     private FunctionAnalConfig anal;
 }

+ 4 - 0
coffee-system/src/main/java/com/coffee/bus/mapper/BusPatientMapper.java

@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.coffee.bus.entity.BusPatientEntity;
 import com.coffee.bus.entity.PatientDeviceRepeatDomain;
+import com.coffee.bus.enums.PatientAlarmEnum;
 import com.coffee.bus.service.dto.PatientMonitorResult;
 import com.coffee.bus.service.dto.PatientDeviceNoneResult;
 import com.coffee.bus.service.dto.PatientMonitorQuery;
@@ -42,4 +43,7 @@ public interface BusPatientMapper extends BaseMapper<BusPatientEntity> {
     IPage<PatientMonitorResult> selectMonitor(IPage<PatientMonitorResult> page, @Param("query") PatientMonitorQuery query);
 
     PatientMonitorResult findByPatientCode(@Param("tenantId") String tenantId,@Param("patientCode")String patientCode);
+
+
+    long selectAlarmCount(@Param("tenantId") String tenantId,@Param("alarmValue") int alarmValue);
 }

+ 2 - 0
coffee-system/src/main/java/com/coffee/bus/registry/constant/DeviceKeyConstant.java

@@ -20,6 +20,8 @@ public class DeviceKeyConstant {
 
     public static final String START_TIME="startTime";
 
+    public static final String MODIFY_TIME="modifyTime";
+
     public static final String PATIENT_CODE="patientCode";
 
     public static final String STATUS="status";

+ 10 - 0
coffee-system/src/main/java/com/coffee/bus/registry/device/ClusterDeviceOperator.java

@@ -89,6 +89,16 @@ public class ClusterDeviceOperator implements DeviceOperator<DeviceCacheInfo> {
         return getValue(DeviceKeyConstant.START_TIME).asDate();
     }
 
+    @Override
+    public void setModifyTime(Date startTime) {
+        configStorage.setConfig(DeviceKeyConstant.MODIFY_TIME,startTime);
+    }
+
+    @Override
+    public Date getModifyTime() {
+        return getValue(DeviceKeyConstant.MODIFY_TIME).asDate();
+    }
+
     @Override
     public void setPatientCode(String patientCode) {
         configStorage.setConfig(DeviceKeyConstant.PATIENT_CODE,patientCode);

+ 12 - 0
coffee-system/src/main/java/com/coffee/bus/registry/device/DeviceOperator.java

@@ -90,6 +90,18 @@ public interface DeviceOperator<T> extends Operator<T> {
      */
     Date getStartTime();
 
+    /**
+     * 设置设备开机时间
+     * @param startTime
+     */
+    void setModifyTime(Date startTime);
+
+    /**
+     * 获取设备开机时间
+     * @return
+     */
+    Date getModifyTime();
+
     /**
      * 设置设备当前绑定泵号
      * @param patientCode

+ 1 - 1
coffee-system/src/main/java/com/coffee/bus/registry/patient/ClusterPatientRegistry.java

@@ -96,7 +96,6 @@ public class ClusterPatientRegistry implements PatientRegistry {
             patientOperator.setWard(clinic.getWard());
             patientOperator.setBedNo(clinic.getBedNo());
             patientOperator.setClinicId(clinic.getId());
-            patientOperator.setFinished(clinic.getFinished());
             //填充输注信息
             BusInfusionHistoryEntity recentInfusion = infusionService.recentInfusionByPatientCode(hospitalId, patientCode);
             if(recentInfusion!=null){
@@ -108,6 +107,7 @@ public class ClusterPatientRegistry implements PatientRegistry {
                     clinic.setFinished(true);
                 }
             }
+            patientOperator.setFinished(clinic.getFinished());
             //填充主副泵信息
             List<BusDeviceRunningEntity> runningList = deviceRunningService.list(new QueryWrapper<BusDeviceRunningEntity>().lambda().eq(BusDeviceRunningEntity::getPatientCode, patientCode).eq(BusDeviceRunningEntity::getTenantId, hospitalId));
             if (CollectionUtil.isNotEmpty(runningList)) {

+ 4 - 1
coffee-system/src/main/java/com/coffee/bus/script/PythonParse.java

@@ -1,6 +1,6 @@
 package com.coffee.bus.script;
 
-import cn.hutool.http.webservice.SoapUtil;
+import cn.hutool.core.util.StrUtil;
 import cn.hutool.json.JSON;
 import cn.hutool.json.JSONUtil;
 import lombok.extern.slf4j.Slf4j;
@@ -46,6 +46,9 @@ public class PythonParse implements ScriptParse {
 
     @Override
     public void reset(String script){
+        if(StrUtil.isEmpty(script)){
+            return;
+        }
         interpreter.exec(Py.newStringUTF8(script));
         pyFunction = interpreter.get(functionName(), PyFunction.class);
     }

+ 1 - 1
coffee-system/src/main/java/com/coffee/bus/service/LocalBusDeviceRunningService.java

@@ -96,7 +96,7 @@ public class LocalBusDeviceRunningService extends BaseService<BusDeviceRunningMa
         if(finishClinic){
             Map<String, List<ManualUndoConfig>> configsMap = undoConfigs.stream().collect(Collectors.groupingBy(ManualUndoConfig::getTenantId));
             configsMap.forEach((k,v)-> {
-                clinicService.finish(v.stream().map(ManualUndoConfig::getPatientCode).collect(Collectors.toList()),v.get(0).getUndo().getUndoTime() ,k);
+                clinicService.finish(v.stream().map(ManualUndoConfig::getClinicId).collect(Collectors.toList()),v.get(0).getUndo().getUndoTime() ,k);
             });
         }
     }

+ 134 - 0
coffee-system/src/main/java/com/coffee/bus/service/LocalBusHospitalConfigService.java

@@ -1,9 +1,19 @@
 package com.coffee.bus.service;
 
+import cn.hutool.json.JSONUtil;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.coffee.bus.entity.BusHospitalConfigEntity;
+import com.coffee.bus.enums.ConfigEnum;
+import com.coffee.bus.hospital.HospitalManagerRegister;
+import com.coffee.bus.hospital.config.bean.*;
 import com.coffee.bus.mapper.BusHospitalConfigMapper;
 import com.coffee.common.crud.BaseService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.Map;
 
 /**
  * @author lifang
@@ -14,6 +24,11 @@ import org.springframework.stereotype.Service;
  */
 @Service
 public class LocalBusHospitalConfigService extends BaseService<BusHospitalConfigMapper, BusHospitalConfigEntity,String> {
+    @Autowired
+    @Lazy
+    private HospitalManagerRegister managerRegister;
+
+
     @Override
     public void validateBeforeSave(BusHospitalConfigEntity entity) {
 
@@ -28,4 +43,123 @@ public class LocalBusHospitalConfigService extends BaseService<BusHospitalConfig
     public void validateBeforeDelete(String id) {
 
     }
+
+    @Override
+    public void postSave(BusHospitalConfigEntity entity) {
+        BusHospitalConfigEntity configEntity = this.getById(entity.getId());
+        managerRegister.refresh(configEntity.getTenantId(),false,true);
+    }
+
+    @Override
+    public void postUpdate(BusHospitalConfigEntity entity) {
+        BusHospitalConfigEntity configEntity = this.getById(entity.getId());
+        managerRegister.refresh(configEntity.getTenantId(),false,true);
+    }
+
+    /**
+     * 描述: 默认配置
+     * @author lifang
+     * @date 2022/5/20 11:23
+     * @param hospitalId
+     * @return void
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public void setDefaultConfig(String hospitalId, ConfigEnum type){
+        //找到默认医院的配置
+        BusHospitalConfigEntity defaultConfig = getDefaultConfig(type);
+        BusHospitalConfigEntity hospitalConfig = this.getOne(new QueryWrapper<BusHospitalConfigEntity>()
+                .lambda()
+                .eq(BusHospitalConfigEntity::getType, type)
+                .eq(BusHospitalConfigEntity::getTenantId, hospitalId));
+        BusHospitalConfigEntity saveOrUpdate = new BusHospitalConfigEntity();
+        if(hospitalConfig!=null){
+            saveOrUpdate.setId(hospitalConfig.getId());
+        };
+        saveOrUpdate.setConfig(defaultConfig.getConfig());
+        saveOrUpdate.setType(type);
+        saveOrUpdate.setTenantId(hospitalId);
+        this.saveOrUpdate(saveOrUpdate);
+    }
+
+
+    public void saveDefaultConfig(){
+        BusHospitalConfigEntity otherConfig = new BusHospitalConfigEntity();
+        otherConfig.setTenantId("1");
+        otherConfig.setType(ConfigEnum.other);
+        otherConfig.setConfig(getOtherDefault());
+
+        try {
+            this.save(otherConfig);
+        } catch (Exception e){
+        }
+
+        BusHospitalConfigEntity undoConfig = new BusHospitalConfigEntity();
+        undoConfig.setTenantId("1");
+        undoConfig.setType(ConfigEnum.undo);
+        undoConfig.setConfig(getUndoDefault());
+        try {
+            this.save(undoConfig);
+        } catch (Exception e){
+        }
+    }
+
+    public BusHospitalConfigEntity getDefaultConfig( ConfigEnum type){
+        return this.getOne(new QueryWrapper<BusHospitalConfigEntity>()
+                .lambda()
+                .eq(BusHospitalConfigEntity::getType,type)
+                .eq(BusHospitalConfigEntity::getTenantId, "1"));
+    }
+
+
+
+    private Map<String,Object> getOtherDefault(){
+        FunctionExtraConfig extraConfig=new FunctionExtraConfig();
+        //不在服务区默认10分钟
+        extraConfig.setLowInfusion(10);
+        //低输注时间默认30分钟
+        extraConfig.setNoSignal(30);
+
+
+        FunctionAnalConfig anal=new FunctionAnalConfig();
+
+        //镇痛消失时间默认120分钟
+        anal.setDisappearTime(120);
+        //镇痛不足判定次数3次
+        anal.setInsufficientCount(3);
+        //镇痛不足判定时间60分钟
+        anal.setInsufficientTime(60);
+        //镇痛不足判定类型 有效
+        anal.setValid(true);
+
+        FunctionOtherConfig result = new FunctionOtherConfig();
+        result.setExtra(extraConfig);
+        result.setAnal(anal);
+        return JSONUtil.parseObj(result);
+    }
+
+    private Map<String,Object> getUndoDefault(){
+        FunctionFinishMonitorConfig finishMonitorConfig = new FunctionFinishMonitorConfig();
+        finishMonitorConfig.setEnable(true);
+        //不在服务区到结束时间默认14天
+        finishMonitorConfig.setNoSignalInterval(14);
+        //关机到结束时间默认14天
+        finishMonitorConfig.setShutDownInterval(14);
+
+        FunctionAutoUndoConfig autoUndoConfig = new FunctionAutoUndoConfig();
+        autoUndoConfig.setEnable(true);
+        autoUndoConfig.setUndoByType(true);
+        //不在服务区到撤泵时间 默认60分钟
+        autoUndoConfig.setNoSignalInterval(60);
+        //关机到撤泵时间 默认60分钟
+        autoUndoConfig.setShutDownInterval(60);
+
+        FunctionManualUndoConfig manualUndoConfig = new FunctionManualUndoConfig();
+        manualUndoConfig.setEnable(false);
+
+        FunctionUndoConfig result = new FunctionUndoConfig();
+        result.setAuto(autoUndoConfig);
+        result.setFinishMonitor(finishMonitorConfig);
+        result.setManual(manualUndoConfig);
+        return JSONUtil.parseObj(result);
+    }
 }

+ 32 - 9
coffee-system/src/main/java/com/coffee/bus/service/LocalBusHospitalService.java

@@ -6,13 +6,12 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.toolkit.IdWorker;
 import com.coffee.bus.bean.GeoPoint;
 import com.coffee.bus.entity.BusHospitalEntity;
-import com.coffee.bus.hospital.HospitalManager;
 import com.coffee.bus.hospital.HospitalManagerRegister;
-import com.coffee.bus.hospital.his.HisScriptSession;
-import com.coffee.bus.hospital.his.HisScriptSessionManager;
 import com.coffee.bus.hospital.his.strategy.HisStrategyEnum;
 import com.coffee.bus.mapper.BusHospitalMapper;
 import com.coffee.bus.utils.CodeUtils;
+import com.coffee.common.cache.ConfigStorage;
+import com.coffee.common.cache.manager.ConfigStorageManager;
 import com.coffee.common.config.mybatis.GetNameInterface;
 import com.coffee.common.crud.BaseService;
 import com.coffee.common.exception.CustomException;
@@ -20,7 +19,9 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.CommandLineRunner;
 import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Service;
-import java.util.Optional;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
 
 /**
  * @author lifang
@@ -31,9 +32,23 @@ import java.util.Optional;
  */
 @Service
 public class LocalBusHospitalService extends BaseService<BusHospitalMapper, BusHospitalEntity,String> implements CommandLineRunner, GetNameInterface<String,String> {
+    @Autowired
+    @Lazy
+    private ConfigStorageManager configStorageManager;
+
+    private ConfigStorage configStorage;
+
     @Autowired
     @Lazy
     private HospitalManagerRegister hospitalManagerRegister;
+    @Autowired
+    @Lazy
+    private LocalBusHospitalConfigService configService;
+    @PostConstruct
+    public void init(){
+        configStorage=configStorageManager.getStorage("hospital_name");
+    }
+
     @Override
     public void validateBeforeSave(BusHospitalEntity entity) {
         long id = IdWorker.getId();
@@ -73,12 +88,15 @@ public class LocalBusHospitalService extends BaseService<BusHospitalMapper, BusH
 
     @Override
     public void postSave(BusHospitalEntity entity) {
-
+        configStorage.setConfig(entity.getId(),entity.getName());
     }
 
     @Override
     public void postUpdate(BusHospitalEntity entity) {
         hospitalManagerRegister.refresh(entity.getId(),true,null!=entity.getScript());
+        if(StrUtil.isNotEmpty(entity.getName())){
+            configStorage.setConfig(entity.getId(),entity.getName());
+        }
     }
 
     @Override
@@ -89,15 +107,18 @@ public class LocalBusHospitalService extends BaseService<BusHospitalMapper, BusH
     @Override
     public void run(String... args) {
         saveDefaultHospital();
+        List<BusHospitalEntity> list = list();
+        list.forEach(entity -> {
+            configStorage.setConfig(entity.getId(),entity.getName());
+        });
+        configService.saveDefaultConfig();
+
     }
 
 
     @Override
     public String getName(String id) {
-        if(StrUtil.isAllBlank(id)){
-            return "";
-        }
-        return Optional.ofNullable(hospitalManagerRegister.get(id).getInfo()).orElse(new BusHospitalEntity()).getName();
+        return configStorage.getConfig(id).asString();
     }
 
 
@@ -117,6 +138,8 @@ public class LocalBusHospitalService extends BaseService<BusHospitalMapper, BusH
         }
     }
 
+
+
     /**
      * 描述: 医院名称是否有效
      * @author lifang

+ 18 - 0
coffee-system/src/main/java/com/coffee/bus/service/LocalBusPatientService.java

@@ -2,9 +2,11 @@ package com.coffee.bus.service;
 
 import cn.hutool.core.collection.CollectionUtil;
 import cn.hutool.core.date.LocalDateTimeUtil;
+import com.baomidou.mybatisplus.core.conditions.Wrapper;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import cn.hutool.core.util.StrUtil;
 import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.coffee.bus.entity.BusClinicEntity;
 import com.coffee.bus.entity.BusPatientEntity;
@@ -107,6 +109,22 @@ public class LocalBusPatientService extends BaseService<BusPatientMapper, BusPat
         return sync?hisScriptSession.syncGetPatientInfo(patientCode,timeout,TimeUnit.SECONDS):hisScriptSession.asyncGetPatientInfo(patientCode,timeout,TimeUnit.SECONDS,true);
     }
 
+    /**
+     * 描述: 对病人报警数量进行统计
+     * @author lifang
+     * @date 2022/5/20 16:42
+     * @param tenantId
+     * @param alarm
+     * @return long
+     */
+    public long patientAlarmCount(String tenantId,PatientAlarmEnum alarm){
+        return this.baseMapper.selectAlarmCount(tenantId,alarm.getValue());
+    }
+
+    public long patientAlarmCount(PatientAlarmEnum alarm){
+        return patientAlarmCount(null,alarm);
+    }
+
     /**
      * 获取给定医院下所有的挂载多个设备的病人信息
      *

+ 3 - 1
coffee-system/src/main/java/com/coffee/bus/service/dto/ManualUndoConfig.java

@@ -25,6 +25,7 @@ import java.util.*;
 public class ManualUndoConfig implements Serializable {
 
     @ApiModelProperty("进行撤泵的所有运行数据id")
+    @NotNull(message = "撤泵泵号不能为空")
     private List<String> deviceIds;
 
     @ApiModelProperty("撤泵病号")
@@ -34,7 +35,8 @@ public class ManualUndoConfig implements Serializable {
     @JsonIgnore
     private String clinicId;
 
-    @ApiModelProperty("医院id")
+    @ApiModelProperty(value = "医院id",hidden = true)
+    @JsonIgnore
     private String tenantId;
 
     @ApiModelProperty("是否为有泵监护,0、无泵 1、有泵")

+ 9 - 9
coffee-system/src/main/java/com/coffee/bus/utils/WsPublishUtils.java

@@ -1,6 +1,7 @@
 package com.coffee.bus.utils;
 
 
+import cn.hutool.core.collection.CollectionUtil;
 import cn.hutool.core.util.ObjectUtil;
 import cn.hutool.json.JSONObject;
 import com.alibaba.fastjson.serializer.JSONObjectCodec;
@@ -62,10 +63,12 @@ public class WsPublishUtils implements Serializable{
     public void publishPatientMonitor(String patientCode,String tenantId){
         Assert.hasText(tenantId,"医院id不能为空");
         PatientMonitorResult message = patientService.lookMonitorByPatientCode(patientCode, tenantId);
-        message.handleWarn();
-        this.publish(WebSocketConstant.getPatientMonitor(null, patientCode, tenantId).getTopic(),
-                TopicMessage.of(message,patientCode)
-        );
+        if(message!=null){
+            message.handleWarn();
+            this.publish(WebSocketConstant.getPatientMonitor(null, patientCode, tenantId).getTopic(),
+                    TopicMessage.of(message,patientCode)
+            );
+        }
     }
 
     /**
@@ -108,8 +111,7 @@ public class WsPublishUtils implements Serializable{
     @Async
     public void publishDeviceRepeat(String tenantId){
         Assert.hasText(tenantId,"医院id不能为空");
-        JSONObject message = new JSONObject().putOpt("count", patientService.count(new QueryWrapper<BusPatientEntity>().lambda().eq(BusPatientEntity::getTenantId, tenantId)
-                .eq(BusPatientEntity::getAlarm, PatientAlarmEnum.DEVICE_REPEAT)));
+        JSONObject message = new JSONObject().putOpt("count", patientService.patientAlarmCount(tenantId,PatientAlarmEnum.DEVICE_REPEAT));
         this.publish(WebSocketConstant.getDeviceRepeat(tenantId).getTopic(),
                 TopicMessage.of(message,tenantId)
         );
@@ -125,9 +127,7 @@ public class WsPublishUtils implements Serializable{
     @Async
     public void publishDeviceNone(String tenantId){
         Assert.hasText(tenantId,"医院id不能为空");
-        JSONObject message = new JSONObject().putOpt("count", patientService.count(new QueryWrapper<BusPatientEntity>()
-                .lambda().eq(BusPatientEntity::getTenantId, tenantId)
-                .eq(BusPatientEntity::getAlarm, PatientAlarmEnum.DEVICE_NONE)));
+        JSONObject message = new JSONObject().putOpt("count",patientService.patientAlarmCount(tenantId,PatientAlarmEnum.NONE));
         this.publish(WebSocketConstant.getDeviceNone(tenantId).getTopic(),
                 TopicMessage.of(message,tenantId)
         );

+ 2 - 2
coffee-system/src/main/java/com/coffee/bus/websocket/WebSocketCloseHandler.java

@@ -24,8 +24,8 @@ public class WebSocketCloseHandler extends Subscribe {
     @Override
     public void close(ChannelContext channelContext) {
         //关闭则取消订阅
-        Map<String, DefaultMessageListener> topicListeners = getTopicListeners(channelContext);
-        topicListeners.forEach((topic,listener)->this.unsubscribe(channelContext,topic));
+//        Map<String, DefaultMessageListener> topicListeners = getTopicListeners(channelContext);
+//        topicListeners.forEach((topic,listener)->this.unsubscribe(channelContext,topic));
     }
 
     @Override

+ 57 - 49
coffee-system/src/main/java/com/coffee/bus/websocket/listener/DeviceInfoListener.java

@@ -116,7 +116,7 @@ public class DeviceInfoListener {
             boolean first = handleRunningInfo(device, deviceOperator,cacheOperation);
 
             //医院相关配置处理
-            handleHospitalConfig(device,cacheOperation);
+//            handleHospitalConfig(device,cacheOperation);
 
             //处理输注参数
             handleInfusion(device, deviceOperator, cacheOperation);
@@ -144,8 +144,10 @@ public class DeviceInfoListener {
             }
 
             cacheOperation.add(()->{
-                wsPublishUtils.publishPatientMonitor(device.getPatientCode(),device.getTenantId());
-                wsPublishUtils.publishMonitorStateCount(device.getTenantId());
+                if (Boolean.TRUE.equals(device.getMaster())) {
+                    wsPublishUtils.publishPatientMonitor(device.getPatientCode(),device.getTenantId());
+                    wsPublishUtils.publishMonitorStateCount(device.getTenantId());
+                }
                 return null;
             });
 
@@ -183,7 +185,6 @@ public class DeviceInfoListener {
             //设备首次运行,记录开机时间
             device.setId(String.valueOf(IdWorker.getId()));
             device.setStartTime(device.getUploadTime());
-            device.setAlias(deviceOperator.getAlias());
             first=true;
         }else {
             device.setId(usingId);
@@ -197,7 +198,6 @@ public class DeviceInfoListener {
                 deviceOperator.setUndo(false);
             }
             deviceOperator.setClassification(device.getClassification());
-
             deviceOperator.setTenantId(device.getTenantId());
             deviceOperator.setUsingId(device.getId());
             deviceOperator.setStatus(device.getRunState());
@@ -222,11 +222,11 @@ public class DeviceInfoListener {
         //当前病号所绑定的泵发生了改变,对当前病号进行处理
         if(StrUtil.isNullOrUndefined(bindDeviceId)){
             //当前的病号之前为无泵状态,无泵 -》 有泵 做处理  修改缓存信息
-            log.error("病号:【{}】临床发生由无泵转为有泵",device.getPatientCode());
+            log.warn("病号:【{}】临床发生由无泵转为有泵",device.getPatientCode());
             patientService.update(new UpdateWrapper<BusPatientEntity>().lambda().eq(BusPatientEntity::getCode,device.getPatientCode())
                     .eq(BusPatientEntity::getTenantId,device.getTenantId())
                     .set(device.isNewInfusion(),BusPatientEntity::getInfusionId,device.getInfusionId())
-                    .set(BusPatientEntity::getAlarm, null)
+                    .set(BusPatientEntity::getAlarm, PatientAlarmEnum.NONE)
             );
             suppliers.add(()->{
                 wsPublishUtils.publishDeviceNone(device.getTenantId());
@@ -234,11 +234,8 @@ public class DeviceInfoListener {
             });
         }else if(ObjectUtil.notEqual(deviceId,bindDeviceId)){
             handleConflictCurrentPatient(device,suppliers);
-            suppliers.add(()->{
-                wsPublishUtils.publishDeviceRepeat(device.getTenantId());
-                return null;
-            });
         }else {
+            //主泵未发生变化,只修改绑定的输注信息
             if(device.isNewInfusion()){
                 patientService.update(new UpdateWrapper<BusPatientEntity>().lambda().eq(BusPatientEntity::getCode,device.getPatientCode())
                         .eq(BusPatientEntity::getTenantId,device.getTenantId())
@@ -343,14 +340,15 @@ public class DeviceInfoListener {
         if(ObjectUtil.notEqual(deviceId,bindDeviceId)){
             //泵号发生改变,获取病号绑定的泵信息,判断绑定的泵开始时间,将开始时间稍后的泵设置为主泵
             DeviceOperator<DeviceCacheInfo> patientCurrentBindDevice = deviceRegistry.getOperator(bindDeviceId);
-            Date startTime = patientCurrentBindDevice.getStartTime();
-            if (startTime==null||startTime.before(device.getStartTime())) {
+            Date modifyTime = patientCurrentBindDevice.getModifyTime();
+            if (modifyTime==null||modifyTime.before(device.getModifyTime())) {
                 log.warn("病号:[{}],之前主泵为:[{}],现在主泵为:[{}]",device.getPatientCode(),bindDeviceId,deviceId);
                 //设置当前上传信息的泵为主泵,将旧泵设置为副泵,并更新病人绑定泵的消息
                 device.setMaster(true);
                 deviceRunningService.update(new UpdateWrapper<BusDeviceRunningEntity>()
                         .lambda()
-                        .eq(BusDeviceRunningEntity::getDeviceId,bindDeviceId)
+                        .eq(BusDeviceRunningEntity::getPatientCode,device.getPatientCode())
+                        .eq(BusDeviceRunningEntity::getTenantId,device.getTenantId())
                         .set(BusDeviceRunningEntity::getMaster,false));
             }else {
                 device.setMaster(false);
@@ -361,6 +359,10 @@ public class DeviceInfoListener {
                     .eq(BusPatientEntity::getTenantId,device.getTenantId())
                     .set(Boolean.TRUE.equals(device.getMaster()),BusPatientEntity::getInfusionId,device.getInfusionId())
                     .set(BusPatientEntity::getAlarm,PatientAlarmEnum.DEVICE_REPEAT));
+            suppliers.add(()->{
+                wsPublishUtils.publishDeviceRepeat(device.getTenantId());
+                return null;
+            });
         }
     }
 
@@ -400,8 +402,8 @@ public class DeviceInfoListener {
      * @param cacheOperation 缓存操作
      */
     private BusInfusionHistoryEntity handleInfusion(BusDeviceRunningEntity device, DeviceOperator<DeviceCacheInfo> deviceOperator, List<Supplier<?>> cacheOperation) {
-        PatientOperator<PatientCacheInfo> operator = patientRegistry.getOperator(device.getTenantId(), device.getPatientCode(),MapUtil.of("startTime", device.getStartTime()));
-        device.setClinicId(operator.getClinicId());
+        PatientOperator<PatientCacheInfo> patientOperator = patientRegistry.getOperator(device.getTenantId(), device.getPatientCode(),MapUtil.of("startTime", device.getStartTime()));
+        device.setClinicId(patientOperator.getClinicId());
 
         BusInfusionHistoryEntity infusionHistory = handleInfusionHistory(device, deviceOperator, cacheOperation);
         BusInfusionModifyEntity busInfusionModify = BusInfusionModifyEntity.parseRunningInfo(device);
@@ -412,33 +414,36 @@ public class DeviceInfoListener {
         if(ObjectUtil.notEqual(signHex,infusionParam)){
             infusionModifyService.save(busInfusionModify);
             device.setInfusionModifyId(busInfusionModify.getId());
+            device.setModifyTime(busInfusionModify.getUpdateTime());
             //参数发生变化后,进行判断
-            PatientOperator<PatientCacheInfo> patientOperator = patientRegistry.getOperator(device.getTenantId(),device.getPatientCode());
-
             if(Boolean.TRUE.equals(patientOperator.getFinished())){
                 //若临床已结束,则只有新的输注能够进行泵冲突处理
                 if(device.isNewInfusion()){
                     handlePatient(device,cacheOperation);
-                    clinicService
-                            .update(new UpdateWrapper<BusClinicEntity>().lambda().eq(BusClinicEntity::getId,patientOperator.getClinicId())
-                                    .set(BusClinicEntity::getFinished,false));
-                    cacheOperation.add(()->{
-                        //重启临床
-                        patientOperator.setFinished(false);
-                        return null;
-                    });
                 }
-            }else {
+                clinicService
+                        .update(new UpdateWrapper<BusClinicEntity>().lambda().eq(BusClinicEntity::getId,patientOperator.getClinicId())
+                                .set(BusClinicEntity::getFinished,false));
+                cacheOperation.add(()->{
+                    //重启临床
+                    patientOperator.setFinished(false);
+                    wsPublishUtils.publishMonitorTotalCount(device.getTenantId());
+                    return null;
+                });
+            } else {
                 handlePatient(device,cacheOperation);
             }
             cacheOperation.add(()->{
                 deviceOperator.setInfusionParam(signHex);
+                deviceOperator.setModifyTime(device.getUploadTime());
                 return null;
             });
         }else {
-            String bindDeviceId = operator.getBindDeviceId();
+            String bindDeviceId = patientOperator.getBindDeviceId();
             if (device.getDeviceId().equals(bindDeviceId)) {
                 device.setMaster(true);
+            }else {
+                device.setMaster(false);
             }
             //填充当前参数修改记录id
             BusInfusionModifyEntity modify = infusionModifyService.getOne(new QueryWrapper<BusInfusionModifyEntity>().lambda()
@@ -488,28 +493,31 @@ public class DeviceInfoListener {
             if(StrUtil.isBlank(lastAlarmSign)||!alarmSign.equals(lastAlarmSign)){
                 //报警及提示发生变化,判断具体变化是由报警引起还是由提示引起
                 BusDeviceRunningEntity lastRunning = deviceRunningService.getOne(new QueryWrapper<BusDeviceRunningEntity>().lambda().eq(BusDeviceRunningEntity::getDeviceId, history.getDeviceId()));
+
                 int change=5;
-                //防止重复插入
-                if(ObjectUtil.equal(lastRunning.getAlarm(),history.getAlarm())){
-                    alarm.setAlarm(false);
-                    alarm.setAlarmState(null);
-                    --change;
-                }
-                if (ObjectUtil.equal(lastRunning.getWarnAnalgesicPoor(), history.getWarnAnalgesicPoor())) {
-                    alarm.setWarnAnalgesicPoor(false);
-                    --change;
-                }
-                if (ObjectUtil.equal(lastRunning.getWarnFlow(), history.getWarnFlow())) {
-                    alarm.setWarnFlow(null);
-                    --change;
-                }
-                if (ObjectUtil.equal(lastRunning.getWarnLowBattery(), history.getWarnLowBattery())) {
-                    alarm.setWarnLowBattery(false);
-                    --change;
-                }
-                if (ObjectUtil.equal(lastRunning.getWarnWillFinished(), history.getWarnWillFinished())) {
-                    alarm.setWarnWillFinished(false);
-                    --change;
+                if(ObjectUtil.isNotNull(lastRunning)){
+                    //防止重复插入
+                    if(ObjectUtil.equal(lastRunning.getAlarm(),history.getAlarm())){
+                        alarm.setAlarm(false);
+                        alarm.setAlarmState(null);
+                        --change;
+                    }
+                    if (ObjectUtil.equal(lastRunning.getWarnAnalgesicPoor(), history.getWarnAnalgesicPoor())) {
+                        alarm.setWarnAnalgesicPoor(false);
+                        --change;
+                    }
+                    if (ObjectUtil.equal(lastRunning.getWarnFlow(), history.getWarnFlow())) {
+                        alarm.setWarnFlow(null);
+                        --change;
+                    }
+                    if (ObjectUtil.equal(lastRunning.getWarnLowBattery(), history.getWarnLowBattery())) {
+                        alarm.setWarnLowBattery(false);
+                        --change;
+                    }
+                    if (ObjectUtil.equal(lastRunning.getWarnWillFinished(), history.getWarnWillFinished())) {
+                        alarm.setWarnWillFinished(false);
+                        --change;
+                    }
                 }
                 if(change!=0){
                     alarmService.save(alarm);

+ 372 - 354
coffee-system/src/main/resources/mapper/bus/BusPatientMapper.xml

@@ -1,371 +1,389 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="com.coffee.bus.mapper.BusPatientMapper">
+    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+    <mapper namespace="com.coffee.bus.mapper.BusPatientMapper">
 
-    <resultMap id="repeatDeviceResult" type="com.coffee.bus.entity.PatientDeviceRepeatDomain">
-        <result column="name" property="name"/>
-        <result column="gender" property="gender"/>
-        <result column="code" property="code"/>
-        <result column="age" property="age"/>
-        <result column="ward" property="ward"/>
-        <result column="bed_no" property="bedNo"/>
-        <result column="clinic_name" property="clinicName"/>
-        <result column="device_running_id" property="deviceRunningId"/>
-        <result column="device_id" property="deviceId"/>
-        <result column="device_alias" property="deviceAlias"/>
-        <result column="device_run_state" property="deviceRunState"/>
-        <result column="clinic_id" property="clinicId"/>
-        <result column="device_alarm" property="deviceAlarm" />
-        <result column="infusion_start_time" property="infusionStartTime"/>
-        <result column="master" property="master"/>
-    </resultMap>
+        <resultMap id="repeatDeviceResult" type="com.coffee.bus.entity.PatientDeviceRepeatDomain">
+            <result column="name" property="name"/>
+            <result column="gender" property="gender"/>
+            <result column="code" property="code"/>
+            <result column="age" property="age"/>
+            <result column="ward" property="ward"/>
+            <result column="bed_no" property="bedNo"/>
+            <result column="clinic_name" property="clinicName"/>
+            <result column="device_running_id" property="deviceRunningId"/>
+            <result column="device_id" property="deviceId"/>
+            <result column="device_alias" property="deviceAlias"/>
+            <result column="device_run_state" property="deviceRunState"/>
+            <result column="clinic_id" property="clinicId"/>
+            <result column="device_alarm" property="deviceAlarm" />
+            <result column="infusion_start_time" property="infusionStartTime"/>
+            <result column="master" property="master"/>
+        </resultMap>
 
-    <resultMap id="monitorResult" type="com.coffee.bus.service.dto.PatientMonitorResult">
-        <result column="patient_name" property="patientName"/>
-        <result column="patient_code" property="patientCode"/>
-        <result column="patient_age" property="patientAge"/>
-        <result column="gender" property="gender"/>
-        <result column="infusion_id" property="infusionId"/>
-        <result column="patient_alarm" property="patientAlarm"/>
-        <result column="device_id" property="deviceId"/>
-        <result column="device_alias" property="deviceAlias"/>
-        <result column="clinic_id" property="clinicId"/>
-        <result column="infusion_finished" property="infusionFinished"/>
-        <result column="ward" property="ward"/>
-        <result column="bed_no" property="bedNo"/>
-        <result column="total_dose" property="totalDose"/>
-        <result column="first_dose" property="firstDose"/>
-        <result column="remain_dose" property="remainDose"/>
-        <result column="input_dose" property="inputDose"/>
-        <result column="append_dose" property="appendDose"/>
-        <result column="append_lock_time" property="appendLockTime"/>
-        <result column="max_dose" property="maxDose"/>
-        <result column="self_control_count" property="selfControlCount"/>
-        <result column="self_control_lock_time" property="selfControlLockTime"/>
-        <result column="pca_valid_count" property="pcaValidCount"/>
-        <result column="pca_invalid_count" property="pcaInvalidCount"/>
-        <result column="pca_total_count" property="pcaTotalCount"/>
-        <result column="continue_dose" property="continueDose"/>
-        <result column="pulse_dose" property="pulseDose"/>
-        <result column="pulse_first_lock_time" property="pulseFirstLockTime"/>
-        <result column="pulse_lock_time" property="pulseLockTime"/>
-        <result column="flow_up_cycle" property="flowUpCycle"/>
-        <result column="flow_down_cycle" property="flowDownCycle"/>
-        <result column="flow_count" property="flowCount"/>
-        <result column="flow_up_limit" property="flowUpLimit"/>
-        <result column="flow_down_limit" property="flowDownLimit"/>
-        <result column="flow_adjust_rate" property="flowAdjustRate"/>
-        <result column="run_state" property="deviceRunState"/>
-        <result column="electric_quantity" property="electricQuantity"/>
-        <result column="warn_flow" property="warnFlow"/>
-        <result column="warn_analgesic_poor" property="warnAnalgesicPoor"/>
-        <result column="warn_low_battery" property="warnLowBattery"/>
-        <result column="warn_will_finished" property="warnWillFinished"/>
-        <result column="device_alarm" property="deviceAlarm"/>
-        <result column="infusion_start_time" property="infusionStartTime"/>
-        <result column="remark" property="remark"/>
-        <result column="device_type" property="deviceType"/>
-        <result column="anal_type" property="analType"/>
-        <result column="ana_doctor" property="anaDoctor"/>
-        <result column="ana_type" property="anaType"/>
-        <result column="surgery_doctor" property="surgeryDoctor"/>
-        <result column="surgery_name" property="surgeryName"/>
-        <result column="finished" property="clinicFinished"/>
-        <result column="monitor_end_time" property="monitorEndTime"/>
-        <result column="monitor_start_time" property="monitorStartTime"/>
-    </resultMap>
+        <resultMap id="monitorResult" type="com.coffee.bus.service.dto.PatientMonitorResult">
+            <result column="patient_name" property="patientName"/>
+            <result column="patient_code" property="patientCode"/>
+            <result column="patient_age" property="patientAge"/>
+            <result column="gender" property="gender"/>
+            <result column="infusion_id" property="infusionId"/>
+            <result column="patient_alarm" property="patientAlarm"/>
+            <result column="device_id" property="deviceId"/>
+            <result column="device_alias" property="deviceAlias"/>
+            <result column="clinic_id" property="clinicId"/>
+            <result column="infusion_finished" property="infusionFinished"/>
+            <result column="ward" property="ward"/>
+            <result column="bed_no" property="bedNo"/>
+            <result column="total_dose" property="totalDose"/>
+            <result column="first_dose" property="firstDose"/>
+            <result column="remain_dose" property="remainDose"/>
+            <result column="input_dose" property="inputDose"/>
+            <result column="append_dose" property="appendDose"/>
+            <result column="append_lock_time" property="appendLockTime"/>
+            <result column="max_dose" property="maxDose"/>
+            <result column="self_control_count" property="selfControlCount"/>
+            <result column="self_control_lock_time" property="selfControlLockTime"/>
+            <result column="pca_valid_count" property="pcaValidCount"/>
+            <result column="pca_invalid_count" property="pcaInvalidCount"/>
+            <result column="pca_total_count" property="pcaTotalCount"/>
+            <result column="continue_dose" property="continueDose"/>
+            <result column="pulse_dose" property="pulseDose"/>
+            <result column="pulse_first_lock_time" property="pulseFirstLockTime"/>
+            <result column="pulse_lock_time" property="pulseLockTime"/>
+            <result column="flow_up_cycle" property="flowUpCycle"/>
+            <result column="flow_down_cycle" property="flowDownCycle"/>
+            <result column="flow_count" property="flowCount"/>
+            <result column="flow_up_limit" property="flowUpLimit"/>
+            <result column="flow_down_limit" property="flowDownLimit"/>
+            <result column="flow_adjust_rate" property="flowAdjustRate"/>
+            <result column="run_state" property="deviceRunState"/>
+            <result column="electric_quantity" property="electricQuantity"/>
+            <result column="warn_flow" property="warnFlow"/>
+            <result column="warn_analgesic_poor" property="warnAnalgesicPoor"/>
+            <result column="warn_low_battery" property="warnLowBattery"/>
+            <result column="warn_will_finished" property="warnWillFinished"/>
+            <result column="device_alarm" property="deviceAlarm"/>
+            <result column="infusion_start_time" property="infusionStartTime"/>
+            <result column="remark" property="remark"/>
+            <result column="device_type" property="deviceType"/>
+            <result column="anal_type" property="analType"/>
+            <result column="ana_doctor" property="anaDoctor"/>
+            <result column="ana_type" property="anaType"/>
+            <result column="surgery_doctor" property="surgeryDoctor"/>
+            <result column="surgery_name" property="surgeryName"/>
+            <result column="finished" property="clinicFinished"/>
+            <result column="monitor_end_time" property="monitorEndTime"/>
+            <result column="monitor_start_time" property="monitorStartTime"/>
+        </resultMap>
 
-    <resultMap id="deviceNone" type="com.coffee.bus.service.dto.PatientDeviceNoneResult">
-        <result column="clinic_id" property="clinicId"/>
-        <result column="name" property="name"/>
-        <result column="gender" property="gender"/>
-        <result column="code" property="code"/>
-        <result column="age" property="age"/>
-        <result column="ward" property="ward"/>
-        <result column="bed_no" property="bedNo"/>
-        <result column="clinic_name" property="clinicName"/>
-        <result column="weight" property="weight"/>
-        <result column="height" property="height"/>
-        <result column="ana_doctor" property="anaDoctor"/>
-        <result column="ana_type" property="anaType"/>
-        <result column="anal_type" property="analType"/>
-        <result column="surgery_doctor" property="surgeryDoctor"/>
-        <result column="asa" property="asa"/>
-        <result column="formula" property="formula"/>
-        <result column="finished" property="finished"/>
-        <result column="config_person" property="configPerson"/>
-    </resultMap>
-    <select id="selectRepeatDevice" resultMap="repeatDeviceResult">
-                 SELECT
-         p.code as code,
-         c.patient_gender  as gender,
-         c.`patient_name` as name,
-         c.patient_age as age,
-         c.ward,
-         c.bed_no,
-         c.id as clinic_id,
-         c.`name` as clinic_name,
-         d.id as device_running_id,
-         d.device_id as device_id,
-         d.alias as device_alias,
-         d.run_state as device_run_state,
-         d.alarm as device_alarm,
-         d.start_time as infusion_start_time,
-         d.master
-        FROM (SELECT `name`,gender,CODE FROM bus_patient WHERE bus_patient.`alarm`=1) AS p
-        left join (SELECT * from bus_device_running where monitor_type=1 ) as d on p.CODE=d.patient_code
-        left join  (SELECT * FROM bus_clinic WHERE finished=0 ) AS c ON  c.`patient_code`=p.code;
-    </select>
-    <select id="selectNoneDevice" resultMap="deviceNone">
-        SELECT
-         p.code as code,
-         c.id as clinic_id,
-         c.patient_gender as gender,
-         c.`patient_name` as name,
-         c.patient_age as age,
-         c.ward as ward,
-         c.bed_no as bed_no,
-         c.`name` as clinic_name,
-         c.weight as weight,
-         c.height as height,
-         c.ana_doctor as ana_doctor,
-         c.ana_type as ana_type,
-         c.anal_type as anal_type,
-         c.surgery_doctor as surgery_doctor,
-         c.asa as asa,
-         c.formula as formula,
-         c.finished as finished,
-         c.monitor_start_time as monitor_start_time,
-         c.config_person as config_person
-        FROM (SELECT `name`,gender,CODE,tenant_id FROM bus_patient WHERE bus_patient.`alarm`=2 ) AS p
-        left join  (SELECT * FROM bus_clinic WHERE finished=0 ) AS c ON  c.`patient_code`=p.code
-        order by c.monitor_start_time desc;
-    </select>
+        <resultMap id="deviceNone" type="com.coffee.bus.service.dto.PatientDeviceNoneResult">
+            <result column="clinic_id" property="clinicId"/>
+            <result column="name" property="name"/>
+            <result column="gender" property="gender"/>
+            <result column="code" property="code"/>
+            <result column="age" property="age"/>
+            <result column="ward" property="ward"/>
+            <result column="bed_no" property="bedNo"/>
+            <result column="clinic_name" property="clinicName"/>
+            <result column="weight" property="weight"/>
+            <result column="height" property="height"/>
+            <result column="ana_doctor" property="anaDoctor"/>
+            <result column="ana_type" property="anaType"/>
+            <result column="anal_type" property="analType"/>
+            <result column="surgery_doctor" property="surgeryDoctor"/>
+            <result column="asa" property="asa"/>
+            <result column="formula" property="formula"/>
+            <result column="finished" property="finished"/>
+            <result column="config_person" property="configPerson"/>
+        </resultMap>
+        <select id="selectRepeatDevice" resultMap="repeatDeviceResult">
+                     SELECT
+             p.code as code,
+             c.patient_gender  as gender,
+             c.`patient_name` as name,
+             c.patient_age as age,
+             c.ward,
+             c.bed_no,
+             c.id as clinic_id,
+             c.`name` as clinic_name,
+             r.id as device_running_id,
+             r.device_id as device_id,
+             d.alias as device_alias,
+             r.run_state as device_run_state,
+             r.alarm as device_alarm,
+             r.start_time as infusion_start_time,
+             r.master
+            FROM (SELECT `name`,gender,CODE FROM bus_patient WHERE bus_patient.`alarm`=1) AS p
+            join (SELECT * from bus_device_running where monitor_type=1 ) as r on p.CODE=r.patient_code
+            join (select device_id,alias from bus_device) as d on d.device_id=r.device_id
+            join  (SELECT * FROM bus_clinic WHERE finished=0 ) AS c ON  c.`patient_code`=p.code;
+        </select>
 
-    <select id="selectMonitor" resultMap="monitorResult" parameterType="com.coffee.bus.service.dto.PatientMonitorQuery">
-        select
-        p.`code` as patient_code,
-        p.alarm as patient_alarm,
-        i.id as infusion_id,
-        i.device_id as device_id,
-        i.clinic_id as clinic_id,
-        i.ward as ward,
-        i.bed_no as bed_no,
-        i.total_dose as total_dose,
-        i.first_dose as first_dose,
-        i.remain_dose as remain_dose,
-        i.input_dose as input_dose,
-        i.append_dose as append_dose,
-        i.append_lock_time as append_lock_time,
-        i.max_dose as max_dose,
-        i.finished as infusion_finished,
-        i.electric_quantity as electric_quantity,
-        i.warn_flow as warn_flow,
-        i.self_control_count as self_control_count,
-        i.self_control_lock_time as self_control_lock_time,
-        i.pca_valid_count as pca_valid_count,
-        i.pca_invalid_count as pca_invalid_count,
-        i.pca_total_count as pca_total_count,
-        i.continue_dose as continue_dose,
-        i.pulse_dose as pulse_dose,
-        i.pulse_lock_time as pulse_lock_time,
-        i.pulse_first_lock_time as pulse_first_lock_time,
-        i.flow_up_cycle as flow_up_cycle,
-        i.flow_down_cycle as flow_down_cycle,
-        i.flow_count as flow_count,
-        i.flow_up_limit as flow_up_limit,
-        i.flow_down_limit as flow_down_limit,
-        i.flow_adjust_rate as flow_adjust_rate,
-        i.run_state as run_state,
-        i.warn_will_finished as warn_will_finished,
-        i.warn_analgesic_poor as warn_analgesic_poor,
-        i.warn_low_battery as warn_low_battery,
-        i.alarm as device_alarm,
-        i.start_time as infusion_start_time,
-        i.remark as remark,
-        i.type as device_type,
-        r.alias as device_alias,
-        c.patient_gender as patient_gender,
-        c.`patient_name` as patient_name,
-        c.finished as finished,
-        c.monitor_start_time as monitor_start_time,
-        c.end_time as monitor_end_time,
-        c.ana_doctor as ana_doctor,
-        c.patient_age as patient_age,
-        c.ana_type as ana_type,
-        c.anal_type as anal_type,
-        c.surgery_doctor as surgery_doctor,
-        c.surgery_name as surgery_name
-        from
-        (select * from bus_patient
-        <where>
-            <if test="query.tenantId!=null">
-                and tenant_id=#{query.tenantId}
-            </if>
-        </where>
-        )
-        as p
-        join
-        (select * from bus_infusion_history
-        <where>
-            is_undo='0'
-            <if test="query.wards != null and query.wards.size > 0">
-                and ward in
-                <foreach item="ward" index="index" collection="query.wards" open="(" separator="," close=")">
-                    #{ward, jdbcType=VARCHAR}
-                </foreach>
-            </if>
-            <if test="query.types != null and query.types.size > 0">
-                and type in
-                <foreach item="type" index="index" collection="query.types" open="(" separator="," close=")">
-                    #{type, jdbcType=VARCHAR}
-                </foreach>
-            </if>
-            <choose>
-                <when test="query.deviceStatus != null and query.deviceStatus.size > 0">
-                    and (
-                    run_state in
-                    <foreach item="status" index="index" collection="query.deviceStatus" open="(" separator=","
-                             close=")">
-                        #{status, jdbcType=VARCHAR}
+        <select id="selectNoneDevice" resultMap="deviceNone">
+            SELECT
+             p.code as code,
+             c.id as clinic_id,
+             c.patient_gender as gender,
+             c.`patient_name` as name,
+             c.patient_age as age,
+             c.ward as ward,
+             c.bed_no as bed_no,
+             c.`name` as clinic_name,
+             c.weight as weight,
+             c.height as height,
+             c.ana_doctor as ana_doctor,
+             c.ana_type as ana_type,
+             c.anal_type as anal_type,
+             c.surgery_doctor as surgery_doctor,
+             c.asa as asa,
+             c.formula as formula,
+             c.finished as finished,
+             c.monitor_start_time as monitor_start_time,
+             c.config_person as config_person
+            FROM (SELECT `name`,gender,CODE,tenant_id FROM bus_patient WHERE bus_patient.`alarm`=2 ) AS p
+            join  (SELECT * FROM bus_clinic WHERE finished=0 ) AS c ON  c.`patient_code`=p.code
+            order by c.monitor_start_time desc;
+        </select>
+
+        <select id="selectMonitor" resultMap="monitorResult" parameterType="com.coffee.bus.service.dto.PatientMonitorQuery">
+            select
+            p.`code` as patient_code,
+            p.alarm as patient_alarm,
+            i.id as infusion_id,
+            i.device_id as device_id,
+            i.clinic_id as clinic_id,
+            i.ward as ward,
+            i.bed_no as bed_no,
+            i.total_dose as total_dose,
+            i.first_dose as first_dose,
+            i.remain_dose as remain_dose,
+            i.input_dose as input_dose,
+            i.append_dose as append_dose,
+            i.append_lock_time as append_lock_time,
+            i.max_dose as max_dose,
+            i.finished as infusion_finished,
+            i.electric_quantity as electric_quantity,
+            i.warn_flow as warn_flow,
+            i.self_control_count as self_control_count,
+            i.self_control_lock_time as self_control_lock_time,
+            i.pca_valid_count as pca_valid_count,
+            i.pca_invalid_count as pca_invalid_count,
+            i.pca_total_count as pca_total_count,
+            i.continue_dose as continue_dose,
+            i.pulse_dose as pulse_dose,
+            i.pulse_lock_time as pulse_lock_time,
+            i.pulse_first_lock_time as pulse_first_lock_time,
+            i.flow_up_cycle as flow_up_cycle,
+            i.flow_down_cycle as flow_down_cycle,
+            i.flow_count as flow_count,
+            i.flow_up_limit as flow_up_limit,
+            i.flow_down_limit as flow_down_limit,
+            i.flow_adjust_rate as flow_adjust_rate,
+            i.run_state as run_state,
+            i.warn_will_finished as warn_will_finished,
+            i.warn_analgesic_poor as warn_analgesic_poor,
+            i.warn_low_battery as warn_low_battery,
+            i.alarm as device_alarm,
+            i.start_time as infusion_start_time,
+            i.remark as remark,
+            i.type as device_type,
+            d.alias as device_alias,
+            c.patient_gender as patient_gender,
+            c.`patient_name` as patient_name,
+            c.finished as finished,
+            c.monitor_start_time as monitor_start_time,
+            c.end_time as monitor_end_time,
+            c.ana_doctor as ana_doctor,
+            c.patient_age as patient_age,
+            c.ana_type as ana_type,
+            c.anal_type as anal_type,
+            c.surgery_doctor as surgery_doctor,
+            c.surgery_name as surgery_name
+            from
+            (select * from bus_patient
+            <where>
+                <if test="query.tenantId!=null">
+                    and tenant_id=#{query.tenantId}
+                </if>
+            </where>
+            )
+            as p
+            join
+            (select * from bus_infusion_history
+            <where>
+                is_undo='0'
+                <if test="query.wards != null and query.wards.size > 0">
+                    and ward in
+                    <foreach item="ward" index="index" collection="query.wards" open="(" separator="," close=")">
+                        #{ward, jdbcType=VARCHAR}
                     </foreach>
-                    <if test="query.deviceAlarms != null and query.deviceAlarms.size > 0">
-                        or alarm in
-                        <foreach item="alarm" index="index" collection="query.deviceAlarms" open="(" separator=","
+                </if>
+                <if test="query.types != null and query.types.size > 0">
+                    and type in
+                    <foreach item="type" index="index" collection="query.types" open="(" separator="," close=")">
+                        #{type, jdbcType=VARCHAR}
+                    </foreach>
+                </if>
+                <choose>
+                    <when test="query.deviceStatus != null and query.deviceStatus.size > 0">
+                        and (
+                        run_state in
+                        <foreach item="status" index="index" collection="query.deviceStatus" open="(" separator=","
                                  close=")">
-                            #{alarm, jdbcType=VARCHAR}
+                            #{status, jdbcType=VARCHAR}
                         </foreach>
+                        <if test="query.deviceAlarms != null and query.deviceAlarms.size > 0">
+                            or alarm in
+                            <foreach item="alarm" index="index" collection="query.deviceAlarms" open="(" separator=","
+                                     close=")">
+                                #{alarm, jdbcType=VARCHAR}
+                            </foreach>
+                        </if>
+                        )
+                    </when>
+                    <otherwise>
+                        <if test="query.deviceAlarms != null and query.deviceAlarms.size > 0">
+                            and alarm in
+                            <foreach item="alarm" index="index" collection="query.deviceAlarms" open="(" separator="," close=")">
+                                #{alarm, jdbcType=VARCHAR}
+                            </foreach>
+                        </if>
+                    </otherwise>
+                </choose>
+                <choose>
+                    <when test="query.warnWillFinished != false or query.warnAnalgesicPoor != false or  query.warnLowBattery != false">
+                        and (
+                        <choose>
+                            <when test="query.warnWillFinished != false">warn_will_finished=1</when>
+                            <otherwise>warn_will_finished!=1</otherwise>
+                        </choose>
+                        <if test="query.warnAnalgesicPoor != false">or warn_analgesic_poor=1 </if>
+                        <if test="query.warnLowBattery != false"> or warn_low_battery=1 </if>
+                        <if test="query.warnFlow !=null">
+                            or warn_flow= #{query.warnFlow}
+                        </if>
+                        )
+                    </when>
+                    <otherwise>
+                        <if test="query.warnFlow !=null">
+                            and warn_flow= #{query.warnFlow}
+                        </if>
+                    </otherwise>
+                </choose>
+            </where>
+            ) as i on p.infusion_id=i.id
+            join (select device_id,alias from bus_device) as d on d.device_id=i.device_id
+            join (select * from bus_clinic where finished=0
+            <where>
+                <if test="query.timeRange != null and query.timeRange.size >0">
+                    and monitor_start_time &gt; #{query.timeRange[0]} and  monitor_start_time &lt; #{query.timeRange[1]}
+                </if>
+            </where>
+            ) c on i.clinic_id=c.id
+            <if test="query.bedNo!=null || query.name!=null || query.code!=null || query.anaDoctor!=null || query.surgeName!=null ||query.gender!=null ||query.anaType!=null">
+                <where>
+                    (1=0
+                    <if test="query.bedNo!=null">
+                        or i.bed_no LIKE concat('%', #{query.bedNo}, '%')
                     </if>
-                    )
-                </when>
-                <otherwise>
-                    <if test="query.deviceAlarms != null and query.deviceAlarms.size > 0">
-                        and alarm in
-                        <foreach item="alarm" index="index" collection="query.deviceAlarms" open="(" separator="," close=")">
-                            #{alarm, jdbcType=VARCHAR}
-                        </foreach>
+                    <if test="query.name!=null">
+                        or p.`name` LIKE concat('%', #{query.name}, '%')
+                    </if>
+                    <if test="query.code!=null">
+                        or p.`code` LIKE concat('%', #{query.code}, '%')
                     </if>
-                </otherwise>
-            </choose>
-            <choose>
-                <when test="query.warnWillFinished != false or query.warnAnalgesicPoor != false or  query.warnLowBattery != false">
-                    and (
-                    <choose>
-                        <when test="query.warnWillFinished != false">warn_will_finished=1</when>
-                        <otherwise>warn_will_finished!=1</otherwise>
-                    </choose>
-                    <if test="query.warnAnalgesicPoor != false">or warn_analgesic_poor=1 </if>
-                    <if test="query.warnLowBattery != false"> or warn_low_battery=1 </if>
-                    <if test="query.warnFlow !=null">
-                        or warn_flow= #{query.warnFlow}
+                    <if test="query.anaDoctor!=null">
+                        or c.`ana_doctor` like concat('%', #{query.anaDoctor}, '%')
                     </if>
-                    )
-                </when>
-                <otherwise>
-                    <if test="query.warnFlow !=null">
-                        and warn_flow= #{query.warnFlow}
+                    <if test="query.surgeName!=null">
+                        or c.`surgery_name` like concat('%',#{query.surgeName}, '%')
                     </if>
-                </otherwise>
-            </choose>
-        </where>
-        ) as i on p.infusion_id=i.id
-        join (select device_id,alias from bus_device_running) as r on r.device_id=i.device_id
-        join (select * from bus_clinic
-        <where>
-            <if test="query.timeRange != null and query.timeRange.size >0">
-                and monitor_start_time &gt; #{query.timeRange[0]} and  monitor_start_time &lt; #{query.timeRange[1]}
+                    <if test="query.gender!=null">
+                        or p.gender LIKE concat('%', #{query.gender}, '%')
+                    </if>
+                    <if test="query.anaType!=null">
+                        or c.ana_type LIKE concat('%', #{query.anaType}, '%')
+                    </if>)
+                </where>
             </if>
-        </where>
-        ) c on i.clinic_id=c.id
-        <if test="query.bedNo!=null || query.name!=null || query.code!=null || query.anaDoctor!=null || query.surgeName!=null ||query.gender!=null ||query.anaType!=null">
+            order by c.monitor_start_time desc
+        </select>
+
+
+        <select id="findByPatientCode" resultMap="monitorResult">
+            select
+            p.alarm as patient_alarm,
+            p.`code` as patient_code,
+            i.device_id as device_id,
+            i.clinic_id as clinic_id,
+            i.ward as ward,
+            i.bed_no as bed_no,
+            i.total_dose as total_dose,
+            i.first_dose as first_dose,
+            i.remain_dose as remain_dose,
+            i.input_dose as input_dose,
+            i.append_dose as append_dose,
+            i.append_lock_time as append_lock_time,
+            i.max_dose as max_dose,
+            i.electric_quantity as electric_quantity,
+            i.warn_flow as warn_flow,
+            i.self_control_count as self_control_count,
+            i.self_control_lock_time as self_control_lock_time,
+            i.pca_valid_count as pca_valid_count,
+            i.pca_invalid_count as pca_invalid_count,
+            i.pca_total_count as pca_total_count,
+            i.continue_dose as continue_dose,
+            i.pulse_dose as pulse_dose,
+            i.pulse_lock_time as pulse_lock_time,
+            i.pulse_first_lock_time as pulse_first_lock_time,
+            i.flow_up_cycle as flow_up_cycle,
+            i.flow_down_cycle as flow_down_cycle,
+            i.flow_count as flow_count,
+            i.flow_up_limit as flow_up_limit,
+            i.flow_down_limit as flow_down_limit,
+            i.flow_adjust_rate as flow_adjust_rate,
+            i.run_state as run_state,
+            i.warn_will_finished as warn_will_finished,
+            i.warn_analgesic_poor as warn_analgesic_poor,
+            i.warn_low_battery as warn_low_battery,
+            i.alarm as device_alarm,
+            i.start_time as infusion_start_time,
+            i.remark as remark,
+            i.type as device_type,
+            d.alias as device_alias,
+            c.finished as finished,
+            c.`patient_name` as patient_name,
+            c.patient_gender as gender,
+            c.monitor_start_time as monitor_start_time,
+            c.end_time as monitor_end_time,
+            c.ana_doctor as ana_doctor,
+            c.patient_age as patient_age,
+            c.ana_type as ana_type,
+            c.anal_type as anal_type,
+            c.surgery_doctor as surgery_doctor,
+            c.surgery_name as surgery_name
+            from
+            (select * from bus_patient where tenant_id=#{tenantId} and code=#{patientCode} )
+            as p
+            join
+              bus_infusion_history as i on p.infusion_id=i.id
+            join (select device_id,alias from bus_device) as d on d.device_id=i.device_id
+            left join bus_clinic c on i.clinic_id=c.id
+            limit 1
+        </select>
+
+        <select id="selectAlarmCount" resultType="long">
+            select count(1) from bus_patient as p
+            join (select * from bus_clinic where finished=0
             <where>
-                (1=0
-                <if test="query.bedNo!=null">
-                    or i.bed_no LIKE concat('%', #{query.bedNo}, '%')
-                </if>
-                <if test="query.name!=null">
-                    or p.`name` LIKE concat('%', #{query.name}, '%')
+                <if test="tenantId!=null">
+                    and tenant_id=#{tenantId}
                 </if>
-                <if test="query.code!=null">
-                    or p.`code` LIKE concat('%', #{query.code}, '%')
-                </if>
-                <if test="query.anaDoctor!=null">
-                    or c.`ana_doctor` like concat('%', #{query.anaDoctor}, '%')
-                </if>
-                <if test="query.surgeName!=null">
-                    or c.`surgery_name` like concat('%',#{query.surgeName}, '%')
-                </if>
-                <if test="query.gender!=null">
-                    or p.gender LIKE concat('%', #{query.gender}, '%')
+            </where>
+            ) as c on p.clinic_id=c.id
+            <where>
+                <if test="alarmValue!=null">
+                    and p.alarm=#{alarmValue}
                 </if>
-                <if test="query.anaType!=null">
-                    or c.ana_type LIKE concat('%', #{query.anaType}, '%')
-                </if>)
             </where>
-        </if>
-        order by c.monitor_start_time desc
-    </select>
-
-
-    <select id="findByPatientCode" resultMap="monitorResult">
-        select
-        p.alarm as patient_alarm,
-        p.`code` as patient_code,
-        i.device_id as device_id,
-        i.clinic_id as clinic_id,
-        i.ward as ward,
-        i.bed_no as bed_no,
-        i.total_dose as total_dose,
-        i.first_dose as first_dose,
-        i.remain_dose as remain_dose,
-        i.input_dose as input_dose,
-        i.append_dose as append_dose,
-        i.append_lock_time as append_lock_time,
-        i.max_dose as max_dose,
-        i.electric_quantity as electric_quantity,
-        i.warn_flow as warn_flow,
-        i.self_control_count as self_control_count,
-        i.self_control_lock_time as self_control_lock_time,
-        i.pca_valid_count as pca_valid_count,
-        i.pca_invalid_count as pca_invalid_count,
-        i.pca_total_count as pca_total_count,
-        i.continue_dose as continue_dose,
-        i.pulse_dose as pulse_dose,
-        i.pulse_lock_time as pulse_lock_time,
-        i.pulse_first_lock_time as pulse_first_lock_time,
-        i.flow_up_cycle as flow_up_cycle,
-        i.flow_down_cycle as flow_down_cycle,
-        i.flow_count as flow_count,
-        i.flow_up_limit as flow_up_limit,
-        i.flow_down_limit as flow_down_limit,
-        i.flow_adjust_rate as flow_adjust_rate,
-        i.run_state as run_state,
-        i.warn_will_finished as warn_will_finished,
-        i.warn_analgesic_poor as warn_analgesic_poor,
-        i.warn_low_battery as warn_low_battery,
-        i.alarm as device_alarm,
-        i.start_time as infusion_start_time,
-        i.remark as remark,
-        i.type as device_type,
-        r.alias as device_alias,
-        c.finished as finished,
-        c.`patient_name` as patient_name,
-        c.patient_gender as gender,
-        c.monitor_start_time as monitor_start_time,
-        c.end_time as monitor_end_time,
-        c.ana_doctor as ana_doctor,
-        c.patient_age as patient_age,
-        c.ana_type as ana_type,
-        c.anal_type as anal_type,
-        c.surgery_doctor as surgery_doctor,
-        c.surgery_name as surgery_name
-        from
-        (select * from bus_patient where tenant_id=#{tenantId} and code=#{patientCode} )
-        as p
-        join
-          bus_infusion_history as i on p.infusion_id=i.id
-        join (select device_id,alias from bus_device_running) as r on r.device_id=i.device_id
-        left join bus_clinic c on i.clinic_id=c.id
-        limit 1
-    </select>
-</mapper>
+        </select>
+    </mapper>