Pārlūkot izejas kodu

Merge branch '2.0' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into 2.0

wangzhinan 1 gadu atpakaļ
vecāks
revīzija
70a88db708
47 mainītis faili ar 6189 papildinājumiem un 40 dzēšanām
  1. 20 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceCategoryDao.java
  2. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/DeviceDao.java
  3. 128 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java
  4. 10 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceWxMessageDao.java
  5. 27 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DoctorHealthStandardDao.java
  6. 28 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/HmTokenDao.java
  7. 12 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientAimBloodPressureDao.java
  8. 13 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientAimBloodSuggerDao.java
  9. 23 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientAimSportsDao.java
  10. 14 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientBloodSuggerDao.java
  11. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/PatientDeviceDao.java
  12. 20 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientDeviceLogDao.java
  13. 27 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientHealthStandardDao.java
  14. 35 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/PatientHealthTimeDao.java
  15. 9 4
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  16. 41 1
      common/common-entity/src/db/2023.sql
  17. 12 4
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java
  18. 120 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/HmToken.java
  19. 23 0
      common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java
  20. 1 1
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/device/DeviceManageEndpoint.java
  21. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DeviceManageService.java
  22. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DmDeviceService.java
  23. 2 2
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/WlyyPatientDeviceService.java
  24. 20 0
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/config/SystemConfig.java
  25. 44 0
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/controller/zy/IotDeviceController.java
  26. 97 2
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/service/IotDeviceService.java
  27. 58 0
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/CallApiGatewaySample.java
  28. 132 0
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/SDKRunnerService.java
  29. 2 2
      svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/ZysoftApiSeconde.java
  30. 5 0
      svr/svr-internet-hospital-entrance/src/main/resources/jwkey/sqsyy_PrivateKey.SM2_V2.key
  31. 4 0
      svr/svr-internet-hospital-entrance/src/main/resources/jwkey/sqsyy_PublicKey.SM2_V2.key
  32. 19 9
      svr/svr-internet-hospital-entrance/src/main/resources/system.properties
  33. 4 2
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java
  34. 4 2
      svr/svr-internet-hospital/src/main/resources/application.yml
  35. 82 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceController.java
  36. 372 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorDeviceController.java
  37. 691 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorHealthController.java
  38. 454 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java
  39. 564 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientHealthController.java
  40. 189 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java
  41. 51 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceService.java
  42. 93 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceWxMessageService.java
  43. 129 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceLogService.java
  44. 652 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java
  45. 1943 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientHealthIndexService.java
  46. 3 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java
  47. 4 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationGuidanceService.java

+ 20 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceCategoryDao.java

@ -0,0 +1,20 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DeviceCategory;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DeviceCategoryDao extends PagingAndSortingRepository<DeviceCategory, Long> {
	@Query("select a from DeviceCategory a where a.del = '1'")
	List<DeviceCategory> findAll();
	@Query("select a from DeviceCategory a where a.code = ?1 and  a.del = '1'")
	DeviceCategory findByCode(String code);
}

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/DeviceDao.java

@ -3,11 +3,11 @@
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.base.dao.device;
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.Device;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

+ 128 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java

@ -0,0 +1,128 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface DevicePatientHealthIndexDao
		extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
	List<DevicePatientHealthIndex> findByIdcardAndType(String idcard, Integer type);
	/**
	 * 按录入时间和患者标识查询健康记录
	 *
	 * @param patientCode
	 * @param date
	 * @return
	 */
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and type = ?2 and a.recordDate = ?3 and a.del = '1'")
	Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate between ?3 and ?4 and a.del = '1' group by a.recordDate order by a.recordDate asc")
	Iterable<DevicePatientHealthIndex> findByPatient(String user, int type, Date begin, Date end);
	@Query("select a.value1 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value1 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue1ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a.value2 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value2 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue2ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a.value3 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value3 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue3ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a.value4 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value4 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue4ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a.value5 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value5 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue5ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a.value6 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value6 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue6ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a.value7 from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate < ?3 and a.value7 > '0' and a.del = '1' order by a.recordDate desc")
	Page<String> findValue7ByPatient(String user, int type, Date recordDate, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate >= ?3 and a.recordDate <= ?4 and a.del = '1'")
	Page<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Date start, Date end, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.value2 =?3 and a.recordDate >= ?4 and a.recordDate <= ?5 and a.del = '1'")
	Page<DevicePatientHealthIndex> findIndexByPatient(String patient, int type,String gi_type, Date start, Date end, Pageable pageRequest);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.del = '1'")
	List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Pageable pageRequest);
	@Query("SELECT a FROM DevicePatientHealthIndex a where a.user = ?1 and a.del = '1' order by a.recordDate desc ")
	List<DevicePatientHealthIndex> findRecentByPatient(String patient);
	@Query("select DATE_FORMAT(a.recordDate,'%Y-%m-%d') from DevicePatientHealthIndex a where a.user = ?1 and a.recordDate >= ?2 and a.recordDate <= ?3 and a.del = '1' group by DATE_FORMAT(a.recordDate,'%Y-%m-%d') order by DATE_FORMAT(a.recordDate,'%Y-%m-%d') desc")
	List<String> findDateList(String patient, Date start, Date end, Pageable pageRequest);
	/**
	 * 获取患者一天血糖值
	 */
	@Query("select a from DevicePatientHealthIndex a where a.type=1 and a.user = ?1 and DATE_FORMAT(a.recordDate,'%Y-%m-%d') = ?2 and a.del = '1' order by a.recordDate,a.id")
	List<DevicePatientHealthIndex> findByDate(String patient, String date);
	@Query(value = "select a.* from wlyy_patient_health_index a where a.user=?1 and a.type=?2 and a.del='1' order by a.record_date desc limit 0,1",nativeQuery = true)
	DevicePatientHealthIndex findLastData(String patient, Integer type);
	/**
	 * 获取患者一天的具体某个类型的数据
	 */
	@Query("select a from DevicePatientHealthIndex a where a.type=?1 and a.user = ?2 and DATE_FORMAT(a.recordDate,'%Y-%m-%d') = ?3 and a.deviceSn = ?4 and a.del = '1' order by a.recordDate,a.id")
	List<DevicePatientHealthIndex> findByDateAndType(int type,String patient, String date,String devicesn);
	
	/**
	 * 获取患者单月的具体某个类型的数据
	 */
	@Query(value = "SELECT a.* FROM wlyy_patient_health_index a WHERE a.type=?1 AND a.USER=?2 AND DATE_FORMAT(a.record_date,'%Y-%m')=?3 AND a.device_sn=?4 AND a.del='1' ORDER BY a.record_date,a.id",nativeQuery = true)
	List<DevicePatientHealthIndex> findByDateMonthAndType(int type,String patient, String date,String devicesn);
	
	
	/**
	 * 上次血糖值
	 */
	@Query(value = "select a.value1 from wlyy_patient_health_index a where a.type=1 and a.user = ?1 and a.id<?2 and a.value2 = ?3 and a.del = '1' order by a.sort_date desc ,record_date desc limit 0,1",nativeQuery = true)
	String getPreValue(String user,Long id,String value2);
	@Query(value = "select a.* from wlyy_patient_health_index a where a.user = ?1 and a.type = ?2 and a.value2 =?3 and a.record_date >= ?4 and a.record_date <= ?5 and a.del = '1' order by a.sort_date desc ,record_date desc limit ?6 ,?7",nativeQuery = true)
	List<DevicePatientHealthIndex> findIndexByPatientNative(String patient, int type,String gi_type, Date start, Date end,int currentSize,int pageSize);
	/**
	 * 获取患者某一天的血糖  普通sql写法
	 * @param patient
	 * @param date
	 * @return
	 */
	@Query(value = "select a.* from wlyy_patient_health_index a where a.type=1 and a.user = ?1 and DATE_FORMAT(a.record_date,'%Y-%m-%d') = ?2 and a.del = '1' order by a.record_date,a.id",nativeQuery = true)
	List<DevicePatientHealthIndex> findByDateNative(String patient, String date );
	@Query(value = "select a.* from wlyy_patient_health_index a where a.user = ?1 and a.type = ?2 and a.record_date >= ?3 and a.record_date <= ?4 and a.del = '1' order by a.sort_date desc ,record_date desc limit ?5 ,?6",nativeQuery = true)
	List<DevicePatientHealthIndex> findIndexByPatientNative(String patient, int type, Date start, Date end,int currentSize,int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from wlyy_patient_health_index a where a.user = ?1 and a.record_date >= ?2 and a.record_date <= ?3 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?4 ,?5",nativeQuery = true)
	List<String> findDateList(String patient,Date start ,Date end,Long currentSize,int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from wlyy_patient_health_index a where a.user = ?1 and a.type=?2 and a.record_date >= ?3 and a.record_date <= ?4 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?5 ,?6",nativeQuery = true)
	List<String> findDateList(String patient,int type,Date start ,Date end,Long currentSize,int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from wlyy_patient_health_index a where a.user = ?1 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?2 ,?3",nativeQuery = true)
	List<String> findDateList1(String patient,int currentSize,int pageSize);
	@Query(value="select * from wlyy_patient_health_index where user = ?1 and type = ?2 ORDER BY record_date desc limit 0 ,5",nativeQuery = true)
	List<DevicePatientHealthIndex> findByPatientAndTypeByPage(String patientCode, int type);
	@Query("select count(a) from DevicePatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1' and a.user = ?4")
	int getCountByTimeAndStatus(Date start, Date end, int status, String patientCode);
}

+ 10 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DeviceWxMessageDao.java

@ -0,0 +1,10 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.DeviceWxMessage;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface DeviceWxMessageDao extends PagingAndSortingRepository<DeviceWxMessage, Long>, JpaSpecificationExecutor<DeviceWxMessage> {
}

+ 27 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DoctorHealthStandardDao.java

@ -0,0 +1,27 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.DoctorHealthStandard;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author huangwenjie
 * @date 2017/9/14 21:43
 */
public interface DoctorHealthStandardDao extends
		PagingAndSortingRepository<DoctorHealthStandard, Long>,
        JpaSpecificationExecutor<DoctorHealthStandard>{
    // 查询医生健康指标预警值方案
    Iterable<DoctorHealthStandard> findByDoctor(String code);
    @Modifying
    @Query("delete DoctorHealthStandard a where a.doctor = ?1")
    int deleteByDoctor(String doctorcode);
    @Query("select a from DoctorHealthStandard a where a.doctor = ?1 and a.type = ?2")
    DoctorHealthStandard findByDoctorType(String patient, int type);
}

+ 28 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/HmTokenDao.java

@ -0,0 +1,28 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.HmToken;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/***
 * @ClassName: HmTokenDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/4/14 18:57
 */
public interface HmTokenDao extends PagingAndSortingRepository<HmToken, Long>, JpaSpecificationExecutor<HmToken> {
    @Query("select accessToken from HmToken where patient = ?1")
    String selectToken(String patient);
    @Query(value = "select t.* from hm_token t where t.patient = ?1 order by t.id desc limit 1",nativeQuery = true)
    HmToken selectT(String patient);
    @Query("select a from HmToken a where a.accessToken is null")
    List<HmToken> findAllList();
}

+ 12 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientAimBloodPressureDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientAimBloodPressure;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/1/5.
 */
public interface PatientAimBloodPressureDao extends PagingAndSortingRepository<PatientAimBloodPressure, Integer>, JpaSpecificationExecutor<PatientAimBloodPressure> {
    public  PatientAimBloodPressure findByPatientcode(String patientcode);
}

+ 13 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientAimBloodSuggerDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientAimBloodSugger;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/1/5.
 */
public interface PatientAimBloodSuggerDao extends PagingAndSortingRepository<PatientAimBloodSugger, Integer>, JpaSpecificationExecutor<PatientAimBloodSugger> {
    public PatientAimBloodSugger findByPatientcode(String patientcode);
}

+ 23 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientAimSportsDao.java

@ -0,0 +1,23 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientAimSports;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * 居民-运动目标
 * @author huangwenjie
 * @date 2017/9/12 16:07
 */
public interface PatientAimSportsDao extends
        PagingAndSortingRepository<PatientAimSports, Long>,
        JpaSpecificationExecutor<PatientAimSports> {
    @Query("from PatientAimSports p where p.code=?1")
    PatientAimSports findByCode(String code);
    @Query("from PatientAimSports p where p.patientcode =?1 and p.bmiMax is not null and p.bmiMin is not null")
    PatientAimSports getPatientAimSportsByPatientCode(String patientCode);
}

+ 14 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientBloodSuggerDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientBloodSugger;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/5/11.
 */
public interface PatientBloodSuggerDao extends PagingAndSortingRepository<PatientBloodSugger,Long> {
//    按ID倒序查最近的有效默认时间段
    @Query(value = "select t.* from wlyy_patient_blood_sugger t where t.del = 1 order by t.id desc limit 0,1 ",nativeQuery = true)
    PatientBloodSugger findRecent();
}

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/PatientDeviceDao.java

@ -1,11 +1,11 @@
package com.yihu.jw.base.dao.device;
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;

+ 20 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientDeviceLogDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.patient.PatientDeviceLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientDeviceLogDao extends PagingAndSortingRepository<PatientDeviceLog, Long>, JpaSpecificationExecutor<PatientDeviceLog> {
    @Query("select pdl from PatientDeviceLog pdl where pdl.patient=?1 and pdl.categoryCode=?2")
    List<PatientDeviceLog> findByPatientAndCategoryCode(String patient,String categoryCode);
    
    @Query("select pdl from PatientDeviceLog pdl where pdl.patient=?1 group by pdl.deviceSn ")
    List<PatientDeviceLog> findByPatientGroupByDeviceSn(String patient);
    @Query("select a from PatientDeviceLog a")
    List<PatientDeviceLog> findAllList();
}

+ 27 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientHealthStandardDao.java

@ -0,0 +1,27 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PatientHealthStandardDao extends
		PagingAndSortingRepository<PatientHealthStandard, Long>,
		JpaSpecificationExecutor<PatientHealthStandard> {
	// 查询患者健康指标预警值
	Iterable<PatientHealthStandard> findByPatient(String patient);
	@Modifying
	@Query("delete PatientHealthStandard a where a.patient = ?1")
	int deleteByPatient(String patient);
	@Query("select a from PatientHealthStandard a where a.patient = ?1 and a.type = ?2")
	PatientHealthStandard findByPatientType(String patient, int type);
}

+ 35 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/PatientHealthTimeDao.java

@ -0,0 +1,35 @@
package com.yihu.jw.device.dao;
import com.yihu.jw.entity.base.device.PatientHealthTime;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Reece on 2017/5/11.
 */
public interface PatientHealthTimeDao extends PagingAndSortingRepository<PatientHealthTime, Long> {
    //    根据居民和设备sn码查询自定义的血糖时间段
    @Query(value = "select t.* from wlyy_patient_health_time t where t.del = 1 and t.user = ?1 and t.device_sn = ?2 ", nativeQuery = true)
    PatientHealthTime findByUserAndSN(String user, String deviceSN);
    //    根据居民和设备sn码修改自定义的血糖时间段
    @Modifying
    @Query("update PatientHealthTime t set t.fastingStart = ?1,t.fastingEnd = ?2,t.afterBreakfastStart = ?3,t.afterBreakfastEnd = ?4," +
            "t.beforeLunchStart = ?5 ,t.beforeLunchEnd = ?6 ,t.afterLunchStart = ?7,t.afterLunchEnd = ?8 ,t.beforeDinnerStart = ?9,t.beforeDinnerEnd = ?10," +
            "t.afterDinnerStart = ?11,t.afterDinnerEnd = ?12,t.beforeSleepStart = ?13,t.beforeSleepEnd = ?14 where t.del = 1 and t.user = ?15 and t.deviceSN = ?16 ")
    int modifyByUserAndSN(String fastingStart, String fastingEnd, String afterBreakfastStart, String afterBreakfastEnd, String beforeLunchStart, String beforeLunchEnd,
                          String afterLunchStart, String afterLunchEnd, String beforeDinnerStart, String beforeDinnerEnd, String afterDinnerStart, String afterDinnerEnd,
                          String beforeSleepStart, String beforeSleepEnd, String user, String deviceSN);
    //    根据居民和设备sn码删除自定义的血糖时间段
    @Modifying
    @Query("update PatientHealthTime t set t.del = 0 where t.user = ?1 and t.deviceSN = ?2 ")
    int deleteByUserAndSN(String user, String deviceSN);
    //    更换个人sv码
    @Modifying
    @Query("update PatientHealthTime t set t.deviceSN = ?3 where t.user = ?1 and t.deviceSN = ?2 ")
    int updateDeviceSN(String user, String deviceSN,String newDeviceSN );
}

+ 9 - 4
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -211,7 +211,8 @@ public class ImService {
     * @param doctorName 医生名字
     * @return
     */
    public List<Map<String, Object>> findConsultRecordByPatient(String patient, String id, String type, int page, int pagesize, String title, Integer status, Integer payStatus, String doctorName) {
    public List<Map<String, Object>> findConsultRecordByPatient(String patient, String id, String type, int page, int pagesize,
                                                                String title, Integer status, Integer payStatus, String doctorName, String doctorId) {
        String sql = "SELECT " +
@ -250,7 +251,9 @@ public class ImService {
                "WHERE a.id=b.consult and d.id = h.doctor_code " +
                "AND b.doctor=d.id and p.id=a.patient AND a.patient='" + patient + "' AND a.type in (" + type + ")";
        /*List<ConsultVO> result = new ArrayList<>();*/
        if (!StringUtils.isEmpty(doctorId)) {
            sql += " and d.id = '" + doctorId + "'";
        }
        if (!StringUtils.isEmpty(title)) {
            title = "%" + title + "%";
            sql += " and a.title like '" + title + "'";
@ -300,7 +303,7 @@ public class ImService {
     * @param title   标题关键字
     * @return
     */
    public Long countConsultRecordByPatient(String patient, String id, String type, String title) {
    public Long countConsultRecordByPatient(String patient, String id, String type, String title, String doctorId) {
        String sql = "SELECT " +
                " COUNT(1) AS \"total\" " +
@ -318,7 +321,9 @@ public class ImService {
        if (!StringUtils.isEmpty(id)) {
            sql += " and a.id = '" + id + "'";
        }
        if (!StringUtils.isEmpty(doctorId)) {
            sql += " and d.id = '" + doctorId + "'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {

+ 41 - 1
common/common-entity/src/db/2023.sql

@ -322,4 +322,44 @@ INSERT INTO `base`.`zy_nation_dict` (`ID`, `ORG_ID`, `NATION_CODE`, `NATION_NAME
ALTER TABLE `wlyy_rehabilitation_guidance` MODIFY COLUMN `type` varchar(50);
ALTER TABLE base_service_item_plan
    ADD COLUMN reservation_type TINYINT(1) NULL;
    ADD COLUMN reservation_type TINYINT(1) NULL;
CREATE TABLE `wlyy_patient_health_standard` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '业务无关主键',
  `patient` varchar(50) NOT NULL COMMENT '患者标识',
  `type` int(11) NOT NULL COMMENT '健康指标类型:1血糖,2血压,3体重,4腰围',
  `min_value_1` double DEFAULT NULL COMMENT '最低安全值(血糖餐前\\收缩压\\体重\\腰围)',
  `max_value_1` double DEFAULT NULL COMMENT '最高安全值(血糖餐前\\收缩压\\体重\\腰围)',
  `min_value_2` double DEFAULT NULL COMMENT '最低安全值(血糖餐后\\舒张压)',
  `max_value_2` double DEFAULT NULL COMMENT '最高安全值(血糖餐后\\舒张压)',
  `doctor` varchar(50) NOT NULL COMMENT '设置医生',
  `czrq` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '设置时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_wlyy_patient_health_standard_1` (`patient`,`type`)
) ENGINE=InnoDB AUTO_INCREMENT=134944 DEFAULT CHARSET=utf8mb4 COMMENT='患者健康指标预警值';
CREATE TABLE `hm_token` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '业务无关主键',
  `patient` varchar(50) NOT NULL COMMENT 'i健康patient',
  `access_token` varchar(255) DEFAULT NULL COMMENT '华米token',
  `refresh_token` varchar(255) DEFAULT NULL,
  `token_type` varchar(50) DEFAULT NULL COMMENT 'token类型',
  `expires_in` varchar(50) DEFAULT NULL COMMENT 'token有效期',
  `create_time` varchar(50) DEFAULT NULL,
  `user_id` varchar(255) DEFAULT NULL COMMENT '华米端id',
  `gender` int(2) DEFAULT NULL COMMENT '华米端性别',
  `nick_name` varchar(255) DEFAULT NULL COMMENT '华米端用户昵称',
  `avatar` varchar(255) DEFAULT NULL COMMENT '头像地址',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4 COMMENT='华米token信息表';
CREATE TABLE `dm_device_category` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '业务无关主键',
  `code` varchar(50) NOT NULL COMMENT '设备类型标识',
  `name` varchar(50) NOT NULL COMMENT '设备类型名称',
  `czrq` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '添加时间',
  `del` varchar(1) DEFAULT '1' COMMENT '作废标识,1正常,0作废',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='设备分类表';

+ 12 - 4
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java

@ -3,10 +3,7 @@ package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.*;
import java.util.Date;
/**
@ -30,6 +27,8 @@ public class Device extends IdEntity {
	private String needRegister;//设备是否注册iot(脉搏波血压计)
	private Integer deviceType;//0健康设备 1安防设备
	private String authorizationTime;//华米手表授权到期时间
	@Column(name="category_code")
	public String getCategoryCode() {
		return categoryCode;
@ -138,4 +137,13 @@ public class Device extends IdEntity {
	public void setDeviceType(Integer deviceType) {
		this.deviceType = deviceType;
	}
	@Transient
	public String getAuthorizationTime() {
		return authorizationTime;
	}
	public void setAuthorizationTime(String authorizationTime) {
		this.authorizationTime = authorizationTime;
	}
}

+ 120 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/HmToken.java

@ -0,0 +1,120 @@
package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/***
 * @ClassName: HmToken
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/4/14 18:50
 */
@Entity
@Table(name = "hm_token")
public class HmToken extends IdEntity {
    private String patient;
    private String accessToken;
    private String refreshToken;
    private String tokenType;
    private String expiresIn;
    private String createTime;
    private String userId;
    //状态1同步中,0空闲
    private String gender;
    private String nickName;
    //上一次同步时间
    private String avatar;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getAccessToken() {
        return accessToken;
    }
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }
    public String getTokenType() {
        return tokenType;
    }
    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }
    public String getExpiresIn() {
        return expiresIn;
    }
    public void setExpiresIn(String expiresIn) {
        this.expiresIn = expiresIn;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getAvatar() {
        return avatar;
    }
    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }
    public String getRefreshToken() {
        return refreshToken;
    }
    public void setRefreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
    }
}

+ 23 - 0
common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java

@ -89,6 +89,11 @@ public class DateUtil {
        return dateTimeFormatter.format(localDateTime);
    }
    public static Date longToDate(long timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp);
        return Date.from(instant);
    }
    /**
     * 时间格式转中文格式
     */
@ -1646,4 +1651,22 @@ public class DateUtil {
        }
        return list;
    }
    /**
     * 日期加
     * @param strDate
     * @param type 1秒
     * @param add
     * @return
     */
    public static String dateAddByType(String strDate,String type,long add){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(strDate, formatter);
        // 在当前时间上添加秒数
        LocalDateTime newTime = null;
        if("1".equals(type)){
            newTime = localDateTime.plusSeconds(add);
        }
        return newTime.format(formatter);
    }
}

+ 1 - 1
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/device/DeviceManageEndpoint.java

@ -3,11 +3,11 @@ package com.yihu.jw.base.endpoint.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.service.device.DeviceManageService;
import com.yihu.jw.base.service.device.DmDeviceService;
import com.yihu.jw.base.service.device.WlyyPatientDeviceService;
import com.yihu.jw.base.service.device.YsDeviceService;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DeviceManageService.java

@ -2,13 +2,13 @@ package com.yihu.jw.base.service.device;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.util.HttpClientUtilCare;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.ResponseContant;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DmDeviceService.java

@ -2,10 +2,10 @@ package com.yihu.jw.base.service.device;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.ResponseContant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

+ 2 - 2
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/WlyyPatientDeviceService.java

@ -1,10 +1,10 @@
package com.yihu.jw.base.service.device;
import com.yihu.jw.base.dao.device.PatientDeviceDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.iot.device.WlyyPatientDeviceVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

+ 20 - 0
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/config/SystemConfig.java

@ -81,5 +81,25 @@ public class SystemConfig {
        return  getSystemProperties().getProperty("jw_licence");
    }
    public String getPlatformPublicKey()
    {
        return  getSystemProperties().getProperty("platform.public.key");
    }
    public String getCompanyPublicKey()
    {
        return  getSystemProperties().getProperty("company.public.key");
    }
    public String getCompanyPrivateKey()
    {
        return  getSystemProperties().getProperty("company.private.key");
    }
    public String getAuthorizationCode()
    {
        return  getSystemProperties().getProperty("authorization.code");
    }
    public String getKeyReadType()
    {
        return  getSystemProperties().getProperty("key.read.type");
    }
}

+ 44 - 0
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/controller/zy/IotDeviceController.java

@ -22,6 +22,39 @@ public class IotDeviceController extends EnvelopRestEndpoint {
    private IotDeviceService iotDeviceService;
    @GetMapping(value = "/uploadDeviceInfo")
    @ApiOperation(value = "设备状态信息上传")
    public Envelop uploadDeviceInfo() {
        try {
            return success(iotDeviceService.uploadDeviceInfo());
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "/uploadDeviceData")
    @ApiOperation(value = "设备业务数据信息上传")
    public Envelop uploadDeviceData() {
        try {
            return success(iotDeviceService.uploadDeviceData());
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "/deviceRegistration")
    @ApiOperation(value = "设备相关基础信息注册")
    public Envelop deviceRegistration() {
        try {
            return success(iotDeviceService.deviceRegistration());
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
    @GetMapping(value = "/accesstoken")
    @ApiOperation(value = "获取accesstoken")
    public Envelop getAccessToken() {
@ -33,4 +66,15 @@ public class IotDeviceController extends EnvelopRestEndpoint {
        }
    }
    @GetMapping(value = "/getAccessToken_bak")
    @ApiOperation(value = "获取getAccessToken_bak")
    public Envelop getAccessToken2() {
        try {
            return success(iotDeviceService.getAccessToken_bak());
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError("查询失败");
        }
    }
}

+ 97 - 2
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/service/IotDeviceService.java

@ -1,11 +1,21 @@
package com.yihu.jw.entrance.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.iot.gateway.GcToken;
import com.yihu.jw.entrance.util.zysoft.SDKRunnerService;
import com.yihu.jw.entrance.util.zysoft.ZysoftBaseService;
import com.yihu.jw.gateway.dao.GcTokenDao;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.util.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -22,13 +32,19 @@ public class IotDeviceService {
    private ZysoftBaseService zysoftBaseService;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private SDKRunnerService sdkRunnerService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private GcTokenDao gcTokenDao;
    /**
     * 获取accesstoken
     * 获取accesstoken,i健康写法暂时不能用
     * @return
     * @throws Exception
     */
    public String getAccessToken() throws Exception{
    public String getAccessToken_bak() throws Exception{
        Map<String,String> header = new HashMap<>();
        List<WlyyHospitalSysDictDO> dictDOList =  wlyyHospitalSysDictDao.findByDictName("zy_iot");
        Map<String,String> dictMap = dictDOList.stream().collect(Collectors.toMap(WlyyHospitalSysDictDO::getDictCode,WlyyHospitalSysDictDO::getDictValue));
@ -42,4 +58,83 @@ public class IotDeviceService {
        return response;
    }
    //设备状态信息上传
    @Transactional
    public String uploadDeviceInfo(){
        Map<String,String> header = new HashMap<>();
        String jsonData = "{\"deviceSn\":\"xty_test\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\"350211A1004\",\"hospitalName\":\"厦门市第三医院\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\",\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        params.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/uploadDeviceInfo","设备状态信息上传",params,header,true,true);
        return response;
    }
    //设备业务数据信息上传
    @Transactional
    public String uploadDeviceData(){
        Map<String,String> header = new HashMap<>();
        String jsonData = "{\"deviceSn\":\"xty_test\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\"350211A1004\",\"hospitalName\":\"厦门市第三医院\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\",\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        params.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/uploadDeviceData","设备业务数据信息上传",params,header,true,true);
        return response;
    }
    //设备相关基础信息注册
    @Transactional
    public String deviceRegistration(){
        Map<String,String> header = new HashMap<>();
        String jsonData = "{\"deviceSn\":\"xty_test\",\"deviceModel\":\"测试\",\"name\":\"血糖仪TEST\",\"hospital\":\"350211A1004\",\"hospitalName\":\"厦门市第三医院\",\"categoryCode\":\"2\",\"categoryName\":\" 血糖仪\",\"commonName\":\" 血糖仪\",\"combinationMethod\":\"1\",\"networkTransmission\":\" 11\",\"deviceUse\":\"2\",\"dropLocation\":\"2\",\"dataAcquisition\":\"IoT_equipment_blood_glucose_mete\",\"companyName\":\"血糖仪厂商名称\",\"companyType\":\"3\"}";
        Map<String,String> params = new HashMap<>();
        params.put("jsonData",jsonData);
        params.put("accesstoken",getAccessToken());
        String response = sdkRunnerService.post("wlw/deviceRegistration","设备相关基础信息注册",params,header,true,true);
        return response;
    }
    /**
     * 获取accesstoken
     * @return
     */
    @Transactional
    public synchronized String getAccessToken(){
        //新增accesstoken 缓存
        Map<String,String> header = new HashMap<>();
        List<WlyyHospitalSysDictDO> dictDOList =  wlyyHospitalSysDictDao.findByDictName("zy_iot");
        Map<String,String> dictMap = dictDOList.stream().collect(Collectors.toMap(WlyyHospitalSysDictDO::getDictCode,WlyyHospitalSysDictDO::getDictValue));
        String appid = dictMap.get("appid");
        String appSecret = dictMap.get("appSecret");
        Map<String,String> params = new HashMap<>();
        params.put("appid",appid);
        params.put("appSecret",appSecret);
        String sql = "SELECT * from gc_token WHERE appid='"+appid+"' and del='1' and out_time>='"+DateUtil.getStringDate()+"' ORDER BY id desc LIMIT 1";
        List<GcToken> gcTokenList = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(GcToken.class));
        if(gcTokenList.size()>0){
            //缓存未失效前直接读缓存
            return gcTokenList.get(0).getAccesstoken();
        }
        String response = sdkRunnerService.post("wlw/accesstoken","获取accesstoken",params,header,true,true);
        JSONObject json = JSON.parseObject(response);
        if(json.getInteger("status")==10000){
            JSONObject result = json.getJSONObject("result");
            String accesstoken = result.getString("accesstoken");
            //两个小时超时
            long createTime = result.getLong("createTime");
            long outTime = result.getLong("outTime");
            outTime = outTime - Math.abs(System.currentTimeMillis()-createTime)-1000;
            //把该用户之前有效的token设置为无效
            gcTokenDao.updateDel(appid);
            GcToken gc = new GcToken();
            gc.setAppid(appid);
            gc.setCreateTime(new Date());
            gc.setOutTime(DateUtil.longToDate(outTime));
            gc.setAccesstoken(accesstoken);
            gc.setDel(1);
            gcTokenDao.save(gc);
            return accesstoken;
        }
        return null;
    }
}

+ 58 - 0
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/CallApiGatewaySample.java

@ -0,0 +1,58 @@
package com.yihu.jw.entrance.util.zysoft;
import cn.com.zoe.crypto.jna.CryptoType;
import com.zoe.phip.ssp.sdk.*;
import java.io.IOException;
import java.util.List;
public class CallApiGatewaySample extends AbstractApiExecuter2 {
    private String apiUrl;
    private List<RequestValue> parameters;
    private RequestMethod method;
    private HeaderValue[] headers;
    public CallApiGatewaySample(byte[] platformPublicKey, byte[] parameterPublicKey, byte[] resultPrivateKey) {
        super(platformPublicKey, parameterPublicKey, resultPrivateKey);
    }
    public CallApiGatewaySample(String publicKeyBase64String, String parameterPublicKey, String resultPrivateKey) {
        super(publicKeyBase64String, parameterPublicKey, resultPrivateKey);
    }
    public CallApiGatewaySample setApiUrl(String apiUrl) {
        this.apiUrl = apiUrl;
        return this;
    }
    public CallApiGatewaySample setParameters(List<RequestValue> parameters) {
        this.parameters = parameters;
        return this;
    }
    public CallApiGatewaySample setMethod(RequestMethod method) {
        this.method = method;
        return this;
    }
    public CallApiGatewaySample setHeaders(HeaderValue[] headers) {
        this.headers = headers;
        return this;
    }
    @Override
    public String run(String authorizationCode, boolean openCrypto, CryptoType type) throws ApiException, IOException {
        if (!CryptoType.NO_CRYPTO.equals(type) && (authorizationCode == null || "".equals(authorizationCode))) {
            throw new ApiException("用户token不能为空", null);
        }
        if (apiUrl == null || "".equals(apiUrl)) {
            throw new ApiException("未填写接口地址", null);
        }
        if (method == null) {
            method = RequestMethod.POST;
        }
        return doHttp(apiUrl, method, authorizationCode, openCrypto, parameters, type, headers);
    }
}

+ 132 - 0
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/SDKRunnerService.java

@ -0,0 +1,132 @@
package com.yihu.jw.entrance.util.zysoft;
import cn.com.zoe.crypto.Base64;
import cn.com.zoe.crypto.jna.CryptoType;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.entrance.config.SystemConfig;
import com.yihu.jw.entrance.service.LogService;
import com.zoe.phip.ssp.sdk.ApiException;
import com.zoe.phip.ssp.sdk.HeaderValue;
import com.zoe.phip.ssp.sdk.RequestMethod;
import com.zoe.phip.ssp.sdk.RequestValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * SDK调用代码参考
 */
@Service
public class SDKRunnerService {
    private static String platformPublicKey;
    private static String companyPrivateKeyBase64String;
    private static String companyPublicKeyBase64String;
    private static String authorizationCode;
    private static String gateway_url;
    @Autowired
    private LogService logService;
    static {
        platformPublicKey = getEncryptData(SystemConfig.getInstance().getPlatformPublicKey());
        companyPrivateKeyBase64String = getEncryptData(SystemConfig.getInstance().getCompanyPrivateKey());
        companyPublicKeyBase64String = getEncryptData(SystemConfig.getInstance().getCompanyPublicKey());
//        platformPublicKey = SystemConfig.getInstance().getPlatformPublicKey();
//        companyPrivateKeyBase64String = SystemConfig.getInstance().getCompanyPrivateKey();
//        companyPublicKeyBase64String = SystemConfig.getInstance().getCompanyPublicKey();
        // 平台分配的授权码
        authorizationCode = SystemConfig.getInstance().getAuthorizationCode();
        gateway_url = SystemConfig.getInstance().getGatewayUrl();
    }
    /**
     *
     * @param api
     * @param params
     * @param header
     * @param openCrypto 是否启用平台加密
     * @param urlEncode url编码
     * @return
     */
    public String post(String api,String content, Map<String,String> params,Map<String,String> header,boolean openCrypto,boolean urlEncode){
        String result = null;
        String msgBody = JSONObject.toJSONString(params, SerializerFeature.WriteMapNullValue);
        String msgHeader = JSONObject.toJSONString(header, SerializerFeature.WriteMapNullValue);
        try {
            // 密钥类型(RSA、SM2、SM2V2)
            CryptoType type = CryptoType.SM2_V2;
            // 接口地址
            String apiUrl = gateway_url+api;
            // 参数
            List<RequestValue> parameters = new ArrayList<>();
            if(params!=null)
            {
                // 普通参数请求示例
//                    new RequestValue("msgHeader", "<?xml version=\"1.0\" encoding=\"utf-8\"?><ROOT></ROOT>", true, openCrypto),
//                    new RequestValue("msgBody", "<?xml version=\"1.0\" encoding=\"utf-8\"?><ROOT></ROOT>", true, openCrypto)
                // new RequestValue("idCard", "123", true, openCrypto)
                //实体参数请求示例
//                    new RequestValue("{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}")
                for(String key :params.keySet())
                {
                    RequestValue obj = new RequestValue(key,params.get(key),urlEncode,openCrypto);
                    parameters.add(obj);
                }
            }
            HeaderValue[] headers = new HeaderValue[header.size()];
//            headers[0] = new HeaderValue("Content-Type","application/json",true);
            int i = 0;
            for(String key :header.keySet())
            {
                headers[i] = new HeaderValue(key,header.get(key),urlEncode);
                i++;
            }
            // 请求方式
            RequestMethod method = RequestMethod.POST;
            //实例化需要使用的接口对象
            CallApiGatewaySample runnable =
                    new CallApiGatewaySample(platformPublicKey, companyPublicKeyBase64String, companyPrivateKeyBase64String)
                            .setApiUrl(apiUrl)
                            .setParameters(parameters)
                            .setHeaders(headers)
                            .setMethod(method);
            // 运行Api进行数据请求
            result = runnable.run(authorizationCode, openCrypto, type);
            //保存http日志
            logService.saveHttpLog(true,api,content,method.name(),msgHeader,msgBody,result,null);
        } catch (ApiException e) {
            //保存http日志
            logService.saveHttpLog(false,api,content,null,msgHeader,msgBody,result,null);
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
    private static String getEncryptData(String value) {
        InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(value);
        try {
            if (stream != null && stream.available() > 0) {
                byte[] bytes = new byte[stream.available()];
                stream.read(bytes);
                return Base64.getEncoder().encodeToString(bytes);
            } else {
                System.out.println("未找到密钥文件:"+value);
            }
        } catch (Exception e) {
            System.out.println("读取密钥文件出错:"+value);
            e.printStackTrace();
        }
        return null;
    }
}

+ 2 - 2
svr/svr-internet-hospital-entrance/src/main/java/com/yihu/jw/entrance/util/zysoft/ZysoftApiSeconde.java

@ -20,8 +20,8 @@ import java.util.Map;
 **/
public class ZysoftApiSeconde extends AbstractApiExecuter2 {
    private static final String keyPath = "D:\\jkzl\\wlyy2.0-springb2.4\\svr\\svr-internet-hospital-entrance\\src\\main\\resources";
//    private static final String keyPath = "/data/hospital/svr-internet-hospital-entrance-10024/resources";
//    private static final String keyPath = "D:\\jkzl\\wlyy2.0-springb2.4\\svr\\svr-internet-hospital-entrance\\src\\main\\resources";
    private static final String keyPath = "/data/hospital/svr-internet-hospital-entrance-10024/resources";
    @Override

+ 5 - 0
svr/svr-internet-hospital-entrance/src/main/resources/jwkey/sqsyy_PrivateKey.SM2_V2.key

@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBG0wawIBAQQg8kLSVhORuWO9i7Rx
CkEQqJusNfbIutl2dTnQ+WgQVZKhRANCAASahdH/xeHWXsxQ6SPfmN+TwslMqy8k
XhH8K+CY71oEZ13991AOv8H21NBd7AZ8Qcj/itJHu3Hf59q0J2pfy7ky
-----END PRIVATE KEY-----

+ 4 - 0
svr/svr-internet-hospital-entrance/src/main/resources/jwkey/sqsyy_PublicKey.SM2_V2.key

@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEmoXR/8Xh1l7MUOkj35jfk8LJTKsv
JF4R/CvgmO9aBGdd/fdQDr/B9tTQXewGfEHI/4rSR7tx3+fatCdqX8u5Mg==
-----END PUBLIC KEY-----

+ 19 - 9
svr/svr-internet-hospital-entrance/src/main/resources/system.properties

@ -1,16 +1,26 @@
#?????? 0?? 1???
key.read.type=0
##test
gateway_url = http://117.25.173.18:18280/
#gateway_url = http://117.25.173.18:18280/
#gateway_licence = 1GPM6UKII0NF33155F0A0000348D061E
#gateway_public_key = PublicKeyTest.key
#jw_hospital = 350211A1004
#jw_licence = 1GPM6UKII0NF33155F0A0000348D061E
#platform.public.key=jwkey/ZOE.PLATFORM_PublicKey.SM2_V2.key
#company.public.key=jwkey/sqsyy_PublicKey.SM2_V2.key
#company.private.key=jwkey/sqsyy_PrivateKey.SM2_V2.key
#authorization.code=1ERSRATH80010100007F0000E43BC68D
###prod
gateway_url = http://10.95.21.21:18280/
gateway_licence = 1GPM6UKII0NF33155F0A0000348D061E
gateway_public_key = PublicKeyTest.key
gateway_public_key = PublicGov.key
jw_hospital = 350211A1004
jw_licence = 1GPM6UKII0NF33155F0A0000348D061E
platform.public.key=jwkey/ZOE.PLATFORM_PublicKey.SM2_V2.key
company.public.key=jwkey/350211A1004_PublicKey.SM2_V2.key
company.private.key=jwkey/350211A1004_PrivateKey.SM2_V2.key
authorization.code=1GPM6UKII0NF33155F0A0000348D061E
###prod
#gateway_url = http://10.95.21.21:18280/
#gateway_licence = 1GPM6UKII0NF33155F0A0000348D061E
#gateway_public_key = PublicGov.key
#jw_hospital = 350211A1004
#jw_licence = 1GPM6UKII0NF33155F0A0000348D061E

+ 4 - 2
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -166,6 +166,8 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	public Envelop records(
								@ApiParam(name = "patient", value = "居民id")
								@RequestParam(value = "patient",required = true) String patient,
								@ApiParam(name = "doctorId", value = "医生id",required = false)
								@RequestParam(value = "doctorId",required = false) String doctorId,
								@ApiParam(name = "title", value = "咨询标题关键字")
								@RequestParam(value = "title",required = false) String title,
								@ApiParam(name = "id", value = "咨询ID")
@ -184,8 +186,8 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
								@RequestParam(value = "doctorName",required = false) String doctorName
								){
		try {
			List<Map<String,Object>>  data = imService.findConsultRecordByPatient(patient, id,type, page,pagesize, title,status,payStatus,doctorName);
			Long total = imService.countConsultRecordByPatient(patient, id,type,title);
			List<Map<String,Object>>  data = imService.findConsultRecordByPatient(patient, id,type, page,pagesize, title,status,payStatus,doctorName,doctorId);
			Long total = imService.countConsultRecordByPatient(patient, id,type,title,doctorId);
			JSONObject result = new JSONObject();
			result.put("total",total);

+ 4 - 2
svr/svr-internet-hospital/src/main/resources/application.yml

@ -1526,8 +1526,10 @@ es:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
#  host:  http://172.26.0.55:9000
#  tHost: 172.26.0.55:9300
  host: http://172.26.0.112:9200
  tHost: http://172.26.0.112:9200
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion

+ 82 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DeviceController.java

@ -0,0 +1,82 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.device.dao.HmTokenDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceCategory;
import com.yihu.jw.entity.care.device.HmToken;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceService;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(value = "/common/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "设备管理")
public class DeviceController extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private HmTokenDao hmTokenDao;
    @ApiOperation("获取设备分类")
    @RequestMapping(value = "DeviceCategory", method = {RequestMethod.POST, RequestMethod.GET})
    public String getDeviceCategory() {
        try {
            List<DeviceCategory> list = deviceService.findAllCategory();
            return write(200, "获取设备分类成功!", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, "获取设备分类失败!");
        }
    }
    @ApiOperation("获取设备列表")
    @RequestMapping(value = "DeviceList", method = {RequestMethod.POST, RequestMethod.GET})
    public String getDeviceList(@ApiParam(name = "category_code", value = "设备类型代码", defaultValue = "1")
                                @RequestParam(value = "category_code", required = true) String categoryCode) {
        try {
            List<Device> list = deviceService.findDeviceByCategory(categoryCode);
            if("4".equals(categoryCode)){
                List<Device> list2 = deviceService.findDeviceByCategory("11");
                list.addAll(list2);
            }
            return write(200, "获取设备列表成功!", "data", list);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, "获取设备列表失败!");
        }
    }
    @ApiOperation("获取设备信息")
    @RequestMapping(value = "DeviceInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public String getDeviceInfo(@ApiParam(name = "id", value = "设备ID", defaultValue = "19")
                                @RequestParam(value = "id", required = true) String id) {
        try {
            Device device = deviceService.findById(id);
            if(device!=null&&"11".equals(device.getCategoryCode())){
                //华米手表返回 授权到期时间
                HmToken hmToken = hmTokenDao.selectT(getRepUID());
                String authorizationTime = null;
                if(hmToken!=null&& StringUtils.isNotBlank(hmToken.getExpiresIn())){
                    authorizationTime = DateUtil.dateAddByType(hmToken.getCreateTime(),"1",Long.parseLong(hmToken.getExpiresIn()));
                    device.setAuthorizationTime(authorizationTime);
                }
            }
            return write(200, "查询成功", "data", device);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}

+ 372 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorDeviceController.java

@ -0,0 +1,372 @@
package com.yihu.jw.hospital.module.health.controller;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceDetailService;
import com.yihu.jw.hospital.module.health.service.DeviceWxMessageService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceLogService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.base.device.DeviceWxMessageDTO;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 医生端:设备管理控制类
 * @author George
 *
 */
@RestController
@RequestMapping(value = "doctor/device")
@Api(value = "患者设备管理--医生端", description = "患者设备管理--医生端")
public class DoctorDeviceController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(DoctorDeviceController.class);
	@Autowired
	private PatientDeviceService patientDeviceService;
	@Autowired
	private DeviceDetailService deviceDetailService;
	@Autowired
	private WechatTemplateConfigDao templateConfigDao;
	@Autowired
	private PushMsgTask pushMsgTask;
	@Autowired
	private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
	@Autowired
	private BasePatientDao patientDao;
	@Autowired
	private BaseDoctorDao doctorService;
	@Autowired
	private PatientDeviceLogService patientDeviceLogService;
	@Autowired
	private CommonUtil commonUtil;
	@Autowired
	private DeviceWxMessageService deviceWxMessageService;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private JmsTemplate jmsTemplate;
//	@Value("${activemq.queue.deviceMeasurementRemindingQueue}")
	private String devcieChannelName="";
	private ObjectMapper  objectMapper=new ObjectMapper();
	@ApiOperation("设备保存接口--医生端")
	@RequestMapping(value = "SavePatientDevice",method = RequestMethod.POST)
	public String saveDevice(@ApiParam(name="data",value="设备数据json",defaultValue = "{\"user\":\"915cca0a-5b1d-11e6-8344-fa163e8aee56\",\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"16C000337\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
							  @RequestParam(value="data",required = true) String data) {
		try {
			DevicePatientDevice device = objectMapper.readValue(data,DevicePatientDevice.class);
			if(StringUtils.isBlank(device.getDeviceSn())){
				return write(-1,"sn码不能为空!");
			}
			// 设置操作医生标识
			device.setDoctor(getUID());
			BaseDoctorDO doctor = doctorService.findByIdAndDel(getUID());
			if (doctor!=null){
				device.setDoctorName(doctor.getName());
			}
			//首绑和设备类型判断  判断是否可以增加积分
			Map<String,Object> checkMap = patientDeviceService.checkBindingFirstAndType(device);
			boolean flag = (Boolean)checkMap.get("flag");
			//绑定
			patientDeviceService.saveDevice(device);
			patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),1,1);
			//修改设备表中{"1":"0", "2":"0"}绑定次数 和其他绑定信息,
			deviceDetailService.updateAfterBinding(device,new Date(),flag);
			return success("设备保存成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("设备保存接口并且添加积分--医生端")
	@RequestMapping(value = "SavePatientDeviceAndCredit",method = RequestMethod.POST)
	public String SavePatientDeviceAndCredit(@ApiParam(name="data",value="设备数据json",defaultValue = "{\"user\":\"915cca0a-5b1d-11e6-834 4-fa163e8aee56\",\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"16C000337\",\"categoryCode\": \"1\",\"userType\": \"-1\"}") @RequestParam(value="data",required = true) String data,
											 @ApiParam(name = "agreementPhoto",value = "协议图片临时路径")@RequestParam(value = "agreementPhoto",required = false)String agreementPhoto) {
		try {
			DevicePatientDevice device = objectMapper.readValue(data,DevicePatientDevice.class);
			// 设置操作医生标识
			device.setDoctor(getUID());
			BaseDoctorDO doctor = doctorService.findByIdAndDel(getUID());
			if (doctor!=null){
				device.setDoctorName(doctor.getName());
			}
			if (StringUtils.isNotEmpty(agreementPhoto)){
				device.setAgreementPhoto(commonUtil.copyTempImage(agreementPhoto));
			}
			/*if ("1".equals(device.getCategoryCode())){
				device.setUserType("-1");
			}*/
			//首绑和设备类型判断  判断是否可以增加积分
			Map<String,Object> checkMap = patientDeviceService.checkBindingFirstAndType(device);
			boolean flag = (Boolean)checkMap.get("flag");
			//绑定
			patientDeviceService.saveDevice(device);
			patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),1,1);
			//修改设备表中{"1":"0", "2":"0"}绑定次数 和其他绑定信息,
			deviceDetailService.updateAfterBinding(device,new Date(),flag);
			return success("设备保存成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("患者设备列表获取--医生端")
	@RequestMapping(value = "PatientDeviceList",method = RequestMethod.GET)
	public String getDeviceByPatient(
			@ApiParam(name="patient",value="患者code",defaultValue = "5f84f2f0f32c45e0977e3a1ea9f2d77c")
			@RequestParam(value="patient",required = true) String patient,
			@ApiParam(name="page",value="分页起始id",defaultValue = "1")
			@RequestParam(value="page",required = true) int page,
			@ApiParam(name="pagesize",value="每页条数",defaultValue = "10")
			@RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<Map<String,Object>> list = patientDeviceService.findByDoctor(patient, getUID(),page, pagesize);
			return write(200, "查询成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除--医生端")
	@RequestMapping(value = "DeletePatientDevice",method = {RequestMethod.POST,RequestMethod.GET})
	public String delete(@ApiParam(name="id",value="删除设备关联ID")
						 @RequestParam(value="id",required = true) String id) {
		try {
			DevicePatientDevice pd = patientDeviceService.findById(id);
			if(pd!=null)
			{
				//2019-08-06 1.6.0版本医生解绑不用判断权限
				List<JSONObject> objects = patientDeviceService.deleteDevice(id,getUID());
				patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),1,2);
				deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
				//设置解绑申请消息为已处理
//				messageDao.updateMessageByRelationCode(pd.getId() + "", 302);
				//发送设备审核消息
				patientDeviceService.sendWxMessage(pd, 1);
				return write(200,"","data",objects);
			}
			else{
				return error(-1, "不存在该设备!");
			}
		} catch (Exception ex) {
			return invalidUserException(ex, -1,ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除--管理端")
	@RequestMapping(value = "unbindDevice",method = {RequestMethod.POST,RequestMethod.GET})
	public String deleteByAdmin(@ApiParam(name="deviceSn",value="设备SN")
						 @RequestParam(value="deviceSn",required = true) String deviceSn,
						@ApiParam(name="type",value="设备类型")
						@RequestParam(value="type",required = true) String type) {
		try{
			List<DevicePatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
			DevicePatientDevice patientDevice = new DevicePatientDevice();
			if (patientDevices!=null && patientDevices.size()>0){
				patientDevice = patientDevices.get(0);
			}
			patientDeviceService.deleteDevices(deviceSn,type,getUID());
			//全部解绑后去判断就更新设备表中是否绑定字段
			patientDeviceLogService.savePatientDeviceLog(patientDevice,deviceSn,1,2);
			deviceDetailService.unBindUpdateIsBinding(deviceSn);
			return write(200,"解绑成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e){
			return errorResult(e);
		}
	}
	@ApiOperation("获取患者设备信息")
	@RequestMapping(value = "PatientDeviceInfo",method = RequestMethod.GET)
	public String getPatientDeviceInfo(@ApiParam(name="id",value="患者设备ID",defaultValue = "34")
									   @RequestParam(value="id",required = true) String id) {
		try {
			DevicePatientDevice device = patientDeviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况")
	@RequestMapping(value = "PatientDeviceIdcard",method = RequestMethod.GET)
	public String getDeviceUser(
			@ApiParam(name="patient",value="患者code",defaultValue = "915cca0a-5b1d-11e6-8344-fa163e8aee56")
			@RequestParam(value="patient",required = true) String patient,
			@ApiParam(name="type",value="设备类型",defaultValue = "1")
			@RequestParam(value="type",required = true) String type,
			@ApiParam(name="device_sn",value="设备SN码",defaultValue = "15L000002")
			@RequestParam(value="device_sn",required = true) String deviceSn) {
		try {
			List<Map<String,String>> list = patientDeviceService.getDeviceUser(patient,deviceSn,type);
			return write(200, "获取设备绑定信息成功!", "data",list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况(管理端)")
	@RequestMapping(value = "getListByDeviceSn",method = RequestMethod.GET)
	public String getDeviceBindUser(@ApiParam(name="type",value="设备类型",defaultValue = "1")
									@RequestParam(value="type",required = true) String type,
									@ApiParam(name="deviceSn",value="设备SN码",defaultValue = "15L000002")
									@RequestParam(value="deviceSn",required = true) String deviceSn){
			JSONArray objects = patientDeviceService.getDeviceByDeviceSn(deviceSn,type);
			return write(200, "获取设备成功!", "data",objects);
	}
	@ApiOperation("根据sn码获取设备的信息和绑定信息")
	@RequestMapping(value = "/getDeviceInfoByDeviceSn",method = RequestMethod.GET)
	public String getDeviceInfoByDeviceSn(@ApiParam(name="deviceSn",value="设备SN码",defaultValue = "15L000002")
														  @RequestParam(value="deviceSn",required = true) String deviceSn){
		try{
			Map<String,Object> checkMap = patientDeviceService.checkBindingDeviceSn(deviceSn);
			boolean checkFlag = (Boolean)checkMap.get("flag");
			if (!checkFlag){
				return write(-1,String.valueOf(checkMap.get("message")));
			}
			return write(200, "获取设备成功!", "data",patientDeviceService.getDeviceByDeviceSn(deviceSn));
		}catch (Exception e){
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/checkIsBinding",method = RequestMethod.POST)
	@ApiOperation(value = "根据sn码查询设备是否已经绑定和存在",notes = "绑定设备前的判断")
	public String findDeviceAndBindingBySn(@ApiParam(name = "deviceSn", value = "", defaultValue = "") @RequestParam(value = "deviceSn")String deviceSn){
		if (org.springframework.util.StringUtils.isEmpty(deviceSn)){
			return write(-1,"参数格式错误!");
		}
		try{
			Map<String,Object> map = patientDeviceService.checkBindingDeviceSn(deviceSn);
			return  write(200,String.valueOf(map.get("message")),"data",(Boolean)map.get("flag"));
		}catch (Exception e){
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/getDevicesList",method = RequestMethod.GET)
	@ApiOperation(value = "医生端-设备管理中设备列表",notes = "设备列表")
	public String getDevicesList(@ApiParam(value = "未测量天数(1今日为测量 2七天未测量 3本月未测量 4超过一个月未测量)", name = "noGaugeDay") @RequestParam(value = "noGaugeDay",required = false)String noGaugeDay,
								 @ApiParam(value = "是否绑定(1绑定 2解绑)", name = "isBinding") @RequestParam(value = "isBinding",required = false)String isBinding,
								 @ApiParam(value = "设备类型(1血糖仪 2血压计,4智能手表)", name = "categoryCode") @RequestParam(value = "categoryCode",required = false)String categoryCode,
								 @ApiParam(value = "今日是否发送消息(1未发送 2已发送)", name = "isSend") @RequestParam(value = "isSend",required = false)String isSend,
								 @ApiParam(name="page",value="第几页",defaultValue = "1") @RequestParam(value="page",required = true) String page,
								 @ApiParam(name="pageSize",value="",defaultValue = "10") @RequestParam(value="pageSize",required = true) String pageSize) {
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}
		try {
			return  write(200,"查找成功!","data",patientDeviceLogService.getDevicesList(getUID(),noGaugeDay,isBinding,categoryCode,isSend,Integer.valueOf(page),Integer.valueOf(pageSize)));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/sendDeviceWxMessage",method = RequestMethod.POST)
	@ApiOperation("给没有测量的居民发送微信消息提醒")
	public String sendDevcieWxMessage(@ApiParam(name = "data",value = "[{\"patient\":\"1\",\"deviceName\":\"同学1\",\"deviceSn\":\"123\",\"categoryCode\":\"1\"}]")
									  @RequestParam(value = "data",required = true)String data){
		try {
			List<DeviceWxMessageDTO> deviceWxMessageDTOList = deviceWxMessageService.batchSaveAndSendActiveMq(data);
			sender(deviceWxMessageDTOList);
			return write(200,"提醒成功!");
		}catch (Exception e){
			return errorResult(e);
		}
	}
	public void sender(List<DeviceWxMessageDTO> deviceWxMessageList){
		//发送到队列
        try{
            deviceWxMessageList.stream().forEach(one->{
                jmsTemplate.send(devcieChannelName, new MessageCreator() {
                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        TextMessage textMessage = session.createTextMessage();
                        textMessage.setText(net.sf.json.JSONObject.fromObject(one).toString());
                        return textMessage;
                    }
                });
            });
        }catch (Exception e){
            e.printStackTrace();
        }
	}
	
	
	@ApiOperation("拒绝居民设备解绑申请")
	@RequestMapping(value = "refusePatientDeviceApply",method = RequestMethod.POST)
	public String refusePatientDeviceApply(
			@ApiParam(name = "id", value = "删除设备关联ID")
			@RequestParam(value = "id", required = true) String id,
			@ApiParam(name = "reason", value = "拒绝原因")
			@RequestParam(value = "reason", required = true) String reason){
		try {
			DevicePatientDevice pd = patientDeviceService.findById(id);
			pd.setApplyStatus(2);
			pd.setRefuseReason(reason);
			patientDeviceDao.save(pd);
			//发送设备审核模板消息
			patientDeviceService.sendWxMessage(pd, 2);
			return write(200,"执行成功");
		}catch (Exception e){
			return errorResult(e);
		}
	}
}

+ 691 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorHealthController.java

@ -0,0 +1,691 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.contant.DeviceHealthContant;
import com.yihu.jw.entity.base.device.DoctorHealthStandard;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping(value = "/doctor/health_index")
@Api(description = "医生端-患者指标")
public class DoctorHealthController extends BaseController {
	@Autowired
	private PatientHealthIndexService healthIndexService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@RequestMapping(value = "recent",method = RequestMethod.GET)
	@ApiOperation("患者最近填写的健康指标")
	public String recent(@ApiParam("患者代码")
						  @RequestParam String patient) {
		try {
			JSONArray array = healthIndexService.findRecentByPatient(patient);
			if (array != null) {
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者标识
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标(图表)")
	public String getHealthIndexChartByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "eb0b478fbe9245428ecf63cd7517206f")
												   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="gi_type",value="就餐类型",defaultValue = "1")
												   @RequestParam(value = "gi_type",required = false) int gi_type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2017-05-22 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2017-06-02 00:00:00")
												   @RequestParam(value="end",required = true) String end) {
		try {
			JSONArray jsonArray = healthIndexService.findChartByPatient(patient,type,gi_type,begin,end);
			List<Map<String,Object>> maps = new ArrayList<>();
			if (type==1){
				JSONArray array = new JSONArray();
				Set<String> list = new HashSet<>();
				for (int i=0;i<maps.size();i++){
					JSONObject jsonObject = new JSONObject();
					Map<String,Object> map = maps.get(i);
					if (array!=null&&array.length()!=0){
						for (int j=0;j<array.length();j++){
							JSONObject object = array.getJSONObject(j);
							if (list.contains(map.get("mid").toString())){
								if (object.getString("mid").equalsIgnoreCase(map.get("mid").toString())){
									if (map.get("code").toString().equalsIgnoreCase("BloodSugar")){
										object.put("mid",map.get("mid"));
										object.put("date",map.get("measure_time").toString());
										object.put("device_sn",map.get("sn").toString());
										object.put("flag","xiaowu");
										object.put("value1",map.get("value"));
										object.put("valuedata",map.get("value"));
									}else if (map.get("code").toString().equalsIgnoreCase("BloodsugarType")){
										object.put("mid",map.get("mid"));
										object.put("date",map.get("measure_time").toString());
										object.put("device_sn",map.get("sn").toString());
										object.put("flag","xiaowu");
										object.put("value2",map.get("value"));
									}
								}
							}else {
								if (map.get("code").toString().equalsIgnoreCase("BloodSugar")){
									jsonObject.put("mid",map.get("mid"));
									jsonObject.put("date",map.get("measure_time").toString());
									jsonObject.put("device_sn",map.get("sn").toString());
									jsonObject.put("flag","xiaowu");
									jsonObject.put("value1",map.get("value"));
									jsonObject.put("valuedata",map.get("value"));
									array.put(jsonObject);
									list.add(map.get("mid").toString());
								}else if (map.get("code").toString().equalsIgnoreCase("BloodsugarType")){
									jsonObject.put("mid",map.get("mid"));
									jsonObject.put("date",map.get("measure_time").toString());
									jsonObject.put("device_sn",map.get("sn").toString());
									jsonObject.put("flag","xiaowu");
									jsonObject.put("value2",map.get("value"));
									array.put(jsonObject);
									list.add(map.get("mid").toString());
								}
							}
						}
					}else {
						if (map.get("code").toString().equalsIgnoreCase("BloodSugar")){
							jsonObject.put("mid",map.get("mid"));
							jsonObject.put("date",map.get("measure_time").toString());
							jsonObject.put("device_sn",map.get("sn").toString());
							jsonObject.put("flag","xiaowu");
							jsonObject.put("value1",map.get("value"));
							jsonObject.put("valuedata",map.get("value"));
							array.put(jsonObject);
							list.add(map.get("mid").toString());
						}else if (map.get("code").toString().equalsIgnoreCase("BloodsugarType")){
							jsonObject.put("mid",map.get("mid"));
							jsonObject.put("date",map.get("measure_time").toString());
							jsonObject.put("device_sn",map.get("sn").toString());
							jsonObject.put("flag","xiaowu");
							jsonObject.put("value2",map.get("value"));
							array.put(jsonObject);
							list.add(map.get("mid").toString());
						}
					}
				}
				for (int z=0;z<array.length();z++){
					JSONObject object = array.getJSONObject(z);
					jsonArray.put(object);
				}
			}else if (type==2){
			}else if (type==3){
			}
			if (jsonArray.length()==0) {
				return success("查询成功!");
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者标识
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart_new",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标(图表)-展会")
	public String getHealthIndexChartByPatient_new(@ApiParam(name="patient",value="患者代码",defaultValue = "eb0b478fbe9245428ecf63cd7517206f")
											   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="gi_type",value="就餐类型",defaultValue = "1")
											   @RequestParam(value = "gi_type",required = false) int gi_type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2017-05-22 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2017-06-02 00:00:00")
											   @RequestParam(value="end",required = true) String end) {
		try {
			JSONArray jsonArray = healthIndexService.findChartByPatient(patient,type,gi_type,begin,end);
			if (jsonArray.length()==0) {
				return success("查询成功!");
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
											  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
											  @RequestParam(value="begin",required = true) String begin,
										  @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
											  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
											  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONObject jsonObject2 = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			if (type == 1) {
				List<Object> list = healthIndexService.findIndexByPatient2(patient, type, begin, end, page, pagesize);
				jsonObject2.put("data",list);
			}else {
				jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
				jsonObject2.put("data", jsonArray);
			}
			return write(200, "查询成功", "list", jsonObject2);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list_new",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标-展会")
	public String getHealthIndexByPatient_new(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
										  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
										  @RequestParam(value="begin",required = true) String begin,
										  @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
										  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
										  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONArray jsonArray = new JSONArray();
			if (type == 1) {
				List<Object> list = healthIndexService.findIndexByPatient2(patient, type, begin, end, page, pagesize);
				jsonArray = new JSONArray(list);
			}else{
				jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list1",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标")
	public String getHealthIndexByPatient1(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
										  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
										  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONObject jsonObject = new JSONObject();
			if (type == 1) {
				jsonObject = healthIndexService.findIndexByPatient3(patient, type, page, pagesize);
			}else{
				jsonObject = healthIndexService.findIndexByPatient1(patient, type, page, pagesize);
			}
			return write(200, "查询成功", "list", jsonObject);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 *
	 * @param patient 患者标识
	 * @return
	 */
	@RequestMapping(value = "standard",method = RequestMethod.GET)
	@ApiOperation("患者健康指标预警值查询")
	public String standard(@ApiParam("患者代码") @RequestParam String patient) {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(patient);
			Iterator<PatientHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					PatientHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型:1血糖,2血压,3体重,4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	@RequestMapping(value = "standard_save",method = RequestMethod.POST)
	@ApiOperation("保存患者健康指标预警值")
	public String standardSave(@ApiParam("患者代码") @RequestParam String patient,
							    @ApiParam("预警值Json") @RequestParam String json) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(patient) || array == null || array.length() == 0) {
				return error(-1, "保存失败!");
			}
				String[] pcodeArray = new String[1];
				if(patient.contains(",")){
					pcodeArray = patient.split(",");
				}else{
					pcodeArray = new String[]{patient};
				}
				if(pcodeArray != null && pcodeArray.length > 0){
					// 生成数据对象
					List<PatientHealthStandard> list = new ArrayList<>();
					//保存患者的数据时,同时医生的预警值方案
					List<DoctorHealthStandard> doclist = new ArrayList<>();
					for (int i = 0; i < array.length(); i++) {
						JSONObject obj = array.getJSONObject(i);
						if (obj == null) {
							continue;
						}
						for (String patientCode: pcodeArray) {
							PatientHealthStandard standard = new PatientHealthStandard();
							standard.setDoctor(getUID());
							standard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
							standard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
							standard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
							standard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
							standard.setType(obj.getInt("type"));
							standard.setPatient(patientCode);
							standard.setCzrq(new Date());
							list.add(standard);
						}
					}
					if (list.size() == 0) {
						return error(-1, "保存失败!");
					}
					// 保存数据库
					Iterable<PatientHealthStandard> iterable = healthIndexService.saveStandard(list, patient);
					if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
						return error(-1, "保存失败!");
					}
				}
			return write(200, "保存成功");
		} catch (Exception e) {
			return invalidUserException(e, -1, "保存失败!");
		}
	}
	@RequestMapping(value = "last",method = RequestMethod.GET)
	@ApiOperation("患者最新健康指标信息")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "")
										   @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
			if (xt != null) {
				map.put("xt", xt);
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
			if (xy != null) {
				map.put("xy", xy);
			}
			DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
			if (tz != null) {
				map.put("tz", tz);
			}
			DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
			if (sg != null) {
				map.put("sg", sg);
			}
			DevicePatientHealthIndex xl = healthIndexService.findLastByPatienIot(patient, 5);
			if (xl != null) {
				map.put("xl", xl);
			}
			return write(200, "查询成功", "data", map);
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "last_new",method = RequestMethod.GET)
	@ApiOperation("患者最新健康指标信息-展会")
	public String getHealthIndexByPatient_new(@ApiParam(name="patient",value="患者代码",defaultValue = "")
										  @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient,1);
			if(xt!=null)
			{
				map.put("xt",xt);
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient,2);
			if(xy!=null)
			{
				map.put("xy",xy);
			}
			DevicePatientHealthIndex tz = healthIndexService.findLastByPatien(patient,3);
			if(tz != null){
				map.put("tz",tz);
			}
			DevicePatientHealthIndex sg = healthIndexService.findLastByPatien(patient,4);
			if(sg != null){
				map.put("sg",sg);
			}
			DevicePatientHealthIndex xl = healthIndexService.findLastByPatien(patient,5);
			if(xl != null){
				map.put("xl",xl);
			}
			return write(200, "查询成功", "data", map);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "getHealthIndexHistory",method = RequestMethod.GET)
	@ApiOperation("获取患者健康指标历史记录")
	public String getHealthIndexHistory(@ApiParam(name="patient",value="患者代码",defaultValue = "P20161008001")
										 @RequestParam(value="patient",required = true) String patient,
										 @ApiParam(name="type",value="指标类型1血糖,2血压,3体重,4腰围",defaultValue = "1")
										 @RequestParam(value="type",required = true) int type,
										 @ApiParam(name="page",value="第几页",defaultValue = "0")
										 @RequestParam(value="page",required = true) int page,
										 @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										 @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<Map<String,String>> list = healthIndexService.getHealthIndexHistory(patient, type, page, pagesize);
			return write(200, "获取患者健康指标历史记录成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "doctorstandard",method = RequestMethod.GET)
	@ApiOperation("医生健康指标预警值方案查询")
	public String doctorstandard(@ApiParam("医生") @RequestParam String doctor) {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			if(StringUtils.isBlank(doctor)){
				doctor = getUID();
			}
			Iterable<DoctorHealthStandard> iterable = healthIndexService.findDoctorStandardByDoctor(doctor);
			if(iterable == null){
				//如果获取不到,则获取系统默认方案
				iterable = healthIndexService.findDoctorStandardByDoctor("default");
			}
			Iterator<DoctorHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					DoctorHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围\BMI)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围\BMI)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压\步数)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压\步数)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型:1血糖,2血压,3BMI,4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	@RequestMapping(value = "savastandbyteamcode",method = RequestMethod.POST)
	@ApiOperation("医生保存团队下所有居民的预警方案")
	public String doctorSaveStandardByTeamCode(
			@ApiParam("团队代码") @RequestParam String teamcode,
			@ApiParam("预警值Json") @RequestParam String json) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(teamcode) || array == null || array.length() == 0) {
				return error(-1, "保存失败!");
			}
			List<BasePatientDO> patients = new ArrayList<>();
			if(!patients.isEmpty()){
				// 生成数据对象
				List<PatientHealthStandard> list = new ArrayList<>();
				//保存患者的数据时,同时医生的预警值方案
				List<DoctorHealthStandard> doclist = new ArrayList<>();
				for (int i = 0; i < array.length(); i++) {
					JSONObject obj = array.getJSONObject(i);
					if (obj == null) {
						continue;
					}
					for (BasePatientDO patient: patients) {
						PatientHealthStandard standard = new PatientHealthStandard();
						standard.setDoctor(getUID());
						standard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
						standard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
						standard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
						standard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
						standard.setType(obj.getInt("type"));
						standard.setPatient(patient.getId());
						standard.setCzrq(new Date());
						list.add(standard);
					}
					DoctorHealthStandard doctorHealthStandard = new DoctorHealthStandard();
					doctorHealthStandard.setDoctor(getUID());
					doctorHealthStandard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
					doctorHealthStandard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
					doctorHealthStandard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
					doctorHealthStandard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
					doctorHealthStandard.setType(obj.getInt("type"));
					doctorHealthStandard.setCzrq(new Date());
					doclist.add(doctorHealthStandard);
				}
				if (list.size() == 0) {
					return error(-1, "保存失败!");
				}
				// 保存数据库
				Iterable<PatientHealthStandard> iterable = healthIndexService.saveStandardPatients(list, patients);
				if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
					return error(-1, "保存失败!");
				}
				Iterable<DoctorHealthStandard> dociterable = healthIndexService.saveDocStandard(doclist, getUID());
				if (dociterable == null || dociterable.iterator() == null || !dociterable.iterator().hasNext()) {
					return error(-1, "保存失败!");
				}
			}
			return write(200, "保存成功");
		} catch (Exception e) {
			return invalidUserException(e, -1, "操作失败!");
		}
	}
	@RequestMapping(value = "/getHealthDateAll",method = RequestMethod.GET)
	@ApiOperation("医生端--查询所有有数据的日期")
	public String getHealthDateAll(@ApiParam(value = "居民code)", name = "patientCode") @RequestParam(value = "patientCode",required = true)String patientCode,
								   @ApiParam(value = "设备sn码", name = "deviceSn") @RequestParam(value = "deviceSn",required = true)String deviceSn,
								   @ApiParam(value = "时间(month:yyyy-MM)", name = "choseMonth") @RequestParam(value = "choseMonth",required = true)String choseMonth,
								   @ApiParam(value = "健康指标类型(1血糖,2血压,3体重,4腰围)",name = "type")@RequestParam(value = "type",required = true)int type){
		try{
			String sql = "select DISTINCT(DATE_FORMAT(a.record_date,'%Y-%m-%d')) result from wlyy_patient_health_index a where a.type="+type+" and a.`user` = '"+patientCode+"' and DATE_FORMAT(a.record_date,'%Y-%m') = '"+choseMonth+"' and a.device_sn = '"+deviceSn+"' and a.del = '1' order by a.record_date,a.id";
			List<Map<String,Object>> reusltList = jdbcTemplate.queryForList(sql);
			List<String> list = new ArrayList<>();
			for (Map<String,Object> map : reusltList){
				list.add(String.valueOf(map.get("result")));
			}
			return write(200, "获取健康指标记录日期成功", "data", list);
		}catch (Exception e){
			return invalidUserException(e, -1, e.getMessage());
		}
	}
	@RequestMapping(value = "/patientHealthIndexByDateAndDeviceSn",method = RequestMethod.GET)
	@ApiOperation("医生端--根据时间和设备sn码查询某个居民的体征记录")
	public String patientHealthIndexByDateAndDeviceSn(@ApiParam(value = "居民code)", name = "patientCode") @RequestParam(value = "patientCode",required = true)String patientCode,
													  @ApiParam(value = "设备sn码", name = "deviceSn") @RequestParam(value = "deviceSn",required = true)String deviceSn,
													  @ApiParam(value = "日期", name = "choseDay") @RequestParam(value = "choseDay",required = true)String choseDay,
													  @ApiParam(value = "健康指标类型(1血糖,2血压,3体重,4腰围)",name = "type")@RequestParam(value = "type",required = true)int type){
		try {
			List<Map<String,String>> list = healthIndexService.getHealthIndexByPatientAndDate(patientCode,deviceSn,choseDay,type);
			return write(200, "获取健康指标历史记录成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@GetMapping(value = "/getDataByType")
	@ApiOperation(value = "体征类型查询数据", notes = "体征类型查询数据")
	public String getDataByType(
			@ApiParam(name = "patient",value = "居民code",required = true) @RequestParam String patient,
			@ApiParam(name = "type", value = "体征类型", required = true) @RequestParam String type,
			@ApiParam(name = "page", value = "页", required = true) @RequestParam(defaultValue = "1") int page,
			@ApiParam(name = "size", value = "数量", required = true) @RequestParam(defaultValue = "15") int size,
			@ApiParam(name = "beginTime", value = "开始时间", required = false) @RequestParam String beginTime,
			@ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam String endTime
	) throws Exception {
		return write(200, "查询成功", "data", new ArrayList<>());
	}
	@RequestMapping(value = "getHealthIndexById",method = RequestMethod.GET)
	@ApiOperation("根据体征记录id获取体征记录详情")
	public String getHealthIndexById(@ApiParam("体征记录id")
						 @RequestParam Long id) {
		try {
			DevicePatientHealthIndex patientHealthIndex = healthIndexService.getHealthIndexById(id);
			return write(200, "查询成功", "data", patientHealthIndex);
		} catch (Exception e) {
			return errorResult(e);
		}
	}
}

+ 454 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java

@ -0,0 +1,454 @@
package com.yihu.jw.hospital.module.health.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.device.dao.PatientHealthTimeDao;
import com.yihu.jw.entity.base.device.PatientHealthTime;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceDetailService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceLogService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceService;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
 * 患者端:设备管理控制类
 *
 * @author George
 */
@RestController
@RequestMapping(value = "patient/device")
@Api(value = "患者设备管理", description = "患者设备管理")
public class PatientDeviceController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(PatientDeviceController.class);
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private PatientHealthIndexService patientHealthIndexService;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private BasePatientDao patientService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private PatientDeviceLogService patientDeviceLogService;
    @Autowired
    private MessageDao messageDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    @ApiOperation("获取居民标准体征预警值")
    @RequestMapping(value = "getDeviceStandard", method = RequestMethod.GET)
    public String getDeviceStandard(@ApiParam(name = "type", value = "类型1血糖,2血压", defaultValue = "1")
                                    @RequestParam(value = "type", required = true) Integer type){
        try {
            JSONObject json = patientHealthIndexService.getealthStandard(type,getRepUID());
            return write(200,"获取成功","data",json);
        } catch (Exception ex) {
            error(ex);
            return error(-1,"获取失败");
        }
    }
    /**
     * 设置及修改血糖仪时间段
     * 默认时间段如下
     * fasting: 00:00-07:59
     * afterBreakfast: 08:00-09:59
     * beforeLunch: 10:00-11:59
     * afterLunch: 12:00-13:59
     * beforeDinner: 14:00-17:59
     * afterDinner: 18:00-19:59
     * beforeSleep: 20:00-23:59
     */
    @ApiOperation("设置修改血糖仪时间段")
    @RequestMapping(value = "/setBloodTime", method = RequestMethod.GET)
    public String setBloodTime(@RequestParam(required = false) String fastingStart,
                               @RequestParam(required = false) String fastingEnd,
                               @RequestParam(required = false) String afterBreakfastStart,
                               @RequestParam(required = false) String afterBreakfastEnd,
                               @RequestParam(required = false) String beforeLunchStart,
                               @RequestParam(required = false) String beforeLunchEnd,
                               @RequestParam(required = false) String afterLunchStart,
                               @RequestParam(required = false) String afterLunchEnd,
                               @RequestParam(required = false) String beforeDinnerStart,
                               @RequestParam(required = false) String beforeDinnerEnd,
                               @RequestParam(required = false) String afterDinnerStart,
                               @RequestParam(required = false) String afterDinnerEnd,
                               @RequestParam(required = false) String beforeSleepStart,
                               @RequestParam(required = false) String beforeSleepEnd,
                               @RequestParam(required = false) String sim,
                               @RequestParam String deviceSN,
                               @RequestParam String categoryCode,
                               @RequestParam String userType,
                               @RequestParam(required = false) String newDeviceSN,
                               @RequestParam(required = false) String hospital,
                               @RequestParam(required = false) String hospitalName,
                               @RequestParam(required = false) String checkDoctorName) {
        try {
//            String user = getUID();
            String user = getRepUID();
            if (StringUtils.isNotEmpty(newDeviceSN)) {
//                校验新的sn码 1.是否被占用 2.是否是真的设备码
                if(!newDeviceSN.equals(deviceSN)){
                    //有改sn码
                    DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(newDeviceSN, userType);
                    if (device != null) {
                        throw new Exception("sn码" + newDeviceSN + "已被使用!");
                    }
                    if(!patientDeviceService.checkDeviceSn(newDeviceSN)){
                        return error(-1,"设备不存在");
                    }
                }
                if ("1".equals(categoryCode)) {
//                        先修改患者设备绑定表
                    int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType,sim,hospital,hospitalName,checkDoctorName);
                    if (rows != 0) {
                        //                只更换设备编码,不更改时间值
//                1.先查询是否自定义时间段,没有则新增,有则修改
                        PatientHealthTime healthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
                        if (healthTime == null) {
                            patientDeviceService.setBloodTime(user, newDeviceSN, "null", "null", "null", "null", "null", "null",
                                    "null", "null", "null", "null", "null", "null", "null", "null");
                        } else {
                            patientDeviceService.updateDeviceSN(user, deviceSN, newDeviceSN);
                        }
                    }
                }else {
                    int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType,sim,hospital,hospitalName,checkDoctorName);
                }
                return write(200, "更改sv码成功!");
            }
            patientDeviceService.setBloodTime(user, deviceSN, fastingStart, fastingEnd, afterBreakfastStart, afterBreakfastEnd, beforeLunchStart, beforeLunchEnd,
                    afterLunchStart, afterLunchEnd, beforeDinnerStart, beforeDinnerEnd, afterDinnerStart, afterDinnerEnd, beforeSleepStart, beforeSleepEnd);
            return write(200, "设置成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            DevicePatientDevice device = objectMapper.readValue(json, DevicePatientDevice.class);
            if(StringUtils.isBlank(device.getDeviceSn())){
                return write(-1,"sn码不能为空!");
            }
            // 设置患者标识
            device.setUser(getRepUID());
//            device.setUser(getUID());
            //患者和设备是否首绑
            Map<String,Object> checkMap = patientDeviceService.checkBindingFirstAndType(device);
            boolean flag = (Boolean)checkMap.get("flag");
            int code = (Integer)checkMap.get("code");
            if (code==-30000){
                return write(-1,"设备不存在或者数据存在错误!");
            }
            BasePatientDO patient = patientService.findById(getRepUID()).orElse(null);
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
                device.setAgentName(patient.getName());
            }
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                patientDeviceService.saveDevice(device);
                patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),2,1);
            }
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            String flagStr ="";
            if ("1".equals(device.getCategoryCode())){
                flagStr="GLU_BIND";
            }else if ("2".equals(device.getCategoryCode())){
                flagStr="BP_BIND";
            }
            //活动的活跃度
            if (flag){
                com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                jsonObject.put("patientId",patient.getId());
                jsonObject.put("taskCode",flagStr);
            }
            if(!"11".equals(device.getCategoryCode())){
                try {
                    String openId = patient.getOpenid();
                    String name = patient.getName();
                    JSONObject sendJson = new JSONObject();
                    String first = "";
                    String remark = "";
                    String deviceName = device.getDeviceName();
                    WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_patient_bind_device","bdsb");
                    first = templateConfig.getFirst();
                    first = first.replace("key1",(deviceName==null?"":deviceName));
                    remark = templateConfig.getRemark();
                    sendJson.put("keyword1", deviceName);
                    sendJson.put("keyword2", DateUtil.dateToStrLong(device.getCzrq()));
                    sendJson.put("keyword3", templateConfig.getKeyword3());
                    sendJson.put("first", first);
                    sendJson.put("remark", remark);
                    sendJson.put("url", templateConfig.getUrl());//带参数的模板跳转链接
                    System.out.println(sendJson.toString());
                    pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 22, openId, name, sendJson);
                }catch (Exception e){
                    logger.info("设备绑定微信模板消息发送失败:"+e.getMessage());
                }
            }
            return success("设备保存成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    public String getDeviceByPatient(@ApiParam(name = "id", value = "分页起始id", defaultValue = "0")
                                     @RequestParam(value = "id", required = true) long id,
                                     @ApiParam(name = "pagesize", value = "每页条数", defaultValue = "10")
                                     @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            Page<DevicePatientDevice> list = patientDeviceService.findByPatient(getRepUID(), id, pagesize);
            return write(200, "查询成功", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    //要增加时间段信息展示
    @ApiOperation("获取患者设备信息")
    @RequestMapping(value = "PatientDeviceInfo", method = RequestMethod.GET)
    public String getPatientDeviceInfo(@ApiParam(name = "id", value = "患者设备ID", defaultValue = "146")
                                       @RequestParam(value = "id", required = true) String id) {
        try {
            Map mapList = new HashMap();
            DevicePatientDevice device = patientDeviceService.findById(id);
            String deviceSN = device.getDeviceSn();
            String user = device.getUser();
            if(!device.getCategoryCode().equals("4")) {
                Map map = patientDeviceService.getBloodSuggerTime(user, deviceSN);
                mapList.put("time", map);
            }
            mapList.put("device", device);
            return write(200, "查询成功", "data", mapList);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 通过sn码获取设备绑定情况
     */
    @ApiOperation("通过sn码获取设备绑定情况")
    @RequestMapping(value = "PatientDeviceIdcard", method = RequestMethod.GET)
    public String getDeviceUser(@ApiParam(name = "type", value = "设备类型", defaultValue = "1")
                                @RequestParam(value = "type", required = true) String type,
                                @ApiParam(name = "device_sn", value = "设备SN码", defaultValue = "15L000002")
                                @RequestParam(value = "device_sn", required = true) String deviceSn) {
        try {
            if (!"11".equals(type)&&deviceDetailService.findByDeviceSn(deviceSn)==null){
                return write(-1,"设备不存在!");
            }
            List<Map<String, String>> list = patientDeviceService.getDeviceUser(getRepUID(), deviceSn, type);
            return write(200, "获取设备绑定信息成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    
    /**
     * 发送设备审核系统消息
     */
    @ApiOperation("发送设备审核系统消息")
    @RequestMapping(value = "sendDeviceReviewMessage",method = RequestMethod.POST)
    public String sendDeviceReviewMessage(@ApiParam(name = "id", value = "删除设备关联ID")
                                              @RequestParam(value = "id", required = true) String id,
                                          @ApiParam(name = "reson", value = "解绑理由")
                                          @RequestParam(value = "reson", required = true) String reson){
        try {
            DevicePatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
//                if (!StringUtils.equals(pd.getUser(), getUID())) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                //居民自主解绑设备时发送消息给医生
                BasePatientDO patient = patientService.findById(getRepUID()).orElse(null);
                String messageContent =  "您的居民"+patient.getName()+"申请解绑智能设备:"+pd.getDeviceName()+",请及时处理";
//                if ("1".equals(pd.getCategoryCode())){
//                    messageContent +="血糖仪,点击下方查看居民详情";
//                }else if ("2".equals(pd.getCategoryCode())){
//                    messageContent +="血压计,点击下方查看居民详情";
//                }else if ("4".equals(pd.getCategoryCode())){
//                    messageContent +="智能手表,点击下方查看居民详情";
//                }
                
                JSONObject contentObj = new JSONObject();
                contentObj.put("reason",reson);
                contentObj.put("messageContent",messageContent);
                contentObj.put("patientName",patient.getName());
                
/*                Message message = new Message();
                message.setCzrq(new Date());
                message.setCreateTime(new Date());
                message.setContent(contentObj.toString());
                message.setRead(1);//设置未读
                message.setReceiver(signFamily.getDoctor());//设置接受医生的code
                message.setSender("admin");//设置发送的用户
                message.setSenderName("系统");
                message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
                message.setSenderPhoto("");
                message.setTitle("解绑设备审核消息");
                message.setType(302);//解绑设备消息
                message.setReadonly(1);//是否只读消息
                message.setSex(1);
                message.setRelationCode(id);
                message.setOver("1");//未处理
                message.setData("");
                message.setDel("1");
                messageDao.save(message);*/
    
                pd.setApplyStatus(1);//审核中
                pd.setApplyReason(reson);
                patientDeviceDao.save(pd);
                
                return success("申请成功!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备删除
     */
    @ApiOperation("设备删除")
    @RequestMapping(value = "DeletePatientDevice",method = {RequestMethod.GET,RequestMethod.POST})
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            DevicePatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
//                if (!StringUtils.equals(pd.getUser(), getUID())) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getRepUID());
//                patientDeviceService.deleteDevice(id, getUID());
                //居民自主解绑设备时发送消息给医生
                BasePatientDO patient = patientService.findById(getRepUID()).orElse(null);
                String messageContent =  "您的居民"+patient.getName()+"解绑了";
                if ("1".equals(pd.getCategoryCode())){
                    messageContent +="血糖仪,点击下方查看居民详情";
                }else if ("2".equals(pd.getCategoryCode())){
                    messageContent +="血压计,点击下方查看居民详情";
                }else if ("4".equals(pd.getCategoryCode())){
                    messageContent +="智能手表,点击下方查看居民详情";
                }
/*                Message message = new Message();
                message.setCzrq(new Date());
                message.setCreateTime(new Date());
                message.setContent(messageContent);
                message.setRead(1);//设置未读
                message.setReceiver(signFamily.getDoctor());//设置接受医生的code
                message.setSender("admin");//设置发送的用户
                message.setSenderName("系统");
                message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
                message.setSenderPhoto("");
                message.setTitle("解绑设备消息");
                message.setType(301);//解绑设备消息
                message.setReadonly(1);//是否只读消息
                message.setSex(1);
                message.setRelationCode(patient.getCode());
                message.setOver("1");//未处理
                message.setData("");
                message.setDel("1");
                messageDao.save(message);*/
                //全部解绑后去判断就更新设备表中是否绑定字段
                patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),2,2);
                deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
                return success("设备已删除!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @ApiOperation("获取居民的设备任务信息")
    @RequestMapping(value = "getPatientDeviceTaskInfo",method = RequestMethod.POST)
    public String getPatientDeviceTaskInfo(@ApiParam(name = "patientCode",value = "患者code")@RequestParam(value = "patientCode",required = true)String patientCode){
        try {
            return write(200,"执行成功","data",patientDeviceService.getPatientDeviceTaskInfo(patientCode));
        }catch (Exception e){
            return write(-1,"执行失败!");
        }
    }
}

+ 564 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientHealthController.java

@ -0,0 +1,564 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping(value = "/patient/health_index")
@Api(description = "患者指标")
public class PatientHealthController extends BaseController {
    @Autowired
    private PatientHealthIndexService healthIndexService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 更改接口(包括手动记录的修改和所有的删除)
     * 血糖  value1 血糖值 value2 1234567血糖时间段
     * 血压  value1 高压 value2 低压 value3脉搏 value4心率不齐(0否 1是)
     * 体重 value1 体重值
     * 腰围 value1 腰围值
     *  @param recordDate 记录时间
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ApiOperation("更改接口(包括手动记录的修改和所有的删除)")
    public String modify(@RequestParam long id,
                         @RequestParam(required = false) String recordDate,
                         @RequestParam(required = false) String value1,
                         @RequestParam(required = false) String value2,
                         @RequestParam(required = false) String value3,
                         @RequestParam(required = false) String value4) {
        try {
            healthIndexService.modify(id,recordDate, value1, value2, value3, value4);
            return write(200, "更改成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "更改失败!");
        }
    }
    @RequestMapping(value = "/getRecentData", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("患者最近的各项健康信息")
    public String getRecentData() {
        try {
            List list = new ArrayList();
            String patient = getRepUID();
//            String patient = getUID();
//            健康指标类型(1血糖,2血压,3体重,4腰围)
            Map map = healthIndexService.findDataByPatient(patient, 1);
            Map map1 = healthIndexService.findDataByPatient(patient, 2);
            Map map2 = healthIndexService.findDataByPatient(patient, 3);
            Map map3 = healthIndexService.findDataByPatient(patient, 4);
//            血糖各个时间段取值
            if (map.size() != 0) {
                Map sugar = new HashMap();
                Object time = map.get("time");
                String isDevice = map.get("isDevice").toString();
                Object value1 = map.get("value1");
                Object value2 = map.get("value2");
                Object value3 = map.get("value3");
                Object value4 = map.get("value4");
                Object value5 = map.get("value5");
                Object value6 = map.get("value6");
                Object value7 = map.get("value7");
                sugar.put("type", 1);
                sugar.put("isDevice", isDevice);
                if (time != null) {
                    sugar.put("time", time);
                }
                if (value1 != null) {
                    sugar.put("value1", value1);
                }
                if (value2 != null) {
                    sugar.put("value2", value2);
                }
                if (value3 != null) {
                    sugar.put("value3", value3);
                }
                if (value4 != null) {
                    sugar.put("value4", value4);
                }
                if (value5 != null) {
                    sugar.put("value5", value5);
                }
                if (value6 != null) {
                    sugar.put("value6", value6);
                }
                if (value7 != null) {
                    sugar.put("value7", value7);
                }
                list.add(sugar);
            }
//            血压  value1高压 value2低压 value3脉搏 value4心率不齐
            if (map1.size() != 0) {
                Map pa = new HashMap();
                Object time = map1.get("time");
                String isDevice = map1.get("isDevice").toString();
                Object value1 = map1.get("value1");
                Object value2 = map1.get("value2");
                Object value3 = map1.get("value3");
                Object value4 = map1.get("value4");
                Object value5 = map1.get("value5");
                Object value6 = map1.get("value6");
                Object value7 = map1.get("value7");
                pa.put("type", 2);
                pa.put("isDevice", isDevice);
                if (time != null) {
                    pa.put("time", time);
                }
                if (value1 != null) {
                    pa.put("value1", value1);
                }
                if (value2 != null) {
                    pa.put("value2", value2);
                }
                if (value3 != null) {
                    pa.put("value3", value3);
                }
                if (value4 != null) {
                    pa.put("value4", value4);
                }
                if (value5 != null) {
                    pa.put("value5", value5);
                }
                if (value6 != null) {
                    pa.put("value6", value6);
                }
                if (value7 != null) {
                    pa.put("value7", value7);
                }
                list.add(pa);
            }
//            体重 value1 体重
            if (map2.size() != 0) {
                Map weight = new HashMap();
                Object time = map2.get("time");
                String isDevice = map2.get("isDevice").toString();
                Object value1 = map2.get("value1");
                Object value2 = map2.get("value2");
                Object value3 = map2.get("value3");
                Object value4 = map2.get("value4");
                Object value5 = map2.get("value5");
                Object value6 = map2.get("value6");
                Object value7 = map2.get("value7");
                weight.put("type", 3);
                weight.put("isDevice", isDevice);
                if (time != null) {
                    weight.put("time", time);
                }
                if (value1 != null) {
                    weight.put("value1", value1);
                }
                if (value2 != null) {
                    weight.put("value2", value2);
                }
                if (value3 != null) {
                    weight.put("value3", value3);
                }
                if (value4 != null) {
                    weight.put("value4", value4);
                }
                if (value5 != null) {
                    weight.put("value5", value5);
                }
                if (value6 != null) {
                    weight.put("value6", value6);
                }
                if (value7 != null) {
                    weight.put("value7", value7);
                }
                list.add(weight);
            }
//            腰围 value1腰围
            if (map3.size() != 0) {
                Map waist = new HashMap();
                Object time = map3.get("time");
                String isDevice = map3.get("isDevice").toString();
                Object value1 = map3.get("value1");
                Object value2 = map3.get("value2");
                Object value3 = map3.get("value3");
                Object value4 = map3.get("value4");
                Object value5 = map3.get("value5");
                Object value6 = map3.get("value6");
                Object value7 = map3.get("value7");
                waist.put("type", 4);
                waist.put("isDevice", isDevice);
                if (time != null) {
                    waist.put("time", time);
                }
                if (value1 != null) {
                    waist.put("value1", value1);
                }
                if (value2 != null) {
                    waist.put("value2", value2);
                }
                if (value3 != null) {
                    waist.put("value3", value3);
                }
                if (value4 != null) {
                    waist.put("value4", value4);
                }
                if (value5 != null) {
                    waist.put("value5", value5);
                }
                if (value6 != null) {
                    waist.put("value6", value6);
                }
                if (value7 != null) {
                    waist.put("value7", value7);
                }
                list.add(waist);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "recent", method = RequestMethod.GET)
    @ApiOperation("患者最近填写的健康指标")
    public String recent() {
        try {
            JSONArray array = healthIndexService.findRecentByPatient(getRepUID());
            if (array != null) {
                return write(200, "查询成功", "list", array);
            } else {
                return error(-1, "查询失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "last", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取患者最后填写的健康指标(新)")
    public String last() {
        try {
            Map<String, Object> map = new HashMap<>();
            String patient = getRepUID();
            DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
            if (xt != null) {
                map.put("xt", xt);
            }
            DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
            if (xy != null) {
                map.put("xy", xy);
            }
            DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
            if (tz != null) {
                map.put("tz", tz);
            }
            DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
            if (sg != null) {
                map.put("sg", sg);
            }
            DevicePatientHealthIndex xl = healthIndexService.findLastByPatienIot(patient, 5);
            if (xl != null) {
                map.put("xl", xl);
            }
            return write(200, "查询成功", "data", map);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "last_new", method = RequestMethod.GET)
    @ApiOperation("获取患者最后填写的健康指标(新)-展会")
    public String last_new() {
        try {
            Map<String, Object> map = new HashMap<>();
            String patient = getRepUID();
            DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
            if (xt != null) {
                map.put("xt", xt);
            }
            DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
            if (xy != null) {
                map.put("xy", xy);
            }
            DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
            if (tz != null) {
                map.put("tz", tz);
            }
            DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
            if (sg != null) {
                map.put("sg", sg);
            }
            DevicePatientHealthIndex xl = healthIndexService.findLastByPatienIot(patient, 5);
            if (xl != null) {
                map.put("xl", xl);
            }
            return write(200, "查询成功", "data", map);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "addPatientHealthIndex", method = RequestMethod.POST)
    @ApiOperation("新增患者指标")
    public String addPatientHealthIndex(@ApiParam(name = "data", value = "指标数据", defaultValue = "{\"gi\":\"5.5\",\"gi_type\":\"1\"}")
                                        @RequestParam(value = "data", required = true) String data,
                                        @ApiParam(name = "type", value = "指标类型", defaultValue = "1")
                                        @RequestParam(value = "type", required = true) String type,
                                        @ApiParam(name = "patient", value = "patient", defaultValue = "1")
                                        @RequestParam(value = "patient", required = false) String patient) {
        try {
            if(StringUtils.isBlank(patient)){
                patient = getRepUID();
            }
            DevicePatientHealthIndex obj = healthIndexService.addPatientHealthIndex(data, type, patient, null);
            
            //血糖和血压需要校验
            if (type.equals("1") || type.equals("2")) {
                healthIndexService.verifyHealthIndex(obj.getId());
            }
            //判断居民的体征预警状态
//            healthIndexService.handlePatientStandarStatus(obj);
            return success("新增患者指标成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "verifyPatientHealthIndex", method = RequestMethod.POST)
    @ApiOperation("校验患者指标")
    public String verifyPatientHealthIndex(@ApiParam(name = "id", value = "指标id", defaultValue = "")
                                           @RequestParam(value = "id", required = true) Long id) {
        try {
            healthIndexService.verifyHealthIndex(id);
            return success("校验患者指标成功!");
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "chart", method = RequestMethod.POST)
    @ApiOperation("根据患者标志获取健康指标(图表)")
    public String getHealthIndexChartByPatient(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重,4腰围)", defaultValue = "1")
                                               @RequestParam(value = "type", required = true) int type,
                                               @ApiParam(name = "gi_type", value = "就餐类型0全部", defaultValue = "1")
                                               @RequestParam(value = "gi_type", required = false) int gi_type,
                                               @ApiParam(name = "begin", value = "开始时间", defaultValue = "2017-05-22 00:00:00")
                                               @RequestParam(value = "begin", required = true) String begin,
                                               @ApiParam(name = "end", value = "结束时间", defaultValue = "2017-06-02 00:00:00")
                                               @RequestParam(value = "end", required = true) String end) {
        try {
            JSONArray jsonArray = healthIndexService.findChartByPatient(getRepUID(), type, gi_type, begin, end);
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "chart_new", method = RequestMethod.POST)
    @ApiOperation("根据患者标志获取健康指标(图表)-展会")
    public String getHealthIndexChartByPatient_new(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重,4腰围)", defaultValue = "1")
                                               @RequestParam(value = "type", required = true) int type,
                                               @ApiParam(name = "gi_type", value = "就餐类型0全部", defaultValue = "1")
                                               @RequestParam(value = "gi_type", required = false) int gi_type,
                                               @ApiParam(name = "begin", value = "开始时间", defaultValue = "2017-05-22 00:00:00")
                                               @RequestParam(value = "begin", required = true) String begin,
                                               @ApiParam(name = "end", value = "结束时间", defaultValue = "2017-06-02 00:00:00")
                                               @RequestParam(value = "end", required = true) String end) {
        try {
            JSONArray jsonArray = healthIndexService.findChartByPatient(getRepUID(), type, gi_type, begin, end);
            if (jsonArray.length()==0) {
                return success("查询成功!");
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiOperation("患者获取健康指标")
    public String getHealthIndexByPatient(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重/身高,4腰围)", defaultValue = "1")
                                          @RequestParam(value = "type", required = true) int type,
                                          @ApiParam(name = "start", value = "开始时间", defaultValue = "2016-07-23 00:00:00")
                                          @RequestParam(value = "start", required = true) String start,
                                          @ApiParam(name = "end", value = "结束时间", defaultValue = "2016-08-23 00:00:00")
                                          @RequestParam(value = "end", required = true) String end,
                                          @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                          @RequestParam(value = "page", required = true) int page,
                                          @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                          @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            JSONObject jsonObject2 = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            if (type == 1) {
                List<Object> list = healthIndexService.findIndexByPatient2(getRepUID(), type, start, end, page, pagesize);
                jsonObject2.put("data",list);
            } else {
                jsonArray = healthIndexService.findIndexByPatient(getRepUID(), type, start, end, page, pagesize);
                JSONArray jsonArray1 = new JSONArray();
                jsonObject2.put("data",jsonArray);
            }
            return write(200, "查询成功", "list", jsonObject2);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "list_new", method = RequestMethod.POST)
    @ApiOperation("患者获取健康指标-展会")
    public String getHealthIndexByPatient_new(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重/身高,4腰围)", defaultValue = "1")
                                          @RequestParam(value = "type", required = true) int type,
                                          @ApiParam(name = "start", value = "开始时间", defaultValue = "2016-07-23 00:00:00")
                                          @RequestParam(value = "start", required = true) String start,
                                          @ApiParam(name = "end", value = "结束时间", defaultValue = "2016-08-23 00:00:00")
                                          @RequestParam(value = "end", required = true) String end,
                                          @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                          @RequestParam(value = "page", required = true) int page,
                                          @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                          @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            JSONArray jsonArray = new JSONArray();
            if (type == 1) {
                List<Object> list = healthIndexService.findIndexByPatient2(getRepUID(), type, start, end, page, pagesize);
                jsonArray = new JSONArray(list);
            } else {
                jsonArray = healthIndexService.findIndexByPatient(getRepUID(), type, start, end, page, pagesize);
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "standard", method = RequestMethod.GET)
    @ApiOperation("患者健康指标预警值查询")
    public String standard() {
        try {
            JSONArray standardArray = new JSONArray();
            JSONArray userArray = new JSONArray();
            Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(getRepUID());
            Iterator<PatientHealthStandard> iterator = null;
            if (iterable != null) {
                iterator = iterable.iterator();
            }
            // 预警值未设置,返回默认值
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            // 默认血糖(餐前,餐后二小时)
            sb.append("{min_value_1:3.9, max_value_1:6.1, min_value_2:4.4, max_value_2:7.8, type:1},");
            // 默认血压(收缩压,舒张压)
            sb.append("{min_value_1:90, max_value_1:139, min_value_2:60, max_value_2:89, type:2}");
            sb.append("]");
            standardArray = new JSONArray(sb.toString());
            if (iterator != null) {
                while (iterator.hasNext()) {
                    PatientHealthStandard phs = iterator.next();
                    if (phs == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // 最低安全值(血糖餐前\收缩压\体重\腰围)
                    json.put("min_value_1", phs.getMinValue1());
                    // 最高安全值(血糖餐前\收缩压\体重\腰围)
                    json.put("max_value_1", phs.getMaxValue1());
                    // 最低安全值(血糖餐后\舒张压)
                    json.put("min_value_2", phs.getMinValue2());
                    // 最高安全值(血糖餐后\舒张压)
                    json.put("max_value_2", phs.getMaxValue2());
                    // 健康指标类型:1血糖,2血压,3体重,4腰围
                    json.put("type", phs.getType());
                    userArray.put(json);
                }
            }
            JSONObject json = new JSONObject();
            json.put("standard", standardArray);
            json.put("custom", userArray);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 奕拓小屋查询体征数据,根据体征类型查询
     *
     * @param type
     * @param page
     * @param size
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping(value = "/getDataByType")
    @ApiOperation(value = "体征类型查询数据", notes = "体征类型查询数据")
    public String getDataByType(
            @ApiParam(name = "type", value = "体征类型", required = true) @RequestParam String type,
            @ApiParam(name = "page", value = "页", required = true) @RequestParam(defaultValue = "1") int page,
            @ApiParam(name = "size", value = "数量", required = true) @RequestParam(defaultValue = "15") int size,
            @ApiParam(name = "beginTime", value = "开始时间", required = false) @RequestParam String beginTime,
            @ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam String endTime
    ) throws Exception {
        return write(200, "查询成功", "data", new ArrayList<>());
    }
    /**
     * 奕拓小屋查询体征数据,根据设备记录id查询详情
     *
     * @param mid
     * @return
     */
    @GetMapping(value = "/getDataDetailById")
    @ApiOperation(value = "根据设备id查询详情", notes = "数据详情")
    public String getDataDetailById(
            @ApiParam(name = "mid", value = "设备测试记录id", required = true) @RequestParam String mid,
            @ApiParam(name = "t'y'pe", value = "体征类型", required = true) @RequestParam String type
    ) throws Exception {
        return write(200, "查询成功", "data", new ArrayList<>());
    }
}

+ 189 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java

@ -0,0 +1,189 @@
package com.yihu.jw.hospital.module.health.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
 * 设备管理(device库)
 * zd
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class DeviceDetailService {
	@Autowired
	private DeviceDetailDao deviceDetailDao;
	@Autowired
	private DeviceDao deviceDao;
	@Autowired
	private BasePatientDao patientDao;
	@Autowired
	private BaseDoctorDao doctorDao;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**
	 * 绑定时更新设备表中的信息
	 * @param patientDevice
	 * @param grantTime
	 * @param isFirst
	 * @throws Exception
	 */
	@Transactional
	public void updateAfterBinding(DevicePatientDevice patientDevice, Date grantTime, boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		int bind = deviceDetail.getIsBinding();
//		SignFamily signFamily = signFamilyDao.findByIdcard(patientDevice.getUserIdcard());
		long adminTeam=0L;
		String hospital = "";
		String isFirstBind = "";
		String hospitalName = "";
		String doctorCode ="";
		String doctorName="";
		String keyType = "1";
		if ("2".equals(patientDevice.getUserType())){
			keyType="2";
		}
//		if (signFamily!=null){
//			adminTeam = signFamily.getAdminTeamId();
//			hospital = signFamily.getHospital();
//			hospitalName = signFamily.getHospitalName();
//			doctorCode = signFamily.getDoctor();
//			doctorName = signFamily.getDoctorName();
//		}
		//设备表没有数据则插入一条数据
		if (deviceDetail==null){
			insertDevice(patientDevice,String.valueOf(adminTeam),hospitalName,hospital,"",doctorCode,doctorName,1);
			deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		}
		isFirstBind = deviceDetail.getBindingCount();
		if (StringUtils.isNotBlank(isFirstBind)){
			JSONObject jsonObject = JSON.parseObject(isFirstBind);
			int bindCount = Integer.valueOf(String.valueOf(jsonObject.get(keyType)));
			jsonObject.replace(keyType,bindCount+1+"");
			isFirstBind = jsonObject.toJSONString();
		}
		if (isFirst){
			String updateFirstSql ="update wlyy_devices dd set dd.is_grant=1,dd.grant_admin_team=?,dd.grant_org_code=?,dd.binding_count=?,dd.grant_time = ?,dd.org_name=?,dd.grant_doctor=?,dd.grant_doctor_name=?,dd.is_binding=1 where dd.device_code=?";
			jdbcTemplate.update(updateFirstSql,new Object[]{String.valueOf(adminTeam),hospital,isFirstBind,grantTime,hospitalName,doctorCode, "",patientDevice.getDeviceSn()});
		}else {
			List<DevicePatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(patientDevice.getDeviceSn());
			int patientDeviceSize = patientDeviceList.size();
			String updateSql = "";
			if (bind == 0){
				updateSql ="update wlyy_devices dd set dd.is_grant=1,dd.grant_admin_team=?,dd.grant_org_code=?,dd.binding_count=?,dd.is_binding=?,dd.org_name=?,dd.grant_doctor=?,dd.grant_doctor_name=?  where dd.device_code=?";
				jdbcTemplate.update(updateSql,new Object[]{String.valueOf(adminTeam),hospital,isFirstBind,patientDeviceSize,hospitalName,doctorCode,"",patientDevice.getDeviceSn()});
			}else if (bind>0){
				updateSql ="update wlyy_devices dd set dd.is_grant=1,dd.binding_count=?,dd.is_binding=? where dd.device_code=?";
				jdbcTemplate.update(updateSql,new Object[]{isFirstBind,patientDeviceSize,patientDevice.getDeviceSn()});
			}
		}
	}
	/**
	 * 绑定时设备表如果没有数据则插入一条数据
	 * @param patientDevice
	 * @param adminTeam
	 * @param orgName
	 * @param orgCode
	 * @param bindCount
	 * @param isBind 0未绑定  1已绑定
	 * @throws Exception
	 */
	public void insertDevice(DevicePatientDevice patientDevice, String adminTeam, String orgName, String orgCode,String bindCount,String doctorCode,String doctorName,int isBind)throws Exception{
		//获取原始数据
		DeviceDetail deviceDetail = new DeviceDetail();
		BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
		BaseDoctorDO doctor = doctorDao.findByIdAndDel(patientDevice.getDoctor());
		Device device = deviceDao.findById(patientDevice.getDeviceId()).orElse(null);
		//添加数据到具体字段
		deviceDetail.setDeviceCode(patientDevice.getDeviceSn());
		deviceDetail.setDeviceName(patientDevice.getDeviceName());
		deviceDetail.setSim(patientDevice.getSim());
		deviceDetail.setGrantAdminTeam(adminTeam);
		deviceDetail.setGrantOrgCode(orgCode);
		deviceDetail.setGrantTime(patientDevice.getCzrq());
		deviceDetail.setApplyDate(DateUtil.getStringDate("yyyy-MM-dd HH:mm:ss"));
		deviceDetail.setOrgName(orgName);
		deviceDetail.setGrantDoctor(doctorCode);
		deviceDetail.setGrantDoctorName(doctorName);
		if (isBind>0){
			deviceDetail.setIsGrant(1);
			deviceDetail.setIsBinding(1);
		}else {
			deviceDetail.setIsGrant(0);
			deviceDetail.setIsBinding(0);
		}
		if (device!=null){
			deviceDetail.setDeviceModel(device.getModel());
		}
		if (StringUtils.isNotEmpty(bindCount)){
			deviceDetail.setBindingCount(bindCount);
		}else {
			if (Integer.valueOf(patientDevice.getUserType())>0){
				deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
			}else {
				deviceDetail.setBindingCount("{\"1\":\"0\"}");
			}
		}
		if (patient!=null){
			deviceDetail.setLinkman(patient.getName());
			deviceDetail.setTel(patient.getPhone());
		}
		if (doctor!=null){
			deviceDetail.setApplicantName(doctor.getName());
			deviceDetail.setApplicantIdentity(doctor.getIdcard());
			deviceDetail.setApplicantTel(doctor.getMobile());
			deviceDetail.setApplicantMail(doctor.getMobile());
		}
		deviceDetailDao.save(deviceDetail);
	}
	/**
	 * 全部解绑后设备表更新为未绑定
	 * @param deviceSn
	 */
	public void unBindUpdateIsBinding(String deviceSn)throws Exception{
		List<DevicePatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(deviceSn);
		String sql = "update wlyy_devices dd set dd.is_binding=? where dd.device_code=?";
		if (patientDeviceList.size()==0){
			jdbcTemplate.update(sql,new Object[]{0,deviceSn});
		}
		if (patientDeviceList.size()==1){
			jdbcTemplate.update(sql,new Object[]{1,deviceSn});
		}
		if (patientDeviceList.size()>1){
			jdbcTemplate.update(sql,new Object[]{2,deviceSn});
		}
	}
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
}

+ 51 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceService.java

@ -0,0 +1,51 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.DeviceCategoryDao;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceCategory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 设备管理
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class DeviceService {
	@Autowired
	private DeviceCategoryDao deviceCategoryDao;
	@Autowired
	private DeviceDao deviceDao;
	/**
	 * 查询所有的设备类型
	 * @return
	 */
	public List<DeviceCategory> findAllCategory() {
		return deviceCategoryDao.findAll();
	}
	/**
	 * 查询设备信息
	 */
	public List<Device> findDeviceByCategory(String categoryCode) {
		return deviceDao.findByCategoryCode(categoryCode);
	}
	/**
	 * 获取设备信息
     */
	public Device findById(String id)
	{
		return deviceDao.findById(Long.valueOf(id)).orElse(null);
	}
}

+ 93 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceWxMessageService.java

@ -0,0 +1,93 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.DeviceWxMessageDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.device.DeviceWxMessage;
import com.yihu.jw.restmodel.base.device.DeviceWxMessageDTO;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@Transactional(rollbackFor = Exception.class)
public class DeviceWxMessageService{
    @Autowired
    private DeviceWxMessageDao deviceWxMessageDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<DeviceWxMessageDTO> batchSaveAndSendActiveMq(String data)throws Exception{
        JSONArray jsonArray = new JSONArray(data);
        List<DeviceWxMessage> messageList = new ArrayList<>();
        for (int i=0;i<jsonArray.length();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            DeviceWxMessage deviceWxMessage = new DeviceWxMessage();
            deviceWxMessage.setPatient(jsonObject.getString("patient"));
            deviceWxMessage.setCategoryCode(jsonObject.getString("categoryCode"));
            deviceWxMessage.setDeviceName(jsonObject.getString("deviceName"));
            deviceWxMessage.setDeviceSn(jsonObject.getString("deviceSn"));
            deviceWxMessage.setCzrq(new Date());
            messageList.add(deviceWxMessage);
        }
        //批量插入数据
        deviceWxMessageDao.saveAll(messageList);
        //放入队列的数据集(相同用户不同设备各发一条  相同设备发一条)
        Map<String,List<String>> map = new HashedMap();
        for (DeviceWxMessage deviceWxMessage : messageList) {
            List<String> deviceTypeList = null;
            if (map.containsKey(deviceWxMessage.getPatient())){
                deviceTypeList = map.get(deviceWxMessage.getPatient());
                if (deviceTypeList==null){
                    deviceTypeList = new ArrayList<>();
                    deviceTypeList.add(deviceWxMessage.getCategoryCode());
                    map.put(deviceWxMessage.getPatient(),deviceTypeList);
                }else {
                    boolean flag = false;
                    if (!deviceTypeList.contains(deviceWxMessage.getCategoryCode())){
                        flag=true;
                    }
                    if (flag){
                        deviceTypeList.add(deviceWxMessage.getCategoryCode());
                        map.put(deviceWxMessage.getPatient(),deviceTypeList);
                    }
                }
            }else {
                deviceTypeList = new ArrayList<>();
                deviceTypeList.add(deviceWxMessage.getCategoryCode());
                map.put(deviceWxMessage.getPatient(),deviceTypeList);
            }
         }
        List<DeviceWxMessageDTO> deviceWxMessageDTOS = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            String patient = entry.getKey();
            List<String> list = entry.getValue();
            for (String deviceType : list){
                DeviceWxMessageDTO deviceWxMessageDTO =  new DeviceWxMessageDTO();
                deviceWxMessageDTO.setPatient(patient);
                deviceWxMessageDTO.setDeviceType(Integer.valueOf(deviceType));
                deviceWxMessageDTO.setCzrq(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
                deviceWxMessageDTOS.add(deviceWxMessageDTO);
            }
        }
        return deviceWxMessageDTOS;
    }
}

+ 129 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceLogService.java

@ -0,0 +1,129 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.device.dao.PatientDeviceLogDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.patient.PatientDeviceLog;
import com.yihu.jw.patient.dao.BasePatientDao;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceLogService {
    @Autowired
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientDao patientDao;
    /**
     * 绑定和解绑的时候会保存一条数据
     * @param patientDevice
     * @param role
     * @param operateCode
     * @throws Exception
     */
    @Transactional
    public void savePatientDeviceLog(DevicePatientDevice patientDevice, String deviceSn, int role, int operateCode)throws Exception{
       if (patientDevice==null){
           patientDevice = patientDeviceDao.findByDeviceSn(deviceSn).get(0);
       }
        PatientDeviceLog patientDeviceLog = new PatientDeviceLog();
        patientDeviceLog.setDeviceId(patientDevice.getDeviceId());
        patientDeviceLog.setPatient(patientDevice.getUser());
        patientDeviceLog.setCategoryCode(patientDevice.getCategoryCode());
        patientDeviceLog.setDeviceName(patientDevice.getDeviceName());
        patientDeviceLog.setDeviceSn(patientDevice.getDeviceSn());
        patientDeviceLog.setRole(role);
        patientDeviceLog.setOperateCode(operateCode);
        patientDeviceLog.setAgreementPhoto(patientDevice.getAgreementPhoto());
        patientDeviceLog.setHospital(patientDevice.getHospital());
        patientDeviceLog.setHospitalName(patientDevice.getHospitalName());
        patientDeviceLog.setCheckDoctorName(patientDevice.getCheckDoctorName());
        if (role==1){
            patientDeviceLog.setOperatorName(patientDevice.getDoctorName());
            patientDeviceLog.setOperator(patientDevice.getDoctor());
        }else if (role==2){
            if(StringUtils.isEmpty(patientDevice.getAgent())){
                BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
                if (patient!=null){
                    patientDeviceLog.setOperatorName(patient.getName());
                    patientDeviceLog.setOperator(patient.getId());
                }
            }else {
                patientDeviceLog.setOperatorName(patientDevice.getAgentName());
                patientDeviceLog.setOperator(patientDevice.getAgent());
            }
        }
        patientDeviceLog.setCreateTime(new Date());
        patientDeviceLog.setIsDel(1);
        patientDeviceLogDao.save(patientDeviceLog);
    }
    public Map<String,Object> getDevicesList(String doctor,String noGaugeDay,String isBinding,String categoryCode,String isSend,int pageNo,int pageSize){
        List<Map<String,Object>> resultList =  new ArrayList<>();
        Map<String,Object> resultMap = new HashedMap();
        int start = (pageNo-1)*pageSize;
        String sql ="SELECT b.*,dd.photo FROM (SELECT a.* FROM (" +
                "  SELECT sf.name, pd.* FROM wlyy_patient_device_log pd" +
                "  LEFT JOIN wlyy_sign_family sf ON pd.patient = sf.patient" +
                "  WHERE" +
                "  pd.is_del = 1 and sf.doctor= '"+doctor+"'  and sf.`status`>0"+
                "  ORDER BY" +
                "  pd.create_time DESC) a" +
                " GROUP BY a.device_sn,a.patient) b" +
                " LEFT JOIN dm_device dd ON b.device_id = dd.id where 1=1 ";
        resultList = jdbcTemplate.queryForList(sql);
        resultMap.put("tatalCount",resultList.size());
        //筛选条件--是否绑定
        if (!StringUtils.isEmpty(isBinding)){
            sql += " and b.operate_code= "+isBinding;
        }
        //筛选条件--设备类型
        if (!StringUtils.isEmpty(categoryCode)){
            sql += " and b.category_code= "+categoryCode;
        }
        //筛选条件--今日未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("1",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE TO_DAYS(record_date)=TO_DAYS(NOW()))";
        }
        //筛选条件--七天内未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("2",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= DATE(record_date))";
        }
        //筛选条件--一个月内未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("3",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= DATE(record_date))";
        }
        //筛选条件--超过一个月未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("4",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE  DATE_SUB(DATE_SUB(CURDATE(), INTERVAL 1 MONTH),INTERVAL 1 DAY) <= DATE(record_date))";
        }
        //发送消息要筛选未发送消息的设备
        if (StringUtils.isNotEmpty(isSend)){
            sql += " and b.device_sn NOT IN (SELECT device_sn FROM wlyy_device_wx_message WHERE TO_DAYS(czrq) = TO_DAYS(NOW()))";
        }
        sql += " limit ?,?";
        resultList = jdbcTemplate.queryForList(sql,new Object[]{start,pageSize});
        resultMap.put("data",resultList);
        return resultMap;
    }
}

+ 652 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java

@ -0,0 +1,652 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.device.PatientBloodSugger;
import com.yihu.jw.entity.base.device.PatientHealthTime;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.patient.PatientDeviceLog;
import com.yihu.jw.message.service.WxMessageUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.Predicate;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceService  {
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientBloodSuggerDao patientBloodSuggerDao;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    /**
     * 验证sn码 先调总部接口 未注册才查询本地数据库,如果也没有才不能绑定
     * 屏蔽总部调总部接口,直接本地数据库验证,modify by Hmf on 2020.1.15
     * @param deviceSn
     * @return
     * @throws Exception
     */
    public Boolean checkDeviceSn(String deviceSn) throws Exception{
        Boolean flag = false;
        DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
        if(deviceDetail != null){
            flag = true;
        }
        return flag;
    }
    /**
     * 保存患者设备
     */
    public boolean saveDevice(DevicePatientDevice patientDevice) throws Exception {
        //判断sn码是否被使用
        String sn = patientDevice.getDeviceSn();
        String type = patientDevice.getCategoryCode();
        Long deviceId = patientDevice.getDeviceId();
        String userType = patientDevice.getUserType();
        if (userType == null) {
            userType = "-1";
            patientDevice.setUserType("-1");
        }
        boolean needVerify = true;
        //修改操作
        if (patientDevice.getId() != null) {
            DevicePatientDevice deviceOld = patientDeviceDao.findById(patientDevice.getId()).orElse(null);
            if (deviceOld != null) {
                if (deviceOld.getDeviceSn().equals(sn)) {
                    needVerify = false;
                }
            } else {
                throw new ServiceException("不存在该条记录!");
            }
        }
        //校验sn码是否被使用
        if (needVerify) {
            DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
            if (device != null && !device.getId().equals(patientDevice.getId())) {
                throw new ServiceException("sn码" + sn + "已被使用!");
            }
        }
        patientDevice.setCzrq(new Date());
        patientDevice.setDel(0);
        //当前用户的身份证
        BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
        patientDevice.setUserIdcard(patient.getIdcard());
        if(checkDeviceSn(sn)){
            savePatientDevice(patientDevice);
        }else {
            String message = "设备不存在";
            throw new ServiceException(message);
        }
        return true;
    }
    /**
     * 设备绑定
     * @param patientDevice
     */
    public void savePatientDevice(DevicePatientDevice patientDevice){
        patientDeviceDao.save(patientDevice);
    }
    public void deleteDevices(String deviceSn, String type, String uuid) {
        List<DevicePatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (patientDevices == null || patientDevices.size() == 0) {
            throw new ServiceException("设备未被绑定!");
        }
        for (DevicePatientDevice patientDevice : patientDevices) {
            patientDeviceDao.delete(patientDevice);
        }
    }
    /**
     * 删除患者设备
     */
    public List<com.alibaba.fastjson.JSONObject> deleteDevice(String id, String uuid) {
        DevicePatientDevice device = patientDeviceDao.findById(Long.valueOf(id)).orElse(null);
        patientDeviceDao.delete(device);
        List<DevicePatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(device.getDeviceSn(), device.getCategoryCode());
        List<com.alibaba.fastjson.JSONObject> objects = new ArrayList<>();
        for (DevicePatientDevice patientDevice : patientDevices) {
            String json = com.alibaba.fastjson.JSONObject.toJSONString(patientDevice) ;
            com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(json) ;
            BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.add(object);
        }
        return objects;
    }
    /**
     * 患者设备列表接口(分页)
     */
    public Page<DevicePatientDevice> findByPatient(String patientCode,final Long id, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = Sort.by(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = PageRequest.of(0, pageSize, sort);
        Specification<DevicePatientDevice> specification = (root, criteriaQuery, criteriaBuilder) -> {
            //增加筛选条件
            Predicate predicate = criteriaBuilder.conjunction();
            predicate.getExpressions().add(criteriaBuilder.equal(root.get("user"), patientCode));
            predicate.getExpressions().add(criteriaBuilder.lt(root.get("id"), id));
            return predicate;
        };
        return patientDeviceDao.findAll(specification, pageRequest);
    }
    /**
     * 患者设备列表接口--医生端
     */
    public List<Map<String, Object>> findByDoctor(String patientCode, String doctorCode, int page, int pagesize) {
        List<Map<String, Object>> re = new ArrayList<>();
        if (page <= 0) {
            page = 1;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        PageRequest pageRequest = PageRequest.of(page - 1, pagesize);
        List<DevicePatientDevice> list = new ArrayList<>();
        list = patientDeviceDao.findByUser(patientCode, pageRequest);
        if (list != null) {
            //获取设备路径,医生姓名
            List<Device> deviceList = deviceDao.findAll();
            BaseDoctorDO self = doctorDao.findByIdAndDel(doctorCode);
            for (DevicePatientDevice item : list) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(item.getDoctor())) {
                    if (StringUtils.equals(item.getDoctor(), doctorCode)) {
                        map.put("role", 1);//可解绑自己绑定的
                    } else {
                        map.put("role", 0);//不同行政团队不可解绑
                    }
                } else {
                    map.put("role", 0);//患者自己绑定无法解绑
                }
                map.put("id", item.getId());
                map.put("deviceId", item.getDeviceId());
                map.put("deviceSn", item.getDeviceSn());
                map.put("user", item.getUser());
                map.put("categoryCode", item.getCategoryCode());
                map.put("userType", item.getUserType());
                map.put("applyStatus", item.getApplyStatus());
                map.put("applyReason", item.getApplyReason());
                map.put("userIdcard", item.getUserIdcard());
                map.put("czrq", DateUtil.dateToStrLong(item.getCzrq()));
                String deviceDoctor = item.getDoctor();
                if (deviceDoctor == null) {
                    map.put("doctor", "");
                    map.put("doctorName", "");
                } else {
                    map.put("doctor", deviceDoctor);
                    if (deviceDoctor.equals(doctorCode)) {
                        map.put("doctorName", self.getName());
                    } else {
                        BaseDoctorDO doctor = doctorDao.findByIdAndDel(deviceDoctor);
                        if (doctor != null) {
                            map.put("doctorName", doctor.getName());
                        } else {
                            map.put("doctorName", "");
                        }
                    }
                }
                //获取设备路径
                for (Device de : deviceList) {
                    if (de.getId().equals(item.getDeviceId())) {
                        map.put("deviceName", de.getName());
                        map.put("devicePhoto", de.getPhoto());
                        map.put("deviceBrands", de.getBrands());
                        break;
                    }
                }
                re.add(map);
            }
        }
        re.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if (o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) > 0) {
                    return -1;
                }
                if (o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) < 0) {
                    return 1;
                }
                return 0;
            }
        });
        return re;
    }
    /**
     * 查询患者已拥有的设备
     *
     * @param patient
     * @return
     */
    public Iterator<DevicePatientDevice> findPatientHave(String patient) {
        return patientDeviceDao.findByUser(patient).iterator();
    }
    /**
     * 获取患者设备信息
     **/
    public DevicePatientDevice findById(String id) {
        return patientDeviceDao.findById(Long.valueOf(id)).orElse(null);
    }
    /**
     * 通过sn码获取设备绑定情况
     **/
    public List<Map<String, String>> getDeviceUser(String user, String deviceSn, String type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        List<DevicePatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (list != null) {
            for (DevicePatientDevice item : list) {
                Map<String, String> map = new HashMap<>();
                map.put("type", item.getUserType());
                String code = item.getUser();
                if (code.equals(user)) {
                    map.put("others", "0");
                } else {
                    map.put("others", "1");
                }
                //获取姓名
                BasePatientDO patient = patientDao.findById(code).orElse(null);
                if (patient != null) {
                    map.put("name", patient.getName());
                } else {
                    map.put("name", code);
                }
                re.add(map);
            }
        }
        return re;
    }
    public JSONArray getDeviceByDeviceSn(String deviceSn, String type) {
        List<DevicePatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        JSONArray objects = new JSONArray();
        for (DevicePatientDevice patientDevice : list) {
            JSONObject object = new JSONObject(patientDevice);
            BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.put(object);
        }
        return objects;
    }
    /**
     * 获取血糖仪各个时间段(无参为默认时间段)
     *
     * @param user
     * @param deviceSN
     * @return
     */
    public Map getBloodSuggerTime(String user, String deviceSN) {
        Map map = new HashMap();
        PatientBloodSugger bloodSugger = null;
        PatientHealthTime patientHealthTime = null;
        if (!StringUtils.isEmpty(user) && !StringUtils.isEmpty(deviceSN)) {
            patientHealthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
        }
        String fastingStart = null;
        String fastingEnd = null;
        String afterBreakFastStart = null;
        String afterBreakFastEnd = null;
        String beforeLunchStart = null;
        String beforeLunchEnd = null;
        String afterLunchStart = null;
        String afterLunchEnd = null;
        String beforeDinnerStart = null;
        String beforeDinnerEnd = null;
        String afterDinnerStart = null;
        String afterDinnerEnd = null;
        String beforeSleepStart = null;
        String beforeSleepEnd = null;
        if (patientHealthTime == null) {
            bloodSugger = patientBloodSuggerDao.findRecent();
            fastingStart = bloodSugger.getFastingStart();
            fastingEnd = bloodSugger.getFastingEnd();
            afterBreakFastStart = bloodSugger.getAfterBreakfastStart();
            afterBreakFastEnd = bloodSugger.getAfterBreakfastEnd();
            beforeLunchStart = bloodSugger.getBeforeLunchStart();
            beforeLunchEnd = bloodSugger.getBeforeLunchEnd();
            afterLunchStart = bloodSugger.getAfterLunchStart();
            afterLunchEnd = bloodSugger.getAfterLunchEnd();
            beforeDinnerStart = bloodSugger.getBeforeDinnerStart();
            beforeDinnerEnd = bloodSugger.getBeforeDinnerEnd();
            afterDinnerStart = bloodSugger.getAfterDinnerStart();
            afterDinnerEnd = bloodSugger.getAfterDinnerEnd();
            beforeSleepStart = bloodSugger.getBeforeSleepStart();
            beforeSleepEnd = bloodSugger.getBeforeSleepEnd();
        } else {
            fastingStart = patientHealthTime.getFastingStart();
            fastingEnd = patientHealthTime.getFastingEnd();
            afterBreakFastStart = patientHealthTime.getAfterBreakfastStart();
            afterBreakFastEnd = patientHealthTime.getAfterBreakfastEnd();
            beforeLunchStart = patientHealthTime.getBeforeLunchStart();
            beforeLunchEnd = patientHealthTime.getBeforeLunchEnd();
            afterLunchStart = patientHealthTime.getAfterLunchStart();
            afterLunchEnd = patientHealthTime.getAfterLunchEnd();
            beforeDinnerStart = patientHealthTime.getBeforeDinnerStart();
            beforeDinnerEnd = patientHealthTime.getBeforeDinnerEnd();
            afterDinnerStart = patientHealthTime.getAfterDinnerStart();
            afterDinnerEnd = patientHealthTime.getAfterDinnerEnd();
            beforeSleepStart = patientHealthTime.getBeforeSleepStart();
            beforeSleepEnd = patientHealthTime.getBeforeSleepEnd();
        }
        map.put("fasting", fastingStart + " - " + fastingEnd);
        map.put("afterBreakFast", afterBreakFastStart + " - " + afterBreakFastEnd);
        map.put("beforeLunch", beforeLunchStart + " - " + beforeLunchEnd);
        map.put("afterLunch", afterLunchStart + " - " + afterLunchEnd);
        map.put("beforeDinner", beforeDinnerStart + " - " + beforeDinnerEnd);
        map.put("afterDinner", afterDinnerStart + " - " + afterDinnerEnd);
        map.put("beforeSleep", beforeSleepStart + " - " + beforeSleepEnd);
        return map;
    }
    /**
     * 用户自定义血糖仪各个时间段
     */
    public void setBloodTime(String user, String deviceSN, String fastingStart, String fastingEnd, String afterBreakfastStart, String afterBreakfastEnd, String beforeLunchStart, String beforeLunchEnd,
                             String afterLunchStart, String afterLunchEnd, String beforeDinnerStart, String beforeDinnerEnd, String afterDinnerStart, String afterDinnerEnd,
                             String beforeSleepStart, String beforeSleepEnd) throws Exception {
        if (StringUtils.isEmpty(fastingStart) && StringUtils.isEmpty(fastingEnd) && StringUtils.isEmpty(afterBreakfastStart) && StringUtils.isEmpty(afterBreakfastEnd) && StringUtils.isEmpty(beforeLunchStart)
                && StringUtils.isEmpty(beforeLunchEnd) && StringUtils.isEmpty(afterLunchStart) && StringUtils.isEmpty(afterLunchEnd) && StringUtils.isEmpty(beforeDinnerStart) && StringUtils.isEmpty(beforeDinnerEnd) && StringUtils.isEmpty(afterDinnerStart)
                && StringUtils.isEmpty(afterDinnerEnd) && StringUtils.isEmpty(beforeSleepStart) && StringUtils.isEmpty(beforeSleepEnd)) {
            patientHealthTimeDao.deleteByUserAndSN(user, deviceSN);
            return;
        }
        PatientHealthTime healthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
        if (healthTime == null) {
            PatientHealthTime patientHealthTime = new PatientHealthTime();
            patientHealthTime.setUser(user);
            patientHealthTime.setDeviceSN(deviceSN);
            patientHealthTime.setFastingStart(fastingStart);
            patientHealthTime.setFastingEnd(fastingEnd);
            patientHealthTime.setAfterBreakfastStart(afterBreakfastStart);
            patientHealthTime.setAfterBreakfastEnd(afterBreakfastEnd);
            patientHealthTime.setBeforeLunchStart(beforeLunchStart);
            patientHealthTime.setBeforeLunchEnd(beforeLunchEnd);
            patientHealthTime.setAfterLunchStart(afterLunchStart);
            patientHealthTime.setAfterLunchEnd(afterLunchEnd);
            patientHealthTime.setBeforeDinnerStart(beforeDinnerStart);
            patientHealthTime.setBeforeDinnerEnd(beforeDinnerEnd);
            patientHealthTime.setAfterDinnerStart(afterDinnerStart);
            patientHealthTime.setAfterDinnerEnd(afterDinnerEnd);
            patientHealthTime.setBeforeSleepStart(beforeSleepStart);
            patientHealthTime.setBeforeSleepEnd(beforeSleepEnd);
            patientHealthTime.setDel(1);
            patientHealthTime.setCzrq(new Date());
            patientHealthTimeDao.save(patientHealthTime);
        } else {
            int rows = patientHealthTimeDao.modifyByUserAndSN(fastingStart, fastingEnd, afterBreakfastStart, afterBreakfastEnd, beforeLunchStart, beforeLunchEnd,
                    afterLunchStart, afterLunchEnd, beforeDinnerStart, beforeDinnerEnd, afterDinnerStart, afterDinnerEnd, beforeSleepStart, beforeSleepEnd, user, deviceSN);
            int str = rows;
        }
    }
    /**
     * 根据user,deviceSN修改血糖时间段
     *
     * @param user
     * @param deviceSN
     * @param newDeviceSN
     * @throws Exception
     */
    public void updateDeviceSN(String user, String deviceSN, String newDeviceSN) throws Exception {
        patientHealthTimeDao.updateDeviceSN(user, deviceSN, newDeviceSN);
    }
    /**
     * 根据user,deviceSN更换绑定血糖仪
     *
     * @param user
     * @param deviceSN
     * @param newDeviceSN
     * @throws Exception
     */
    public int updatePatientDevice(String user, String deviceSN, String newDeviceSN, String userType,String sim,String hospital,String hospitalName,String checkDoctorName) throws Exception {
        int rows = patientDeviceDao.updatePatientDevice(user, deviceSN, newDeviceSN, userType,sim,hospital,hospitalName,checkDoctorName);
        return rows;
    }
    public Map<String,Object> getDeviceByDeviceSn(String deviceSn)throws Exception {
        Map<String,Object> map  = new HashedMap();
        String sql = "SELECT d.id,d.device_name deviceName,d.device_model deviceMode,d.sim,CAST(e.is_multi_user AS UNSIGNED INTEGER) isMultiUser,e.category_code as deviceType,e.multi_user multiUser,e.id as device_id FROM wlyy_devices d LEFT JOIN dm_device e ON d.device_model = e.model WHERE d.device_code='"+deviceSn+"'";
        List<Map<String,Object>> mapSqlList = jdbcTemplate.queryForList(sql);
        if (mapSqlList!=null && mapSqlList.size()>0){
            map = mapSqlList.get(0);
        }
        List<DevicePatientDevice> list = patientDeviceDao.findByDeviceSn(deviceSn);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (DevicePatientDevice patientDevice : list) {
            Map<String,Object> infoMap = new HashedMap();
            BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
            if (patient!=null){
                infoMap.put("patientDeviceId",patientDevice.getId());
                infoMap.put("userCode",patient.getId());
                infoMap.put("userName",patient.getName());
                infoMap.put("idCard",patient.getIdcard());
                infoMap.put("userType",patientDevice.getUserType());
            }
            mapList.add(infoMap);
        }
        map.put("bindingInfo",mapList);
        return map;
    }
    public Map<String,Object> checkBindingFirstAndType(DevicePatientDevice patientDevice)throws Exception{
        Map<String,Object> resultMap = new HashedMap();
        boolean flag = true;
        int code = 200;
        String msg = "";
        String deviceSn = patientDevice.getDeviceSn();
        String userType = patientDevice.getUserType();
        //判断患者是否第一次绑定设备
        List<PatientDeviceLog> patientDeviceLogList = patientDeviceLogDao.findByPatientAndCategoryCode(patientDevice.getUser(),patientDevice.getCategoryCode());
        if (patientDeviceLogList!=null && patientDeviceLogList.size()>0){
            flag=false;
            msg="已经绑定过同样类型的设备了";
            code=-10000;
        }
        //设备是否是第一次被绑定
        String keyType = "1";
        if("2".equals(userType)){
            keyType = "2";
        }
        DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
        if (deviceDetail!=null && StringUtils.isNotEmpty(deviceDetail.getBindingCount())){
            JSONObject jsonObject =new JSONObject(String.valueOf(deviceDetail.getBindingCount()));
            if (jsonObject.getInt(keyType)>0){
                flag=false;
                msg="设备不是首次绑定";
                code = -20000;
            }
        }
        resultMap.put("flag",flag);
        resultMap.put("msg",msg);
        resultMap.put("code",code);
        return resultMap;
    }
    /**
     * 验证sn码 先调总部接口 未注册才查询本地数据库,如果也没有才不能绑定
     * @param deviceSn
     * @return
     * @throws Exception
     */
    public Map<String,Object> checkBindingDeviceSn(String deviceSn) throws Exception{
        Boolean flag = false;
        String message = "设备不存在!";
        Integer resultCode = 200;
        Map<String, String> params = new HashMap<>();
        params.put("deviceSn", deviceSn);
        Map<String,Object> map1 = new HashedMap();
        map1.put("code",resultCode);
        map1.put("message",message);
        map1.put("flag",flag);
        return map1;
    }
    public Map<String,Object> getPatientDeviceTaskInfo(String patientCode)throws Exception{
        Map<String,Object> resultMap = new HashedMap();
        String sql = "SELECT d.binding_count,pd.user_type FROM wlyy_patient_device pd LEFT JOIN wlyy_devices d ON pd.device_sn = d.device_code where pd.del=0 and pd.user='"+patientCode+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        int count = 0;
        //查询一共绑定了多少个设备
        for (Map<String,Object> map : list){
            if (map.get("binding_count")!=null){
                JSONObject jsonObject =  new JSONObject(String.valueOf(map.get("binding_count")));
                Set<String> keyset = jsonObject.keySet();
                for (String key : keyset){
                    if (key.equals(String.valueOf(map.get("user_type"))) && jsonObject.getInt(key)==1){
                        count++;
                    }
                }
            }
        }
        resultMap.put("deviceCount",count);
        //体征上传表查询是否有今天的数据
        int healthBp = 0;
        int healthBs = 0;
        int resultHealty= 0;
        String today = DateUtil.dateToStr(DateUtil.getDateShort(new Date()),"yyyy-MM-dd");
        String healthSql ="SELECT type as healtyType,device_sn deviceSn FROM wlyy_patient_health_index where record_date >'"+today+" 00:00:00' and record_date <='"+today+" 23:59:59' and  status = 0 and  del = 1 and user = '"+patientCode+"'";
        List<Map<String,Object>>  maps =jdbcTemplate.queryForList(healthSql);
        for (Map<String,Object> map : maps){
            if (map.get("type")!=null && String.valueOf(map.get("Type")).equals("1")){
                //血糖
                healthBs=1;
            }
            if (map.get("type")!=null && String.valueOf(map.get("Type")).equals("2")){
                //血压
                healthBp=1;
            }
        }
        if (healthBp==1 && healthBs ==0){
            resultHealty =1;
        }
        if (healthBs ==1 && healthBp==0){
            resultHealty = 2;
        }
        if (healthBp ==1 && healthBs ==1){
            resultHealty = 3;
        }
        resultMap.put("resultHealty",resultHealty);
        return resultMap;
    }
    /**
     * 发送设备审核消息
     * @param patientDevice
     * @param type 1同意解绑,2不同意
     */
    public void sendWxMessage(DevicePatientDevice patientDevice, int type) {
        BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
        WxTemplateConfigDO templateConfig = null;
        //判断是同意解绑还是拒绝解绑
        if(type == 1){
            templateConfig = wxMessageUtil.findByWechatIdAndTemplateNameAndSceneAndStatus(null,"template_process_feedback","unbind",1);
        }else if(type == 2) {
            templateConfig = wxMessageUtil.findByWechatIdAndTemplateNameAndSceneAndStatus(null,"template_process_feedback", "refuse",1);
        }
        WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
        BeanUtils.copyProperties(templateConfig,newConfig);
        String first = newConfig.getFirst();
        first = first.replace("key1", patientDevice.getDeviceName());
        String keyword2 = newConfig.getKeyword2();
        if(keyword2.contains("key2")){
            keyword2 = keyword2.replace("key2", patientDevice.getRefuseReason());
        }
        newConfig.setFirst(first);
        newConfig.setKeyword2(keyword2);
        newConfig.setKeyword1(DateUtil.dateToStrShort(new Date()));
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("deviceId", patientDevice.getCategoryCode());
        json.put("id", patientDevice.getId());
        if(patient != null && StringUtils.isNotBlank(patient.getOpenid())) {
            wxMessageUtil.putWxMsg(null,  patient.getOpenid(),newConfig, 33, json);
        }
    }
}

+ 1943 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientHealthIndexService.java

@ -0,0 +1,1943 @@
package com.yihu.jw.hospital.module.health.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.contant.DeviceHealthContant;
import com.yihu.jw.device.dao.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.device.*;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.message.service.WxMessageUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthIndexService {
    private Logger logger = LoggerFactory.getLogger(PatientHealthIndexService.class);
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private PatientHealthStandardDao patientHealthStandardDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    @Autowired
    private PatientAimSportsDao patientAimSportsDao;
    @Autowired
    private DoctorHealthStandardDao doctorHealthStandardDao;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private PatientAimBloodSuggerDao patientAimBloodSuggerDao;
    @Autowired
    private PatientAimBloodPressureDao patientAimBloodPressureDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    public DevicePatientHealthIndex getHealthIndexById(Long id) {
        return patientHealthIndexDao.findById(id).orElse(null);
    }
    /**
     * 获取居民标准预警值
     *
     * @param type
     * @param patientCode
     * @return
     */
    public JSONObject getealthStandard(Integer type, String patientCode) {
        //血糖校验
        JSONObject json = new JSONObject();
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueBefore = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueBefore = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueAfter = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueAfter = standard.getMinValue2();
                }
            }
            json.put("maxValueAfter", maxValueAfter);
            json.put("maxValueBefore", maxValueBefore);
            json.put("minValueBefore", minValueBefore);
            json.put("minValueAfter", minValueAfter);
        }
        //血压校验
        else if (type == 2) {
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            json.put("minValueSZY", minValueSZY);
            json.put("maxValueSZY", maxValueSZY);
            json.put("minValueSSY", minValueSSY);
            json.put("maxValueSSY", maxValueSSY);
            
        }
        return json;
        
    }
    
    
    //更改接口(包括手动记录的修改和所有的删除)
    public void modify(long id, String recordDate, String value1, String value2, String value3, String value4) throws Exception {
        
        DevicePatientHealthIndex result = findOne(id);
        if (result != null) {
            //字段值均为空为删除
            if (StringUtils.isEmpty(value1) && StringUtils.isEmpty(value2) && StringUtils.isEmpty(value3) && StringUtils.isEmpty(value4)) {
                result.setDel("0");
            } else {
                if (StringUtils.isNotEmpty(recordDate)) {
                    result.setRecordDate(DateUtil.strToDate(recordDate));
                } else {
                    throw new ServiceException("Record date can not be null!");
                }
                
                result.setDel("1");
                if (StringUtils.isNotEmpty(value1)) {
                    result.setValue1(value1);
                }
                if (StringUtils.isNotEmpty(value2)) {
                    result.setValue2(value2);
                }
                if (StringUtils.isNotEmpty(value3)) {
                    result.setValue3(value3);
                }
                if (StringUtils.isNotEmpty(value4)) {
                    result.setValue4(value4);
                }
            }
            
            update(result);
            if ("1".equals(result.getType()) || "2".equals(result.getType())) {
                verifyHealthIndex(result.getId());
            }
        } else {
            throw new ServiceException("Result not exit!");
        }
        
    }
    
    /**
     * 获取居民最新各类健康记录
     */
    public Map findDataByPatient(String patient, int type) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sql = "SELECT " +
                " * " +
                " FROM " +
                "  wlyy_patient_health_index a " +
                " WHERE " +
                " a. USER = ? " +
                " AND a.type = ? " +
                " AND a.del = 1 " +
                " ORDER BY " +
                " a.record_date DESC " +
                "LIMIT 0,1 ";
        List<Map<String, Object>> devicePatient = findDataByPatient(sql, patient, type);
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> device : devicePatient) {
            String time = device.get("record_date") == null ? null : device.get("record_date").toString();
            String deviceSN = device.get("device_sn") == null ? "0" : "1";
            String value1 = device.get("value1") == null ? null : device.get("value1").toString();
            String value2 = device.get("value2") == null ? null : device.get("value2").toString();
            String value3 = device.get("value3") == null ? null : device.get("value3").toString();
            String value4 = device.get("value4") == null ? null : device.get("value4").toString();
            String value5 = device.get("value5") == null ? null : device.get("value5").toString();
            String value6 = device.get("value6") == null ? null : device.get("value6").toString();
            String value7 = device.get("value7") == null ? null : device.get("value7").toString();
            map.put("isDevice", deviceSN);
            if (StringUtils.isNotEmpty(time)) {
                Date date = sdf.parse(time);
                time = sdf.format(date);
                map.put("time", time);
            }
            if (StringUtils.isNotEmpty(value1)) {
                map.put("value1", value1);
            }
            if (StringUtils.isNotEmpty(value2)) {
                map.put("value2", value2);
                
            }
            if (StringUtils.isNotEmpty(value3)) {
                map.put("value3", value3);
            }
            if (StringUtils.isNotEmpty(value4)) {
                map.put("value4", value4);
            }
            if (StringUtils.isNotEmpty(value5)) {
                map.put("value5", value5);
            }
            if (StringUtils.isNotEmpty(value6)) {
                map.put("value6", value6);
            }
            if (StringUtils.isNotEmpty(value7)) {
                map.put("value7", value7);
            }
        }
        return map;
    }
    
    
    /**
     * 判断当前值是否在区间内
     */
    private boolean checkHealthIndex(Double current, Double max, Double min) {
        if (current > max || current < min || current < 0) {
            return false;
        }
        return true;
    }
    /**
     * 判断当前指标偏高或偏低
     */
    private int checkHealthIndexDetail(Double current, Double max, Double min) {
        if (current > max ) {
            return 1;
        }else if(current < min || current < 0){
            return 2;
        }
        return 0;
    }
    
    /**
     * 推送信息
     */
//    private void sendMessage(String content, BasePatientDO patient, DevicePatientHealthIndex model, String oldMsgContent) {
//        String patientCode = patient.getId();
//        String patientName = patient.getName();
//        // 消息接收者
//        List<String> receivers = new ArrayList<String>();
//        // 查询病人家庭签约的健康管理师
//        SignFamily signFamily = signFamilyDao.findByjiatingPatientYes(patientCode);
//        String healthDoctorFamily = "";
//        String doctorFamily = "";
//        /*String doctorName = "";
//        String doctorOpenID = "";*/
//        if (signFamily != null) {
//            healthDoctorFamily = signFamily.getDoctorHealth();
//            doctorFamily = signFamily.getDoctor();
//            if (StringUtils.isNotEmpty(healthDoctorFamily) && StringUtils.isNotEmpty(doctorFamily)){
//                // 添加到消息接收人列表
//                if (doctorFamily.equals(healthDoctorFamily)){
//                    System.out.println("-------------健管师和家医同一个人-------------");
//                    receivers.add(healthDoctorFamily);
//                }else {
//                    System.out.println("-------------健管师和家医不是同一个人-------------");
//                    receivers.add(healthDoctorFamily);
//                    receivers.add(doctorFamily);
//                }
//            }else if (StringUtils.isNotEmpty(healthDoctorFamily) && StringUtils.isEmpty(doctorFamily)){
//                System.out.println("-------------家医为空-------------");
//                receivers.add(healthDoctorFamily);
//            }else if (StringUtils.isNotEmpty(doctorFamily) && StringUtils.isEmpty(healthDoctorFamily)){
//                System.out.println("-------------健管师为空-------------");
//                receivers.add(doctorFamily);
//            }
//        }
//
//        List<Message> messages = new ArrayList<Message>();
//        JSONArray array = new JSONArray();
//        //判断是否是今日测量数据,如果不是则不进行体征干预
//        if(model.getRecordDate().compareTo(DateUtil.getNowDateShort()) > -1) {
//            for (String receiver : receivers) {
//                if (StringUtils.isEmpty(receiver)) {
//                    continue;
//                }
//                // 保存异常消息
//                Message message = new Message();
//                message.setCode(getCode());
//                message.setCzrq(new Date());
//                message.setCreateTime(new Date());
//                message.setRead(1);
//                message.setOver("1");
//                message.setReceiver(receiver);
//                message.setSender(patientCode);
//                message.setSex(patient.getSex());
//                message.setSenderName(patient.getName());
//                message.setSenderPhoto(patient.getPhoto());
//                message.setTitle("预警值信息");
//                message.setContent(content);
//                message.setType(2);
//                message.setDel("1");
//                message.setValue1(Double.valueOf(model.getValue1()));
//                message.setValue2(Double.valueOf(model.getValue2()));
//                message.setTzCode(String.valueOf(model.getId()));//消息关联的体征id
//                message.setTzType(String.valueOf(model.getType()));//体征类别 (1血糖,2血压,3体重,4腰围)
//                messages.add(message);
//
//                if (messageService.getMessageNoticeSettingByMessageType(receiver, "1", MessageNoticeSetting.MessageTypeEnum.healthSignSwitch.getValue())) {
//                    // 异常通知
//                    JSONObject json = new JSONObject();
//                    json.put("receiver", receiver);
//                    json.put("type", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.D_HI_01.name());
//                    json.put("title", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.体征指标.name());
//                    json.put("msg", oldMsgContent);
//                    json.put("data", "");
//                    array.put(json);
//                }
//            }
//            // 批量保存消息
//            messageDao.save(messages);
//            for (String receiver : receivers) {
//                if (StringUtils.isEmpty(receiver)) {
//                    continue;
//                }
//
//            }
//            // 推送消息给医生
//            pushMsgTask.put(array);
//        }
//    }
    
    /**
     * 获取患者某天血糖值
     *
     * @return
     */
    private com.alibaba.fastjson.JSONObject getPatientXT_Json(String patient, String dateString) throws ParseException {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("user", patient);
        boolean hadData = false;
        Date date = DateUtil.strToDateShort(dateString);
        /***************** 按时间排序 ***************************/
        
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",DATE_FORMAT(record_date, '%Y-%m-%d %H:%i:%s')'record_date' " +
                ",DATE_FORMAT(sort_date, '%Y-%m-%d %H:%i:%s') 'sort_date'" +
                ",czrq as createDate" +
                ",min(czrq) czrq " +
                " from wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type = 1" +
                " and DATE_FORMAT(record_date,'%Y-%m-%d') = '" + dateString + "'" +
                " and del = '1' " +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date,id desc ";
        List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,dateString);
        SimpleDateFormat dateFormat6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd");
        if (list != null && list.size() > 0) {
            obj.put("type", 1);
            obj.put("czrq", date);
            obj.put("recordDate", date);
            obj.put("sortDate", date);
            for (Map<String, Object> item : list) {
                String data = item.get("value1").toString();
                String dataType = item.get("value2").toString();
                String deviceSn = item.get("device_sn") == null ? "" : item.get("device_sn").toString();
                System.out.println(item.get("record_date").toString());
                Date recordDate = dateFormat6.parse(item.get("record_date").toString());
                Long id = Long.parseLong(item.get("id") + "");
                Date createDate = (Date)item.get("createDate");
                
                String recordTime = DateUtil.dateToStr(recordDate,DateUtil.YYYY_MM_DD);
                String createTime = DateUtil.dateToStr(createDate,DateUtil.YYYY_MM_DD);
                
                if (data != null && dataType != null) {
                    if (dataType.equals("1")) {
                        obj.put("value1", data);
                        obj.put("time1", recordDate);
                        obj.put("id1", id);
                        obj.put("deviceSn1", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("2")) {
                        obj.put("value2", data);
                        obj.put("time2", recordDate);
                        obj.put("id2", id);
                        obj.put("deviceSn2", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("3")) {
                        obj.put("value3", data);
                        obj.put("time3", recordDate);
                        obj.put("id3", id);
                        obj.put("deviceSn3", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("4")) {
                        obj.put("value4", data);
                        obj.put("time4", recordDate);
                        obj.put("id4", id);
                        obj.put("deviceSn4", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("5")) {
                        obj.put("value5", data);
                        obj.put("time5", recordDate);
                        obj.put("id5", id);
                        obj.put("deviceSn5", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("6")) {
                        obj.put("value6", data);
                        obj.put("time6", recordDate);
                        obj.put("id6", id);
                        obj.put("deviceSn6", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("7")) {
                        obj.put("value7", data);
                        obj.put("time7", recordDate);
                        obj.put("id7", id);
                        obj.put("deviceSn7", deviceSn);
                        hadData = true;
                    }
                    
                    //是否为补传数据(设备上传且测量时间和创建时间不匹配)
                    judgeIsSupplement(obj,recordTime,createTime,deviceSn,dataType);
                    
                    obj.put("healthindexid", id);
                    obj.put("valuedata", data);
                    obj.put("dataType",dataType);
                }
            }
        }
        if (hadData) {
            return obj;
        } else {
            return null;
        }
    }
    
    
    /**
     * 是否为补传数据(设备上传且测量时间和创建时间不匹配)
     * @param obj
     * @param recordDate
     * @param createDate
     * @param deviceSn
     * @param num
     */
    private void judgeIsSupplement(com.alibaba.fastjson.JSONObject obj,String recordDate,String createDate,String deviceSn,String num){
        if ("".equals(deviceSn)){
            obj.put("isSupplement"+num,0);
        }else {
            if (recordDate.compareTo(createDate)==0){
                obj.put("isSupplement"+num,0);
            }else {
                obj.put("isSupplement"+num,1);
            }
        }
    }
    
    private com.alibaba.fastjson.JSONArray getPatientXT_Json1(String patient,Long page,Integer pageSize) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("user", patient);
        boolean hadData = false;
        /***************** 按时间排序 ***************************/
        
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",DATE_FORMAT(record_date,'%Y-%m-%d') as record_date " +
                ",sort_date" +
                ",min(czrq) czrq " +
                " from wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type = 1" +
                " and del = '1' " +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date,id desc limit "+page+","+pageSize;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> item : list) {
                obj.put("type", 1);
                obj.put("czrq", item.get("czrq"));
                obj.put("recordDate", item.get("record_date"));
                obj.put("sortDate", item.get("sort_date"));
                String data = item.get("value1").toString();
                String dataType = item.get("value2").toString();
                String deviceSn = item.get("device_sn") == null ? "" : item.get("device_sn").toString();
                String recordDate = item.get("record_date").toString();
                Long id = Long.parseLong(item.get("id") + "");
                if (data != null && dataType != null) {
                    if (dataType.equals("1")) {
                        obj.put("value1", data);
                        obj.put("time1", recordDate);
                        obj.put("id1", id);
                        obj.put("deviceSn1", deviceSn);
                    } else if (dataType.equals("2")) {
                        obj.put("value2", data);
                        obj.put("time2", recordDate);
                        obj.put("id2", id);
                        obj.put("deviceSn2", deviceSn);
                        
                    } else if (dataType.equals("3")) {
                        obj.put("value3", data);
                        obj.put("time3", recordDate);
                        obj.put("id3", id);
                        obj.put("deviceSn3", deviceSn);
                        
                    } else if (dataType.equals("4")) {
                        obj.put("value4", data);
                        obj.put("time4", recordDate);
                        obj.put("id4", id);
                        obj.put("deviceSn4", deviceSn);
                    } else if (dataType.equals("5")) {
                        obj.put("value5", data);
                        obj.put("time5", recordDate);
                        obj.put("id5", id);
                        obj.put("deviceSn5", deviceSn);
                    } else if (dataType.equals("6")) {
                        obj.put("value6", data);
                        obj.put("time6", recordDate);
                        obj.put("id6", id);
                        obj.put("deviceSn6", deviceSn);
                    } else if (dataType.equals("7")) {
                        obj.put("value7", data);
                        obj.put("time7", recordDate);
                        obj.put("id7", id);
                        obj.put("deviceSn7", deviceSn);
                    }
                    obj.put("healthindexid", id);
                    obj.put("valuedata", data);
                    obj.put("dataType",dataType);
                    array.add(obj);
                }
            }
        }
        return array;
    }
    
    /**
     * 校验指标是否超标,发送消息
     */
    public void verifyHealthIndex(Long id) {
        //指标信息
        DevicePatientHealthIndex data = findOne(id);
        String patientCode = data.getUser();
        //患者信息
        BasePatientDO patient = patientDao.findById(patientCode).orElse(null);
        
        int type = data.getType();
        String msgContent = "";
        String oldMsgContent = "";
        //血糖校验
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueBefore = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueBefore = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueAfter = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueAfter = standard.getMinValue2();
                }
            }
            int index = Integer.valueOf(data.getValue2());
            String value1 = data.getValue1();
            // 餐后
            if (index % 2 == 0) {
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueAfter, minValueAfter)) {
                    oldMsgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                    if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueAfter ,minValueAfter)==1){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏高</span>";
                    }else if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueAfter ,minValueAfter)==2){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏低</span>";
                    }
                    //体征异常,更新体征数据状态
                    updateStatus(data);
                }
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    oldMsgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                    if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueBefore ,minValueBefore)==1){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏高</span>";
                    }else if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueBefore ,minValueBefore)==2){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏低</span>";
                    }
                    updateStatus(data);
                }
            }
        }
        //血压校验
        else if (type == 2) {
            String value1 = data.getValue1();
            String value2 = data.getValue2();
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            // 收缩压/舒张压校验
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY) || !checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                oldMsgContent = patient.getName() + "血压异常(舒张压 " + value2 + "mmHg、收缩压 " + value1 + "mmHg)";
                if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY)==1||checkHealthIndexDetail(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)==1){
                    msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血压偏高</span>";
                }else if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY)==2||checkHealthIndexDetail(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)==2){
                    msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血压偏低</span>";
                }
                updateStatus(data);
            }
        }
        
        //超标则发送消息
        if (msgContent != null && msgContent.length() > 0) {
//            sendMessage(msgContent, patient, data,oldMsgContent);
        }
    }
    
    /********************************************物联网 start***********************************************************/
    /**
     * 修改体征异常状态
     * @param data
     */
    public void updateStatus(DevicePatientHealthIndex data){
        data.setStatus(1);
        patientHealthIndexDao.save(data);
    }
    
    /**
     * 按id查找体征记录
     * @param id
     * @return
     */
    public DevicePatientHealthIndex findOne(Long id){
        return patientHealthIndexDao.findById(id).orElse(null);
    }
    
    /**
     * 体征保存
     * @param data
     * @return
     */
    public DevicePatientHealthIndex save(DevicePatientHealthIndex data){
        return patientHealthIndexDao.save(data);
    }
    
    /**
     * 体征修改
     * @param data
     * @return
     */
    public DevicePatientHealthIndex update(DevicePatientHealthIndex data){
        return patientHealthIndexDao.save(data);
    }
    
    /**
     * 查询最近的一条体征数据
     * @param sql
     * @param patient
     * @param type
     * @return
     */
    public List<Map<String, Object>> findDataByPatient(String sql,String patient,Integer type){
        return jdbcTemplate.queryForList(sql, patient, type);
    }
    
    /**
     * 患者最近填写的健康指标
     * @param patient
     * @return
     */
    public List<DevicePatientHealthIndex> findRecentByPatientIterable(String patient){
        return patientHealthIndexDao.findRecentByPatient(patient);
    }
    
    /**
     * 根据患者标志获取健康指标
     * @param patient
     * @param type
     * @return
     */
    public DevicePatientHealthIndex findLastByPatienIot(String patient,Integer type){
        return findLastByPatien(patient,type);
    }
    /**
     * 查询指标记录
     * @param patient
     * @param startDate
     * @param endDate
     * @param page
     * @param size
     * @return
     */
    public List<String> findDateListIot(String patient,int type,Date startDate,Date endDate, Long page, Integer size){
        return patientHealthIndexDao.findDateList(patient,type,startDate,endDate,page,size);
    }
    
    
    public List<String> findDateListIot1(String patient,Date startDate,Date endDate, Long page, Integer size){
        return patientHealthIndexDao.findDateList(patient,startDate,endDate,page,size);
    }
    
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @param type
     * @param size
     * @param gi_type
     * @param begin
     * @param end
     * @return
     */
    public List<Map<String, Object>> findByPatientAndTime(String sql,String patient,Integer type,Integer size,Integer gi_type, String begin, String end){
        return jdbcTemplate.queryForList(sql);
    }
    
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @param date
     * @return
     */
    public List<Map<String, Object>> getPatientXT_JsonIot(String sql,String patient, String date){
        return jdbcTemplate.queryForList(sql);
    }
    
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @return
     */
    public List<Map<String, Object>> getPatientXT_JsonIot(String sql,String patient,Integer type,Integer page,Integer size, String begin,String end){
        return jdbcTemplate.queryForList(sql);
    }
    
    /**
     * 转map
     * @param index
     * @return
     */
    private Map<String, Object> indexToMap(DevicePatientHealthIndex index){
        Map<String, Object> map = new HashedMap();
        map.put("value1",index.getValue1());
        map.put("value2",index.getValue2());
        map.put("value3",index.getValue3());
        map.put("value4",index.getValue4());
        map.put("value5",index.getValue5());
        map.put("value6",index.getValue6());
        map.put("value7",index.getValue7());
        map.put("device_sn",index.getDeviceSn());
        map.put("record_date",index.getRecordDate());
        return map;
    }
    
    
    
    /********************************************物联网 end***********************************************************/
    
    /**
     * 新增患者指标
     * 【血糖】{"time":"2016-09-09 17:00:00","gi":"血糖值(mmol/L)"}
     * 【血压】{"time":"2016-09-09 17:00:00","sys":"收缩压(mmHg)","dia":"舒张压(mmHg)","pul":"脉搏(次/分)","ano":"有无心率不齐0否 1是","user":"身份标识"}
     * 【体重/身高】{"time":"2016-09-09 17:00:00","weight":"体重值(kg)","height":"身高(cm)"}
     * 【腰围】{"time":"2016-09-09 17:00:00","waistline":"腰围值(cm)"}
     *
     * @return
     */
    public DevicePatientHealthIndex addPatientHealthIndex(String data, String type, String patientCode, String deviceSn) throws Exception {
        Map<String, String> map = (Map<String, String>) objectMapper.readValue(data, Map.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
        Date currentTime = new Date();
        obj.setCzrq(currentTime);
        obj.setDel("1");
        obj.setStatus(0);
        Date time = currentTime;
        if (map.containsKey("time")) {
            String da = map.get("time");
//            time = DateUtil.strToDate(da);
            time = sdf.parse(da);
        }
        obj.setRecordDate(time);    //记录时间
        obj.setSortDate(time);      //排序时间
        
        String idcard = "";
        BasePatientDO patient = null;
        if (deviceSn != null && deviceSn.length() > 0)   //设备数据
        {
            obj.setDeviceSn(deviceSn);
            String userType = "-1";
            if (map.containsKey("user")) { //存在身份标识 ,多用户
                userType = map.get("user");
            }
            //根据设备获取患者(不同厂家sn码一样的问题未解决!!)
            DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
            if (device != null) {
                patientCode = device.getUser();
                patient = patientDao.findById(patientCode).orElse(null);
                idcard = device.getUserIdcard();
            }
            DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
        }
        //自输数据
        else {
            patient = patientDao.findById(patientCode).orElse(null);
            if (patient != null) {
                idcard = patient.getIdcard();
            }
        }
        
        //身份证不为空
        if (patient != null) {
            obj.setUser(patientCode);
            obj.setName(patient.getName());
            obj.setIdcard(idcard);
            
            String msgContent = "";
            // 1血糖 2血压 3体重 4腰围
            switch (type) {
                case "1": {
                    obj.setType(1);
                    String value1 = map.get("gi");  //血糖值
                    String gi_type = map.get("gi_type"); //血糖值类型对应1到7
                    String recordDate = map.get("recordDate");
                    obj.setValue1(value1);
                    obj.setValue2(gi_type);
                    if (StringUtils.isNotBlank(recordDate)) {
                        obj.setRecordDate(DateUtil.strToDateAppendNowTime(recordDate, DateUtil.YYYY_MM_DD_HH_MM_SS));
                    }
                    break;
                }
                case "2": {
                    obj.setType(2);
                    String value1 = map.get("sys");  //收缩压
                    String value2 = map.get("dia");  //舒张压
                    obj.setValue1(value1);
                    obj.setValue2(value2);
                    obj.setValue3(map.get("pul"));     //脉搏
                    obj.setValue4(map.get("ano"));     //有无心率不齐
                    break;
                }
                case "3": {
                    obj.setType(3);
                    
                    String weight = map.get("weight");
                    String height = map.get("height");
                    
                    obj.setValue1(weight); //体重
                    obj.setValue2(height); //身高
                    
                    PatientAimSports patientAimSports = new PatientAimSports();
                    patientAimSports = patientAimSportsDao.getPatientAimSportsByPatientCode(patientCode);
                    //如果该患者没有设置运动目标,则获取预置数据
                    if (patientAimSports == null || StringUtils.isBlank(patientAimSports.getCode())) {
                        patientAimSports = patientAimSportsDao.findByCode("default");
                    }
                    
                    double bmi = CommonUtil.getBMIByWeightAndHeight(map.get("weight"), map.get("height"));
                    DecimalFormat df1 = new DecimalFormat("###.00");
                    obj.setValue3(df1.format(bmi));
                    
                    double bmiMin = new Double("18.5");
                    double bmiMax = new Double("23.9");
                    
                    if (patientAimSports != null && StringUtils.isNoneEmpty(patientAimSports.getCode())) {
                        bmiMin = Double.parseDouble(patientAimSports.getBmiMin());
                        bmiMax = Double.parseDouble(patientAimSports.getBmiMax());
                    }
                    
                    //设置BMI值
                    if (bmi < bmiMin) {
                        obj.setValue4("1");
                    } else if (bmi > bmiMax) {
                        obj.setValue4("-1");
                    } else {
                        obj.setValue4("0");
                    }
                    
                    break;
                }
                case "4": {
                    obj.setType(4);
                    obj.setValue1(map.get("waistline"));  //腰围
                    obj.setValue2(map.get("hipline"));
                    break;
                }
                default: {
                    throw new ServiceException("暂不支持该指标!");
                }
            }
            
            obj = save(obj);
            
            //判断是否有未结束的续方咨询,发送消息给对应的医生
            sendPrescriptionHealthIndexMsgresult(obj,patient);
        } else {
            throw new ServiceException("不存在该患者!");
        }
        
        
        return obj;
    }
    
    /**
     * 判断是否有未结束的续方咨询,发送消息给对应的医生
     * @param result
     * @param patient
     */
    private void sendPrescriptionHealthIndexMsgresult(DevicePatientHealthIndex result, BasePatientDO patient) {
        
        List<ConsultTeamDo> consultTeams = consultTeamDao.findUnfinishedConsultPrescription(patient.getId());
        
        for (ConsultTeamDo consultTeam:consultTeams) {
            if(consultTeam.getHealthindexType() != null){
                JSONObject contentPatient = new JSONObject();
                //患者发送的消息
                contentPatient.put("title", "【本消息为系统提醒】:");
                if(1 == result.getType()){
                    contentPatient.put("tzMsg", "体征记录:血糖 "+result.getValue1()+" mmol/L");
                    contentPatient.put("type",2);
                }else if(2 == result.getType()){
                    contentPatient.put("tzMsg", "体征记录:血压 "+result.getValue1()+"/"+result.getValue2()+" mmHg");
                    contentPatient.put("type",1);
                }else{}
                
                contentPatient.put("tzTime", "检测时间:"+DateUtil.dateToStrLong(result.getRecordDate()));
                contentPatient.put("tzAlert","温馨提示:本条体征为居民上传的健康体征数据,您可以");
                contentPatient.put("needUpload","false");
                contentPatient.put("healthindexid",result.getId());//体征记录 ID
                
                //患者发送Im消息
                imUtil.sendTopicIM(patient.getId(), patient.getName(), consultTeam.getConsult(), "16", contentPatient.toString(), null);
            }
        }
    }
    
    /**
     * 设置默认监控方案
     * @param patient
     * @return
     */
    public String setDefaultAim(String patient){
        PatientAimBloodSugger patientAimBloodSugger = patientAimBloodSuggerDao.findByPatientcode(patient);
        PatientAimBloodPressure patientAimBloodPressure =  patientAimBloodPressureDao.findByPatientcode(patient);
        if(patientAimBloodSugger==null){
            PatientAimBloodSugger pa = new PatientAimBloodSugger();
            pa.setPatientcode(patient);
            pa.setCode(CommonUtil.getCode());
            pa.setCreateTime(new Date());
            pa.setUnit("mmol/L");
            pa.setFbg("7.0");
            pa.setHpg("11.1");
            pa.setFbgMin("4.0");
            pa.setHpgMin("4.0");
            patientAimBloodSuggerDao.save(pa);
        }
        if(patientAimBloodPressure==null){
            PatientAimBloodPressure pa = new PatientAimBloodPressure();
            pa.setPatientcode(patient);
            pa.setCode(CommonUtil.getCode());
            pa.setCreateTime(new Date());
            pa.setSbp("140");
            pa.setSbpMin("90");
            pa.setDbp("90");
            pa.setDbpMin("60");
            pa.setUnit("mmHg");
            patientAimBloodPressureDao.save(pa);
        }
        return "1";
    }
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @param patientCode
     * @param date
     * @return
     */
    public Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date) {
        return patientHealthIndexDao.findByPatienDate(patientCode, type, date);
    }
    /**
     * 按时间段查询患者健康指标
     *
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
    public JSONArray findChartByPatient(String patient, int type, int gi_type, String begin, String end) throws ParseException {
        JSONArray re = new JSONArray();
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",DATE_FORMAT(record_date, '%Y-%m-%d %H:%i:%s')'record_date' " +
                ",DATE_FORMAT(sort_date, '%Y-%m-%d %H:%i:%s') 'sort_date'" +
                ",min(czrq) czrq " +
                " from wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type =" + type +
                " and record_date >= '" + begin + "'" +
                " and record_date <= '" + end + "' " +
                " and del = '1' ";
        String conditionApp = "";
        if (gi_type != 0) {
            conditionApp = " and value2 = '" + gi_type + "' ";
        }
        sql = sql + conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = findByPatientAndTime(sql,patient,type,1000,gi_type,begin,end);
        for (Map<String, Object> map : list) {
            JSONObject json = new JSONObject();
            json.put("id", map.get("id"));
            json.put("patient", map.get("user"));
            json.put("value1", map.get("value1"));
            json.put("value2", map.get("value2"));
            json.put("value3", map.get("value3"));
            json.put("value4", map.get("value4"));
            json.put("value5", map.get("value5"));
            json.put("value6", map.get("value6"));
            json.put("value7", map.get("value7"));
            json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
            json.put("type", map.get("type"));
            
//            Date date = (Date) map.get("record_date");
            SimpleDateFormat dateFormat6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = dateFormat6.parse(map.get("record_date").toString()) ;
            if (type == 2) {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
            } else {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
            }
            json.put("sortDate", map.get("sort_date"));
            json.put("czrq", map.get("czrq"));
            
            re.put(json);
        }
        return re;
    }
    
    /**
     * 按时间段查询患者健康指标
     *
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
    public com.alibaba.fastjson.JSONObject findChartByPatientIot(String patient, int type, int gi_type, String begin, String end,String time) {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONArray re = new com.alibaba.fastjson.JSONArray();
        int high = 0;//偏高
        int normal = 0;//正常
        int low = 0;//偏低
        boolean flag = false;//高危标志 true高危。
        
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",record_date" +
                ",sort_date" +
                ",min(czrq) czrq " +
                " from wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type =" + type +
                " and record_date >= '" + begin + "'" +
                " and record_date <= '" + end + "' " +
                " and del = '1' ";
        String conditionApp = "";
        if (gi_type != 0) {
            conditionApp = " and value2 = '" + gi_type + "' ";
        }
        sql = sql + conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
        List<Map<String, Object>> list = findByPatientAndTime(sql,patient,type,1000,gi_type,begin,end);
        for (Map<String, Object> map : list) {
            String value1 = map.get("value1").toString();
            String value2 = map.get("value2").toString();
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("id", map.get("id"));
            json.put("patient", map.get("user"));
            json.put("value1", value1);
            json.put("value2", value2);
            json.put("value3", map.get("value3"));
            json.put("value4", map.get("value4"));
            json.put("value5", map.get("value5"));
            json.put("value6", map.get("value6"));
            json.put("value7", map.get("value7"));
            json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
            json.put("type", map.get("type"));
            
            Date date = (Date) map.get("record_date");
            if (type == 2) {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
            } else {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
            }
            json.put("sortDate", map.get("sort_date"));
            json.put("czrq", map.get("czrq"));
            
            
            //统计加指标分析
            int returnInt = 0;
            if(type==1){
                //血糖
                Double maxValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE;
                Double minValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE;
                Double maxValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER;
                Double minValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER;
                int index = Integer.parseInt(value2);
                Double intVlue1 = NumberUtils.toDouble(value1);
                if(index % 2 == 0){
                    //餐后
                    returnInt = checkHealth(maxValueAfter,minValueAfter,intVlue1);
                    switch (returnInt){
                        case 0:
                            normal++;
                            break;
                        case 1:
                            high++;
                            break;
                        default:
                            low++;
                            break;
                    }
                    if(intVlue1>=maxValueAfter){
                        flag = true;
                    }
                }else {
                    //餐前
                    returnInt = checkHealth(maxValueBefore,minValueBefore,intVlue1);
                    switch (returnInt){
                        case 0:
                            normal++;
                            break;
                        case 1:
                            high++;
                            break;
                        default:
                            low++;
                            break;
                    }
                    if(intVlue1>=maxValueBefore){
                        flag = true;
                    }
                }
            }else if(type==2){
                //血压
                Double intVlue1 = NumberUtils.toDouble(value1);
                Double intVlue2 = NumberUtils.toDouble(value2);
                Double maxValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MAX;
                Double minValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MIN;
                Double maxValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MAX;
                Double minValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MIN;
                
                returnInt = checkHealth(maxValueSSY,minValueSSY,intVlue1);
                switch (returnInt){
                    case 0:
                        normal++;
                        break;
                    case 1:
                        high++;
                        if(intVlue1>=maxValueSSY){
                            flag = true;
                        }
                        break;
                    default:
                        low++;
                        break;
                }
                returnInt = checkHealth(maxValueSZY,minValueSZY,intVlue2);
                switch (returnInt){
                    case 0:
                        normal++;
                        break;
                    case 1:
                        high++;
                        if(intVlue2>=maxValueSSY){
                            flag = true;
                        }
                        break;
                    default:
                        low++;
                        break;
                }
            }
            
            re.add(json);
        }
        jsonObject.put("list",re);
        com.alibaba.fastjson.JSONObject total = new com.alibaba.fastjson.JSONObject();
        total.put("high",high);
        total.put("normal",normal);
        total.put("low",low);
        jsonObject.put("total",total);
        String content = "";
        if(high>0){
            content = "居民"+time+"内有"+high+"次指标偏高";
            if(low>0){
                content+=",有"+low+"次指标偏低";
            }else {
                content+="。";
            }
            if(flag){
                content+="居民"+time+"内控制不理想,可能伴有靶器官损害或其他并发症。建议由健管师进行电话随访不少于每月4次,至少每2周面对面随访一次,建议动员居民至医院全科医生就诊,特殊情况建议入户诊疗。病情严重建议转诊专科医师进行进一步治疗。";
            }else {
                content+="居民"+time+"内控制不理想但低于急危值,建议至少每2周面对面随访一次,建议动员居民至医院全科医生就诊,特殊情况建议入户诊疗。病情严重建议转诊专科医师进行进一步治疗。";
            }
        }else if(low>0){
            content = "居民"+time+"内有"+low+"次指标偏低。";
            content+="居民"+time+"内控制不理想但低于急危值,建议至少每2周面对面随访一次,建议动员居民至医院全科医生就诊,特殊情况建议入户诊疗。病情严重建议转诊专科医师进行进一步治疗。";
        }else {
            content = "居民"+time+"内指标没有异常。居民"+time+"内相对稳定,建议至少每周面对面随访一次,全科医生根据居民情况安排预约转诊专科医师,并跟踪治疗情况。";
        }
        jsonObject.put("content",content);
        
        return jsonObject;
    }
    
    /**
     * 指标验证
     * @param max
     * @param min
     * @param value
     * @return -1偏低,0正常,1偏高
     */
    private Integer checkHealth(Double max,Double min,Double value){
        if(max<value){
            return 1;
        }else if(min>value){
            return -1;
        }else {
            return 0;
        }
    }
    
    /**
     * 查询指标记录
     *
     * @param patient
     * @param type
     * @param start
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    public JSONArray findIndexByPatient(String patient, int type, String start, String end, int page, int pageSize) throws Exception {
        JSONArray re = new JSONArray();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
        
        } else {
            // 排序
            Sort sort = Sort.by(Direction.DESC, "recordDate");
            PageRequest pageRequest = PageRequest.of(page, pageSize, sort);
            String sql = "SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",DATE_FORMAT(record_date, '%Y-%m-%d %H:%i:%s')'record_date' " +
                    ",DATE_FORMAT(sort_date, '%Y-%m-%d %H:%i:%s') 'sort_date'" +
                    ",czrq as createDate" +
                    ",min(czrq) czrq " +
                    " from wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and record_date >= '" + start + "'" +
                    " and record_date <= '" + end + "' " +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
                json.put("id", map.get("id"));
                json.put("healthindexid", map.get("id"));
                json.put("patient", map.get("user"));
                json.put("value1", map.get("value1"));
                json.put("value2", map.get("value2"));
                json.put("value3", map.get("value3"));
                json.put("value4", map.get("value4"));
                json.put("value5", map.get("value5"));
                json.put("value6", map.get("value6"));
                json.put("value7", map.get("value7"));
                json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
                json.put("type", map.get("type"));
                System.out.println(map.get("record_date"));
                SimpleDateFormat dateFormat6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = dateFormat6.parse(map.get("record_date").toString()) ;
                if (type == 2) {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
                } else {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
                }
                json.put("sortDate", map.get("sort_date"));
                json.put("czrq", map.get("czrq"));
                
                //是否为补传数据(设备上传且测量时间和创建时间不匹配)
                Date recordDate = dateFormat6.parse(map.get("record_date").toString());
                Date createDate =  dateFormat6.parse( map.get("createDate").toString());
                String recordTime = DateUtil.dateToStr(recordDate,DateUtil.YYYY_MM_DD);
                String createTime = DateUtil.dateToStr(createDate,DateUtil.YYYY_MM_DD);
                if (map.get("device_sn") == null){
                    json.put("isSupplement",0);
                }else {
                    if (recordTime.compareToIgnoreCase(createTime)==0){
                        json.put("isSupplement",0);
                    }else {
                        json.put("isSupplement",1);
                    }
                }
                
                re.put(json);
            }
        }
        return re;
    }
    
    public JSONObject findIndexByPatient1(String patient, int type,int page, int pageSize) {
        JSONArray re = new JSONArray();
        JSONObject object = new JSONObject();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
        
        } else {
            // 排序
            Sort sort = Sort.by(Direction.DESC, "recordDate");
            PageRequest pageRequest = PageRequest.of(page, pageSize, sort);
            String sql = "SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
            String sqlCount = "select count(1) as total from (SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc) phi ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String,Object>> rstotal2 = jdbcTemplate.queryForList(sqlCount);
            Long taskCount = 0L;
            if(rstotal2!=null&&rstotal2.size()>0){
                Object object1 = rstotal2.get(0).get("total");
                if (object1 != null ){
                    taskCount = Long.parseLong(object1.toString());
                }
            }
            object.put("totalCount",taskCount);
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
                json.put("id", map.get("id"));
                json.put("healthindexid", map.get("id"));
                json.put("patient", map.get("user"));
                json.put("value1", map.get("value1"));
                json.put("value2", map.get("value2"));
                json.put("value3", map.get("value3"));
                json.put("value4", map.get("value4"));
                json.put("value5", map.get("value5"));
                json.put("value6", map.get("value6"));
                json.put("value7", map.get("value7"));
                json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
                json.put("type", map.get("type"));
                
                Date date = (Date) map.get("record_date");
                if (type == 2) {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
                } else {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
                }
                json.put("sortDate", map.get("sort_date"));
                json.put("czrq", map.get("czrq"));
                
                re.put(json);
            }
        }
        object.put("pageSize",pageSize);
        object.put("currPage",page+1);
        object.put("detailModelList",re);
        return object;
    }
    
    
    /**
     * 查询指标记录
     *
     * @param patient
     * @param type
     * @param start
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    public List<Object> findIndexByPatient2(String patient, int type, String start, String end, int page, int pageSize) throws ParseException {
        List<Object> re = new ArrayList<>();
        if (page > 0) {
            page = page - 1;
        }
        
        Date startDate = DateUtil.strToDate(start, DateUtil.YYYY_MM_DD_HH_MM_SS);
        Date endDate = DateUtil.strToDate(end, DateUtil.YYYY_MM_DD_HH_MM_SS);
        if (type == 1)   //血糖特殊处理
        {
            PageRequest pageRequest = PageRequest.of(page, pageSize);
            //根据时间过滤排序
            List<String> dateList = findDateListIot(patient,type, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            if (dateList != null && dateList.size() > 0) {
                for (String dateString : dateList) {
                    com.alibaba.fastjson.JSONObject obj = getPatientXT_Json(patient, dateString);
                    if (obj != null) {
                        re.add(obj);
                    }
                }
            }
        } else {
            // 排序
            
        }
        return re;
    }
    
    
    public JSONObject findIndexByPatient3(String patient, int type,int page, int pageSize) {
        List<Object> re = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        if (page > 0) {
            page = page - 1;
        }
        
        if (type == 1)   //血糖特殊处理
        {
            PageRequest pageRequest = PageRequest.of(page, pageSize);
            jsonObject.put("currPage",page+1);
            com.alibaba.fastjson.JSONArray array = getPatientXT_Json1(patient, pageRequest.getOffset(), pageRequest.getPageSize());
            jsonObject.put("detailModelList",array);
            //根据时间过滤排序
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            String sql = "select count(1) as total from (SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type = 1" +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date,id desc ) phi";
            List<Map<String,Object>> rstotal2 = jdbcTemplate.queryForList(sql);
            Long taskCount = 0L;
            if(rstotal2!=null&&rstotal2.size()>0){
                Object object1 = rstotal2.get(0).get("total");
                if (object1 != null ){
                    taskCount = Long.parseLong(object1.toString());
                }
            }
            jsonObject.put("totalCount",taskCount);
            
        } else {
            // 排序
            
        }
        
        jsonObject.put("pageSize",pageSize);
        
        return jsonObject;
    }
    
    /**
     * 查询患者健康指标预警值
     *
     * @param patient
     * @return
     */
    public Iterable<PatientHealthStandard> findStandardByPatient(String patient) {
        return patientHealthStandardDao.findByPatient(patient);
    }
    
    /**
     * 保存患者健康指标预警值
     *
     * @param list
     */
    public Iterable<PatientHealthStandard> saveStandard(List<PatientHealthStandard> list, String patient) {
        // 先删除
        patientHealthStandardDao.deleteByPatient(patient);
        return patientHealthStandardDao.saveAll(list);
    }
    
    /**
     * 查询患者最近填写的血糖、血压等记录
     *
     * @param patient
     * @return
     */
    public JSONArray findRecentByPatient(String patient) {
        JSONArray array = new JSONArray();
        List<DevicePatientHealthIndex> iterable = patientHealthIndexDao.findRecentByPatient(patient);
        if (iterable != null) {
            Iterator<DevicePatientHealthIndex> iterator = iterable.iterator();
            while (iterator != null && iterator.hasNext()) {
                DevicePatientHealthIndex phi = iterator.next();
                if (phi == null) {
                    continue;
                }
                JSONObject json = new JSONObject();
                // 设置健康指标类型(1血糖,2血压,3体重,4腰围)
                json.put("type", phi.getType());
                if (1 == phi.getType() && StringUtils.isNotBlank(phi.getValue2())) {
                    int gi_type = Integer.parseInt(phi.getValue2());
                    switch (gi_type) {
                        case 1:
                            // 设置血糖/收缩压/体重/腰围/早餐前空腹
                            json.put("value1", phi.getValue1());
                            json.put("time1", phi.getRecordDate());
                            break;
                        case 2:
                            // 设置舒张压/早餐后血糖
                            json.put("value2", phi.getValue2());
                            json.put("time2", phi.getRecordDate());
                            break;
                        case 3:
                            // 设置午餐前血糖
                            json.put("value3", phi.getValue3());
                            json.put("time3", phi.getRecordDate());
                            break;
                        case 4:
                            // 设置午餐后血糖
                            json.put("value4", phi.getValue4());
                            json.put("time4", phi.getRecordDate());
                            break;
                        case 5:
                            // 设置晚餐前血糖
                            json.put("value5", phi.getValue5());
                            json.put("time5", phi.getRecordDate());
                            break;
                        case 6:
                            // 设置晚餐后血糖
                            json.put("value6", phi.getValue6());
                            json.put("time6", phi.getRecordDate());
                            break;
                        case 7:
                            // 设置睡前血糖
                            json.put("value7", phi.getValue7());
                            json.put("time7", phi.getRecordDate());
                            break;
                    }
                } else {
                    json.put("value1", phi.getValue1());
                    json.put("value2", phi.getValue2());
                    // 设置午餐前血糖
                    json.put("value3", phi.getValue3());
                    // 设置午餐后血糖
                    json.put("value4", phi.getValue4());
                    // 设置晚餐前血糖
                    json.put("value5", phi.getValue5());
                    // 设置晚餐后血糖
                    json.put("value6", phi.getValue6());
                    // 设置睡前血糖
                    json.put("value7", phi.getValue7());
                }
                
                
                json.put("date", DateUtil.dateToStrShort(phi.getRecordDate()));
                array.put(json);
            }
        }
        return array;
    }
    
    /**
     * 根据患者标志获取健康指标
     *
     * @param patientCode 患者标志
     * @return 健康指标列表
     */
    public DevicePatientHealthIndex findLastByPatien(String patientCode, int type) {
        //最新血糖指标
        if (type == 1) {
            DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode, 1);
            return obj;
        } else if (type == 2) {  //其他指标
            return patientHealthIndexDao.findLastData(patientCode, 2);
        } else {
            return patientHealthIndexDao.findLastData(patientCode, type);
        }
    }
    
    /**
     * 获取患者健康指标历史记录
     * 1血糖,2血压,3体重,4腰围
     */
    public List<Map<String, String>> getHealthIndexHistory(String patientCode, int type, int page, int pagesize) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        
        // 排序
        Sort sort = Sort.by(Direction.DESC, "recordDate");
        PageRequest pageRequest = PageRequest.of(page, pagesize, sort);
        List<DevicePatientHealthIndex> list = patientHealthIndexDao.findIndexByPatient(patientCode, type, pageRequest);
        
        if (list != null && list.size() > 0) {
            for (DevicePatientHealthIndex item : list) {
                Map<String, String> map = new HashMap<>();
                if (type == 1)    //血糖
                {
                    String gi = item.getValue1();
                    String giType = item.getValue2();
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("gi", gi); //  血糖值
                    map.put("gi_type", giType); //  血糖值类型
                    String text = gi + " mmol/L";
                    if ("1".equals(giType)) {
                        text += "(早餐前)";
                    } else if ("2".equals(giType)) {
                        text += "(早餐后)";
                    } else if ("3".equals(giType)) {
                        text += "(午餐前)";
                    } else if ("4".equals(giType)) {
                        text += "(午餐后)";
                    } else if ("5".equals(giType)) {
                        text += "(晚饭前)";
                    } else if ("6".equals(giType)) {
                        text += "(晚饭后)";
                    } else if ("7".equals(giType)) {
                        text += "(睡前)";
                    }
                    map.put("text", text); //  展示
                    re.add(map);
                } else if (type == 2) //血压
                {
                    String sys = item.getValue1();   //收缩压
                    String dia = item.getValue2();    //舒张压
                    String pul = item.getValue3();    //脉搏
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("sys", sys);
                    map.put("dia", dia);
                    map.put("pul", pul);
                    re.add(map);
                } else if (type == 3) //体重
                {
                    String weight = item.getValue1();   //体重
                    String height = item.getValue2();   //身高
                    String bmi = item.getValue3();      //BMI
                    map.put("time", DateUtil.dateToStrShort(item.getRecordDate()));
                    map.put("weight", weight);
                    map.put("height", height);
                    map.put("bmi", bmi);
                    map.put("text", weight + " kg");
                    re.add(map);
                }
            }
        }
        
        return re;
    }
    
    /**
     * 保存医生预警值方案
     *
     * @param doclist
     * @param uid
     * @return
     */
    public Iterable<DoctorHealthStandard> saveDocStandard(List<DoctorHealthStandard> doclist, String uid) throws Exception {
        // 先删除
        doctorHealthStandardDao.deleteByDoctor(uid);
        return doctorHealthStandardDao.saveAll(doclist);
    }
    
    /**
     * 查询患者健康指标预警值
     *
     * @param code
     * @return
     */
    public Iterable<DoctorHealthStandard> findDoctorStandardByDoctor(String code) {
        return doctorHealthStandardDao.findByDoctor(code);
    }
    
    /**
     * 批量保存患者预警方案
     *
     * @param list
     * @param patients
     * @return
     */
    public Iterable<PatientHealthStandard> saveStandardPatients(List<PatientHealthStandard> list, List<BasePatientDO> patients) {
        
        for (BasePatientDO patient : patients) {
            patientHealthStandardDao.deleteByPatient(patient.getId());
        }
        return patientHealthStandardDao.saveAll(list);
    }
    
    public List<Map<String, String>> getHealthIndexByPatientAndDate(String patientCode, String deviceSn, String choseDate,int type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        
        // 排序
        List<DevicePatientHealthIndex> list = new ArrayList<>();
        
        if(choseDate.length() == 7){
            list = patientHealthIndexDao.findByDateMonthAndType(type,patientCode,choseDate,deviceSn);
        }else{
            list = patientHealthIndexDao.findByDateAndType(type,patientCode,choseDate,deviceSn);
        }
        
        if (list != null && list.size() > 0) {
            for (DevicePatientHealthIndex item : list) {
                Map<String, String> map = new HashMap<>();
                if (type == 1)    //血糖
                {
                    String gi = item.getValue1();
                    String giType = item.getValue2();
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("gi", gi); //  血糖值
                    map.put("gi_type", giType); //  血糖值类型
                    String text = gi + " mmol/L";
                    if ("1".equals(giType)) {
                        text += "(早餐前)";
                    } else if ("2".equals(giType)) {
                        text += "(早餐后)";
                    } else if ("3".equals(giType)) {
                        text += "(午餐前)";
                    } else if ("4".equals(giType)) {
                        text += "(午餐后)";
                    } else if ("5".equals(giType)) {
                        text += "(晚饭前)";
                    } else if ("6".equals(giType)) {
                        text += "(晚饭后)";
                    } else if ("7".equals(giType)) {
                        text += "(睡前)";
                    }
                    map.put("text", text); //  展示
//                    re.add(map);
                } else if (type == 2) //血压
                {
                    String sys = item.getValue1();   //收缩压
                    String dia = item.getValue2();    //舒张压
                    String pul = item.getValue3();    //脉搏
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("sys", sys);
                    map.put("dia", dia);
                    map.put("pul", pul);
//                    re.add(map);
                } else if (type == 3) //体重
                {
                    String weight = item.getValue1();   //体重
                    String height = item.getValue2();   //身高
                    String bmi = item.getValue3();      //BMI
                    map.put("time", DateUtil.dateToStrShort(item.getRecordDate()));
                    map.put("weight", weight);
                    map.put("height", height);
                    map.put("bmi", bmi);
                    map.put("text", weight + " kg");
//                    re.add(map);
                }else if(type == 4){
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("value1", item.getValue1());
                    map.put("value2", item.getValue2());
                }
                map.put("type", item.getType().toString());
                re.add(map);
            }
        }
        
        return re;
    }
}

+ 3 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java

@ -364,13 +364,14 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
                                         @RequestParam(value = "article", required = false) String article,
                                         @ApiParam(name = "doctor", value = "医生code", required = false)
                                         @RequestParam(value = "doctor", required = false) String doctor,
                                         @ApiParam(name = "relationCode", value = "执行计划id", required = false)
                                         @RequestParam(value = "relationCode", required = false) String relationCode,
                                         @ApiParam(name = "page", value = "页码", required = false)
                                         @RequestParam(value = "page", required = false) Integer page,
                                         @ApiParam(name = "pagesize", value = "每页大小", required = false)
                                         @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        try {
            return rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,article,page,pagesize);
            return rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,article,relationCode,page,pagesize);
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");

+ 4 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationGuidanceService.java

@ -176,7 +176,7 @@ public class RehabilitationGuidanceService {
    }
    public PageEnvelop selectPatientGuidances(String patient, String doctor, String article, Integer page, Integer pagesize) {
    public PageEnvelop selectPatientGuidances(String patient, String doctor, String article,String relationCode, Integer page, Integer pagesize) {
        if (page >= 1) {
            page--;
        }
@ -204,6 +204,9 @@ public class RehabilitationGuidanceService {
        if (StringUtils.isNoneBlank(doctor)) {
            filters.put("doctor", new SearchFilter("doctor", SearchFilter.Operator.EQ, doctor));
        }
        if (StringUtils.isNoneBlank(relationCode)) {
            filters.put("relationCode", new SearchFilter("relationCode", SearchFilter.Operator.EQ, relationCode));
        }
        Specification<RehabilitationguidancePatientDO> spec = DynamicSpecifications.bySearchFilter(filters.values(), RehabilitationguidancePatientDO.class);
        Page<RehabilitationguidancePatientDO> rehabilitationguidancePatientDOS = rehabilitationGuidancePatientDao.findAll(spec, pageRequest);
        for (RehabilitationguidancePatientDO rehabilitationguidancePatientDO : rehabilitationguidancePatientDOS) {