Quellcode durchsuchen

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

# Conflicts:
#	common/common-entity/sql记录
wangjun vor 4 Jahren
Ursprung
Commit
15d7b9d8d4
100 geänderte Dateien mit 12567 neuen und 160 gelöschten Zeilen
  1. 5 1
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  2. 190 0
      common/common-entity/sql记录
  3. 16 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/doctor/BaseDoctorDO.java
  4. 42 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java
  5. 16 15
      common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServicePackageSignRecordDO.java
  6. 69 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/apply/PatientBedApplyDo.java
  7. 111 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java
  8. 317 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java
  9. 241 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientHealthIndex.java
  10. 297 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/PatientDevice.java
  11. 81 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/label/WlyyPatientLabelDO.java
  12. 10 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/lifeCare/LifeCareOrderDO.java
  13. 60 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/role/DoctorRole.java
  14. 42 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/role/DoctorRoleRealm.java
  15. 61 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/role/WlyyUserRole.java
  16. 5 5
      common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringConclusionDO.java
  17. 78 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringDoctorStatusDo.java
  18. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderCancelLog.java
  19. 37 21
      common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderDO.java
  20. 81 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderPatientConfirmLog.java
  21. 621 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentBaseInfoDo.java
  22. 96 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentCognitiveAbilityDo.java
  23. 151 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentLivingAbilityDo.java
  24. 72 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentRecordDO.java
  25. 124 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentSocialAbilityDo.java
  26. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  27. 76 7
      svr/svr-cloud-care/pom.xml
  28. 125 0
      svr/svr-cloud-care/sql/sql
  29. 20 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/apply/PatientBedApplyDao.java
  30. 21 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDao.java
  31. 16 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java
  32. 70 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DevicePatientHealthIndexDao.java
  33. 54 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/PatientDeviceDao.java
  34. 22 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/label/WlyyPatientLabelDao.java
  35. 19 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/role/DoctorRoleDao.java
  36. 17 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/role/DoctorRoleRealmDao.java
  37. 15 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/role/UserRoleDao.java
  38. 17 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringConclusionDao.java
  39. 16 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringDoctorStatusDao.java
  40. 14 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringOrderCancelLogDao.java
  41. 24 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringOrderDao.java
  42. 12 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringOrderPatientConfirmLogDao.java
  43. 9 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/ArchiveDao.java
  44. 19 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentBaseInfoDao.java
  45. 19 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentCognitiveAbilityDao.java
  46. 18 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentLivingAbilityDao.java
  47. 1 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentRecordDao.java
  48. 18 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentSocialAbilityDao.java
  49. 3 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/ServicePackageRecordDao.java
  50. 793 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/BaseController.java
  51. 8 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/WeixinBaseController.java
  52. 56 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/apply/PatientBedApplyEndPoint.java
  53. 53 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DeviceController.java
  54. 120 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorDeviceController.java
  55. 318 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorHealthController.java
  56. 214 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PatientDeviceController.java
  57. 20 12
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/dict/DictEndpoint.java
  58. 35 5
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorEndpoint.java
  59. 65 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/label/PatientLabelEndpoint.java
  60. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/org/OrgEndpoint.java
  61. 47 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/patient/PatientEndpoint.java
  62. 226 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/security/SecurityMonitoringOrderEndpoint.java
  63. 145 15
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/sign/SignEndpoint.java
  64. 73 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/StatisticsEndpoint.java
  65. 93 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/apply/PatientBedApplyService.java
  66. 104 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/DictService.java
  67. 185 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/DeviceDetailService.java
  68. 38 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/DeviceService.java
  69. 656 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java
  70. 1599 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientHealthIndexService.java
  71. 42 8
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doctor/CareDoctorService.java
  72. 83 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/label/PatientLableService.java
  73. 1 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/lifeCare/LifeCareOrderService.java
  74. 110 9
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/patient/CarePatientService.java
  75. 218 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/role/RoleService.java
  76. 829 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java
  77. 55 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/ArchiveService.java
  78. 429 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/CapacityAssessmentRecordService.java
  79. 81 47
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/ServicePackageService.java
  80. 141 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsService.java
  81. 211 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/CommonUtil.java
  82. 143 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ConcealUtil.java
  83. 57 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ConstantUtil.java
  84. 33 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MessageUtil.java
  85. 81 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MyJdbcTemplate.java
  86. 168 0
      svr/svr-statistics-es/doc/es/QuartzJobConfig.java
  87. 127 0
      svr/svr-statistics-es/doc/es/QuartzJobConfig1.java
  88. 116 0
      svr/svr-statistics-es/doc/es/统计新增索引.txt
  89. 192 0
      svr/svr-statistics-es/doc/sql/统计相关表数据备份20171121.txt
  90. BIN
      svr/svr-statistics-es/doc/业务文档/统计指标流程.docx
  91. BIN
      svr/svr-statistics-es/doc/部署文档/正式库/后台/tomcat部署.docx
  92. 455 0
      svr/svr-statistics-es/pom.xml
  93. 120 0
      svr/svr-statistics-es/readme.MD
  94. 56 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/Application.java
  95. 49 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/AsyncConfig.java
  96. 240 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/DataSourceConfig.java
  97. 30 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/MVCConfig.java
  98. 61 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/SwaggerConfig.java
  99. 55 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/WebSecurityConfig.java
  100. 0 0
      svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/jpa/HibernateProperties.java

+ 5 - 1
business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java

@ -28,6 +28,10 @@ public interface SystemMessageDao extends PagingAndSortingRepository<SystemMessa
    List<SystemMessageDO> queryByRelationCodeAndTypeIn(String relationCode,String[] type);
    //获取资质申请审核有效的未结束已发送的消息
    @Query("select a from SystemMessageDO a where a.type in ('401','408') and a.del='1' and a.over='1' and relationCode = ?1  ")
    @Query("select a from SystemMessageDO a where a.type in ('401','408') and a.del='1' and a.over='1' and a.relationCode = ?1  ")
    List<SystemMessageDO> findMessageByRelationCode(String relationCode);
    @Modifying
    @Query("delete from SystemMessageDO a  where a.receiver = ?1 and a.relationCode = ?2 and a.type =?3")
    int orderMessageDelByType(String doctor, String orderId,String type);
}

+ 190 - 0
common/common-entity/sql记录

@ -196,6 +196,196 @@ alter table base_patient add `archive_status` tinyint(1) DEFAULT NULL COMMENT '
alter table base_patient add `medicare_number` varchar(50) DEFAULT NULL COMMENT '医疗保险号';
alter table base_patient add `ssc` varchar(50) DEFAULT NULL COMMENT '社保卡号';
alter table base_patient add `archive_type` tinyint(1) DEFAULT NULL COMMENT '档案类型 1老人 2新生儿';
-- 2021-04-07 ysj
alter table base_doctor add `level` tinyint(4) DEFAULT NULL COMMENT '类型 1社区医生,2助老员';
-- 2021-04-08 lb
CREATE TABLE `base_patient_bed_apply` (
  `id` varchar(50) NOT NULL,
  `patient` varchar(50) NOT NULL,
  `patient_name` varchar(50) DEFAULT NULL,
  `idcard` varchar(50) DEFAULT NULL COMMENT '身份证',
   org_code varchar(50) DEFAULT NULL COMMENT '申请机构code',
   org_name varchar(50) DEFAULT NULL COMMENT '申请机构名称',
   status tinyint(4) DEFAULT '1' COMMENT '状态 -1取消 0已完成 1未处理 2未评估',
  `create_time` timestamp NULL DEFAULT NULL ,
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者称名',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='居民床位申请';
CREATE TABLE `base_capacity_assessment_baseinfo` (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` tinyint(2) DEFAULT NULL,
  `age` varchar(5) DEFAULT NULL,
  `nation` varchar(20) DEFAULT NULL COMMENT '名族',
  `nation_name` varchar(50) DEFAULT NULL COMMENT '名族名称',
  `religion` varchar(20) DEFAULT NULL COMMENT '宗教信仰 0无;1有',
  `idcard` varchar(20) DEFAULT NULL,
  `domicile` varchar(20) DEFAULT NULL COMMENT '户籍 0本地户口;1外地户口',
  `marriage` varchar(20) DEFAULT NULL COMMENT '婚姻状况 10.未婚 20.已婚 30.丧偶 40.离婚 90.未说明的婚姻状况',
  `marriage_remark` varchar(255) DEFAULT NULL COMMENT '婚姻状况 备注',
  `education` varchar(20) DEFAULT NULL COMMENT '文化程度 0文盲及半文盲;1小学;2初中;3高中/技校/中专;4大学专科及以上;5不详',
  `income_type` varchar(20) DEFAULT NULL COMMENT '主要经济来源 0退休金/养老金;1子女补贴;2亲友资助;3其他补贴',
  `pension_flag` varchar(20) DEFAULT NULL COMMENT '是否有养老金收入 0无 1有',
  `pension_count` varchar(20) DEFAULT NULL COMMENT '养老金收入 元/月',
  `family_type` varchar(20) DEFAULT NULL COMMENT '是否为经济困难家庭 0否 1特困 2低保 3低保边缘 ',
  `disability_certificate` varchar(20) DEFAULT NULL COMMENT '是否为持证残疾人 0否 1是 ',
  `medical_insurance` varchar(20) DEFAULT NULL COMMENT '是否购买了商业健康(医疗)保险 0否 1是 ',
  `living_type` varchar(20) DEFAULT NULL COMMENT '现住场所:1自有产权房、私房等;2各类租赁房等;3养老院或类似机构;4护理院或类似机构;5医院或类似机构',
  `living_together` varchar(20) DEFAULT NULL COMMENT '同居者类型 0独居;1与配偶/伴侣居住;2与子女居住;3与孙辈居住;4与父母居住;5与兄弟姐妹居住;6与其他亲友居住;7其他',
  `living_together_remark` varchar(255) DEFAULT NULL COMMENT '同居者备注',
  `dementia_flag` varchar(20) DEFAULT NULL COMMENT '痴呆症 0无 1有',
  `mental_illness` varchar(20) DEFAULT NULL COMMENT '精神疾病(可多选)0无;1精神分裂症;2双相情感障碍;3偏执性精神障碍;4分裂情感性障碍;5癫痫所致精神障碍;6精神发育迟滞伴发精神障碍',
  `disease_type` varchar(20) DEFAULT NULL COMMENT '患病类型可多选;0无 1肿瘤(晚期)2严重心律失常3压疮4慢性心力衰竭(心功能III-IV级)5慢性肾功能衰竭(尿毒症期)6多器官功能衰竭7蛋白质能量营养不足(重度)8慢性阻塞性肺疾病(肺心病心功能III-IV级)9呼吸衰竭10脑血管意外合并吞咽障碍11其他',
  `disease_remark` varchar(255) DEFAULT NULL COMMENT '其他疾病',
  `fall_lately` varchar(20) DEFAULT NULL COMMENT '近30天跌倒 0无;1一次;2两次;3三次及以上',
  `lost_lately` varchar(20) DEFAULT NULL COMMENT '近30天走失 0无;1一次;2两次;3三次及以上',
  `choking_lately` varchar(20) DEFAULT NULL COMMENT '近30天噎食 0无;1一次;2两次;3三次及以上',
  `suicide_lately` varchar(20) DEFAULT NULL COMMENT '近30天自杀 0无;1一次;2两次;3三次及以上',
  `remark_lately` varchar(255) DEFAULT NULL COMMENT '近30天意外 其他 0无;1一次;2两次;3三次及以上',
  `medical_services` varchar(255) DEFAULT NULL COMMENT '近7天是否接受过医疗护理服务 0无1有',
  `domicile_county` varchar(255) DEFAULT NULL COMMENT '户籍  区(县、市)',
  `domicile_county_name` varchar(255) DEFAULT NULL COMMENT '户籍  区(县、市)',
  `domicile_street` varchar(255) DEFAULT NULL COMMENT '户籍  街(镇)',
  `domicile_street_name` varchar(255) DEFAULT NULL COMMENT '户籍  街(镇)',
  `domicile_org` varchar(255) DEFAULT NULL COMMENT '户籍 社(村)',
  `domicile_org_name` varchar(255) DEFAULT NULL COMMENT '户籍 社(村)',
  `domicile_building` varchar(255) DEFAULT NULL COMMENT '户籍 xx幢',
  `domicile_room` varchar(255) DEFAULT NULL COMMENT '户籍 xx室',
  `live_county` varchar(255) DEFAULT NULL COMMENT '居住地  区(县、市)',
  `live_county_name` varchar(255) DEFAULT NULL COMMENT '居住地名称  区(县、市)',
  `live_street` varchar(255) DEFAULT NULL COMMENT '居住地  街(镇)',
  `live_street_name` varchar(255) DEFAULT NULL COMMENT '居住地名称  街(镇)',
  `live_org` varchar(255) DEFAULT NULL COMMENT '居住地 社(村)',
  `live_org_name` varchar(255) DEFAULT NULL COMMENT '居住地名称 社(村)',
  `live_building` varchar(255) DEFAULT NULL COMMENT '居住地 xx幢',
  `live_room` varchar(255) DEFAULT NULL COMMENT '居住地 xx室',
  `postcode` varchar(50) DEFAULT NULL COMMENT '邮编',
  `residence_phone` varchar(50) DEFAULT NULL COMMENT '住宅电话',
  `patient_phone` varchar(50) DEFAULT NULL COMMENT '手机',
  `proxy_name` varchar(50) DEFAULT NULL COMMENT '代理人姓名',
  `applicant_relation` varchar(50) DEFAULT NULL COMMENT '与申请人关系',
  `proxy_address` varchar(255) DEFAULT NULL COMMENT '代理人地址',
  `proxy_telephone` varchar(50) DEFAULT NULL COMMENT '代理人电话',
  `proxy_phone` varchar(50) DEFAULT NULL COMMENT '代理人手机',
  `applicant_sign` varchar(255) DEFAULT NULL COMMENT '申请人(代理人) 签字结果图片url',
  `applicant_date` varchar(50) DEFAULT NULL COMMENT '申请日期',
  `service_type` varchar(50) DEFAULT NULL COMMENT '养老服务形式 0居家养老 1机构养老',
  `acceptable_services_life1` varchar(50) DEFAULT NULL COMMENT '直接生活照顾  1穿衣;2修饰;3口腔清洁;4皮肤清洁;5喂食服务;6排泄照料 ',
  `acceptable_services_life2` varchar(50) DEFAULT NULL COMMENT '间接生活照顾  1居室清洁;2更换洗涤;3上门维修;4定期探访;5膳食服务;6文化教育;7娱乐休闲;8室外休闲(户外);9紧急呼援;10法律援助;11转介服务;12咨询服务',
  `acceptable_services_mental` varchar(50) DEFAULT NULL COMMENT '精神心理照顾 1危机干预;2沟通;3精神支持;4心理疏导;5心理咨询',
  `acceptable_services_rehabilitation` varchar(255) DEFAULT NULL COMMENT '康复护理照顾 1定期翻身;2压疮预;3防活动肢体;4肢体保健;5康复活动;6预防保健;7健康咨询;8健康管理;9健康教育;10临终关怀 ',
  `acceptable_services_other` varchar(255) DEFAULT NULL COMMENT '其他',
  `create_time` datetime DEFAULT NULL,
  `medical_insurance_type` varchar(20) DEFAULT NULL COMMENT '医保类别 1职工基本医疗保险 2城乡居民基本医疗保险 3其他医疗保障 4无任何保障',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-基本信息表';
CREATE TABLE `base_capacity_assessment_living_ability` (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `eating_ability_score` varchar(50) DEFAULT NULL COMMENT '进食能力得分 10可独立进食;5需部分帮助;0需要极大帮助或完全依赖他人',
  `shower_ability_score` varchar(50) DEFAULT NULL COMMENT '洗澡能力得分 5可独立完成;0需要帮助',
  `washing_ability_score` varchar(50) DEFAULT NULL COMMENT '洗漱能力得分 5可独立完成;0需要帮助',
  `dressing_ability_score` varchar(50) DEFAULT NULL COMMENT '穿衣能力得分 10可独立完成;5需要部分帮助;0需要极大帮助或完全依赖他人',
  `excretion_ability_score` varchar(50) DEFAULT NULL COMMENT '排便控制能力得分 10可自主控制;5偶尔失控(每周小于一次,或需要他人提示);0完全失控',
  `urination_ability_score` varchar(50) DEFAULT NULL COMMENT '排尿控制能力得分 10可自主控制;5偶尔失控(每周小于一次,或需要他人提示);0完全失控或留置导尿管',
  `toilet_ability_score` varchar(50) DEFAULT NULL COMMENT '如厕能力得分 10可独立完成;5需部分帮助;0需要极大帮助或完全依赖他人',
  `transfer_bed_ability_score` varchar(50) DEFAULT NULL COMMENT '床椅转移能力得分 15可独立完成10需要部分帮忙5需要极大帮忙0完全依赖他人',
  `walking_ability_score` varchar(50) DEFAULT NULL COMMENT '平地行走能力得分 15可独立行走45m;10需要部分帮助;5需要极大帮助;0完全依赖他人',
  `down_stairs_ability_score` varchar(50) DEFAULT NULL COMMENT '上下楼梯能力得分10可独立上下楼梯(连续10~15个台阶);5需要部分帮忙0需要极大帮助或完全依赖他人',
  `total_score` varchar(50) DEFAULT NULL COMMENT '日常生活能力总分 上述得分和 总分100 ',
  `ability_grade` varchar(50) DEFAULT NULL COMMENT '能力等级:0能力完好(100);1轻度受损(65-95);2中度受损(45-60);3重度受损(≤40)',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-日常生活能力评估表';
CREATE TABLE `base_capacity_assessment_cognitive_ability` (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `question1` varchar(4) DEFAULT NULL COMMENT '问题一得分 总分3分',
  `question2` varchar(4) DEFAULT NULL COMMENT '问题二得分 总分5分',
  `question3` varchar(4) DEFAULT NULL COMMENT '问题三得分 总分5分',
  `question4` varchar(4) DEFAULT NULL COMMENT '问题四得分 总分3分',
  `total_score` varchar(50) DEFAULT NULL COMMENT '认知能力 上述得分和  ',
  `ability_grade` varchar(50) DEFAULT NULL COMMENT '能力等级:0能力完好(16);1轻度受损(13-15);2中度受损(9-12);3重度受损(≤8)',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-认知能力表';
CREATE TABLE `base_capacity_assessment_social_ability` (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `aggress_score` varchar(4) DEFAULT NULL COMMENT '攻击行为得分 总分3分',
  `depressed_score` varchar(4) DEFAULT NULL COMMENT '抑郁状态得分 总分5分',
  `consciousness_score` varchar(4) DEFAULT NULL COMMENT '意识水平得分 总分5分',
  `communicate_score` varchar(4) DEFAULT NULL COMMENT '沟通交流得分 总分3分',
  `social_skills_score` varchar(50) DEFAULT NULL COMMENT '社交能力得分   ',
  `vision_score` varchar(50) DEFAULT NULL COMMENT '视力功能得分   ',
  `hearing_score` varchar(50) DEFAULT NULL COMMENT '听力能力得分   ',
  `total_score` varchar(50) DEFAULT NULL COMMENT ' 精神状态与社会交流能力总分 上述得分和 总分22',
  `ability_grade` varchar(50) DEFAULT NULL COMMENT '能力等级:0能力完好(22);1轻度受损(15-21);2中度受损(7-14);3重度受损(≤6)',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-精神状态与社会交流能力表';
CREATE TABLE `base_security_monitoring_order_cancel_log` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) NOT NULL COMMENT '工单id',
  `patient` varchar(50) NOT NULL COMMENT '居民code',
  `cancel_type` int(1) NOT NULL COMMENT '取消类型:1-调度员取消,2-居民取消 3 医生取消',
  `cancel_reason` varchar(50) DEFAULT NULL COMMENT '取消理由',
  `time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '取消时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='安防工单取消记录';
CREATE TABLE `base_semoni_patient_confirm_log` (
  `id` varchar(50) NOT NULL,
  `order_id` varchar(50) NOT NULL COMMENT '工单id',
  `patient` varchar(50) NOT NULL COMMENT '居民',
  `patient_name` varchar(50) NOT NULL COMMENT '居民姓名',
  `type` int(1) NOT NULL COMMENT '确认操作类型:1-确认基础信息无误或变更,2-确认医生变更服务信息,3-同意工单转接  4同意取消工单',
  `description` varchar(200) DEFAULT NULL COMMENT '操作描述',
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者称名',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '转接时间',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='安防服务工单居民确认操作日志记录';
CREATE TABLE `base_semoni_doctor_status` (
  `id` varchar(50) NOT NULL,
  `doctor` varchar(50) NOT NULL COMMENT '医生code',
  `status` int(1) NOT NULL DEFAULT '1' COMMENT '医生状态:1-待派单,2-待接单,3-待服务,4-服务中,5-停止接单',
  `create_user` varchar(50) DEFAULT NULL COMMENT '创建者id',
  `create_user_name` varchar(50) DEFAULT NULL COMMENT '创建者称名',
  `create_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '转接时间',
  `update_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_user` varchar(50) DEFAULT NULL,
  `update_user_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='医生安防服务工单状态情况';
alter TABLE base.base_security_monitoring_order add COLUMN doctor_confirm_finish_img VARCHAR(3000) DEFAULT NULL COMMENT '医生确认完成照片';
alter TABLE base.base_security_monitoring_order add COLUMN doctor_confirm_finish_time timestamp NULL DEFAULT NULL COMMENT '医生确认完成时间';
-- 2021-04-09 中山消息推送
alter table wlyy_outpatient ADD last_remind_time timestamp ;
alter table wlyy_outpatient ADD remind_doctor  varchar(50) ;

+ 16 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/doctor/BaseDoctorDO.java

@ -282,6 +282,13 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
    private String jyzxChargeType;
    private String visitTime;
    /**
     * 类型 1社区医生,2助老员
     */
    private Integer level;
    @Column(name = "visit_time")
    public String getVisitTime() {
        return visitTime;
@ -747,4 +754,13 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
    public void setXtfzChargeType(String xtfzChargeType) {
        this.xtfzChargeType = xtfzChargeType;
    }
    @Column(name = "level")
    public Integer getLevel() {
        return level;
    }
    public void setLevel(Integer level) {
        this.level = level;
    }
}

+ 42 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java

@ -6,6 +6,7 @@ import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
@ -273,6 +274,11 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
    private Integer archiveStatus;//档案状态【1.未管理 2.死亡 3.正常 4.高危】【必填】
    private Integer archiveType;// 档案类型 1老人 2新生儿
    private String archiveStatusName;
    private String archiveTypeName;
    private String bloodName;
    private String marriageName;
    public String getCardType() {
        return cardType;
    }
@ -796,4 +802,40 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
    public void setMedicareNumber(String medicareNumber) {
        this.medicareNumber = medicareNumber;
    }
    @Transient
    public String getArchiveStatusName() {
        return archiveStatusName;
    }
    public void setArchiveStatusName(String archiveStatusName) {
        this.archiveStatusName = archiveStatusName;
    }
    @Transient
    public String getArchiveTypeName() {
        return archiveTypeName;
    }
    public void setArchiveTypeName(String archiveTypeName) {
        this.archiveTypeName = archiveTypeName;
    }
    @Transient
    public String getBloodName() {
        return bloodName;
    }
    public void setBloodName(String bloodName) {
        this.bloodName = bloodName;
    }
    @Transient
    public String getMarriageName() {
        return marriageName;
    }
    public void setMarriageName(String marriageName) {
        this.marriageName = marriageName;
    }
}

+ 16 - 15
common/common-entity/src/main/java/com/yihu/jw/entity/base/servicePackage/ServicePackageSignRecordDO.java

@ -10,6 +10,7 @@ import javax.persistence.Transient;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 签约记录表
@ -33,11 +34,11 @@ public class ServicePackageSignRecordDO extends UuidIdentityEntityWithCreateTime
    private List<ServicePackageRecordDO> recordDOList;
    //社区医生
    private String doctorInfo;
    private List<Map<String,Object>> doctorList;
    //助老员
    private String helperInfo;
    private List<Map<String,Object>> helperList;
    //服务包
    private String packageInfo;
    private List<Map<String,Object>> packageList;
    public String getPatient() {
        return patient;
@ -111,29 +112,29 @@ public class ServicePackageSignRecordDO extends UuidIdentityEntityWithCreateTime
    }
    @Transient
    public String getDoctorInfo() {
        return doctorInfo;
    public List<Map<String,Object>> getDoctorList() {
        return doctorList;
    }
    public void setDoctorInfo(String doctorInfo) {
        this.doctorInfo = doctorInfo;
    public void setDoctorList(List<Map<String,Object>> doctorList) {
        this.doctorList = doctorList;
    }
    @Transient
    public String getHelperInfo() {
        return helperInfo;
    public List<Map<String,Object>> getHelperList() {
        return helperList;
    }
    public void setHelperInfo(String helperInfo) {
        this.helperInfo = helperInfo;
    public void setHelperList(List<Map<String,Object>> helperList) {
        this.helperList = helperList;
    }
    @Transient
    public String getPackageInfo() {
        return packageInfo;
    public List<Map<String,Object>> getPackageList() {
        return packageList;
    }
    public void setPackageInfo(String packageInfo) {
        this.packageInfo = packageInfo;
    public void setPackageList(List<Map<String,Object>> packageList) {
        this.packageList = packageList;
    }
}

+ 69 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/apply/PatientBedApplyDo.java

@ -0,0 +1,69 @@
package com.yihu.jw.entity.care.apply;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Bing on 2021/4/8.
 */
@Entity
@Table(name="base_patient_bed_apply")
public class PatientBedApplyDo extends UuidIdentityEntityWithOperator {
    private String patient;
    private String patientName;
    private String idcard;
    private String orgCode;
    private String orgName;
    private Integer status; //状态 -1取消 0已完成 1未处理 2未评估
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 111 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java

@ -0,0 +1,111 @@
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 java.util.Date;
/**
 * 设备列表
 */
@Entity
@Table(name = "dm_device")
@SequenceGenerator(name="id_generated", sequenceName="dm_device")
public class Device extends IdEntity {
	private String categoryCode;
	private String photo;
	private String brands;
	private String model;
	private String isMultiUser;
	private String multiUser;
	private String name;
	private Date czrq;
	private String del;
	@Column(name="category_code")
	public String getCategoryCode() {
		return categoryCode;
	}
	public void setCategoryCode(String categoryCode) {
		this.categoryCode = categoryCode;
	}
	@Column(name="photo")
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	@Column(name="brands")
	public String getBrands() {
		return brands;
	}
	public void setBrands(String brands) {
		this.brands = brands;
	}
	@Column(name="model")
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	@Column(name="is_multi_user")
	public String getIsMultiUser() {
		return isMultiUser;
	}
	public void setIsMultiUser(String isMultiUser) {
		this.isMultiUser = isMultiUser;
	}
	@Column(name="multi_user")
	public String getMultiUser() {
		return multiUser;
	}
	public void setMultiUser(String multiUser) {
		this.multiUser = multiUser;
	}
	@Column(name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	@Column(name="czrq")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	@Column(name="del")
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
}

+ 317 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java

@ -0,0 +1,317 @@
package com.yihu.jw.entity.care.device;
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 java.util.Date;
/**
 * Created by ysj on 2018/01/10.
 * 设备表
 */
@Entity
@Table(name = "wlyy_devices")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_devices")
public class DeviceDetail extends IdEntity {
    private String deviceName;//设备名称
    private String deviceModel;//型号
    private String deviceCode;//设备唯一标识
    private String manufacturer;//厂家名称
    private String applyDate;//申请日期
    private String orgName;//(居民)机构名称
    private String linkman;//联系人(居民)
    private String tel;//联系人(居民)电话
    private String serverIp;//服务IP地址
    private String manufacturerCode;//厂商代码threeNod:三诺 urion:优瑞恩 bioland:爱奥乐 comvee:康为
    private String address;//厂家地址
    private String representative;//法人代表
    private String applicantName;//申请注册人(发放人/医生)
    private String applicantIdentity;//申请人(发放人/医生)身份证号
    private String applicantTel;//申请人(发放人/医生)手机
    private String applicantMail;//申请人(发放人/医生)邮箱
    //1.4.8版本新增字段
    private String sim;//SIM卡
    private String manufacturerId;//厂商表的业务关联code
    private Integer isGrant;//是否发放(0否1是)
    private String grantAdminTeam;//发放的患者所在团队
    private String grantOrgCode;//发放所在机构
    private Integer isBinding;//是否绑定(0否 1 绑定单端口 2 绑定双端口)
    private String bindingCount;//绑定次数({"1":"0", "2":"0"})
    private Date grantTime;//发放时间
    //1.5.0版本新增字段
    private String grantDoctor;//发放医生code
    private String grantDoctorName;//发放医生姓名
    /** default constructor */
    public DeviceDetail() {
    }
    /** full constructor */
    public DeviceDetail(String deviceName, String deviceModel, String deviceCode, String manufacturer, String applyDate
            , String orgName, String linkman, String tel, String serverIp, String manufacturerCode, String address
            , String representative, String applicantName, String applicantIdentity, String applicantTel, String applicantMail) {
        this.deviceName = deviceName;
        this.deviceModel = deviceModel;
        this.deviceCode = deviceCode;
        this.manufacturer = manufacturer;
        this.applyDate = applyDate;
        this.orgName = orgName;
        this.linkman = linkman;
        this.tel = tel;
        this.serverIp = serverIp;
        this.manufacturerCode = manufacturerCode;
        this.address = address;
        this.representative = representative;
        this.applicantName = applicantName;
        this.applicantIdentity = applicantIdentity;
        this.applicantTel = applicantTel;
        this.applicantMail = applicantMail;
    }
    @Column(name = "device_name")
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    @Column(name = "device_model")
    public String getDeviceModel() {
        return deviceModel;
    }
    public void setDeviceModel(String deviceModel) {
        this.deviceModel = deviceModel;
    }
    @Column(name = "device_code")
    public String getDeviceCode() {
        return deviceCode;
    }
    public void setDeviceCode(String deviceCode) {
        this.deviceCode = deviceCode;
    }
    @Column(name = "manufacturer")
    public String getManufacturer() {
        return manufacturer;
    }
    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }
    @Column(name = "apply_date")
    public String getApplyDate() {
        return applyDate;
    }
    public void setApplyDate(String applyDate) {
        this.applyDate = applyDate;
    }
    @Column(name = "org_name")
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "linkman")
    public String getLinkman() {
        return linkman;
    }
    public void setLinkman(String linkman) {
        this.linkman = linkman;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "tel")
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    @Column(name = "server_ip")
    public String getServerIp() {
        return serverIp;
    }
    public void setServerIp(String serverIp) {
        this.serverIp = serverIp;
    }
    @Column(name = "manufacturerCode")
    public String getManufacturerCode() {
        return manufacturerCode;
    }
    public void setManufacturerCode(String manufacturerCode) {
        this.manufacturerCode = manufacturerCode;
    }
    @Column(name = "address")
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "representative")
    public String getRepresentative() {
        return representative;
    }
    public void setRepresentative(String representative) {
        this.representative = representative;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "applicant_name")
    public String getApplicantName() {
        return applicantName;
    }
    public void setApplicantName(String applicantName) {
        this.applicantName = applicantName;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "applicant_identity")
    public String getApplicantIdentity() {
        return applicantIdentity;
    }
    public void setApplicantIdentity(String applicantIdentity) {
        this.applicantIdentity = applicantIdentity;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "applicant_tel")
    public String getApplicantTel() {
        return applicantTel;
    }
    public void setApplicantTel(String applicantTel) {
        this.applicantTel = applicantTel;
    }
    @Column(name = "applicant_mail")
    public String getApplicantMail() {
        return applicantMail;
    }
    public void setApplicantMail(String applicantMail) {
        this.applicantMail = applicantMail;
    }
    @Column(name = "manufacturer_id")
    public String getManufacturerId() {
        return manufacturerId;
    }
    public void setManufacturerId(String manufacturerId) {
        this.manufacturerId = manufacturerId;
    }
    @Column(name = "sim")
    public String getSim() {
        return sim;
    }
    public void setSim(String sim) {
        this.sim = sim;
    }
    @Column(name = "is_grant")
    public Integer getIsGrant() {
        return isGrant;
    }
    public void setIsGrant(Integer grant) {
        isGrant = grant;
    }
    @Column(name = "grant_admin_team")
    public String getGrantAdminTeam() {
        return grantAdminTeam;
    }
    public void setGrantAdminTeam(String grantAdminTeam) {
        this.grantAdminTeam = grantAdminTeam;
    }
    @Column(name = "grant_org_code")
    public String getGrantOrgCode() {
        return grantOrgCode;
    }
    public void setGrantOrgCode(String grantOrgCode) {
        this.grantOrgCode = grantOrgCode;
    }
    @Column(name = "is_binding")
    public Integer getIsBinding() {
        return isBinding;
    }
    public void setIsBinding(Integer isBinding) {
        this.isBinding = isBinding;
    }
    @Column(name = "binding_count")
    public String getBindingCount() {
        return bindingCount;
    }
    public void setBindingCount(String bindingCount) {
        this.bindingCount = bindingCount;
    }
    @Column(name = "grant_time")
    public Date getGrantTime() {
        return grantTime;
    }
    public void setGrantTime(Date grantTime) {
        this.grantTime = grantTime;
    }
    @Column(name = "grant_doctor")
    public String getGrantDoctor() {
        return grantDoctor;
    }
    public void setGrantDoctor(String grantDoctor) {
        this.grantDoctor = grantDoctor;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "grant_doctor_name")
    public String getGrantDoctorName() {
        return grantDoctorName;
    }
    public void setGrantDoctorName(String grantDoctorName) {
        this.grantDoctorName = grantDoctorName;
    }
}

+ 241 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientHealthIndex.java

@ -0,0 +1,241 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.*;
import java.util.Date;
/**
 * 健康指标
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_health_index")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_patient_health_index")
public class DevicePatientHealthIndex extends IdEntity {
	// 患者标志
	private String user;
	// 干预标志
	private String intervene;
	// 血糖/收缩压/体重/腰围/早餐前空腹
	private String value1;
	// 舒张压/早餐后空腹/身高
	private String value2;
	// 午餐空腹/BMI
	private String value3;
	// 午餐后/偏胖-1/正常0/偏瘦1
	private String value4;
	// 晚餐空腹
	private String value5;
	// 晚餐后
	private String value6;
	// 睡前
	private String value7;
	// 健康指标类型(1血糖,2血压,3体重/身高/BMI,4腰围)
	private Integer type;
	// 记录时间
	private Date recordDate;
	// 排序日期
	private Date sortDate;
	// 添加时间
	private Date czrq;
	// 是否作废,1正常,0作废
	private String del;
	//身份证号码
	private String idcard;
	//设备编号
	private String deviceSn;
	private Integer status;//状态:0为标准,1为异常
	private String name;//居民姓名
	private String hospital;//医院
	private String hospitalName;//医院名称
	@Transient
	private Integer flag;//标识智能设备或者健康小屋
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getIntervene() {
		return intervene;
	}
	public void setIntervene(String intervene) {
		this.intervene = intervene;
	}
	public String getValue1() {
		return value1;
	}
	public void setValue1(String value1) {
		this.value1 = value1;
	}
	public String getValue2() {
		return value2;
	}
	public void setValue2(String value2) {
		this.value2 = value2;
	}
	public String getValue3() {
		return value3;
	}
	public void setValue3(String value3) {
		this.value3 = value3;
	}
	public String getValue4() {
		return value4;
	}
	public void setValue4(String value4) {
		this.value4 = value4;
	}
	public String getValue5() {
		return value5;
	}
	public void setValue5(String value5) {
		this.value5 = value5;
	}
	public String getValue6() {
		return value6;
	}
	public void setValue6(String value6) {
		this.value6 = value6;
	}
	public String getValue7() {
		return value7;
	}
	public void setValue7(String value7) {
		this.value7 = value7;
	}
	@Column(name = "record_date")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getRecordDate() {
		return recordDate;
	}
	public void setRecordDate(Date recordDate) {
		this.recordDate = recordDate;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	@Column(name = "sort_date")
	public Date getSortDate() {
		return sortDate;
	}
	public void setSortDate(Date sortDate) {
		this.sortDate = sortDate;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	@Column(name = "Idcard")
//	@Convert(converter = StringFStringEncryptConverter.class)
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	@Column(name = "device_sn")
	public String getDeviceSn() {
		return deviceSn;
	}
	public void setDeviceSn(String deviceSn) {
		this.deviceSn = deviceSn;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	@Transient
	public Integer getFlag() {
		return flag;
	}
	public void setFlag(Integer flag) {
		this.flag = flag;
	}
//	@Convert(converter = StringFStringEncryptConverter.class)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getHospital() {
		return hospital;
	}
	public void setHospital(String hospital) {
		this.hospital = hospital;
	}
	@Column(name = "hospital_name")
	public String getHospitalName() {
		return hospitalName;
	}
	public void setHospitalName(String hospitalName) {
		this.hospitalName = hospitalName;
	}
}

+ 297 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/PatientDevice.java

@ -0,0 +1,297 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "wlyy_patient_device")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_patient_device")
public class PatientDevice extends IdEntity {
    // 设备ID
    private Long deviceId;
    // 设备标识
    private String deviceSn;
    //sim卡号
    private String sim;
    // 设备名称
    private String deviceName;
    // 用户code
    private String user;
    // 设备类型标识 1血糖仪,2.血压计,3药盒,4智能手表
    private String categoryCode;
    // 用户类型标准 -1代表单用户
    private String userType;
    // 用户身份证
    private String userIdcard;
    // 操作医生代码
    private String doctor;
    //操作医生姓名
    private String doctorName;
    //代绑人代码(家人)
    private String agent;
    //代绑人姓名
    private String agentName;
    // 操作时间
    private Date czrq;
    //解绑人
    private String delUser;
    //1-解绑,0-绑定
    private Integer del;
    //设备活动类型
    private String deviceActivityType;
    //上传的协议图片地址
    private String agreementPhoto;
    //居民签约所在社区
    private String hospital;
    //居民签约所在社区名字
    private String hospitalName;
    //登记医生名字
    private String checkDoctorName;
    
    //0未申请 1审核中 2被拒绝
    private Integer applyStatus;
    
    //申请原因
    private String applyReason;
    //医生拒绝原因
    private String refuseReason;
  //========================非表字段======================
    //患者居住地址
    private String address;
    @Column(name = "device_id")
    public Long getDeviceId() {
        return deviceId;
    }
    public void setDeviceId(Long deviceId) {
        this.deviceId = deviceId;
    }
    @Column(name = "device_sn")
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    @Column(name = "sim")
    public String getSim() {
        return sim;
    }
    public void setSim(String sim) {
        this.sim = sim;
    }
    @Column(name = "device_name")
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    @Column(name = "user")
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    @Column(name = "category_code")
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    @Column(name = "user_type")
    public String getUserType() {
        return userType;
    }
    public void setUserType(String userType) {
        this.userType = userType;
    }
    @Column(name = "user_idcard")
    public String getUserIdcard() {
        return userIdcard;
    }
    public void setUserIdcard(String userIdcard) {
        this.userIdcard = userIdcard;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "czrq")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "agent")
    public String getAgent() {
        return agent;
    }
    public void setAgent(String agent) {
        this.agent = agent;
    }
    @Column(name = "agent_name")
    public String getAgentName() {
        return agentName;
    }
    public void setAgentName(String agentName) {
        this.agentName = agentName;
    }
    @Column(name = "del_user")
    public String getDelUser() {
        return delUser;
    }
    public void setDelUser(String delUser) {
        this.delUser = delUser;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    @Column(name = "device_activity_type")
    public String getDeviceActivityType() {
        return deviceActivityType;
    }
    public void setDeviceActivityType(String deviceActivityType) {
        this.deviceActivityType = deviceActivityType;
    }
    @Column(name = "agreement_photo")
    public String getAgreementPhoto() {
        return agreementPhoto;
    }
    public void setAgreementPhoto(String agreementPhoto) {
        this.agreementPhoto = agreementPhoto;
    }
    @Column(name = "hospital")
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Column(name = "hospital_name")
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    @Column(name = "check_doctor_name")
    public String getCheckDoctorName() {
        return checkDoctorName;
    }
    public void setCheckDoctorName(String checkDoctorName) {
        this.checkDoctorName = checkDoctorName;
    }
    @Transient
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public PatientDevice(String address, Date czrq, String userIdcard, String deviceSn, Long deviceId) {
        this.address = address;
        this.czrq = czrq;
        this.userIdcard = userIdcard;
        this.deviceSn = deviceSn;
        this.deviceId = deviceId;
    }
    public PatientDevice() {
    }
    
    public Integer getApplyStatus() {
        return applyStatus;
    }
    
    public void setApplyStatus(Integer applyStatus) {
        this.applyStatus = applyStatus;
    }
    
    public String getApplyReason() {
        return applyReason;
    }
    
    public void setApplyReason(String applyReason) {
        this.applyReason = applyReason;
    }
    public String getRefuseReason() {
        return refuseReason;
    }
    public void setRefuseReason(String refuseReason) {
        this.refuseReason = refuseReason;
    }
}

+ 81 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/label/WlyyPatientLabelDO.java

@ -0,0 +1,81 @@
package com.yihu.jw.entity.care.label;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by ysj on 2021/4/7.
 */
@Entity
@Table(name = "wlyy_patient_label")
public class WlyyPatientLabelDO extends UuidIdentityEntity {
    // 标签code
    private String labelCode;
    // 标签名称
    private String labelName;
    // 标签类型 1.服务类型 2居民标签
    private String labelType;
    // 是否系统标签
    private Integer isSystem;
    // 排序
    private Integer sort;
    // 操作日期
    private Date czrq;
    private String patient;
    public String getLabelCode() {
        return labelCode;
    }
    public void setLabelCode(String labelCode) {
        this.labelCode = labelCode;
    }
    public String getLabelName() {
        return labelName;
    }
    public void setLabelName(String labelName) {
        this.labelName = labelName;
    }
    public String getLabelType() {
        return labelType;
    }
    public void setLabelType(String labelType) {
        this.labelType = labelType;
    }
    public Integer getIsSystem() {
        return isSystem;
    }
    public void setIsSystem(Integer isSystem) {
        this.isSystem = isSystem;
    }
    public Integer getSort() {
        return sort;
    }
    public void setSort(Integer sort) {
        this.sort = sort;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
}

+ 10 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/lifeCare/LifeCareOrderDO.java

@ -254,6 +254,7 @@ public class LifeCareOrderDO extends UuidIdentityEntityWithOperator {
     * 服务机构
     */
    private String hospital;
    private String hospitalName;
    private Integer type;//发起工单类型(1本人发起 2家人待预约 3医生代预约)
    private String relationCode;//业务关联
@ -513,6 +514,15 @@ public class LifeCareOrderDO extends UuidIdentityEntityWithOperator {
        this.hospital = hospital;
    }
    @Column(name = "hospital_name")
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    @Transient
    public List<LifeCareFeeDetailDO> getFeeDetailList() {
        return feeDetailList;

+ 60 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/role/DoctorRole.java

@ -0,0 +1,60 @@
package com.yihu.jw.entity.care.role;
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 java.util.Date;
/**
 * 医生角色
 */
@Entity
@Table(name = "wlyy_role")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_role")
public class DoctorRole extends IdEntity {
    private String code;        // 角色编码
    private String name;        // 角色名称
    private String czy;       // 操作员
    private Date czrq;       // 操作日期
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "czy")
    public String getCzy() {
        return czy;
    }
    public void setCzy(String czy) {
        this.czy = czy;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "czrq")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 42 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/role/DoctorRoleRealm.java

@ -0,0 +1,42 @@
package com.yihu.jw.entity.care.role;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
 * 医生角色权限区域
 **/
@Entity
@Table(name = "wlyy_role_area")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_role_area")
public class DoctorRoleRealm extends IdEntity {
    // 角色编码
    private String roleCode;
    // 区域编码
    private String areaCode;
    @Column(name = "role_code")
    public String getRoleCode() {
        return roleCode;
    }
    public void setRoleCode(String roleCode) {
        this.roleCode = roleCode;
    }
    @Column(name = "area_code")
    public String getAreaCode() {
        return areaCode;
    }
    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }
}

+ 61 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/role/WlyyUserRole.java

@ -0,0 +1,61 @@
package com.yihu.jw.entity.care.role;
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 java.util.Date;
/**
 * 医生角色
 */
@Entity
@Table(name = "wlyy_user_role")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_user_role")
public class WlyyUserRole extends IdEntity {
    private String user;    // 用户编码
    private String role;    // 角色编码
    private String czy;     // 操作员
    private Date czrq;      // 操作日期
    @Column(name = "user")
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    @Column(name = "role")
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }
    public String getCzy() {
        return czy;
    }
    @Column(name = "czy")
    public void setCzy(String czy) {
        this.czy = czy;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "czrq")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
}

+ 5 - 5
common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringConclusionDO.java

@ -13,7 +13,7 @@ import javax.persistence.Table;
@Table(name = "base_security_monitoring_conclusion")
public class SecurityMonitoringConclusionDO extends UuidIdentityEntityWithOperator {
    private String orerId;//工单id
    private String orderId;//工单id
    private String patient;//工单服务的居民
    private String patientName;//居民姓名
    private String doctor;//医生
@ -21,12 +21,12 @@ public class SecurityMonitoringConclusionDO extends UuidIdentityEntityWithOperat
    private Integer status;//处置状态 1已确认安全 2已转送医疗机构 3已处置完成
    private String conclusion;//处置小结
    public String getOrerId() {
        return orerId;
    public String getOrderId() {
        return orderId;
    }
    public void setOrerId(String orerId) {
        this.orerId = orerId;
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    public String getPatient() {

+ 78 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringDoctorStatusDo.java

@ -0,0 +1,78 @@
package com.yihu.jw.entity.care.securitymonitoring;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 医生安防服务工单状态情况
*
* @author Administrator on  2019年03月19日
*
*/
@Entity
@Table(name = "base_semoni_doctor_status")
public class SecurityMonitoringDoctorStatusDo extends UuidIdentityEntityWithOperator {
    /**
     * 医生派单状态
     */
    public enum Status {
        waitForSend(1, "待派单"),
        waitForAccept(2, "待接单"),
        waitForServe(3, "待服务"),
        serving(4, "服务中"),
        stopped(5, "停止接单");
        private Integer type;
        private String desc;
        Status(Integer type, String desc) {
            this.type = type;
            this.desc = desc;
        }
        public Integer getType() {
            return type;
        }
        public void setType(Integer type) {
            this.type = type;
        }
    }
    /**
     * wlyy_doctor中医生code
     */
    private String doctor;
    /**
     * 医生状态:1-待派单,2-待接单,3-待服务,4-服务中,5-停止接单
     */
    private Integer status;
	@Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
	@Column(name = "status")
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 86 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderCancelLog.java

@ -0,0 +1,86 @@
package com.yihu.jw.entity.care.securitymonitoring;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import org.springframework.expression.EvaluationContext;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Bing on 2021/4/7.
 */
@Entity
@Table(name="base_security_monitoring_order_cancel_log")
public class SecurityMonitoringOrderCancelLog extends UuidIdentityEntity {
    /**
     * 工单id
     */
    private String orderId;
    /**
     * 居民code
     */
    private String patient;
    /**
     * 取消类型:1-调度员取消,2-居民取消
     */
    private Integer cancelType;
    /**
     * 取消理由
     */
    private String cancelReason;
    /**
     * 取消时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date time;
    @Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "cancel_type")
    public Integer getCancelType() {
        return cancelType;
    }
    public void setCancelType(Integer cancelType) {
        this.cancelType = cancelType;
    }
    @Column(name = "cancel_reason")
    public String getCancelReason() {
        return cancelReason;
    }
    public void setCancelReason(String cancelReason) {
        this.cancelReason = cancelReason;
    }
    @Column(name = "time")
    public Date getTime() {
        return time;
    }
    public void setTime(Date time) {
        this.time = time;
    }
}

+ 37 - 21
common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderDO.java

@ -23,12 +23,12 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
        cancel(-1, "已取消"),
        waitForSend(1, "待处置"),
        waitForAccept(2, "前往居民定位"),
        waitForArrive(2, "前往居民定位"),
        signed(3, "已签到"),
        registerSummary(4, "已登记小结,"),
        waitForAdded(5, "待补录"),
        waitForCommnet(5, "待评价"),
        complete(6,"已完成");
        waitForCommnet(6, "待评价"),
        complete(7,"已完成");
        private Integer type;
        private String desc;
@ -274,7 +274,7 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
    /**
     * 服务小结
     */
    private SecurityMonitoringOrderDO monitoringOrder;
    private SecurityMonitoringConclusionDO monitoringConclusion;
    /**
     * 服务医生响应时间(第一条咨询或者接单时间)
@ -314,15 +314,16 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
    private String hospital;
    private Integer conclusionStatus;//服务小结登记状态:1待补录;2-已补录
    private Integer type;//发起工单类型(1本人发起 2家人待预约 3医生代预约)
    private String authorizeImage;//电子健康卡授权图片
    private String relationCode;//业务关联
    private String serviceStatus;//服务类型 1-预约项目 2-即时项目
    private String orderInfo;//工单详情 0-未推送 1-未确认 2-已确认
    private String doctorConfirmFinishImg;
    /**
     * 快捷类型,1是快捷类型,其他值不是
     * 医生确认医生结束服务时间
     */
    private String shortcutType;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date doctorConfirmFinishTime;
@ -562,12 +563,12 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
    }
    @Transient
    public SecurityMonitoringOrderDO getMonitoringOrder() {
        return monitoringOrder;
    public SecurityMonitoringConclusionDO getMonitoringConclusion() {
        return monitoringConclusion;
    }
    public void setMonitoringOrder(SecurityMonitoringOrderDO monitoringOrder) {
        this.monitoringOrder = monitoringOrder;
    public void setMonitoringConclusion(SecurityMonitoringConclusionDO monitoringConclusion) {
        this.monitoringConclusion = monitoringConclusion;
    }
    @Column(name = "service_response_time")
@ -632,6 +633,14 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
        this.type = type;
    }
    public String getAuthorizeImage() {
        return authorizeImage;
    }
    public void setAuthorizeImage(String authorizeImage) {
        this.authorizeImage = authorizeImage;
    }
    @Column(name = "relation_code")
    public String getRelationCode() {
        return relationCode;
@ -659,15 +668,6 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
        this.orderInfo = orderInfo;
    }
    @Column(name = "shortcut_type")
    public String getShortcutType() {
        return shortcutType;
    }
    public void setShortcutType(String shortcutType) {
        this.shortcutType = shortcutType;
    }
    public Integer getConclusionStatus() {
        return conclusionStatus;
    }
@ -675,4 +675,20 @@ public class SecurityMonitoringOrderDO extends UuidIdentityEntityWithOperator {
    public void setConclusionStatus(Integer conclusionStatus) {
        this.conclusionStatus = conclusionStatus;
    }
    public String getDoctorConfirmFinishImg() {
        return doctorConfirmFinishImg;
    }
    public void setDoctorConfirmFinishImg(String doctorConfirmFinishImg) {
        this.doctorConfirmFinishImg = doctorConfirmFinishImg;
    }
    public Date getDoctorConfirmFinishTime() {
        return doctorConfirmFinishTime;
    }
    public void setDoctorConfirmFinishTime(Date doctorConfirmFinishTime) {
        this.doctorConfirmFinishTime = doctorConfirmFinishTime;
    }
}

+ 81 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/securitymonitoring/SecurityMonitoringOrderPatientConfirmLog.java

@ -0,0 +1,81 @@
package com.yihu.jw.entity.care.securitymonitoring;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Bing on 2021/4/7.
 */
@Entity
@Table(name="base_semoni_patient_confirm_log")
public class SecurityMonitoringOrderPatientConfirmLog extends UuidIdentityEntityWithOperator {
    /**
     * 工单id
     */
    private String orderId;
    /**
     * 居民
     */
    private String patient;
    /**
     * 居民姓名
     */
    private String patientName;
    /**
     * 确认操作类型:1-确认基础信息无误或变更,2-确认上门医生变更上门信息,3-同意工单转接,4-同意取消工单
     */
    private Integer type;
    /**
     * 操作描述
     */
    private String description;
    @Column(name = "order_id")
    public String getOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "patient_name")
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    @Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

+ 621 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentBaseInfoDo.java

@ -0,0 +1,621 @@
package com.yihu.jw.entity.care.sign;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
 * 能力评估-基本信息表
 * Created by Bing on 2021/4/1.
 */
@Entity
@Table(name="base_capacity_assessment_baseinfo")
public class CapacityAssessmentBaseInfoDo extends UuidIdentityEntityWithCreateTime {
    private String  assessmentYear;    //评估年份
    private Integer status; //状态 0失效 1有效
    private String  patient;    //
    private String  name;   //
    private Integer sex;    //
    private String  age;    //
    private String  nation; //名族
    private String  nationName; //名族
    private String  religion;   //宗教信仰 0无;1有
    private String  idcard; //
    private String  domicile;   //户籍 0本地户口;1外地户口
    private String  marriage;   //婚姻状况 10.未婚 20.已婚 30.丧偶 40.离婚 90.未说明的婚姻状况
    private String  marriageRemark;    //婚姻状况 备注
    private String  education;  //文化程度 0文盲及半文盲;1小学;2初中;3高中/技校/中专;4大学专科及以上;5不详
    private String  incomeType;    //主要经济来源 0退休金/养老金;1子女补贴;2亲友资助;3其他补贴
    private String  pensionFlag;   //是否有养老金收入 0无 1有
    private String  pensionCount;  //养老金收入 元/月
    private String  familyType;    //是否为经济困难家庭 0否 1特困 2低保 3低保边缘
    private String  disabilityCertificate; //是否为持证残疾人 0否 1是
    private String  medicalInsuranceType; //医保类别 1职工基本医疗保险 2城乡居民基本医疗保险 3其他医疗保障 4无任何保障
    private String  medicalInsurance;  //是否购买了商业健康(医疗)保险 0否 1是
    private String  livingType;    //现住场所:1自有产权房、私房等;2各类租赁房等;3养老院或类似机构;4护理院或类似机构;5医院或类似机构
    private String  livingTogether;    //同居者类型 0独居;1与配偶/伴侣居住;2与子女居住;3与孙辈居住;4与父母居住;5与兄弟姐妹居住;6与其他亲友居住;7其他
    private String  livingTogetherRemark; //同居者备注
    private String  dementiaFlag;  //痴呆症 0无 1有
    private String  mentalIllness; //精神疾病(可多选)0无;1精神分裂症;2双相情感障碍;3偏执性精神障碍;4分裂情感性障碍;5癫痫所致精神障碍;6精神发育迟滞伴发精神障碍
    private String  diseaseType;   //患病类型可多选;0无 1肿瘤(晚期)2严重心律失常3压疮4慢性心力衰竭(心功能III-IV级)5慢性肾功能衰竭(尿毒症期)6多器官功能衰竭7蛋白质能量营养不足(重度)8慢性阻塞性肺疾病(肺心病心功能III-IV级)9呼吸衰竭10脑血管意外合并吞咽障碍11其他
    private String  diseaseRemark; //其他疾病
    private String  fallLately;    //近30天跌倒 0无;1一次;2两次;3三次及以上
    private String  lostLately;    //近30天走失 0无;1一次;2两次;3三次及以上
    private String  chokingLately; //近30天噎食 0无;1一次;2两次;3三次及以上
    private String  suicideLately; //近30天自杀 0无;1一次;2两次;3三次及以上
    private String  remarkLately;  //近30天意外 其他
    private String  medicalServices;   //近7天是否接受过医疗护理服务 0无1有
    private String  domicileCounty;    //户籍  区(县、市)
    private String  domicileStreet;   //户籍  街(镇)
    private String  domicileOrg;   //户籍 社(村)
    private String  domicileCountyName;    //户籍名称  区(县、市)
    private String  domicileStreetName;   //户籍名称  街(镇)
    private String  domicileOrgName;   //户籍名称 社(村)
    private String  domicileBuilding;  //户籍 xx幢
    private String  domicileRoom;  //户籍 xx室
    private String  liveCounty;    //居住地  区(县、市)
    private String  liveStreet;   //居住地  街(镇)
    private String  liveOrg;   //居住地 社(村)
    private String  liveCountyName;    //居住地名称  区(县、市)
    private String  liveStreetName;   //居住地名称  街(镇)
    private String  liveOrgName;   //居住地名称 社(村)
    private String  liveBuilding;  //居住地 xx幢
    private String  liveRoom;  //居住地 xx室
    private String  postcode;   //邮编
    private String  residencePhone;    //住宅电话
    private String  patientPhone;  //手机
    private String  proxyName; //代理人姓名
    private String  applicantRelation; //与申请人关系
    private String  proxyAddress;  //代理人地址
    private String  proxyTelephone;    //代理人电话
    private String  proxyPhone;    //代理人手机
    private String  applicantSign; //申请人(代理人) 签字结果图片url
    private String  applicantDate;  //申请日期
    private String  serviceType;   //养老服务形式 0居家养老 1机构养老
    private String  acceptableServicesLife1;  //直接生活照顾  1穿衣;2修饰;3口腔清洁;4皮肤清洁;5喂食服务;6排泄照料
    private String  acceptableServicesLife2;  //间接生活照顾  1居室清洁;2更换洗涤;3上门维修;4定期探访;5膳食服务;6文化教育;7娱乐休闲;8室外休闲(户外);9紧急呼援;10法律援助;11转介服务;12咨询服务
    private String  acceptableServicesMental; //精神心理照顾 1危机干预;2沟通;3精神支持;4心理疏导;5心理咨询
    private String  acceptableServicesRehabilitation; //康复护理照顾 1定期翻身;2压疮预;3防活动肢体;4肢体保健;5康复活动;6预防保健;7健康咨询;8健康管理;9健康教育;10临终关怀
    private String  acceptableServicesOther;  //其他
    private String  birthday;  //出生日期
    public String getAssessmentYear() {
        return assessmentYear;
    }
    public void setAssessmentYear(String assessmentYear) {
        this.assessmentYear = assessmentYear;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getNation() {
        return nation;
    }
    public void setNation(String nation) {
        this.nation = nation;
    }
    public String getNationName() {
        return nationName;
    }
    public void setNationName(String nationName) {
        this.nationName = nationName;
    }
    public String getReligion() {
        return religion;
    }
    public void setReligion(String religion) {
        this.religion = religion;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getDomicile() {
        return domicile;
    }
    public void setDomicile(String domicile) {
        this.domicile = domicile;
    }
    public String getMarriage() {
        return marriage;
    }
    public void setMarriage(String marriage) {
        this.marriage = marriage;
    }
    public String getMarriageRemark() {
        return marriageRemark;
    }
    public void setMarriageRemark(String marriageRemark) {
        this.marriageRemark = marriageRemark;
    }
    public String getEducation() {
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public String getIncomeType() {
        return incomeType;
    }
    public void setIncomeType(String incomeType) {
        this.incomeType = incomeType;
    }
    public String getPensionFlag() {
        return pensionFlag;
    }
    public void setPensionFlag(String pensionFlag) {
        this.pensionFlag = pensionFlag;
    }
    public String getPensionCount() {
        return pensionCount;
    }
    public void setPensionCount(String pensionCount) {
        this.pensionCount = pensionCount;
    }
    public String getFamilyType() {
        return familyType;
    }
    public void setFamilyType(String familyType) {
        this.familyType = familyType;
    }
    public String getDisabilityCertificate() {
        return disabilityCertificate;
    }
    public void setDisabilityCertificate(String disabilityCertificate) {
        this.disabilityCertificate = disabilityCertificate;
    }
    public String getMedicalInsuranceType() {
        return medicalInsuranceType;
    }
    public void setMedicalInsuranceType(String medicalInsuranceType) {
        this.medicalInsuranceType = medicalInsuranceType;
    }
    public String getMedicalInsurance() {
        return medicalInsurance;
    }
    public void setMedicalInsurance(String medicalInsurance) {
        this.medicalInsurance = medicalInsurance;
    }
    public String getLivingType() {
        return livingType;
    }
    public void setLivingType(String livingType) {
        this.livingType = livingType;
    }
    public String getLivingTogether() {
        return livingTogether;
    }
    public void setLivingTogether(String livingTogether) {
        this.livingTogether = livingTogether;
    }
    public String getLivingTogetherRemark() {
        return livingTogetherRemark;
    }
    public void setLivingTogetherRemark(String livingTogetherRemark) {
        this.livingTogetherRemark = livingTogetherRemark;
    }
    public String getDementiaFlag() {
        return dementiaFlag;
    }
    public void setDementiaFlag(String dementiaFlag) {
        this.dementiaFlag = dementiaFlag;
    }
    public String getMentalIllness() {
        return mentalIllness;
    }
    public void setMentalIllness(String mentalIllness) {
        this.mentalIllness = mentalIllness;
    }
    public String getDiseaseType() {
        return diseaseType;
    }
    public void setDiseaseType(String diseaseType) {
        this.diseaseType = diseaseType;
    }
    public String getDiseaseRemark() {
        return diseaseRemark;
    }
    public void setDiseaseRemark(String diseaseRemark) {
        this.diseaseRemark = diseaseRemark;
    }
    public String getFallLately() {
        return fallLately;
    }
    public void setFallLately(String fallLately) {
        this.fallLately = fallLately;
    }
    public String getLostLately() {
        return lostLately;
    }
    public void setLostLately(String lostLately) {
        this.lostLately = lostLately;
    }
    public String getChokingLately() {
        return chokingLately;
    }
    public void setChokingLately(String chokingLately) {
        this.chokingLately = chokingLately;
    }
    public String getSuicideLately() {
        return suicideLately;
    }
    public void setSuicideLately(String suicideLately) {
        this.suicideLately = suicideLately;
    }
    public String getRemarkLately() {
        return remarkLately;
    }
    public void setRemarkLately(String remarkLately) {
        this.remarkLately = remarkLately;
    }
    public String getMedicalServices() {
        return medicalServices;
    }
    public void setMedicalServices(String medicalServices) {
        this.medicalServices = medicalServices;
    }
    public String getDomicileCounty() {
        return domicileCounty;
    }
    public void setDomicileCounty(String domicileCounty) {
        this.domicileCounty = domicileCounty;
    }
    public String getDomicileStreet() {
        return domicileStreet;
    }
    public void setDomicileStreet(String domicileStreet) {
        this.domicileStreet = domicileStreet;
    }
    public String getDomicileOrg() {
        return domicileOrg;
    }
    public void setDomicileOrg(String domicileOrg) {
        this.domicileOrg = domicileOrg;
    }
    public String getDomicileCountyName() {
        return domicileCountyName;
    }
    public void setDomicileCountyName(String domicileCountyName) {
        this.domicileCountyName = domicileCountyName;
    }
    public String getDomicileStreetName() {
        return domicileStreetName;
    }
    public void setDomicileStreetName(String domicileStreetName) {
        this.domicileStreetName = domicileStreetName;
    }
    public String getDomicileOrgName() {
        return domicileOrgName;
    }
    public void setDomicileOrgName(String domicileOrgName) {
        this.domicileOrgName = domicileOrgName;
    }
    public String getDomicileBuilding() {
        return domicileBuilding;
    }
    public void setDomicileBuilding(String domicileBuilding) {
        this.domicileBuilding = domicileBuilding;
    }
    public String getDomicileRoom() {
        return domicileRoom;
    }
    public void setDomicileRoom(String domicileRoom) {
        this.domicileRoom = domicileRoom;
    }
    public String getLiveCounty() {
        return liveCounty;
    }
    public void setLiveCounty(String liveCounty) {
        this.liveCounty = liveCounty;
    }
    public String getLiveStreet() {
        return liveStreet;
    }
    public void setLiveStreet(String liveStreet) {
        this.liveStreet = liveStreet;
    }
    public String getLiveOrg() {
        return liveOrg;
    }
    public void setLiveOrg(String liveOrg) {
        this.liveOrg = liveOrg;
    }
    public String getLiveCountyName() {
        return liveCountyName;
    }
    public void setLiveCountyName(String liveCountyName) {
        this.liveCountyName = liveCountyName;
    }
    public String getLiveStreetName() {
        return liveStreetName;
    }
    public void setLiveStreetName(String liveStreetName) {
        this.liveStreetName = liveStreetName;
    }
    public String getLiveOrgName() {
        return liveOrgName;
    }
    public void setLiveOrgName(String liveOrgName) {
        this.liveOrgName = liveOrgName;
    }
    public String getLiveBuilding() {
        return liveBuilding;
    }
    public void setLiveBuilding(String liveBuilding) {
        this.liveBuilding = liveBuilding;
    }
    public String getLiveRoom() {
        return liveRoom;
    }
    public void setLiveRoom(String liveRoom) {
        this.liveRoom = liveRoom;
    }
    public String getPostcode() {
        return postcode;
    }
    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }
    public String getResidencePhone() {
        return residencePhone;
    }
    public void setResidencePhone(String residencePhone) {
        this.residencePhone = residencePhone;
    }
    public String getPatientPhone() {
        return patientPhone;
    }
    public void setPatientPhone(String patientPhone) {
        this.patientPhone = patientPhone;
    }
    public String getProxyName() {
        return proxyName;
    }
    public void setProxyName(String proxyName) {
        this.proxyName = proxyName;
    }
    public String getApplicantRelation() {
        return applicantRelation;
    }
    public void setApplicantRelation(String applicantRelation) {
        this.applicantRelation = applicantRelation;
    }
    public String getProxyAddress() {
        return proxyAddress;
    }
    public void setProxyAddress(String proxyAddress) {
        this.proxyAddress = proxyAddress;
    }
    public String getProxyTelephone() {
        return proxyTelephone;
    }
    public void setProxyTelephone(String proxyTelephone) {
        this.proxyTelephone = proxyTelephone;
    }
    public String getProxyPhone() {
        return proxyPhone;
    }
    public void setProxyPhone(String proxyPhone) {
        this.proxyPhone = proxyPhone;
    }
    public String getApplicantSign() {
        return applicantSign;
    }
    public void setApplicantSign(String applicantSign) {
        this.applicantSign = applicantSign;
    }
    public String getApplicantDate() {
        return applicantDate;
    }
    public void setApplicantDate(String applicantDate) {
        this.applicantDate = applicantDate;
    }
    public String getServiceType() {
        return serviceType;
    }
    public void setServiceType(String serviceType) {
        this.serviceType = serviceType;
    }
    public String getAcceptableServicesLife1() {
        return acceptableServicesLife1;
    }
    public void setAcceptableServicesLife1(String acceptableServicesLife1) {
        this.acceptableServicesLife1 = acceptableServicesLife1;
    }
    public String getAcceptableServicesLife2() {
        return acceptableServicesLife2;
    }
    public void setAcceptableServicesLife2(String acceptableServicesLife2) {
        this.acceptableServicesLife2 = acceptableServicesLife2;
    }
    public String getAcceptableServicesMental() {
        return acceptableServicesMental;
    }
    public void setAcceptableServicesMental(String acceptableServicesMental) {
        this.acceptableServicesMental = acceptableServicesMental;
    }
    public String getAcceptableServicesRehabilitation() {
        return acceptableServicesRehabilitation;
    }
    public void setAcceptableServicesRehabilitation(String acceptableServicesRehabilitation) {
        this.acceptableServicesRehabilitation = acceptableServicesRehabilitation;
    }
    public String getAcceptableServicesOther() {
        return acceptableServicesOther;
    }
    public void setAcceptableServicesOther(String acceptableServicesOther) {
        this.acceptableServicesOther = acceptableServicesOther;
    }
    @Transient
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
}

+ 96 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentCognitiveAbilityDo.java

@ -0,0 +1,96 @@
package com.yihu.jw.entity.care.sign;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 *能力评估-认知能力表
 * Created by Bing on 2021/4/1.
 */
@Entity
@Table(name="base_capacity_assessment_cognitive_ability")
public class CapacityAssessmentCognitiveAbilityDo extends UuidIdentityEntityWithCreateTime {
    private String  assessmentYear;    //评估年份
    private Integer status; //状态 0失效 1有效
    private String  patient;    //
    private String  question1;  //问题一得分 总分3分
    private String  question2;  //问题二得分 总分5分
    private String  question3;  //问题三得分 总分5分
    private String  question4;  //问题四得分 总分3分
    private String  totalScore;    //认知能力 上述得分和
    private String  abilityGrade;  //能力等级:0能力完好(16);1轻度受损(13-15);2中度受损(9-12);3重度受损(≤8)
    public String getAssessmentYear() {
        return assessmentYear;
    }
    public void setAssessmentYear(String assessmentYear) {
        this.assessmentYear = assessmentYear;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getQuestion1() {
        return question1;
    }
    public void setQuestion1(String question1) {
        this.question1 = question1;
    }
    public String getQuestion2() {
        return question2;
    }
    public void setQuestion2(String question2) {
        this.question2 = question2;
    }
    public String getQuestion3() {
        return question3;
    }
    public void setQuestion3(String question3) {
        this.question3 = question3;
    }
    public String getQuestion4() {
        return question4;
    }
    public void setQuestion4(String question4) {
        this.question4 = question4;
    }
    public String getTotalScore() {
        return totalScore;
    }
    public void setTotalScore(String totalScore) {
        this.totalScore = totalScore;
    }
    public String getAbilityGrade() {
        return abilityGrade;
    }
    public void setAbilityGrade(String abilityGrade) {
        this.abilityGrade = abilityGrade;
    }
}

+ 151 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentLivingAbilityDo.java

@ -0,0 +1,151 @@
package com.yihu.jw.entity.care.sign;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 能力评估-日常生活能力评估表
 * Created by Bing on 2021/4/1.
 */
@Entity
@Table(name="base_capacity_assessment_living_ability")
public class CapacityAssessmentLivingAbilityDo extends UuidIdentityEntityWithCreateTime {
    private String  assessmentYear; //评估年份
    private Integer status; //状态 0失效 1有效
    private String  patient;    //
    private String  eatingAbilityScore; //进食能力得分 10可独立进食;5需部分帮助;0需要极大帮助或完全依赖他人
    private String  showerAbilityScore; //洗澡能力得分 5可独立完成;0需要帮助
    private String  washingAbilityScore;    //洗漱能力得分 5可独立完成;0需要帮助
    private String  dressingAbilityScore;   //穿衣能力得分 10可独立完成;5需要部分帮助;0需要极大帮助或完全依赖他人
    private String  excretionAbilityScore;  //排便控制能力得分 10可自主控制;5偶尔失控(每周小于一次,或需要他人提示);0完全失控
    private String  urinationAbilityScore;  //排尿控制能力得分 10可自主控制;5偶尔失控(每周小于一次,或需要他人提示);0完全失控或留置导尿管
    private String  toiletAbilityScore; //如厕能力得分 10可独立完成;5需部分帮助;0需要极大帮助或完全依赖他人
    private String  transferBedAbilityScore;   //床椅转移能力得分 15可独立完成10需要部分帮忙5需要极大帮忙0完全依赖他人
    private String  walkingAbilityScore;    //平地行走能力得分 15可独立行走45m;10需要部分帮助;5需要极大帮助;0完全依赖他人
    private String  downStairsAbilityScore; //上下楼梯能力得分10可独立上下楼梯(连续10~15个台阶);5需要部分帮忙0需要极大帮助或完全依赖他人
    private String  totalScore; //日常生活能力总分 上述得分和 总分100
    private String  abilityGrade;   //能力等级:0能力完好(100);1轻度受损(65-95);2中度受损(45-60);3重度受损(≤40)
    public String getAssessmentYear() {
        return assessmentYear;
    }
    public void setAssessmentYear(String assessmentYear) {
        this.assessmentYear = assessmentYear;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getEatingAbilityScore() {
        return eatingAbilityScore;
    }
    public void setEatingAbilityScore(String eatingAbilityScore) {
        this.eatingAbilityScore = eatingAbilityScore;
    }
    public String getShowerAbilityScore() {
        return showerAbilityScore;
    }
    public void setShowerAbilityScore(String showerAbilityScore) {
        this.showerAbilityScore = showerAbilityScore;
    }
    public String getWashingAbilityScore() {
        return washingAbilityScore;
    }
    public void setWashingAbilityScore(String washingAbilityScore) {
        this.washingAbilityScore = washingAbilityScore;
    }
    public String getDressingAbilityScore() {
        return dressingAbilityScore;
    }
    public void setDressingAbilityScore(String dressingAbilityScore) {
        this.dressingAbilityScore = dressingAbilityScore;
    }
    public String getExcretionAbilityScore() {
        return excretionAbilityScore;
    }
    public void setExcretionAbilityScore(String excretionAbilityScore) {
        this.excretionAbilityScore = excretionAbilityScore;
    }
    public String getUrinationAbilityScore() {
        return urinationAbilityScore;
    }
    public void setUrinationAbilityScore(String urinationAbilityScore) {
        this.urinationAbilityScore = urinationAbilityScore;
    }
    public String getToiletAbilityScore() {
        return toiletAbilityScore;
    }
    public void setToiletAbilityScore(String toiletAbilityScore) {
        this.toiletAbilityScore = toiletAbilityScore;
    }
    public String getTransferBedAbilityScore() {
        return transferBedAbilityScore;
    }
    public void setTransferBedAbilityScore(String transferBedAbilityScore) {
        this.transferBedAbilityScore = transferBedAbilityScore;
    }
    public String getWalkingAbilityScore() {
        return walkingAbilityScore;
    }
    public void setWalkingAbilityScore(String walkingAbilityScore) {
        this.walkingAbilityScore = walkingAbilityScore;
    }
    public String getDownStairsAbilityScore() {
        return downStairsAbilityScore;
    }
    public void setDownStairsAbilityScore(String downStairsAbilityScore) {
        this.downStairsAbilityScore = downStairsAbilityScore;
    }
    public String getTotalScore() {
        return totalScore;
    }
    public void setTotalScore(String totalScore) {
        this.totalScore = totalScore;
    }
    public String getAbilityGrade() {
        return abilityGrade;
    }
    public void setAbilityGrade(String abilityGrade) {
        this.abilityGrade = abilityGrade;
    }
}

+ 72 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentRecordDO.java

@ -30,6 +30,7 @@ public class CapacityAssessmentRecordDO extends UuidIdentityEntityWithCreateTime
     * 性别,1男,2女
     */
    private Integer sex;
    private String sexName;
    /**
     * 手机号
@ -60,26 +61,31 @@ public class CapacityAssessmentRecordDO extends UuidIdentityEntityWithCreateTime
     * 能力完好(0级) 轻度受损(1级) 中度受损(2级) 重度受损(3级)
     */
    private Integer livingAbility;
    private String livingAbilityName;
    /**
     * 认知能力
     * 能力完好(0级) 轻度受损(1级) 中度受损(2级) 重度受损(3级)
     */
    private Integer cognitiveAbility;
    private String cognitiveAbilityName;
    /**
     *精神状态与社会交流能力
     * 能力完好(0级) 轻度受损(1级) 中度受损(2级) 重度受损(3级)
     */
    private Integer socialAbility;
    private String socialAbilityName;
    /**
     * 能力总体评价
     * 能力完好(0级) 轻度失能(1级) 中度失能(2级) 重度失能(3级)
     */
    private Integer comprehensiveAbility;
    private String comprehensiveAbilityName;
    /**
     * 等级结论
     * 能力完好(0级) 轻度失能(1级) 中度失能(2级) 重度失能(3级)
     */
    private Integer levelConclusion;
    private String levelConclusionName;
    private String doctor;
    private String doctorName;
    private String orgCode;
@ -88,6 +94,7 @@ public class CapacityAssessmentRecordDO extends UuidIdentityEntityWithCreateTime
     * 认可结果(0未认可,1已认可,2不认可)
     */
    private Integer status;
    private String statusName;
    /**
     * 签字结果图片url
     */
@ -100,6 +107,7 @@ public class CapacityAssessmentRecordDO extends UuidIdentityEntityWithCreateTime
     * 是否分配服务包(0未分配,1已分配)
     */
    private Integer servicePackageStatus;
    private String servicePackageStatusName;
    /**
     * 年纪
@ -310,4 +318,68 @@ public class CapacityAssessmentRecordDO extends UuidIdentityEntityWithCreateTime
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    @Transient
    public String getSexName() {
        return sexName;
    }
    public void setSexName(String sexName) {
        this.sexName = sexName;
    }
    @Transient
    public String getLivingAbilityName() {
        return livingAbilityName;
    }
    public void setLivingAbilityName(String livingAbilityName) {
        this.livingAbilityName = livingAbilityName;
    }
    @Transient
    public String getCognitiveAbilityName() {
        return cognitiveAbilityName;
    }
    public void setCognitiveAbilityName(String cognitiveAbilityName) {
        this.cognitiveAbilityName = cognitiveAbilityName;
    }
    @Transient
    public String getSocialAbilityName() {
        return socialAbilityName;
    }
    public void setSocialAbilityName(String socialAbilityName) {
        this.socialAbilityName = socialAbilityName;
    }
    @Transient
    public String getComprehensiveAbilityName() {
        return comprehensiveAbilityName;
    }
    public void setComprehensiveAbilityName(String comprehensiveAbilityName) {
        this.comprehensiveAbilityName = comprehensiveAbilityName;
    }
    @Transient
    public String getLevelConclusionName() {
        return levelConclusionName;
    }
    public void setLevelConclusionName(String levelConclusionName) {
        this.levelConclusionName = levelConclusionName;
    }
    @Transient
    public String getStatusName() {
        return statusName;
    }
    public void setStatusName(String statusName) {
        this.statusName = statusName;
    }
    @Transient
    public String getServicePackageStatusName() {
        return servicePackageStatusName;
    }
    public void setServicePackageStatusName(String servicePackageStatusName) {
        this.servicePackageStatusName = servicePackageStatusName;
    }
}

+ 124 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/sign/CapacityAssessmentSocialAbilityDo.java

@ -0,0 +1,124 @@
package com.yihu.jw.entity.care.sign;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 能力评估-精神状态与社会交流能力表
 * Created by Bing on 2021/4/1.
 */
@Entity
@Table(name = "base_capacity_assessment_social_ability")
public class CapacityAssessmentSocialAbilityDo extends UuidIdentityEntityWithCreateTime {
    private String assessmentYear;    //评估年份
    private Integer status; //状态 0失效 1有效
    private String  patient;    //
    private String  aggressScore;  //攻击行为得分 总分3分
    private String  depressedScore;    //抑郁状态得分 总分5分
    private String  consciousnessScore;    //意识水平得分 总分5分
    private String  communicateScore;  //沟通交流得分 总分3分
    private String  socialSkillsScore;    //社交能力得分
    private String  visionScore;   //视力功能得分
    private String  hearingScore;  //听力能力得分
    private String  totalScore;    // 精神状态与社会交流能力总分 上述得分和 总分22
    private String  abilityGrade;  //能力等级:0能力完好(22);1轻度受损(15-21);2中度受损(7-14);3重度受损(≤6)
    public String getAssessmentYear() {
        return assessmentYear;
    }
    public void setAssessmentYear(String assessmentYear) {
        this.assessmentYear = assessmentYear;
    }
    public Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getAggressScore() {
        return aggressScore;
    }
    public void setAggressScore(String aggressScore) {
        this.aggressScore = aggressScore;
    }
    public String getDepressedScore() {
        return depressedScore;
    }
    public void setDepressedScore(String depressedScore) {
        this.depressedScore = depressedScore;
    }
    public String getConsciousnessScore() {
        return consciousnessScore;
    }
    public void setConsciousnessScore(String consciousnessScore) {
        this.consciousnessScore = consciousnessScore;
    }
    public String getCommunicateScore() {
        return communicateScore;
    }
    public void setCommunicateScore(String communicateScore) {
        this.communicateScore = communicateScore;
    }
    public String getSocialSkillsScore() {
        return socialSkillsScore;
    }
    public void setSocialSkillsScore(String socialSkillsScore) {
        this.socialSkillsScore = socialSkillsScore;
    }
    public String getVisionScore() {
        return visionScore;
    }
    public void setVisionScore(String visionScore) {
        this.visionScore = visionScore;
    }
    public String getHearingScore() {
        return hearingScore;
    }
    public void setHearingScore(String hearingScore) {
        this.hearingScore = hearingScore;
    }
    public String getTotalScore() {
        return totalScore;
    }
    public void setTotalScore(String totalScore) {
        this.totalScore = totalScore;
    }
    public String getAbilityGrade() {
        return abilityGrade;
    }
    public void setAbilityGrade(String abilityGrade) {
        this.abilityGrade = abilityGrade;
    }
}

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java

@ -18,7 +18,7 @@ import java.util.Date;
public class SystemMessageDO extends UuidIdentityEntity {
    /**
     *消息类型 上门服务400开头,生活照料500开头
     *消息类型 上门服务400开头,生活照料500开头 ,安防监控600开头
     */
    private String type;
    /**

+ 76 - 7
svr/svr-cloud-care/pom.xml

@ -109,7 +109,12 @@
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <!-- SPRINGSIDE -->
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
            <version>4.2.3-GA</version>
        </dependency>
        <!-- 文件服务器 -->
        <dependency>
@ -261,19 +266,83 @@
        <finalName>svr-cloud-care</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <mainClass>com.yihu.SvrCloudCareApplication</mainClass>
                    <archive>
                        <!-- 生成的jar中,不要包含pom.xml和pom.properties这两个文件 -->
                        <addMavenDescriptor>false</addMavenDescriptor>
                        <manifest>
                            <!-- 是否要把第三方jar加入到类构建路径 -->
                            <addClasspath>true</addClasspath>
                            <!-- 外部依赖jar包的最终位置 -->
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.yihu.SvrCloudCareApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!--拷贝依赖到jar外面的lib目录-->
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-lib</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <!-- 依赖包输出目录,将来不打进jar包里 -->
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <excludeTransitive>false</excludeTransitive>
                            <stripVersion>false</stripVersion>
                            <includeScope>runtime</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!--指定配置文件,将resources打成外部resource-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <filteringDeploymentDescriptors>true</filteringDeploymentDescriptors>
                    <archive>
                        <!-- 指定配置文件目录,这样jar运行时会去找到同目录下的resources文件夹下查找 -->
                        <manifestEntries>
                            <Class-Path>resources/</Class-Path>
                        </manifestEntries>
                    </archive>
                    <!-- 打包时忽略的文件(也就是不打进jar包里的文件) -->
                    <excludes>
                        <exclude>**/*.yml</exclude>
                        <exclude>**/*.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!-- 拷贝资源文件 外面的resource目录-->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <!-- 资源文件输出目录 -->
                            <outputDirectory>${project.build.directory}/resources</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

+ 125 - 0
svr/svr-cloud-care/sql/sql

@ -0,0 +1,125 @@
CREATE TABLE base.base_capacity_assessment_baseinfo (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `sex` tinyint(2) DEFAULT NULL,
  `age` varchar(5) DEFAULT NULL,
  `nation` varchar(20) DEFAULT NULL COMMENT '名族',
  `nation_name` varchar(50) DEFAULT NULL COMMENT '名族名称',
  `religion` varchar(20) DEFAULT NULL COMMENT '宗教信仰 0无;1有',
  `idcard` varchar(20) DEFAULT NULL,
  `domicile` varchar(20) DEFAULT NULL COMMENT '户籍 0本地户口;1外地户口',
  `marriage` varchar(20) DEFAULT NULL COMMENT '婚姻状况 10.未婚 20.已婚 30.丧偶 40.离婚 90.未说明的婚姻状况',
  `marriage_remark` varchar(255) DEFAULT NULL COMMENT '婚姻状况 备注',
  `education` varchar(20) DEFAULT NULL COMMENT '文化程度 0文盲及半文盲;1小学;2初中;3高中/技校/中专;4大学专科及以上;5不详',
  `income_type` varchar(20) DEFAULT NULL COMMENT '主要经济来源 0退休金/养老金;1子女补贴;2亲友资助;3其他补贴',
  `pension_flag` varchar(20) DEFAULT NULL COMMENT '是否有养老金收入 0无 1有',
  `pension_count` varchar(20) DEFAULT NULL COMMENT '养老金收入 元/月',
  `family_type` varchar(20) DEFAULT NULL COMMENT '是否为经济困难家庭 0否 1特困 2低保 3低保边缘 ',
  `disability_certificate` varchar(20) DEFAULT NULL COMMENT '是否为持证残疾人 0否 1是 ',
  `medical_insurance_type` varchar(20) DEFAULT NULL COMMENT '医保类别 1职工基本医疗保险 2城乡居民基本医疗保险 3其他医疗保障 4无任何保障',
  `medical_insurance` varchar(20) DEFAULT NULL COMMENT '是否购买了商业健康(医疗)保险 0否 1是 ',
  `living_type` varchar(20) DEFAULT NULL COMMENT '现住场所:1自有产权房、私房等;2各类租赁房等;3养老院或类似机构;4护理院或类似机构;5医院或类似机构',
  `living_together` varchar(20) DEFAULT NULL COMMENT '同居者类型 0独居;1与配偶/伴侣居住;2与子女居住;3与孙辈居住;4与父母居住;5与兄弟姐妹居住;6与其他亲友居住;7其他',
  `living_together_remark` varchar(255) DEFAULT NULL COMMENT '同居者备注',
  `dementia_flag` varchar(20) DEFAULT NULL COMMENT '痴呆症 0无 1有',
  `mental_illness` varchar(20) DEFAULT NULL COMMENT '精神疾病(可多选)0无;1精神分裂症;2双相情感障碍;3偏执性精神障碍;4分裂情感性障碍;5癫痫所致精神障碍;6精神发育迟滞伴发精神障碍',
  `disease_type` varchar(20) DEFAULT NULL COMMENT '患病类型可多选;0无 1肿瘤(晚期)2严重心律失常3压疮4慢性心力衰竭(心功能III-IV级)5慢性肾功能衰竭(尿毒症期)6多器官功能衰竭7蛋白质能量营养不足(重度)8慢性阻塞性肺疾病(肺心病心功能III-IV级)9呼吸衰竭10脑血管意外合并吞咽障碍11其他',
  `disease_remark` varchar(255) DEFAULT NULL COMMENT '其他疾病',
  `fall_lately` varchar(20) DEFAULT NULL COMMENT '近30天跌倒 0无;1一次;2两次;3三次及以上',
  `lost_lately` varchar(20) DEFAULT NULL COMMENT '近30天走失 0无;1一次;2两次;3三次及以上',
  `choking_lately` varchar(20) DEFAULT NULL COMMENT '近30天噎食 0无;1一次;2两次;3三次及以上',
  `suicide_lately` varchar(20) DEFAULT NULL COMMENT '近30天自杀 0无;1一次;2两次;3三次及以上',
  `remark_lately` varchar(255) DEFAULT NULL COMMENT '近30天意外 其他 0无;1一次;2两次;3三次及以上',
  `medical_services` varchar(255) DEFAULT NULL COMMENT '近7天是否接受过医疗护理服务 0无1有',
  `domicile_county` varchar(255) DEFAULT NULL COMMENT '户籍  区(县、市)',
  `domicile_county_name` varchar(255) DEFAULT NULL COMMENT '户籍  区(县、市)',
  `domicile_street` varchar(255) DEFAULT NULL COMMENT '户籍  街(镇)',
  `domicile_street_name` varchar(255) DEFAULT NULL COMMENT '户籍  街(镇)',
  `domicile_org` varchar(255) DEFAULT NULL COMMENT '户籍 社(村)',
  `domicile_org_name` varchar(255) DEFAULT NULL COMMENT '户籍 社(村)',
  `domicile_building` varchar(255) DEFAULT NULL COMMENT '户籍 xx幢',
  `domicile_room` varchar(255) DEFAULT NULL COMMENT '户籍 xx室',
  `live_county` varchar(255) DEFAULT NULL COMMENT '居住地  区(县、市)',
  `live_county_name` varchar(255) DEFAULT NULL COMMENT '居住地名称  区(县、市)',
  `live_street` varchar(255) DEFAULT NULL COMMENT '居住地  街(镇)',
  `live_street_name` varchar(255) DEFAULT NULL COMMENT '居住地名称  街(镇)',
  `live_org` varchar(255) DEFAULT NULL COMMENT '居住地 社(村)',
  `live_org_name` varchar(255) DEFAULT NULL COMMENT '居住地名称 社(村)',
  `live_building` varchar(255) DEFAULT NULL COMMENT '居住地 xx幢',
  `live_room` varchar(255) DEFAULT NULL COMMENT '居住地 xx室',
  `postcode` varchar(50) DEFAULT NULL COMMENT '邮编',
  `residence_phone` varchar(50) DEFAULT NULL COMMENT '住宅电话',
  `patient_phone` varchar(50) DEFAULT NULL COMMENT '手机',
  `proxy_name` varchar(50) DEFAULT NULL COMMENT '代理人姓名',
  `applicant_relation` varchar(50) DEFAULT NULL COMMENT '与申请人关系',
  `proxy_address` varchar(255) DEFAULT NULL COMMENT '代理人地址',
  `proxy_telephone` varchar(50) DEFAULT NULL COMMENT '代理人电话',
  `proxy_phone` varchar(50) DEFAULT NULL COMMENT '代理人手机',
  `applicant_sign` varchar(255) DEFAULT NULL COMMENT '申请人(代理人) 签字结果图片url',
  `applicant_date` varchar(50) DEFAULT NULL COMMENT '申请日期',
  `service_type` varchar(50) DEFAULT NULL COMMENT '养老服务形式 0居家养老 1机构养老',
  `acceptable_services_life1` varchar(50) DEFAULT NULL COMMENT '直接生活照顾  1穿衣;2修饰;3口腔清洁;4皮肤清洁;5喂食服务;6排泄照料 ',
  `acceptable_services_life2` varchar(50) DEFAULT NULL COMMENT '间接生活照顾  1居室清洁;2更换洗涤;3上门维修;4定期探访;5膳食服务;6文化教育;7娱乐休闲;8室外休闲(户外);9紧急呼援;10法律援助;11转介服务;12咨询服务',
  `acceptable_services_mental` varchar(50) DEFAULT NULL COMMENT '精神心理照顾 1危机干预;2沟通;3精神支持;4心理疏导;5心理咨询',
  `acceptable_services_rehabilitation` varchar(255) DEFAULT NULL COMMENT '康复护理照顾 1定期翻身;2压疮预;3防活动肢体;4肢体保健;5康复活动;6预防保健;7健康咨询;8健康管理;9健康教育;10临终关怀 ',
  `acceptable_services_other` varchar(255) DEFAULT NULL COMMENT '其他',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-基本信息表';
CREATE TABLE base.base_capacity_assessment_living_ability (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `eating_ability_score` varchar(50) DEFAULT NULL COMMENT '进食能力得分 10可独立进食;5需部分帮助;0需要极大帮助或完全依赖他人',
  `shower_ability_score` varchar(50) DEFAULT NULL COMMENT '洗澡能力得分 5可独立完成;0需要帮助',
  `washing_ability_score` varchar(50) DEFAULT NULL COMMENT '洗漱能力得分 5可独立完成;0需要帮助',
  `dressing_ability_score` varchar(50) DEFAULT NULL COMMENT '穿衣能力得分 10可独立完成;5需要部分帮助;0需要极大帮助或完全依赖他人',
  `excretion_ability_score` varchar(50) DEFAULT NULL COMMENT '排便控制能力得分 10可自主控制;5偶尔失控(每周小于一次,或需要他人提示);0完全失控',
  `urination_ability_score` varchar(50) DEFAULT NULL COMMENT '排尿控制能力得分 10可自主控制;5偶尔失控(每周小于一次,或需要他人提示);0完全失控或留置导尿管',
  `toilet_ability_score` varchar(50) DEFAULT NULL COMMENT '如厕能力得分 10可独立完成;5需部分帮助;0需要极大帮助或完全依赖他人',
  `transfer_bed_ability_score` varchar(50) DEFAULT NULL COMMENT '床椅转移能力得分 15可独立完成10需要部分帮忙5需要极大帮忙0完全依赖他人',
  `walking_ability_score` varchar(50) DEFAULT NULL COMMENT '平地行走能力得分 15可独立行走45m;10需要部分帮助;5需要极大帮助;0完全依赖他人',
  `down_stairs_ability_score` varchar(50) DEFAULT NULL COMMENT '上下楼梯能力得分10可独立上下楼梯(连续10~15个台阶);5需要部分帮忙0需要极大帮助或完全依赖他人',
  `total_score` varchar(50) DEFAULT NULL COMMENT '日常生活能力总分 上述得分和 总分100 ',
  `ability_grade` varchar(50) DEFAULT NULL COMMENT '能力等级:0能力完好(100);1轻度受损(65-95);2中度受损(45-60);3重度受损(≤40)',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-日常生活能力评估表';
CREATE TABLE base.base_capacity_assessment_cognitive_ability (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `question1` varchar(4) DEFAULT NULL COMMENT '问题一得分 总分3分',
  `question2` varchar(4) DEFAULT NULL COMMENT '问题二得分 总分5分',
  `question3` varchar(4) DEFAULT NULL COMMENT '问题三得分 总分5分',
  `question4` varchar(4) DEFAULT NULL COMMENT '问题四得分 总分3分',
  `total_score` varchar(50) DEFAULT NULL COMMENT '认知能力 上述得分和  ',
  `ability_grade` varchar(50) DEFAULT NULL COMMENT '能力等级:0能力完好(16);1轻度受损(13-15);2中度受损(9-12);3重度受损(≤8)',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-认知能力表';
CREATE TABLE base.base_capacity_assessment_social_ability (
  `id` varchar(50) NOT NULL,
  `assessment_year` varchar(4) DEFAULT NULL COMMENT '评估年份',
  `status` tinyint(5) DEFAULT '1' COMMENT '状态 0失效 1有效 ',
  `patient` varchar(50) DEFAULT NULL,
  `aggress_score` varchar(4) DEFAULT NULL COMMENT '攻击行为得分 总分3分',
  `depressed_score` varchar(4) DEFAULT NULL COMMENT '抑郁状态得分 总分5分',
  `consciousness_score` varchar(4) DEFAULT NULL COMMENT '意识水平得分 总分5分',
  `communicate_score` varchar(4) DEFAULT NULL COMMENT '沟通交流得分 总分3分',
  `social_skills_score` varchar(50) DEFAULT NULL COMMENT '社交能力得分   ',
  `vision_score` varchar(50) DEFAULT NULL COMMENT '视力功能得分   ',
  `hearing_score` varchar(50) DEFAULT NULL COMMENT '听力能力得分   ',
  `total_score` varchar(50) DEFAULT NULL COMMENT ' 精神状态与社会交流能力总分 上述得分和 总分22',
  `ability_grade` varchar(50) DEFAULT NULL COMMENT '能力等级:0能力完好(22);1轻度受损(15-21);2中度受损(7-14);3重度受损(≤6)',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力评估-精神状态与社会交流能力表';

+ 20 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/apply/PatientBedApplyDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.care.dao.apply;
import com.yihu.jw.entity.care.apply.PatientBedApplyDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Bing on 2021/4/8.
 */
public interface PatientBedApplyDao extends PagingAndSortingRepository<PatientBedApplyDo,String>,
        JpaSpecificationExecutor<PatientBedApplyDo> {
    PatientBedApplyDo findByPatientAndOrgCodeAndStatus(String patient,String orgCode,Integer status);
    List<PatientBedApplyDo> findByOrgCodeAndStatusIn(String orgCode,Integer[] status);
    List<PatientBedApplyDo> queryByIdcardAndOrgCodeAndStatusIn(String idcard,String orgCode,Integer[] status);
}

+ 21 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDao.java

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

+ 16 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author yeshijie on 2018/1/10.
 */
public interface DeviceDetailDao extends PagingAndSortingRepository<DeviceDetail, Long>, JpaSpecificationExecutor<DeviceDetail> {
    @Query(value = "select a.* from wlyy_devices a where a.device_code=?1 limit 0,1",nativeQuery = true)
    DeviceDetail findBySn(String sn);
}

+ 70 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DevicePatientHealthIndexDao.java

@ -0,0 +1,70 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
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 recordDate order by recordDate asc")
	Iterable<DevicePatientHealthIndex> findByPatient(String user, int type, Date begin, Date end);
	@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(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.* 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, 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.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, int currentSize, int pageSize);
	
	@Query(value= " select * from wlyy_patient_health_index where type in (1,2) and record_date BETWEEN ?1 AND ?2  AND user in (select p.code from wlyy.wlyy_patient p INNER JOIN wlyy.wlyy_sign_family s on s.patient = p.code RIGHT JOIN wlyy.wlyy_sign_patient_label_info sp on sp.patient = p.code where  s.status > 0 AND s.admin_team_code = ?3 and (s.doctor = ?4 or s.doctor_health =?4) and sp.status = 1 and sp.label_type = 3 and (sp.label = 1 or sp.label = 2))",nativeQuery = true)
	List<DevicePatientHealthIndex> findByTeamcodeAndRecordDate(Date start, Date end, String teamcode, String doctorcode);
	@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 user = ?4")
	int getCountByTimeAndStatus(Date start, Date end, int status, String patientCode);
}

+ 54 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/PatientDeviceDao.java

@ -0,0 +1,54 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.PatientDevice;
import org.springframework.data.domain.Pageable;
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;
import java.util.List;
public interface PatientDeviceDao extends PagingAndSortingRepository<PatientDevice, Long>, JpaSpecificationExecutor<PatientDevice> {
    @Query("select a from PatientDevice a where a.user = ?1 ")
    Iterable<PatientDevice> findByUser(String user);
    @Query("select a from PatientDevice a where a.user = ?1 ")
    List<PatientDevice> findByPatient(String user);
    @Query("select a from PatientDevice a where a.user = ?1 and a.del=0 and a.deviceName like '%药盒%'")
    List<PatientDevice> findByPatientAndDel(String user);
    @Query("select a from PatientDevice a where a.user = ?1 and a.deviceSn=?2 ")
    List<PatientDevice> findByPatientAndDeviceSn(String user, String deviceSn);
    List<PatientDevice> findByUser(String user, Pageable pageRequest);
    List<PatientDevice> findByUserAndDoctor(String user, String doctor, Pageable pageRequest);
    List<PatientDevice> findByDeviceSnAndCategoryCode(String deviceSn, String categoryCode);
    PatientDevice findByDeviceSnAndCategoryCodeAndUserType(String deviceSn, String categoryCode, String userType);
    PatientDevice findByDeviceIdAndDeviceSnAndUserType(Long deviceId, String deviceSn, String userType);
    PatientDevice findByDeviceSnAndUserType(String deviceSn, String userType);
    @Query("select pd from PatientDevice pd where pd.deviceSn = ?1 and pd.del=0")
    List<PatientDevice> findByDeviceSn(String deviceSn);
    //更换患者绑定的血糖仪
    @Modifying
    @Query("update PatientDevice t set t.deviceSn = ?3 , t.userType = ?4,t.sim=?5,t.hospital=?6,t.hospitalName=?7,t.checkDoctorName=?8 where t.user = ?1 and t.deviceSn = ?2 ")
    int updatePatientDevice(String user, String deviceSN, String newDeviceSN, String userType, String sim, String hospital, String hospitalName, String checkDoctorName);
    @Query("select a from PatientDevice a")
    List<PatientDevice> findAll();
    @Query("select a from PatientDevice a where a.user=?1 and a.del=0")
    List<PatientDevice> findAllByUser(String user);
}

+ 22 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/label/WlyyPatientLabelDao.java

@ -0,0 +1,22 @@
package com.yihu.jw.care.dao.label;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
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;
import java.util.List;
/**
 * Created by yeshijie on 2021/4/7.
 */
public interface WlyyPatientLabelDao extends PagingAndSortingRepository<WlyyPatientLabelDO, String>, JpaSpecificationExecutor<WlyyPatientLabelDO> {
    @Modifying
    @Query("delete WlyyPatientLabelDO a where a.patient=?1 and a.labelType=?2")
    int deleteByPatientAndLabelType(String patient,String labelType) throws Exception;
    @Query("from WlyyPatientLabelDO w where  w.patient=?1 ")
    List<WlyyPatientLabelDO> findByPatient(String patient);
}

+ 19 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/role/DoctorRoleDao.java

@ -0,0 +1,19 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.care.dao.role;
import com.yihu.jw.entity.care.role.DoctorRole;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DoctorRoleDao extends PagingAndSortingRepository<DoctorRole, Long> {
    @Query(value = "select b.* from wlyy_user_role a,wlyy_role b where a.role = b.code and a.user = ?1",nativeQuery = true)
    List<DoctorRole> findUserRole(String user);
}

+ 17 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/role/DoctorRoleRealmDao.java

@ -0,0 +1,17 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.care.dao.role;
import com.yihu.jw.entity.care.role.DoctorRoleRealm;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DoctorRoleRealmDao extends PagingAndSortingRepository<DoctorRoleRealm, Long> {
    List<DoctorRoleRealm> findByRoleCode(String roleCode);
}

+ 15 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/role/UserRoleDao.java

@ -0,0 +1,15 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.care.dao.role;
import com.yihu.jw.entity.care.role.WlyyUserRole;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface UserRoleDao extends PagingAndSortingRepository<WlyyUserRole, Long> {
}

+ 17 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringConclusionDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.care.dao.security;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringConclusionDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/4/7.
 */
public interface SecurityMonitoringConclusionDao extends PagingAndSortingRepository<SecurityMonitoringConclusionDO,String>,
        JpaSpecificationExecutor<SecurityMonitoringConclusionDO> {
    @Query("select c from SecurityMonitoringConclusionDO c where c.orderId = ?1")
    SecurityMonitoringConclusionDO findByOrderId(String orderId);
}

+ 16 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringDoctorStatusDao.java

@ -0,0 +1,16 @@
package com.yihu.jw.care.dao.security;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringDoctorStatusDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/4/7.
 */
public interface SecurityMonitoringDoctorStatusDao extends PagingAndSortingRepository<SecurityMonitoringDoctorStatusDo,String>,
        JpaSpecificationExecutor<SecurityMonitoringDoctorStatusDo> {
    SecurityMonitoringDoctorStatusDo findByDoctor(String doctor);
    SecurityMonitoringDoctorStatusDo queryByDoctorAndStatusIn(String doctor, Integer[] status);
}

+ 14 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringOrderCancelLogDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.care.dao.security;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderCancelLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/4/7.
 */
public interface SecurityMonitoringOrderCancelLogDao extends PagingAndSortingRepository<SecurityMonitoringOrderCancelLog,String>,
        JpaSpecificationExecutor<SecurityMonitoringOrderCancelLog> {
}

+ 24 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringOrderDao.java

@ -0,0 +1,24 @@
package com.yihu.jw.care.dao.security;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderDO;
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;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Created by Bing on 2021/4/6.
 */
public interface SecurityMonitoringOrderDao extends PagingAndSortingRepository<SecurityMonitoringOrderDO,String>,
        JpaSpecificationExecutor<SecurityMonitoringOrderDO> {
    boolean existsByPatientAndStatusIn(String patient,Integer[] status);
    @Modifying
    @Transactional
    @Query("update SecurityMonitoringOrderDO o set o.conclusionStatus = 1,o.status='4' where o.id=?1")
    void updateConclusionStatus(String orderId);
}

+ 12 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/security/SecurityMonitoringOrderPatientConfirmLogDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.care.dao.security;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderPatientConfirmLog;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/4/7.
 */
public interface SecurityMonitoringOrderPatientConfirmLogDao extends PagingAndSortingRepository<SecurityMonitoringOrderPatientConfirmLog,String>,
        JpaSpecificationExecutor<SecurityMonitoringOrderPatientConfirmLog> {
}

+ 9 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/ArchiveDao.java

@ -1,9 +1,13 @@
package com.yihu.jw.care.dao.sign;
import com.yihu.jw.entity.care.archive.ArchiveDO;
import javafx.scene.shape.Arc;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by yeshijie on 2021/2/24.
 */
@ -12,4 +16,9 @@ public interface ArchiveDao extends PagingAndSortingRepository<ArchiveDO, String
    ArchiveDO findByIdcardAndDoctorCode(String idcard, String doctorCode);
    ArchiveDO findByPatientAndDoctorCode(String patient, String doctorCode);
    List<ArchiveDO> findByPatient(String patient);
    @Query(value = "SELECT a.* FROM wlyy_archive a WHERE a.idcard=?1 order by a.create_time desc limit 1",nativeQuery = true)
    ArchiveDO findByIdcard(String idcard);
}

+ 19 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentBaseInfoDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.care.dao.sign;
import com.yihu.jw.entity.care.sign.CapacityAssessmentBaseInfoDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Bing on 2021/4/1.
 */
public interface CapacityAssessmentBaseInfoDao extends PagingAndSortingRepository<CapacityAssessmentBaseInfoDo, String>,
        JpaSpecificationExecutor<CapacityAssessmentBaseInfoDo> {
    @Query("select c from CapacityAssessmentBaseInfoDo c where c.patient=?1 and c.assessmentYear=?2 and c.status=1")
    List<CapacityAssessmentBaseInfoDo> findByPatientAndYear(String patient, String year);
}

+ 19 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentCognitiveAbilityDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.care.dao.sign;
import com.yihu.jw.entity.care.sign.CapacityAssessmentCognitiveAbilityDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Bing on 2021/4/1.
 */
public interface CapacityAssessmentCognitiveAbilityDao extends PagingAndSortingRepository<CapacityAssessmentCognitiveAbilityDo, String>,
        JpaSpecificationExecutor<CapacityAssessmentCognitiveAbilityDo> {
    @Query("select c from CapacityAssessmentCognitiveAbilityDo c where c.patient=?1 and c.assessmentYear=?2 and c.status=1")
    List<CapacityAssessmentCognitiveAbilityDo> findByPatientAndYear(String patient, String year);
}

+ 18 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentLivingAbilityDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.care.dao.sign;
import com.yihu.jw.entity.care.sign.CapacityAssessmentLivingAbilityDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Bing on 2021/4/1.
 */
public interface CapacityAssessmentLivingAbilityDao extends PagingAndSortingRepository<CapacityAssessmentLivingAbilityDo, String>,
        JpaSpecificationExecutor<CapacityAssessmentLivingAbilityDo> {
    @Query("select c from CapacityAssessmentLivingAbilityDo c where c.patient=?1 and c.assessmentYear=?2 and c.status=1")
    List<CapacityAssessmentLivingAbilityDo> findByPatientAndYear(String patient, String year);
}

+ 1 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentRecordDao.java

@ -10,5 +10,6 @@ import org.springframework.data.repository.PagingAndSortingRepository;
public interface CapacityAssessmentRecordDao extends PagingAndSortingRepository<CapacityAssessmentRecordDO, String>,
        JpaSpecificationExecutor<CapacityAssessmentRecordDO> {
    CapacityAssessmentRecordDO findByPatient(String patient);
}

+ 18 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/CapacityAssessmentSocialAbilityDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.care.dao.sign;
import com.yihu.jw.entity.care.sign.CapacityAssessmentSocialAbilityDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Bing on 2021/4/1.
 */
public interface CapacityAssessmentSocialAbilityDao extends PagingAndSortingRepository<CapacityAssessmentSocialAbilityDo, String>,
        JpaSpecificationExecutor<CapacityAssessmentSocialAbilityDo> {
    @Query("select c from CapacityAssessmentSocialAbilityDo c where c.patient=?1 and c.assessmentYear=?2 and c.status=1")
    List<CapacityAssessmentSocialAbilityDo> findByPatientAndYear(String patient, String year);
}

+ 3 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/sign/ServicePackageRecordDao.java

@ -4,11 +4,13 @@ import com.yihu.jw.entity.base.servicePackage.ServicePackageRecordDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by yeshijie on 2021/2/25.
 */
public interface ServicePackageRecordDao extends PagingAndSortingRepository<ServicePackageRecordDO, String>, JpaSpecificationExecutor<ServicePackageRecordDO> {
    List<ServicePackageRecordDO> findBySignId(String signId);
}

+ 793 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/BaseController.java

@ -0,0 +1,793 @@
package com.yihu.jw.care.endpoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
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.Page;
import org.springframework.util.ReflectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "返回的json里的status是200,成功"),
        @ApiResponse(code = 403, message = "返回的json里的status是403,该操作没有权限"),
        @ApiResponse(code = 997, message = "返回的json里的status是997,重新登陆"),
        @ApiResponse(code = 998, message = "返回的json里的status是998,登录超时,请重新登录"),
        @ApiResponse(code = 999, message = "返回的json里的status是999,帐号在别处登录,请重新登录")
})
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger("error_logger");
    @Autowired
    protected HttpServletRequest request;
    /**
     * 獲取髮送請求用戶的uid
     * @return
     */
    public String getUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("uid");
//            return "xh1D2017031502222";// wjw00000001000e6badcfa163e424589/wjw00000001000e6badcfa163e424525
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人的code
     * @return
     */
    public String getRepresentedUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取平台端
     * @return
     */
    public Integer getPlatform() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getInt("platform");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人code,若没有则返回当前登录者
     * @return
     */
    public String getRepUID(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            if(json.isNull("represented")){
                return json.getString("uid");
            }
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getLastUid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String id = json.getString("lastUid");
            if(StringUtils.isNoneBlank(id)){
                return id;
            }else{
               return json.getString("uid");
            }
        } catch (Exception e) {
            return null;
        }
    }
    public String getAppVersion() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("appVersion");
        } catch (Exception e) {
            return null;
        }
    }
    public String getOpenid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("openid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取用户ID
     *
     * @return
     */
    public long getId() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getLong("id");
        } catch (Exception e) {
            return 0;
        }
    }
    public String getIMEI() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("imei");
        } catch (Exception e) {
            return null;
        }
    }
    public String getToken() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("token");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色code
     * @return
     */
    public String getCurrentRoleCode(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String currentUserRole = json.getJSONObject("currentUserRole").getString("code");
            return currentUserRole;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色级别
     * @return
     */
    public String getCurrentRoleLevel(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").get("level")+"";
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色是否是管理员
     * @return
     */
    public String getCurrentRoleIsManange(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").getString("isManage");
        } catch (Exception e) {
            return null;
        }
    }
    public void error(Exception e) {
        logger.error(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+":"+getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void warn(Exception e) {
        logger.warn(getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void infoMessage(String message) {
        logger.info(message);
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 接口处理成功
     *
     * @param msg
     * @return
     */
    public String success(String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONObject value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value,String key2, JSONObject value2) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            json.put(key2, value2);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param total 总数
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, int total, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put("total", total);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, int total, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put("total", total);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            // 是否为第一页
            map.put("isFirst", list.isFirst());
            // 是否为最后一页
            map.put("isLast", list.isLast());
            // 总条数
            map.put("total", list.getTotalElements());
            // 总页数
            map.put("totalPages", list.getTotalPages());
            map.put(key, list.getContent());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", page == null ? false : page.isFirst());
            // 是否为最后一页
            json.put("isLast", page == null ? true : page.isLast());
            // 总条数
            json.put("total", page == null ? 0 : page.getTotalElements());
            // 总页数
            json.put("totalPages", page == null ? 0 : page.getTotalPages());
            json.put(key, array);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Map<?, ?> value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, String value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, IdEntity entity) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, entity);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", isFirst);
            // 是否为最后一页
            json.put("isLast", isLast);
            // 总条数
            json.put("total", total);
            // 总页数
            json.put("totalPages", totalPages);
            json.put(key, values);
            return json.toString();
        } catch (Exception e) {
            logger.error("BaseController:", e.getMessage());
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public String trimEnd(String param, String trimChars) {
        if (param.endsWith(trimChars)) {
            param = param.substring(0, param.length() - trimChars.length());
        }
        return param;
    }
    /**
     * 无效用户消息返回
     *
     * @param e
     * @param defaultCode
     * @param defaultMsg
     * @return
     */
    public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
        try {
            // if (e instanceof UndeclaredThrowableException) {
            // UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
            // InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
            // if (iue != null) {
            // return error(iue.getCode(), iue.getMsg());
            // }
            // }
            return error(defaultCode, defaultMsg);
        } catch (Exception e2) {
            return null;
        }
    }
    public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String... propertyNames) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans) {
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    public Map<String, Object> copyBeanProperties(Object bean, String... propertyNames) {
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames) {
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
    /**
     * 数据保留两位小数,**.0 去掉小数点
     * @param obj
     * @return
     */
    public String getNumberFormat(Object obj){
        if(obj != null){
            Double d = Double.valueOf(obj.toString());
            NumberFormat df = NumberFormat.getInstance();
            df.setGroupingUsed(false);
            df.setMaximumFractionDigits(2);
            return df.format(d);
        }else {
            return "";
        }
    }
    public String write(int code, String errorMsg, int page, int rows, long total, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("successFlg", code == 0);
            map.put("errorMsg", errorMsg);
            // 是否为第一页
            map.put("errorCode", code);
            // 是否为最后一页
            map.put("currPage", page);
            // 分页大小
            map.put("pageSize", rows);
            // 总条数
            map.put("totalCount", total);
            // 总页数
            map.put("totalPage", Math.ceil((double)total/(rows)));
            // 结果集
            map.put("detailModelList", list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    
    /**
     * 判断是否是观察者模式
     * @return
     */
    public boolean getObserverStatus () {
    
        String userAgent = request.getHeader("userAgent");
        if (StringUtils.isEmpty(userAgent)) {
            userAgent = request.getHeader("User-Agent");
        }
        logger.debug("userAgent:" + userAgent);
        JSONObject json = new JSONObject(userAgent);
        String observer = json.has("observer") ? json.getString("observer") : "";
        //如果是观察者直接返回true
        if (!org.springframework.util.StringUtils.isEmpty(observer) && observer.equals("1")) {
            return true;
        }else{
            return false;
        }
    }
    //获取ip地址
    public String getIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
    //获取手机型号
    public String getPhoneType(){
        String userAgent = request.getHeader("User-Agent");
        Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");
        Matcher matcher = pattern.matcher(userAgent);
        String model = null;
        if (matcher.find()) {
            model = matcher.group(1).trim();
        }else{
            model = "未知型号";
        }
        return model;
    }
}

+ 8 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/WeixinBaseController.java

@ -0,0 +1,8 @@
package com.yihu.jw.care.endpoint;
public class WeixinBaseController extends BaseController {
}

+ 56 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/apply/PatientBedApplyEndPoint.java

@ -0,0 +1,56 @@
package com.yihu.jw.care.endpoint.apply;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.apply.PatientBedApplyService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * Created by Bing on 2021/4/8.
 */
@RestController
@Api(description = "居民床位申请")
@RequestMapping(value = "bed_apply")
public class PatientBedApplyEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private PatientBedApplyService patientBedApplyService;
    @PostMapping("/apply")
    @ApiOperation("居民申请机构床位")
    public ObjEnvelop apply(@ApiParam(name = "idcard", value = "居民idcard", required = true)
                            @RequestParam(value = "idcard") String idcard,
                            @ApiParam(name = "orgCode", value = "机构code", required = true)
                            @RequestParam(value = "orgCode") String orgCode) {
        try {
            JSONObject result = patientBedApplyService.apply(idcard, orgCode);
            if (result.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                return ObjEnvelop.getError(result.getString(ResponseContant.resultMsg));
            }
            return ObjEnvelop.getSuccess("操作成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("申请失败" + e.getMessage());
        }
    }
    @GetMapping("/getApplyList")
    @ApiOperation("居民申请机构床位")
    public ListEnvelop getApplyList(@ApiParam(name = "doctor", value = "doctor", required = true)
                                    @RequestParam(value = "doctor") String doctor) {
        try {
            return ListEnvelop.getSuccess("查询成功", patientBedApplyService.getApplyList(doctor));
        } catch (Exception e) {
            e.printStackTrace();
            return ListEnvelop.getError("查询失败");
        }
    }
}

+ 53 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DeviceController.java

@ -0,0 +1,53 @@
package com.yihu.jw.care.endpoint.device;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.DeviceService;
import com.yihu.jw.entity.care.device.Device;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
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;
    @ApiOperation("获取设备列表")
    @RequestMapping(value = "DeviceList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    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);
            return write(200, "获取设备列表成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "获取设备列表失败!");
        }
    }
    @ApiOperation("获取设备信息")
    @RequestMapping(value = "DeviceInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceInfo(@ApiParam(name = "id", value = "设备ID", defaultValue = "19")
                                @RequestParam(value = "id", required = true) String id) {
        try {
            Device device = deviceService.findById(id);
            return write(200, "查询成功", "data", device);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}

+ 120 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorDeviceController.java

@ -0,0 +1,120 @@
package com.yihu.jw.care.endpoint.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.DeviceDetailService;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.util.CommonUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
 * 医生端:设备管理控制类
 * @author George
 *
 */
@RestController
@RequestMapping(value = "doctor/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@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 BasePatientDao patientDao;
	@Autowired
	private BaseDoctorDao doctorDao;
	@Autowired
	private CommonUtil commonUtil;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JmsTemplate jmsTemplate;
	private ObjectMapper  objectMapper=new ObjectMapper();
	@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) {
			error(ex);
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@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 {
			PatientDevice device = patientDeviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			error(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) {
			error(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);
	}
}

+ 318 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorHealthController.java

@ -0,0 +1,318 @@
package com.yihu.jw.care.endpoint.device;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.PatientHealthIndexService;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
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.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/doctor/health_index", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@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) {
			error(e);
			return error(-1, "查询失败");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @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);
			if (jsonArray.length()==0) {
				return success("查询成功!");
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@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 jsonObject = new JSONObject();
			if (type == 1) {
				List<Object> list = healthIndexService.findIndexByPatient2(patient, type, begin, end, page, pagesize);
				jsonObject.put("data",list);
			}else{
				JSONArray jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
				jsonObject.put("data",jsonArray);
			}
			return write(200, "查询成功", "list", jsonObject);
		} catch (Exception ex) {
			error(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) {
			error(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();
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ PatientHealthIndexService.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ PatientHealthIndexService.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ PatientHealthIndexService.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ PatientHealthIndexService.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			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, "查询失败!");
		}
	}
	@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 (Exception ex) {
			error(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();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ PatientHealthIndexService.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ PatientHealthIndexService.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ PatientHealthIndexService.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ PatientHealthIndexService.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ PatientHealthIndexService.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			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, "查询失败!");
		}
	}
	@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());
		}
	}
	@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) {
			error(e);
			return error(-1, "查询失败");
		}
	}
}

+ 214 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PatientDeviceController.java

@ -0,0 +1,214 @@
package com.yihu.jw.care.endpoint.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.DeviceDetailService;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.service.device.PatientHealthIndexService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
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.stereotype.Controller;
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.ResponseBody;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 患者端:设备管理控制类
 *
 * @author George
 */
@Controller
@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 PatientDeviceDao patientDeviceDao;
    @Autowired
    private PatientHealthIndexService patientHealthIndexService;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private BasePatientDao patientDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    @ApiOperation("获取居民标准体征预警值")
    @RequestMapping(value = "getDeviceStandard", method = RequestMethod.GET)
    @ResponseBody
    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,"获取失败");
        }
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    @ResponseBody
    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 {
            PatientDevice device = objectMapper.readValue(json, PatientDevice.class);
            // 设置患者标识
            device.setUser(getRepUID());
            //患者和设备是否首绑
            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 = patientDao.findById(getRepUID());
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
                device.setAgentName(patient.getName());
            }
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                patientDeviceService.saveDevice(device);
            }
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            return success("设备保存成功!");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    @ResponseBody
    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<PatientDevice> 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)
    @ResponseBody
    public String getPatientDeviceInfo(@ApiParam(name = "id", value = "患者设备ID", defaultValue = "146")
                                       @RequestParam(value = "id", required = true) String id) {
        try {
            Map mapList = new HashMap();
            PatientDevice device = patientDeviceService.findById(id);
            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)
    @ResponseBody
    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 (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 = "DeletePatientDevice",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            PatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getRepUID());
                //全部解绑后去判断就更新设备表中是否绑定字段
                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)
    @ResponseBody
    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,"执行失败!");
        }
    }
}

+ 20 - 12
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/dict/DictEndpoint.java

@ -1,9 +1,11 @@
package com.yihu.jw.care.endpoint.dict;
import com.yihu.jw.area.service.*;
import com.yihu.jw.care.service.common.DictService;
import com.yihu.jw.entity.base.area.*;
import com.yihu.jw.restmodel.base.area.*;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import io.swagger.annotations.Api;
@ -17,7 +19,6 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2021/2/24.
@ -40,18 +41,25 @@ public class DictEndpoint extends EnvelopRestEndpoint {
    private BaseStreetService baseStreetService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DictService dictService;
    @ApiOperation("查询字典")
    @GetMapping(value= "findDict")
    public MixEnvelop findDict(@ApiParam(name = "name", value = "name", required = false)
                               @RequestParam(value = "name", required = false)String name,
                               @ApiParam(name = "modelName", value = "modelName", required = false)
                               @RequestParam(value = "modelName", required = false)String modelName,
                               @ApiParam(name = "code", value = "code", required = false)
                               @RequestParam(value = "code", required = false)String code,
                               @ApiParam(name = "value", value = "value", required = false)
                               @RequestParam(value = "value", required = false)String value,
                               @ApiParam(name = "page", value = "page", required = false)
                               @RequestParam(value = "page", required = false) Integer page,
                               @ApiParam(name = "pageSize", value = "pageSize", required = false)
                               @RequestParam(value = "pageSize", required = false)Integer pageSize){
    @GetMapping(value = "getNationDict")
    @ApiOperation("获取民族信息列表")
    public ListEnvelop<Map<String,Object>> getNationDict(){
        try {
            String sql = "SELECT t.NATION_CODE code,t.NATION_NAME name FROM zy_nation_dict t";
            List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
            return success(rs);
        } catch (Exception e) {
            e.printStackTrace();
            return ListEnvelop.getError("获取字典信息失败!");
        }
        return dictService.findDictsByNameCode(modelName,name,code,value,page,pageSize);
    }
    @GetMapping(value = BaseHospitalRequestMapping.Prescription.findCommity)

+ 35 - 5
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorEndpoint.java

@ -1,7 +1,10 @@
package com.yihu.jw.care.endpoint.doctor;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.doctor.CareDoctorService;
import com.yihu.jw.care.service.sign.CapacityAssessmentRecordService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
@ -9,10 +12,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@ -29,6 +29,8 @@ public class DoctorEndpoint extends EnvelopRestEndpoint {
    private BaseDoctorDao doctorDao;
    @Autowired
    private CareDoctorService doctorService;
    @Autowired
    private CapacityAssessmentRecordService capacityAssessmentRecordService;
    @GetMapping(value = "doctorPage")
    @ApiOperation(value = "获取医生记录分页")
@ -52,13 +54,41 @@ public class DoctorEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "doctorInfo")
    @ApiOperation(value = "获取医生详情")
    public ObjEnvelop doctorInfo (
            @ApiParam(name = "doctorId", value = "医生id", required = true)
            @RequestParam(value = "doctorId",required = true) String doctorId,
            @ApiParam(name = "isRole", value = "是否返回角色(1是 0否)", required = false)
            @RequestParam(value = "isRole",required = false) String isRole) throws Exception {
        try{
            return ObjEnvelop.getSuccess("查询成功",doctorService.doctorInfo(doctorId,isRole));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError("查询失败");
        }
    }
    @GetMapping(value = "patientCount")
    @ApiOperation(value = "获取我的居民统计数量")
    public ObjEnvelop patientCount (
            @ApiParam(name = "doctorId", value = "医生id", required = true)
            @RequestParam(value = "doctorId",required = true) String doctorId) throws Exception {
        try{
            return ObjEnvelop.getSuccess("查询成功",doctorService.doctorInfo(doctorId));
            return ObjEnvelop.getSuccess("查询成功",capacityAssessmentRecordService.getPatientNum(doctorId));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError("查询失败");
        }
    }
    @PostMapping(value = "updateDoctor")
    @ApiOperation(value = "修改医生信息")
    public Envelop update(
            @ApiParam(name = "baseDoctorVo", value = "JSON数据", required = true)
            @RequestParam(value = "baseDoctorVo") String baseDoctorVo)throws Exception{
        JSONObject jsonObject = JSONObject.parseObject(baseDoctorVo);
        Boolean update = doctorService.update(jsonObject);
        if (!update){
            return failed("保存失败,参数不可为空");
        }
        return success("保存成功");
    }
}

+ 65 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/label/PatientLabelEndpoint.java

@ -0,0 +1,65 @@
package com.yihu.jw.care.endpoint.label;
import com.yihu.jw.care.service.label.PatientLableService;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2021/4/8.
 */
@RestController
@RequestMapping(value = "patientLable")
@Api(value = "居民标签", description = "居民标签", tags = {"医生端-居民标签"})
public class PatientLabelEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private PatientLableService patientLableService;
    @GetMapping(value = "findSignPatientLabelNumByTeamCode")
    @ApiOperation(value = "按团队查找签约居民的标签统计")
    public ListEnvelop findSignPatientLabelNumByTeamCode (
            @ApiParam(name = "teamCode", value = "团队code", required = true)
            @RequestParam(value = "teamCode",required = true) String teamCode) throws Exception {
        try{
            return ListEnvelop.getSuccess("查询成功",patientLableService.findSignPatientLabelNumByTeamCode(teamCode));
        }catch (Exception e){
            e.printStackTrace();
            return ListEnvelop.getError("查询失败");
        }
    }
    @GetMapping(value = "findSignPatientLabelListByTeamCode")
    @ApiOperation(value = "按团队和标签查找签约居民")
    public PageEnvelop<List<Map<String,Object>>> findSignPatientLabelListByTeamCode (
            @ApiParam(name = "teamCode", value = "团队code", required = true)
            @RequestParam(value = "teamCode",required = true) String teamCode,
            @ApiParam(name = "labelCode", value = "标签", required = true)
            @RequestParam(value = "labelCode",required = true) String labelCode,
            @ApiParam(name = "name", value = "姓名或身份证", required = false)
            @RequestParam(value = "name",required = false) String name,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size) throws Exception {
        try{
            return patientLableService.findSignPatientLabelListByTeamCode(teamCode, labelCode, name, page, size);
        }catch (Exception e){
            e.printStackTrace();
            return PageEnvelop.getError("查询失败");
        }
    }
}

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/org/OrgEndpoint.java

@ -24,7 +24,7 @@ public class OrgEndpoint extends EnvelopRestEndpoint {
    @ApiOperation(value = "获取机构成员")
    public ListEnvelop findOrgList(@ApiParam(name = "type", value = "机构类型1. 等级医院2. 社区医院3.  养老机构")
                                      @RequestParam(value = "type", required = false) String type,
                                      @ApiParam(name = "name", value = "医生姓名")
                                      @ApiParam(name = "name", value = "机构名称")
                                      @RequestParam(value = "name", required = false) String name) {
        try {
            return ListEnvelop.getSuccess("获取成功",orgService.findOrgList(type,name));

+ 47 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/patient/PatientEndpoint.java

@ -2,6 +2,7 @@ package com.yihu.jw.care.endpoint.patient;
import com.yihu.jw.care.aop.ServicesAuth;
import com.yihu.jw.care.aop.ServicesAuthAOP;
import com.yihu.jw.care.dao.label.WlyyPatientLabelDao;
import com.yihu.jw.care.service.patient.CarePatientService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
@ -11,10 +12,7 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@ -30,6 +28,8 @@ public class PatientEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private CarePatientService patientService;
    @Autowired
    private WlyyPatientLabelDao patientLabelDao;
    @Autowired
    ServicesAuthAOP servicesAuthAOP;
    @GetMapping(value = "testServicesAuth1")
@ -91,4 +91,47 @@ public class PatientEndpoint extends EnvelopRestEndpoint {
            return failed("获取失败",-1);
        }
    }
    @PostMapping(value = "updPatient")
    @ApiOperation(value = "修改居民信息")
    public Envelop updPatient(@ApiParam(name = "jsonData", value = "json格式")
                                  @RequestParam(value = "jsonData", required = true)String jsonData,
                                  @ApiParam(name = "doctorId", value = "医生id")
                                  @RequestParam(value = "doctorId", required = false)String doctorId)throws Exception{
        try{
            patientService.updPatient(jsonData, doctorId);
            return success("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return failed("修改失败",-1);
        }
    }
    @GetMapping(value = "findPatientLabel")
    @ApiOperation(value = "获取居民标签信息")
    public Envelop findPatientLabel(@ApiParam(name = "patientId", value = "居民id")
                                   @RequestParam(value = "patientId", required = true)String patientId)throws Exception{
        try{
            return success("修改成功",patientLabelDao.findByPatient(patientId));
        }catch (Exception e){
            e.printStackTrace();
            return failed("修改失败",-1);
        }
    }
    @PostMapping(value = "updPatientLabel")
    @ApiOperation(value = "修改居民标签信息")
    public Envelop updPatientLabel(@ApiParam(name = "jsonData", value = "json格式")
                              @RequestParam(value = "jsonData", required = true)String jsonData,
                              @ApiParam(name = "patientId", value = "居民id")
                              @RequestParam(value = "patientId", required = true)String patientId)throws Exception{
        try{
            patientService.updPatientLabel(jsonData, patientId);
            return success("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return failed("修改失败",-1);
        }
    }
}

+ 226 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/security/SecurityMonitoringOrderEndpoint.java

@ -0,0 +1,226 @@
package com.yihu.jw.care.endpoint.security;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.service.security.SecurityMonitoringOrderService;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringConclusionDO;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * 安防监护 服务工单
 * Created by Bing on 2021/4/6.
 */
@RestController
@RequestMapping(value = "security/order")
@Api(description = "安防监护 服务工单相关")
public class SecurityMonitoringOrderEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private SecurityMonitoringOrderService securityMonitoringOrderService;
    @PostMapping(value = "createOrder")
    @ApiOperation(value = "创建安防服务工单")
    public ObjEnvelop createOrder(@ApiParam(name="jsonData",value = "json数据",required = true)
                               @RequestParam(value = "jsonData")String jsonData){
        try {
            JSONObject result = securityMonitoringOrderService.createOrder(jsonData);
            if (result.getIntValue("resultFlag") == 0) {
                return ObjEnvelop.getError(result.getString("resultMsg"));
            }
            return ObjEnvelop.getSuccess("创建成功",result.getJSONObject("resultMsg"));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError("创建失败"+e.getMessage());
        }
    }
    @GetMapping(value = "getSecurityOrderList")
    @ApiOperation(value = "获取安防工单列表")//TODO 查询需要修改
    public ListEnvelop getSecurityOrderList(@ApiParam(name="doctor",value = "医生ID",required = true)
                                            @RequestParam(value = "doctor")String doctor,
                                            @ApiParam(name="patient",value = "patient")
                                            @RequestParam(value = "patient",required = false)String patient,
                                            @ApiParam(name="status",value = "工单状态-1已取消1待处置2前往居民定位3已签到4已登记小结5待补录6待评价7已完成")
                                            @RequestParam(value = "status",required = false)String status,
                                            @ApiParam(name="page",value = "page",required = true)
                                            @RequestParam(value = "page")Integer page,
                                            @ApiParam(name="pageSize",value = "pageSize",required = true)
                                            @RequestParam(value = "pageSize")Integer pageSize){
        try {
            page = page>1?page-1:0;
            return ListEnvelop.getSuccess("查询成功",securityMonitoringOrderService.getSecurityOrderList(doctor, patient, status, page, pageSize));
        }catch (Exception e){
            e.printStackTrace();
            return ListEnvelop.getError("查询失败");
        }
    }
    @GetMapping(value = "getSecurityOrderDetail")
    @ApiOperation(value = "获取安防工单详情")//
    public ObjEnvelop getSecurityOrderDetail(@ApiParam(name="orderId",value = "orderId",required = true)
                                            @RequestParam(value = "orderId")String orderId){
        try {
            JSONObject result = securityMonitoringOrderService.getSecurityOrderDetail(orderId);
            if (result.getIntValue("resultFlag") == 0) {
                return ObjEnvelop.getError(result.getString("resultMsg"));
            }
            return ObjEnvelop.getSuccess("创建成功",result.getJSONObject("resultMsg"));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError("查询失败");
        }
    }
    @PostMapping("acceptOrder")
    @ApiOperation(value = "接单")
    @ObserverRequired
    public ObjEnvelop acceptOrder(
            @ApiParam(value = "工单id", name = "orderId", required = true) @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "医生code", name = "doctor", required = true) @RequestParam(value = "doctor", required = true) String doctor) {
        try {
            JSONObject result =  securityMonitoringOrderService.acceptOrder(orderId,doctor);
            if (result.getIntValue("resultFlag") == 0) {
                return ObjEnvelop.getError(result.getString("resultMsg"));
            }
            return ObjEnvelop.getSuccess("接单成功",result.getJSONObject("resultMsg"));
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "操作失败!" + e.getMessage());
        }
    }
    @PostMapping(value = "cancelOrder")
    @ApiOperation(value = "取消工单")
    public Envelop cancelOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "reason", value = "取消理由") @RequestParam(value = "reason", required = true) String reason,
            @ApiParam(name = "doctor", value = "医生id") @RequestParam(value = "doctor", required = true) String doctor) {
        JSONObject result = new JSONObject();
        try{
            result = securityMonitoringOrderService.cancelOrder(orderId, 2, reason,doctor);
            if (result.getIntValue("resultFlag") == 0) {
                return ObjEnvelop.getError(result.getString("resultMsg"));
            }
            return ObjEnvelop.getSuccess("工单已取消",result.getJSONObject("resultMsg"));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError("工单取消失败"+e.getMessage());
        }
    }
    @PostMapping("signIn")
    @ApiOperation(value = "上门服务签到")
    public ObjEnvelop signIn(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "签到时间", name = "signTime")
            @RequestParam(value = "signTime", required = false) String signTime,
            @ApiParam(value = "签到方式:1-定位,2-扫码,3-拍照", name = "signWay")
            @RequestParam(value = "signWay", required = false) Integer signWay,
            @ApiParam(value = "签到地址", name = "signLocation")
            @RequestParam(value = "signLocation", required = false) String signLocation,
            @ApiParam(value = "签到照片", name = "signImg")
            @RequestParam(value = "signImg", required = false) String signImg,
            @ApiParam(value = "二维码内容", name = "twoDimensionalCode")
            @RequestParam(value = "twoDimensionalCode", required = false) String twoDimensionalCode) {
        try {
            SecurityMonitoringOrderDO securityMonitoringOrderDO = securityMonitoringOrderService.signIn(orderId, signTime, signWay, signLocation, signImg,twoDimensionalCode,getUID());
            if (securityMonitoringOrderDO != null){
                return ObjEnvelop.getSuccess("操作成功", securityMonitoringOrderDO);
            }else {
                return ObjEnvelop.getError("扫码签到失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "操作失败!" + e.getMessage());
        }
    }
    @PostMapping("updateDoorConclusion")
    @ApiOperation("编辑保存服务工单小结")
    public ObjEnvelop updateDoorConclusion(
            @ApiParam(value = "处置状态",name = "manageStatus",required = true)
            @RequestParam Integer manageStatus,
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "服务小结", name = "conclusion")
            @RequestParam(value = "conclusion", required = true) String conclusion,
            @ApiParam(value = "补录状态", name = "examPapeStatus")
            @RequestParam(value = "examPapeStatus", required = false) Integer examPapeStatus) {
        try {
            SecurityMonitoringConclusionDO doorConclusion = securityMonitoringOrderService.updateDoorConclusion(manageStatus, orderId,conclusion,examPapeStatus);
            return ObjEnvelop.getSuccess( "保存成功", doorConclusion);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "保存失败!" + e.getMessage());
        }
    }
    @PostMapping(value = "cancelConclusion")
    @ResponseBody
    @ApiOperation("取消登记服务小结")
    public ObjEnvelop cancelConclusion(@ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId) {
        try {
            securityMonitoringOrderService.cancelConclusion(orderId);
            return ObjEnvelop.getSuccess("取消成功",200);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("取消失败");
        }
    }
    @GetMapping("getDoorConclusion")
    @ApiOperation("获取服务工单小结")
    public ObjEnvelop getDoorConclusion(
            @ApiParam(value = "医生code", name = "doctor")
            @RequestParam(value = "doctor", required = false) String doctor,
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = false) String orderId) {
        try {
            // 没有提供工单id的情况下,默认代入上一次服务信息记录
            if (StringUtils.isEmpty(orderId)) {
                orderId = securityMonitoringOrderService.getOrderIdByDoctor(doctor);
                if (StringUtils.isEmpty(orderId)) {
                    return ObjEnvelop.getError("获取失败,该医生暂无工单" );
                }
            }
            // 根据orderId查询工单小结表
            SecurityMonitoringConclusionDO doorConclusion = securityMonitoringOrderService.getDoorConclusion(orderId);
            return ObjEnvelop.getSuccess("获取成功", doorConclusion);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("获取失败!" + e.getMessage());
        }
    }
    @PostMapping("saveOrderFinishBydoctor")
    @ApiOperation(value = "医生确认完成工单")
    @ObserverRequired
    public ObjEnvelop saveOrderFinishBydoctor(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "医生确认结束服务照片", name = "finishImg")
            @RequestParam(value = "finishImg", required = false) String finishImg) {
        try {
            return ObjEnvelop.getSuccess("操作成功", securityMonitoringOrderService.saveOrderFinishBydoctor(orderId, finishImg));
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "操作失败!" + e.getMessage());
        }
    }
}

Datei-Diff unterdrückt, da er zu groß ist
+ 145 - 15
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/sign/SignEndpoint.java


+ 73 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/StatisticsEndpoint.java

@ -0,0 +1,73 @@
package com.yihu.jw.care.endpoint.statistics;
import com.yihu.jw.care.service.statistics.StatisticsService;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by yeshijie on 2021/4/7.
 */
@RestController
@RequestMapping(value = "statistics")
@Api(value = "统计相关", description = "统计相关", tags = {"统计相关"})
public class StatisticsEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private StatisticsService statisticsService;
    /**
     * 统计首页头部数据
     * @param startDate
     * @param endDate
     * @param area
     * @param level 2 市  3区  4医院 5、科室 6医生
     * @return
     */
    @GetMapping(value = "indexTopNum")
    @ApiOperation(value = "统计首页头部数据")
    public ObjEnvelop indexTopNum(
            @RequestParam(required = true) String startDate,
            @RequestParam(required = true) String endDate,
            @RequestParam(required = true) String area,
            @RequestParam(required = true) Integer level) {
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.indexTopNum(area,startDate,endDate,level));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ObjEnvelop.getError("查询失败",-1);
    }
    /**
     * 首页 养护服务
     * @param startDate
     * @param endDate
     * @param area
     * @param level 2 市  3区  4医院 5、科室 6医生
     * @return
     */
    @GetMapping(value = "indexMaintenanceServices")
    @ApiOperation(value = "首页-养护服务")
    public ObjEnvelop indexMaintenanceServices(
            @RequestParam(required = true) String startDate,
            @RequestParam(required = true) String endDate,
            @RequestParam(required = true) String area,
            @RequestParam(required = true) int type,
            @RequestParam(required = true) Integer level) {
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.indexMaintenanceServices(area,startDate,endDate,level,type));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ObjEnvelop.getError("查询失败",-1);
    }
}

+ 93 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/apply/PatientBedApplyService.java

@ -0,0 +1,93 @@
package com.yihu.jw.care.service.apply;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.apply.PatientBedApplyDao;
import com.yihu.jw.care.dao.sign.ArchiveDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.apply.PatientBedApplyDo;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Bing on 2021/4/8.
 */
@Service
public class PatientBedApplyService extends BaseJpaService<PatientBedApplyDo, PatientBedApplyDao> {
    @Autowired
    private PatientBedApplyDao patientBedApplyDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private ArchiveDao archiveDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    public JSONObject apply(String idcard,String orgCode){
        JSONObject result = new JSONObject();
        BasePatientDO basePatientDo = basePatientDao.findByIdcardAndDel(idcard,"1");
        //展示只能申请一个机构
        List<PatientBedApplyDo> applyList = patientBedApplyDao.queryByIdcardAndOrgCodeAndStatusIn(idcard,orgCode,new Integer[]{0,1,2});
        if (applyList.size()>0){
            String failMsg = "当前用户已申请过该机构,无法重复申请";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            return result;
        }
        else {
            BaseOrgDO baseOrgDO = baseOrgDao.findByCode(orgCode);
            if (baseOrgDO==null){
                String failMsg = "申请机构不存在";
                result.put(ResponseContant.resultFlag, ResponseContant.fail);
                result.put(ResponseContant.resultMsg,failMsg);
                return result;
            }
            PatientBedApplyDo patientBedApplyDo = new PatientBedApplyDo();
            if (basePatientDo!=null){
                patientBedApplyDo.setPatient(basePatientDo.getId());
                patientBedApplyDo.setPatientName(basePatientDo.getName());
            }
            patientBedApplyDo.setOrgCode(orgCode);
            patientBedApplyDo.setIdcard(idcard);
            patientBedApplyDo.setOrgName(baseOrgDO.getName());
            patientBedApplyDo.setStatus(1);//申请床位是未选择医生 设为未建档(医生未创建建档记录)。
            patientBedApplyDao.save(patientBedApplyDo);
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg,patientBedApplyDo);
        }
        return result;
    }
    public List<PatientBedApplyDo> getApplyList(String doctor){
        List<PatientBedApplyDo> result = new ArrayList<>();
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        if (doctorDO.getLevel()==2){//助老员
            List<BaseDoctorHospitalDO> hospitalDOS = baseDoctorHospitalDao.findByDoctorCode(doctor);
            for (BaseDoctorHospitalDO obj:hospitalDOS){
                List<PatientBedApplyDo> list = patientBedApplyDao.findByOrgCodeAndStatusIn(obj.getOrgCode(),new Integer[]{1,2});
                result.addAll(list);
            }
        }
        return result;
    }
}

+ 104 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/common/DictService.java

@ -0,0 +1,104 @@
package com.yihu.jw.care.service.common;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2021/4/7.
 */
@Service
public class DictService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 字典翻译
     * @param dictName
     * @param code
     * @return
     */
    public String fingByNameAndCode(String dictName,String code){
        if(StringUtils.isBlank(dictName)||StringUtils.isBlank(code)||"null".equals(code)){
            return null;
        }
        String key = "dict:"+dictName+":"+code;
        if (redisTemplate.hasKey(key)){
            return redisTemplate.opsForValue().get(key);
        }
        List<WlyyHospitalSysDictDO> sysDictDOList =  wlyyHospitalSysDictDao.findByDictNameAndDictCode(dictName, code);
        if(sysDictDOList.size()==0){
            return null;
        }
        String value = sysDictDOList.get(0).getDictValue();
        redisTemplate.opsForValue().set(key,value);
        return value;
    }
    //查字典
    public List<Map<String,Object>> findDictsByName(String dictName){
        String  sql = "select t.dict_code code,t.dict_value name from wlyy_hospital_sys_dict t where t.dict_name = '"+dictName+"'";
        return jdbcTemplate.queryForList(sql);
    }
    //查字典
    public MixEnvelop findDictsByNameCode(String modelName,String name,String code,String value,Integer page ,Integer pageSize){
        String  sql = "select t.id as \"id\"," +
                " t.dict_name  as \"dictName\","+
                " t.model_name  as \"modelName\","+
                " t.dict_code  as \"dictCode\","+
                " t.dict_value   as \"dictValue\","+
                " t.sort   as \"sort\","+
                " t.py_code  as \"pyCode\","+
                " t.hospital  as \"hospital\","+
                " t.img_url  as \"imgUrl\","+
                " t.create_time as \"createTime\""+
                " from wlyy_hospital_sys_dict t where 1=1 ";
        if (StringUtils.isNoneBlank(name)){
            sql+=" and t.dict_name like '%"+name+"%'";
        }
        if (StringUtils.isNoneBlank(modelName)){
            sql+=" and t.model_name like '%"+modelName+"%'";
        }
        if (StringUtils.isNoneBlank(code)){
            sql+=" and t.dict_code like '%"+code+"%'";
        }
        if (StringUtils.isNoneBlank(value)){
            sql+=" and t.dict_value like '%"+value+"%'";
        }
        sql+=" and t.dict_code is not null and  t.dict_code != ''";
        if (page==null||pageSize==null){
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            MixEnvelop mixEnvelop = new MixEnvelop();
            mixEnvelop.setTotalCount(list==null?0:list.size());
            mixEnvelop.setDetailModelList(list);
            return  mixEnvelop;
        }else {
            String pageSql = sql + " limit " +(page-1)*pageSize + ","+pageSize;
            List<Map<String,Object>> list = jdbcTemplate.queryForList(pageSql);
            List<Map<String,Object>> listCount = jdbcTemplate.queryForList(sql);
            MixEnvelop mixEnvelop = new MixEnvelop();
            mixEnvelop.setTotalCount(listCount==null?0:listCount.size());
            mixEnvelop.setCurrPage(page);
            mixEnvelop.setPageSize(pageSize);
            mixEnvelop.setDetailModelList(list);
            return  mixEnvelop;
        }
    }
}

+ 185 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/DeviceDetailService.java

@ -0,0 +1,185 @@
package com.yihu.jw.care.service.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.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.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
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 extends BaseJpaService<DeviceDetail, DeviceDetailDao> {
	@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(PatientDevice patientDevice, Date grantTime, boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		int bind = deviceDetail.getIsBinding();
		long adminTeam=0L;
		String hospital = "";
		String isFirstBind = "";
		String hospitalName = "";
		String doctorCode ="";
		String doctorName="";
		String keyType = "1";
		if ("2".equals(patientDevice.getUserType())){
			keyType="2";
		}
		//设备表没有数据则插入一条数据
		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, doctorName,patientDevice.getDeviceSn()});
		}else {
			List<PatientDevice> 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,doctorName,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(PatientDevice 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());
		BaseDoctorDO doctor = doctorDao.findById(patientDevice.getDoctor());
		Device device = deviceDao.findOne(patientDevice.getDeviceId());
		//添加数据到具体字段
		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<PatientDevice> 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});
			//deviceDetailDao.updateUnbindAll(0,deviceSn);
		}
		if (patientDeviceList.size()==1){
			jdbcTemplate.update(sql,new Object[]{1,deviceSn});
			//deviceDetailDao.updateUnbindAll(1,deviceSn);
		}
		if (patientDeviceList.size()>1){
			jdbcTemplate.update(sql,new Object[]{2,deviceSn});
			//deviceDetailDao.updateUnbindAll(2,deviceSn);
		}
	}
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
}

+ 38 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/DeviceService.java

@ -0,0 +1,38 @@
package com.yihu.jw.care.service.device;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.mysql.query.BaseJpaService;
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 extends BaseJpaService<Device, DeviceDao> {
	@Autowired
	private DeviceDao deviceDao;
	/**
	 * 查询设备信息
	 */
	public List<Device> findDeviceByCategory(String categoryCode) {
		return deviceDao.findByCategoryCode(categoryCode);
	}
	/**
	 * 获取设备信息
     */
	public Device findById(String id)
	{
		return deviceDao.findOne(Long.valueOf(id));
	}
}

+ 656 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java

@ -0,0 +1,656 @@
package com.yihu.jw.care.service.device;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.service.wechat.WeiXinAccessTokenUtils;
import com.yihu.jw.care.util.ConcealUtil;
import com.yihu.jw.care.util.MyJdbcTemplate;
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.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
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.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import javax.annotation.PostConstruct;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceService extends BaseJpaService<PatientDevice, PatientDeviceDao> {
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private PatientHealthIndexService healthIndexService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private MyJdbcTemplate myJdbcTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
    //健康问题 高血压
    private static final String gxy = "HP0093";
    //健康问题 糖尿病
    private static final String tnb = "HP0047";
    Map<Integer, String> relations = new HashMap<>();
    @Value("${es.index.Statistics}")
    private String esIndex;
    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
        relations.put(8, "免疫关联");
    }
    /**
     * 验证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(PatientDevice 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) {
            PatientDevice deviceOld = patientDeviceDao.findOne(patientDevice.getId());
            if (deviceOld != null) {
                if (deviceOld.getDeviceSn().equals(sn)) {
                    needVerify = false;
                }
            } else {
                throw new Exception("不存在该条记录!");
            }
        }
        //校验sn码是否被使用
        if (needVerify) {
            PatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
            if (device != null && !device.getId().equals(patientDevice.getId())) {
                throw new Exception("sn码" + sn + "已被使用!");
            }
        }
        patientDevice.setCzrq(new Date());
        patientDevice.setDel(0);
        //当前用户的身份证
        BasePatientDO patient = patientDao.findById(patientDevice.getUser());
        patientDevice.setUserIdcard(patient.getIdcard());
        if(checkDeviceSn(sn)){
            patientDeviceDao.save(patientDevice);
        }else {
            String message = "设备不存在";
            throw new Exception(message);
        }
        return true;
    }
    public void deleteDevices(String deviceSn, String type, String uuid) {
        List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (patientDevices == null || patientDevices.size() == 0) {
            throw new RuntimeException("设备未被绑定!");
        }
        for (PatientDevice patientDevice : patientDevices) {
            patientDeviceDao.delete(patientDevice);
        }
    }
    /**
     * 删除患者设备
     */
    public List<com.alibaba.fastjson.JSONObject> deleteDevice(String id, String uuid) {
        PatientDevice device = patientDeviceDao.findOne(Long.valueOf(id));
        patientDeviceDao.delete(device);
        List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(device.getDeviceSn(), device.getCategoryCode());
        List<com.alibaba.fastjson.JSONObject> objects = new ArrayList<>();
        for (PatientDevice 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());
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.add(object);
        }
        return objects;
    }
    /**
     * 患者设备列表接口(分页)
     */
    public Page<PatientDevice> findByPatient(String patientCode, long id, int pageSize) {
        if (id < 0) {
            id = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("patient", new SearchFilter("user", Operator.EQ, patientCode));
        //filters.put("del", new SearchFilter("del", Operator.EQ, 0));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<PatientDevice> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientDevice.class);
        return patientDeviceDao.findAll(spec, 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 = new PageRequest(page - 1, pagesize);
        List<PatientDevice> list = new ArrayList<>();
        list = patientDeviceDao.findByUser(patientCode, pageRequest);
        if (list != null) {
            //获取设备路径,医生姓名
            List<Device> deviceList = deviceDao.findAll();
            BaseDoctorDO self = doctorDao.findById(doctorCode);
            for (PatientDevice item : list) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(item.getDoctor())) {
                    if (StringUtils.equals(item.getDoctor(), doctorCode)) {
                        map.put("role", 1);//可解绑自己绑定的
                    } else {
                    }
                } 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.findById(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<PatientDevice> findPatientHave(String patient) {
        return patientDeviceDao.findByUser(patient).iterator();
    }
    /**
     * 获取患者设备信息
     **/
    public PatientDevice findById(String id) {
        return patientDeviceDao.findOne(Long.valueOf(id));
    }
    /**
     * 通过sn码获取设备绑定情况
     **/
    public List<Map<String, String>> getDeviceUser(String user, String deviceSn, String type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        List<PatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (list != null) {
            for (PatientDevice 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);
                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<PatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        JSONArray objects = new JSONArray();
        for (PatientDevice patientDevice : list) {
            JSONObject object = new JSONObject(patientDevice);
            BasePatientDO patient = patientDao.findById(patientDevice.getUser());
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.put(object);
        }
        return objects;
    }
    /**
     * 根据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;
    }
    /**
     * 个人信息
     * @param patientCode
     */
    public com.alibaba.fastjson.JSONObject deviceInfo(String deviceSn,String patientCode){
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        List<PatientDevice> device = patientDeviceDao.findByDeviceSn(deviceSn);
        jsonObject.put("sim",device.get(0).getSim());
        jsonObject.put("deviceSn",device.get(0).getDeviceSn());
        jsonObject.put("categoryCode",device.get(0).getCategoryCode());
        jsonObject.put("deviceName",device.get(0).getDeviceName());
        BasePatientDO patient = patientDao.findById(patientCode);
        //个人信息
        jsonObject.put("sex",patient.getSex());//性別,1男,2女
        jsonObject.put("name",null==patient.getName()?"": ConcealUtil.nameOrAddrConceal(patient.getName()));
            jsonObject.put("doctorName","");//全科医生
            jsonObject.put("doctorHealthName","");//全科医生
            jsonObject.put("hospitalName","");//社区
        jsonObject.put("address",null==patient.getAddress()?"":ConcealUtil.nameOrAddrConceal(patient.getAddress()));
        jsonObject.put("idCard",ConcealUtil.idCardConceal(patient.getIdcard()));
        jsonObject.put("age", IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday()));
        return jsonObject;
    }
    /**
     * 设备使用数据
     * @param page
     * @param pageSize
     * @param deviceSn
     * @return
     */
    public com.alibaba.fastjson.JSONObject deviceUseData(Integer page,Integer pageSize,String deviceSn){
        StringBuffer sql = new StringBuffer("SELECT DATE_FORMAT(h.record_date,'%Y-%m-%d %H:%i:%S') recodeDate,h.type,h.value1,h.value2,h.value3,p.name ");
        sql.append("from wlyy_patient_health_index h LEFT JOIN wlyy_patient p on h.user=p.code ");
        if(StringUtils.isNoneBlank(deviceSn)){
            sql.append("where h.device_sn = '"+deviceSn+"' and h.type in (1,2) ");
        }
        sql.append(" ORDER BY record_date desc limit ?,?");
        List<com.alibaba.fastjson.JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),new Object[]{(page-1)*pageSize,pageSize});
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("list",list);
        StringBuffer sqlTotal = new StringBuffer("SELECT count(h.id) c ");
        sqlTotal.append("from wlyy_patient_health_index h LEFT JOIN wlyy_patient p on h.user=p.code ");
        if(StringUtils.isNoneBlank(deviceSn)){
            sqlTotal.append("where h.device_sn = '"+deviceSn+"' ");
        }
        List<com.alibaba.fastjson.JSONObject> list2 = myJdbcTemplate.queryJson(sqlTotal.toString(),new Object[]{});
        if(list2.size()>0){
            json.put("total",list2.get(0).getInteger("c"));
        }else{
            json.put("total",0);
        }
        return json;
    }
    /**
     * 居民 医生搜索
     * @param name
     * @param page
     * @param pageSize
     */
    public List<com.alibaba.fastjson.JSONObject> searchPatient(String name,Integer page,Integer pageSize,String idcards){
        Object o[] = null;
        StringBuffer sql = new StringBuffer("SELECT p.code,p.name,p.address,p.idcard,p.sex,GROUP_CONCAT(label_name) labelName,t.doctor_name doctorName ");
        sql.append("FROM ( SELECT DISTINCT f.* FROM wlyy_patient_device d, wlyy_sign_family f ");
        sql.append("WHERE f.`status` > 0 AND f.patient = d.`user` ) t, wlyy_patient p LEFT JOIN ");
        sql.append("wlyy_sign_patient_label_info l on  p. CODE = l.patient and l.`status`=1 ");
        sql.append("AND l.label_type = 3 and (l.label=2 or l.label=1) WHERE t.patient = p. CODE ");
        if(StringUtils.isNotBlank(name)){
            sql.append(" and (p.`name` like '%"+name+"%' or t.doctor_name like '%"+name+"%') ");
        }
        if(StringUtils.isNotBlank(idcards)){
            idcards = "'"+idcards.replaceAll(",","','")+"'";
            sql.append(" and p.idcard in ("+idcards+") ");
            sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex ");
            o = new Object[]{};
        }else {
            sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex LIMIT ?,? ");
            o = new Object[]{(page-1)*pageSize,pageSize};
        }
        List<com.alibaba.fastjson.JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),o);
        list.forEach(json->{
            json.put("age", IdCardUtil.getAgeForIdcard(String.valueOf(json.get("idcard"))));
            json.put("address", null==json.get("address")?"":ConcealUtil.nameOrAddrConceal(json.get("address").toString()));
            json.put("name", null==json.get("name")?"":ConcealUtil.nameOrAddrConceal(json.get("name").toString()));
            json.put("idcard", null==json.get("idcard")?"":ConcealUtil.idCardConceal(json.get("idcard").toString()));
        });
        return list;
    }
    /**
     * 判断当前值是否在区间内
     */
    private String checkHealthIndex(Double current, Double max) {
        if (current > max ) {
            return "偏高";
        }
        return "偏低";
    }
    /**
     * 名字转换
     * @param type
     * @param value
     * @return
     */
    private String getTypeName(String type,String value){
        String name = "";
        //1早餐前、2早餐后、3午餐前、4午餐后、5晚餐前 6晚餐后 7睡前)
        if ("1".equals(type)){
            switch (value){
                case "1":
                    name = "早餐前";
                    break;
                case "2":
                    name = "早餐后";
                    break;
                case "3":
                    name = "午餐前";
                    break;
                case "4":
                    name = "午餐后";
                    break;
                case "5":
                    name = "晚餐前";
                    break;
                case "6":
                    name = "晚餐后";
                    break;
                default:
                    name = "睡前";
                    break;
            }
        }else if("3".equals(type)){
            name = "收缩压";
        }else {
            name = "舒张压";
        }
        return name;
    }
    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 wlyy.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<PatientDevice> list = patientDeviceDao.findByDeviceSn(deviceSn);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (PatientDevice patientDevice : list) {
            Map<String,Object> infoMap = new HashedMap();
            BasePatientDO patient = patientDao.findById(patientDevice.getUser());
            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(PatientDevice 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();
        //设备是否是第一次被绑定
        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;
    }
    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;
        boolean hasUploadHealth = false;
        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;
    }
    /**
     * 根据设备sn及居民code获取居民有效的设备绑定数据
     * @param deviceSn 设备sn码
     * @return
     */
    public List<PatientDevice> findByDeviceSn(String deviceSn){
       return  patientDeviceDao.findByDeviceSn(deviceSn);
    }
}

+ 1599 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientHealthIndexService.java

@ -0,0 +1,1599 @@
package com.yihu.jw.care.service.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.DevicePatientHealthIndexDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.util.CommonUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
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.SimpleDateFormat;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthIndexService extends BaseJpaService<DevicePatientHealthIndex, DevicePatientHealthIndexDao> {
    private Logger logger = LoggerFactory.getLogger(PatientHealthIndexService.class);
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    // 血糖餐前最小值
    public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;
    // 血糖餐前最大值
    public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;
    // 血糖餐后最小值
    public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;
    // 血糖餐后最大值
    public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;
    // 舒张压最小值
    public static final double HEALTH_STANDARD_SZY_MIN = 60;
    // 舒张压最大值
    public static final double HEALTH_STANDARD_SZY_MAX = 90;
    // 收缩压最小值
    public static final double HEALTH_STANDARD_SSY_MIN = 90;
    // 收缩压最大值
    public static final double HEALTH_STANDARD_SSY_MAX = 140;
    /**
     * 获取居民标准预警值
     *
     * @param type
     * @param patientCode
     * @return
     */
    public JSONObject getealthStandard(Integer type, String patientCode) {
        //血糖校验
        JSONObject json = new JSONObject();
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            Double maxValueBefore = HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = HEALTH_STANDARD_ST_MIN_AFTER;
            json.put("maxValueAfter", maxValueAfter);
            json.put("maxValueBefore", maxValueBefore);
            json.put("minValueBefore", minValueBefore);
            json.put("minValueAfter", minValueAfter);
        }
        //血压校验
        else if (type == 2) {
            // 血压记录,查询患者血压预警值
            Double maxValueSSY = HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = HEALTH_STANDARD_SZY_MIN;
            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 = patientHealthIndexDao.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 Exception("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);
                }
            }
            patientHealthIndexDao.save(result);
            if ("1".equals(result.getType()) || "2".equals(result.getType())) {
                verifyHealthIndex(result.getId());
            }
        } else {
            throw new Exception("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;
    }
    
    
    /**
     * 获取患者某天血糖值
     *
     * @return
     */
    private com.alibaba.fastjson.JSONObject getPatientXT_Json(String patient, String dateString) {
        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" +
                ",record_date" +
                ",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 = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,dateString);
        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();
                Date recordDate = (Date)item.get("record_date");
                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,Integer 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 = patientHealthIndexDao.findOne(id);
        String patientCode = data.getUser();
        //患者信息
        BasePatientDO patient = patientDao.findById(patientCode);
        
        int type = data.getType();
        String msgContent = "";
        String oldMsgContent = "";
        //血糖校验
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            Double maxValueBefore = HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = HEALTH_STANDARD_ST_MIN_AFTER;
            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();
            // 血压记录,查询患者血压预警值
            Double maxValueSSY = HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = HEALTH_STANDARD_SZY_MIN;
            // 收缩压/舒张压校验
            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);
            }
        }
    }
    
    /**
     * 修改体征异常状态
     * @param data
     */
    public void updateStatus(DevicePatientHealthIndex data){
        data.setStatus(1);
        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, Integer page, Integer size,String start, String end){
        return patientHealthIndexDao.findDateList(patient,type,startDate,endDate,page,size);
    }
    
    
    public List<String> findDateListIot1(String patient,Date startDate,Date endDate, Integer page, Integer size,String start, String end){
        
        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);
    }
    
    /********************************************物联网 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码一样的问题未解决!!)
            PatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
            if (device != null) {
                patientCode = device.getUser();
                patient = patientDao.findById(patientCode);
                idcard = device.getUserIdcard();
            }
            DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
        }
        //自输数据
        else {
            patient = patientDao.findById(patientCode);
            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); //身高
                    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");
                    
                    //设置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 Exception("暂不支持该指标!");
                }
            }
            patientHealthIndexDao.save(obj);
        } else {
            throw new Exception("不存在该患者!");
        }
        
        
        return obj;
    }
    
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @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) {
        JSONArray re = new JSONArray();
        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 = 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");
            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 = jdbcTemplate.queryForList(sql);
        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 = HEALTH_STANDARD_ST_MAX_BEFORE;
                Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
                Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
                Double minValueAfter = 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 = HEALTH_STANDARD_SSY_MAX;
                Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
                Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
                Double minValueSZY = 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) {
        JSONArray re = new JSONArray();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
        
        } else {
            // 排序
            Sort sort = new Sort(Direction.DESC, "recordDate");
            PageRequest pageRequest = new PageRequest(page, pageSize, sort);
            String sql = "SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",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);
            List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,type,pageRequest.getOffset(),pageRequest.getPageSize(),start,end);
            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"));
                
                //是否为补传数据(设备上传且测量时间和创建时间不匹配)
                Date recordDate = (Date)map.get("record_date");
                Date createDate = (Date) map.get("createDate");
                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 = new Sort(Direction.DESC, "recordDate");
            PageRequest pageRequest = new PageRequest(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>> 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) {
        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 = new PageRequest(page, pageSize);
            //根据时间过滤排序
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            List<String> dateList = findDateListIot(patient,type, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize(), start, end);
            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 = new PageRequest(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 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 = new Sort(Direction.DESC, "recordDate");
        PageRequest pageRequest = new PageRequest(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;
    }
    
    public List<Map<String, String>> getHealthIndexByPatientAndDate(String patientCode, String deviceSn, String choseDate,int type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        
        // 排序
        Sort sort = new Sort(Direction.DESC, "recordDate");
        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;
    }
    public DevicePatientHealthIndex getHealthIndexById(Long id) {
        return patientHealthIndexDao.findOne(id);
    }
}

+ 42 - 8
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doctor/CareDoctorService.java

@ -1,5 +1,7 @@
package com.yihu.jw.care.service.doctor;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.role.RoleService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.DoctorSpecialDiseaseDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
@ -34,21 +36,29 @@ public class CareDoctorService extends BaseJpaService<BaseDoctorDO, BaseDoctorDa
    private StringRedisTemplate redisTemplate;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private RoleService roleService;
    /**
     * 获取医生详情
     * @return
     */
    public Map<String,Object> doctorInfo(String doctorId){
        String sql = "SELECT d.id,d.name,d.photo,d.introduce,d.mobile,d.idcard,d.sex,h.dept_code deptCode,h.dept_name deptName,d.job_title_code jobTitleCode,d.job_title_name jobTitleName ";
        sql += "from base_doctor d left join base_doctor_hospital h on d.id = h.doctor_code  and h.del = 1" +
                "WHERE d.id = '"+doctorId+"' ";
    public Map<String,Object> doctorInfo(String doctorId,String isRole){
        String sql = "SELECT d.id,d.name,d.level,d.photo,d.introduce,d.expertise,d.mobile,d.idcard,d.sex,h.dept_code deptCode,h.dept_name deptName,d.job_title_code jobTitleCode,d.job_title_name jobTitleName ";
        sql += " ,h.org_code orgCode,org.address orgAddress,h.org_name orgName from base_doctor d left join base_doctor_hospital h on d.id = h.doctor_code  and h.del = 1" +
                " LEFT JOIN base_org org on h.org_code = org.`code`  WHERE d.id = '"+doctorId+"' limit 1 ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map :list){
            String idcard = map.get("idcard").toString();
            map.put("age", IdCardUtil.getAgeForIdcard(idcard));
        Map<String,Object> map = list.get(0);
        String idcard = map.get("idcard").toString();
        map.put("age", IdCardUtil.getAgeForIdcard(idcard));
        if("1".equals(isRole)){
            //获取医生角色和区域权限
            List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(map.get("id").toString());
            map.put("userRole", roleMap);
        }
        return list.get(0);
        return map;
    }
    /**
@ -84,4 +94,28 @@ public class CareDoctorService extends BaseJpaService<BaseDoctorDO, BaseDoctorDa
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,count);
    }
    /**
     * 修改医生服务配置
     * @param jsonObject
     */
    public Boolean update(JSONObject jsonObject)throws Exception{
        //取出数据
        String doctorId = jsonObject.get("doctorId").toString();
        String name = jsonObject.get("name").toString();
        Integer sex = jsonObject.getInteger("sex");
        String introduce = jsonObject.get("introduce").toString();
        String expertise = jsonObject.get("expertise").toString();
        String photo = jsonObject.get("photo").toString();
        BaseDoctorDO doctorDO = baseDoctorDao.findOne(doctorId);
        if (doctorDO!=null){
            doctorDO.setIntroduce(introduce);
            doctorDO.setExpertise(expertise);
            doctorDO.setPhoto(photo);
            doctorDO.setName(name);
            doctorDO.setSex(sex);
            baseDoctorDao.save(doctorDO);
        }
        return true;
    }
}

+ 83 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/label/PatientLableService.java

@ -0,0 +1,83 @@
package com.yihu.jw.care.service.label;
import com.yihu.jw.care.dao.label.WlyyPatientLabelDao;
import com.yihu.jw.care.service.common.DictService;
import com.yihu.jw.care.util.ConstantUtil;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
 * Created by yeshijie on 2021/4/8.
 */
@Service
public class PatientLableService extends BaseJpaService<WlyyPatientLabelDO, WlyyPatientLabelDao> {
    @Autowired
    private WlyyPatientLabelDao patientLabelDao;
    @Autowired
    private DictService dictService;
    /**
     * 按团队查找签约居民的标签统计
     * @param teamCode
     * @return
     */
    public List<Map<String,Object>> findSignPatientLabelNumByTeamCode(String teamCode){
        String sql = "SELECT COUNT(a.id) num,dict.dict_code labelCode,dict.dict_value labelName " +
                " from wlyy_hospital_sys_dict dict " +
                "LEFT JOIN (SELECT DISTINCT l.id,l.label_code  " +
                "from base_service_package_sign_record sr,base_service_package_record r,  " +
                "                base_service_package_item i,base_patient p,wlyy_patient_label l " +
                "                WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id  " +
                "                and i.del = 1 and i.team_code = '"+teamCode+"' " +
                "                and sr.patient = p.id and p.id = l.patient and l.label_type = 1) " +
                "a on dict.dict_code = a.label_code  " +
                "where dict.dict_name = '"+ConstantUtil.DICT_SERVICE_TYPE+"'  " +
                "GROUP BY labelCode,labelName ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:list){
            if(map.get("labelCode")==null){
                list.remove(map);
                break;
            }
        }
        return list;
    }
    /**
     * 按团队和标签查找签约居民
     * @param teamCode
     * @return
     */
    public PageEnvelop<List<Map<String,Object>>> findSignPatientLabelListByTeamCode(String teamCode, String labelCode, String name, int page, int size){
        String sql = "SELECT DISTINCT p.id,p.name,p.photo,p.idcard,p.mobile,p.openid,p.sex " ;
        String countSql = "SELECT count(p.id) ";
        String filters = "from base_service_package_sign_record sr,base_service_package_record r,  " +
                "                base_service_package_item i,base_patient p,wlyy_patient_label l " +
                "                WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id  " +
                "                and i.del = 1 and i.team_code =  '"+teamCode+"' " +
                "                and sr.patient = p.id and p.id = l.patient and l.label_type = 1 and l.label_code =  '"+labelCode+"' ";
        if(StringUtils.isNotBlank(name)){
            filters += " and (p.name like '%"+name+"%' or p.idcard like '%"+name+"%') ";
        }
        String orderBy = " ORDER BY sr.create_time DESC " +
                "LIMIT "+ (page - 1) * size + "," + size;
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql+filters+orderBy);
        for (Map<String,Object> map : list){
            String idcard = map.get("idcard").toString();
            map.put("age", IdCardUtil.getAgeForIdcard(idcard));
        }
        Long count = jdbcTemplate.queryForObject(countSql+filters,Long.class);
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,count);
    }
}

+ 1 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/lifeCare/LifeCareOrderService.java

@ -179,6 +179,7 @@ public class LifeCareOrderService extends BaseJpaService<LifeCareOrderDO, LifeCa
                "  o.number as number, " +
                "  o.patient_expected_serve_time as serveTime, o.doctor, o.doctor_name as doctorName, " +
                "  o.serve_address as address, " +
                "  o.type as type, " +
                "  o.serve_lon as lon, " +
                "  o.serve_lat as lat, " +
                "  o.`status` as status " +

+ 110 - 9
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/patient/CarePatientService.java

@ -1,7 +1,15 @@
package com.yihu.jw.care.service.patient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.label.WlyyPatientLabelDao;
import com.yihu.jw.care.service.common.DictService;
import com.yihu.jw.care.service.sign.ServicePackageService;
import com.yihu.jw.care.util.ConstantUtil;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSignRecordDO;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientMedicardCardService;
import com.yihu.jw.restmodel.web.PageEnvelop;
@ -9,9 +17,12 @@ import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@ -28,16 +39,19 @@ import java.util.Map;
 * @since 1.
 */
@Service
public class CarePatientService<T, R extends CrudRepository> extends BaseJpaService<BasePatientDO, BasePatientDao> {
public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatientDao> {
    @Autowired
    private BasePatientDao basePatientDao;
    private BasePatientDao patientDao;
    @Autowired
    private BasePatientMedicardCardService basePatientMedicardCardService;
    @Autowired
    private ObjectMapper objectMapper;
    private ServicePackageService servicePackageService;
    @Autowired
    private WlyyPatientLabelDao patientLabelDao;
    @Autowired
    private DictService dictService;
    /**
     * 签约记录
@ -53,7 +67,7 @@ public class CarePatientService<T, R extends CrudRepository> extends BaseJpaServ
        String filters = " from base_service_package_sign_record sr,base_service_package_record r, " +
                "base_service_package_item i,base_team_member m,base_patient p " +
                "WHERE sr.id = r.sign_id and r.service_package_id = i.service_package_id " +
                "WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id " +
                "and i.del = 1 and m.team_code = i.team_code and p.id = sr.patient " +
                "and m.doctor_code = '"+doctorId+"' and m.del = '1' ";
@ -81,8 +95,95 @@ public class CarePatientService<T, R extends CrudRepository> extends BaseJpaServ
     * @param patientId
     * @return
     */
    public BasePatientDO findPatientById(String patientId) throws Exception{
        return basePatientDao.findById(patientId);
    public JSONObject findPatientById(String patientId) throws Exception{
        JSONObject res = new JSONObject();
        BasePatientDO patientDO = patientDao.findById(patientId);
        patientDO.setArchiveStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_ARCHIVESTATUS,String.valueOf(patientDO.getArchiveStatus())));
        patientDO.setNationalName(dictService.fingByNameAndCode(ConstantUtil.DICT_NATIONAL,String.valueOf(patientDO.getNational())));
        patientDO.setArchiveTypeName(dictService.fingByNameAndCode(ConstantUtil.DICT_ARCHIVETYPE,String.valueOf(patientDO.getArchiveType())));
        patientDO.setBloodName(dictService.fingByNameAndCode(ConstantUtil.DICT_BLOOD,String.valueOf(patientDO.getBlood())));
        patientDO.setMarriageName(dictService.fingByNameAndCode(ConstantUtil.DICT_MARRIAGE_STATUS,String.valueOf(patientDO.getMarriage())));
        res.put("patient",patientDO);
        String sql = "select * from base_service_package_sign_record where patient = '"+patientId+"' and status = 1 limit 1";
        List<ServicePackageSignRecordDO> signRecordDOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(ServicePackageSignRecordDO.class));
        if(signRecordDOs.size()>0){
            ServicePackageSignRecordDO signRecordDO = signRecordDOs.get(0);
            String signId = signRecordDO.getId();
            List<Map<String,Object>> packageList = servicePackageService.fingdBySignId(signId);
            List<Map<String,Object>> doctorList = servicePackageService.fingdDoctorBySignId(signId,1);
            List<Map<String,Object>> helperList = servicePackageService.fingdDoctorBySignId(signId,2);
            signRecordDO.setDoctorList(doctorList);
            signRecordDO.setHelperList(helperList);
            signRecordDO.setPackageList(packageList);
            res.put("signRecordDO",signRecordDO);
        }
        return res;
    }
    /**
     * 修改居民信息
     * @param jsonData
     * @param doctorId
     */
    @Transactional(rollbackFor = Exception.class)
    public void updPatient(String jsonData,String doctorId) throws Exception{
        JSONObject jsonObject = JSON.parseObject(jsonData);
        BasePatientDO patientDetail = JSONObject.parseObject(jsonObject.getJSONObject("patient").toJSONString(), BasePatientDO.class);
        BasePatientDO patientBrief = patientDao.findById(patientDetail.getId());
        patientBrief.setName(patientDetail.getName());
        patientBrief.setSex(patientDetail.getSex());
        patientBrief.setIdcard(patientDetail.getIdcard());
        patientBrief.setProvinceCode(patientDetail.getProvinceCode());
        patientBrief.setProvinceName(patientDetail.getProvinceName());
        patientBrief.setCityCode(patientDetail.getCityCode());
        patientBrief.setCityName(patientDetail.getCityName());
        patientBrief.setTownCode(patientDetail.getTownCode());
        patientBrief.setTownName(patientDetail.getTownName());
        patientBrief.setLiveProvinceCode(patientDetail.getLiveProvinceCode());
        patientBrief.setLiveProvinceName(patientDetail.getLiveProvinceName());
        patientBrief.setLiveCityCode(patientDetail.getLiveCityCode());
        patientBrief.setLiveCityName(patientDetail.getLiveCityName());
        patientBrief.setLiveTownCode(patientDetail.getLiveTownCode());
        patientBrief.setLiveTownName(patientDetail.getLiveTownName());
        patientBrief.setLiveStreetCode(patientDetail.getLiveStreetCode());
        patientBrief.setLiveStreetName(patientDetail.getLiveStreetName());
        patientBrief.setAddress(patientDetail.getAddress());
        patientBrief.setCommitteeCode(patientDetail.getCommitteeCode());
        patientBrief.setCommitteeName(patientDetail.getCommitteeName());
        patientBrief.setArchiveStatus(patientDetail.getArchiveStatus());
        patientBrief.setSsc(patientDetail.getSsc());
        patientBrief.setMedicareNumber(patientDetail.getMedicareNumber());
        patientBrief.setMobile(patientDetail.getMobile());
        patientBrief.setMobileRemarks(patientDetail.getMobileRemarks());
        patientDao.save(patientBrief);
        JSONObject jsonObject1 = jsonObject.getJSONObject("signRecordDO");
        if(jsonObject1!=null){
            servicePackageService.servicePackageSign(jsonObject1.toJSONString(),doctorId,patientBrief.getId());
            servicePackageService.setPatientServiceItems(patientBrief.getId());
        }
    }
    /**
     * 修改居民标签信息
     * @param jsonData
     * @param patientId
     */
    @Transactional(rollbackFor = Exception.class)
    public void updPatientLabel(String jsonData,String patientId) throws Exception{
        patientLabelDao.deleteByPatientAndLabelType(patientId,"2");
        JSONArray jsonArray = JSON.parseArray(jsonData);
        List<WlyyPatientLabelDO> labelDOList = new ArrayList<>();
        for (int i=0;i<jsonArray.size();i++){
            WlyyPatientLabelDO labelDO = JSONObject.parseObject(jsonArray.getJSONObject(i).toJSONString(), WlyyPatientLabelDO.class);
            labelDO.setPatient(patientId);
            labelDO.setCzrq(new Date());
            labelDO.setLabelType("2");
            labelDOList.add(labelDO);
        }
        patientLabelDao.save(labelDOList);
    }
}

+ 218 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/role/RoleService.java

@ -0,0 +1,218 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.care.service.role;
import com.yihu.jw.care.dao.role.DoctorRoleDao;
import com.yihu.jw.care.dao.role.DoctorRoleRealmDao;
import com.yihu.jw.care.service.doctor.CareDoctorService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.care.role.DoctorRole;
import com.yihu.jw.entity.care.role.DoctorRoleRealm;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 医生角色管理类.
 */
@Service("doctorRoleService")
@Transactional(rollbackFor = Exception.class)
public class RoleService extends BaseJpaService<DoctorRole, DoctorRoleDao> {
    @Autowired
    private DoctorRoleDao doctorRoleDao;
    @Autowired
    private DoctorRoleRealmDao doctorRoleRealmDao;
    private Clock clock = Clock.DEFAULT;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private CareDoctorService doctorInfoService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 获取用户角色列表
     */
    public List<DoctorRole> getUserRole(String user) {
        return doctorRoleDao.findUserRole(user);
    }
    /**
     * 区域去末尾零
     */
    private String getShortArea(String area) {
        char strs[] = area.toCharArray();// 将字符串转化成字符数组
        String last = "";
        for (int i = area.length() - 1; i >= 0; i--) {
            if ('0' == strs[i]) {
                last += "0";
            } else {
                break;
            }
        }
        if (last.length() > 0) {
            return area.substring(0, area.lastIndexOf(last));
        } else {
            return area;
        }
    }
    /**
     * 获取角色区域
     */
    public List<Map<String, String>> getUserRoleAndArea(String user) {
        List<Map<String, String>> re = new ArrayList<>();
        List<DoctorRole> roleList = doctorRoleDao.findUserRole(user);
        int resultLevel = 5;
        for (DoctorRole one : roleList) {
            if(resultLevel>roleConverse(one.getCode())){
                resultLevel=roleConverse(one.getCode());
            }
        }
        if (roleList != null && roleList.size() > 0) {
            //遍历角色
            for (DoctorRole role : roleList) {
                if(role.getCode().length()!=6&&role.getCode().length()!=10){
                    continue;
                }
                Map<String, String> map = new HashMap<>();
                map.put("code", role.getCode());
                map.put("name", role.getName());
                //获取区域权限
                String areaString = "";
                List<DoctorRoleRealm> areaList = doctorRoleRealmDao.findByRoleCode(role.getCode());
                if (areaList != null && areaList.size() > 0) {
                    //获取最大权限区域
                    List<String> areas = new ArrayList<>();
                    List<String> orgs = new ArrayList<>();
                    for (DoctorRoleRealm areaItem : areaList) {
                        String currentArea = areaItem.getAreaCode();
                        int currentLength = currentArea.length();
                        if (currentLength == 6) //区域
                        {
                            areas.add(currentArea);
                        } else {               //机构
                            orgs.add(currentArea);
                        }
                    }
                    //区域权限重复校验
                    for (int i = areas.size() - 1; i >= 0; i--) {
                        String currentArea = areas.get(i);
                        for (int j = 0; j < areas.size() - i - 1; j++) {
                            String shortArea = getShortArea(areas.get(j));
                            if (currentArea.startsWith(shortArea))   //包含则移除
                            {
                                areas.remove(i);
                            }
                        }
                    }
                    //机构权限重复校验
                    for (int m = orgs.size() - 1; m >= 0; m--) {
                        String currentOrg = orgs.get(m);
                        for (int n = 0; n < areas.size() - m - 1; n++) {
                            String shortArea = getShortArea(areas.get(n));
                            if (currentOrg.startsWith(shortArea))   //包含则移除
                            {
                                orgs.remove(m);
                            }
                        }
                    }
                    for (String item : areas) {
                        areaString += item + ",";
                    }
                    for (String item : orgs) {
                        areaString += item + ",";
                    }
                    areaString = areaString.substring(0, areaString.length() - 1);
                }
                map.put("areas", areaString);
                map.put("level",roleConverse(role.getCode())+"");
                map.put("isManage", "1");
                if(resultLevel==roleConverse(role.getCode())){
                    map.put("high", "1");
                }else{
                    map.put("high", "0");
                }
                re.add(map);
            }
        }
        return re;
    }
    /**
     * 角色code转成角色级别
     * @param roleCode 角色code
     * @return 1、省级,2、市级,3、区级,4、机构
     */
    public Integer roleConverse(String roleCode){
        if(roleCode.length()==6){
            if("0".equals(roleCode.substring(3,4))){
                return 1;
            }else if("00".equals(roleCode.substring(4))){
                return 2;
            }else{
                return 3;
            }
        }else{
            return 4;
        }
    }
    public Map<String,Object> findManageUserRole(String doctor){
        String sql ="SELECT " +
                " r.id, " +
                " r.`code`, " +
                " r.`name`, " +
                " r.description " +
                " FROM " +
                " manage_role_user m " +
                " JOIN manage_roles r ON m.role_id = r.id " +
                " WHERE " +
                " m.user_code = '"+doctor+"' and r.`code` ='dispatcher' ";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        if(rs!=null&&rs.size()>0){
            return rs.get(0);
        }
        return null;
    }
    public List<Map<String,Object>> queryDispatcherInfoByHospital(String hospital){
        String sql ="SELECT " +
                " d.`code`, " +
                " d.`name`, " +
                " d.`hospital_name` as hospitalName " +
                " FROM " +
                " manage_role_user m " +
                " JOIN manage_roles r ON m.role_id = r.id " +
                " JOIN (select code,name,hospital_name from wlyy_doctor where hospital = '"+ hospital +"') as d ON m.user_code = d.code" +
                " WHERE " +
                " r.code = 'dispatcher'";
        return jdbcTemplate.queryForList(sql);
    }
}

+ 829 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java

@ -0,0 +1,829 @@
package com.yihu.jw.care.service.security;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.dao.security.*;
import com.yihu.jw.care.service.sign.ServicePackageService;
import com.yihu.jw.care.util.MessageUtil;
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.base.servicePackage.ServicePackageRecordDO;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.entity.care.securitymonitoring.*;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Bing on 2021/4/6.
 */
@Service
public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonitoringOrderDO, SecurityMonitoringOrderDao> {
    @Autowired
    private SecurityMonitoringOrderDao securityMonitoringOrderDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private ServicePackageService servicePackageService;
    @Autowired
    private SecurityMonitoringOrderCancelLogDao securityMonitoringOrderCancelLogDao;
    @Autowired
    private MessageUtil messageUtil;
    @Autowired
    private SecurityMonitoringOrderPatientConfirmLogDao securityMonitoringOrderPatientConfirmLogDao;
    @Autowired
    private SecurityMonitoringDoctorStatusDao doctorStatusDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private SecurityMonitoringConclusionDao securityMonitoringConclusionDao;
    private Logger logger = LoggerFactory.getLogger(SecurityMonitoringOrderService.class);
    public JSONObject createOrder(String jsonData){
        logger.info("创建上门服务jsonData参数:" + jsonData);
        JSONObject result = new JSONObject();
        JSONObject jsonObjectParam;
        try {
            jsonObjectParam = JSONObject.parseObject(jsonData);
        } catch (Exception e) {
            result.put("resultFlag", 0);
            String failMsg = "参数转换成JSON对象异常:" + e.getMessage();
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        SecurityMonitoringOrderDO orderDO = null;
        try {
            orderDO = EntityUtils.jsonToEntity(jsonObjectParam.get("order").toString(), SecurityMonitoringOrderDO.class);
        } catch (Exception e) {
            result.put("resultFlag", 0);
            String failMsg = "服务工单服务基本信息:" + e.getMessage();
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setStatus(1);
        orderDO.setNumber(getRandomIntStr());
        orderDO.setCreateTime(new Date());
        orderDO.setCreateUser(orderDO.getCreateUser());
        orderDO.setCreateUserName(orderDO.getCreateUserName());
        orderDO.setOrderInfo("0");
        if(StringUtils.isEmpty(orderDO.getPatient())){
            result.put("resultFlag", 0);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        BasePatientDO patientDO = basePatientDao.findById(orderDO.getPatient());
        if (patientDO==null){
            result.put("resultFlag", 0);
            String failMsg = "当前服务对象未建档";
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        //签约防走失服务包
        List<ServicePackageRecordDO> signRecords = servicePackageService.servicePackageByPatient(orderDO.getPatient(),"3");
        if (signRecords.size()==0) {
            result.put("resultFlag", 0);
            String failMsg = "当前服务对象未签约防走失服务包,请完成签约后再发起工单!";
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        //已取消的订单也可以申请
        boolean bool = securityMonitoringOrderDao.existsByPatientAndStatusIn(orderDO.getPatient(),
                new Integer[]{SecurityMonitoringOrderDO.Status.waitForSend.getType(),
                        SecurityMonitoringOrderDO.Status.waitForArrive.getType(),
                        SecurityMonitoringOrderDO.Status.signed.getType(),
                        SecurityMonitoringOrderDO.Status.registerSummary.getType(),
                        SecurityMonitoringOrderDO.Status.waitForAdded.getType(),
                });
        if(bool){
            String failMsg = "当前服务对象存在未完成的服务,请先完成该服务!";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setCreateTime(new Date());
        //判断创建预警服务类型,发起类型(1本人发起 2家人待预约 3医生代预约)
        orderDO.setType(3);//发起类型
        orderDO.setServiceStatus("2");
        this.save(orderDO);
        result.put("resultFlag", 1);
        result.put("resultMsg",orderDO);
        return result;
    }
    public JSONObject getSecurityOrderDetail(String orderID){
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO orderDO = securityMonitoringOrderDao.findOne(orderID);
        if (orderDO==null){
            String failMsg = "工单不存在!";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        Integer conclusionStatus = Integer.valueOf(orderDO.getConclusionStatus()==null?"0":(orderDO.getConclusionStatus()+""));
        String conclusionStatusName = "";
        switch (conclusionStatus){
            case 1:conclusionStatusName="待补录";break;
            case 2:conclusionStatusName="已登记";break;
        }
        if (conclusionStatus==2){
            SecurityMonitoringConclusionDO conclusionDO = securityMonitoringConclusionDao.findByOrderId(orderDO.getId());
            if (conclusionDO!=null){
                orderDO.setMonitoringConclusion(conclusionDO);
            }
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(orderDO, SerializerFeature.WriteMapNullValue));
        jsonObject.put("conclusionStatusName",conclusionStatusName);
        Integer statustemp = Integer.valueOf(orderDO.getStatus()+"");
        String statusName = "";
        switch (statustemp){
            case -1:statusName="已取消";break;
            case 1:statusName="待处置";break;
            case 2:statusName="前往居民定位";break;
            case 3:statusName="已签到";break;
            case 4:statusName="已登记小结";break;
            case 5:statusName="待补录";break;
            case 6:statusName="待评价";break;
            case 7:statusName="已完成";break;
        }
        jsonObject.put("statusName",statusName);
        result.put("resultFlag", 1);
        result.put("resultMsg",jsonObject);
        return result;
    }
    public JSONArray getSecurityOrderList(String doctor, String patient, String status, Integer page, Integer pageSize){
        String sql = " select p.id patientCode,p.name,p.sex,p.idcard,ord.id orderId,ord.number,ord.serve_desc,ord.create_time,ord.`status`,ord.doctor," +
                "ord.doctor_name,ord.patient_phone,ord.conclusion_status from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
                "where 1=1 ";
        if (StringUtils.isNotBlank(doctor)){
            sql +=" and ord.doctor = '"+doctor+"' ";
        }
        if (StringUtils.isNotBlank(patient)){
            sql+=" and ord.patient_name= like '%"+patient+"%' ";
        }
        if (StringUtils.isNotBlank(status)){
            sql+=" and ord.status='"+Integer.parseInt(status)+"' ";
        }
        if (StringUtils.isBlank(status)||status.equals("1")){//状态为空或待处置时 查询该医生签约团队居民的预警
        }
        sql+=" order by ord.create_time desc limit " + (page*pageSize) + "," + pageSize;
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql);
        JSONArray result = new JSONArray();
        for (Map<String,Object>one:sqlResult){
            JSONObject tmp = new JSONObject();
            tmp.put("patientCode",one.get("patientCode"));
            tmp.put("patientName",one.get("name"));
            tmp.put("sex",one.get("sex"));
            tmp.put("idcard",one.get("idcard"));
            tmp.put("number",one.get("number"));
            tmp.put("id",one.get("orderId"));
            tmp.put("serveDesc",one.get("serve_desc"));
            Date date = (Date)one.get("create_time");
            tmp.put("createTime", DateUtil.dateToStr(date,"yyyy-MM-dd hh:mm:ss"));
            tmp.put("status",one.get("status"));
            tmp.put("doctor",one.get("doctor"));
            tmp.put("doctorName",one.get("doctor_ame"));
            tmp.put("patientPhone",one.get("patient_phone"));
            tmp.put("conclusionStatus",one.get("conclusion_status"));
            Integer conclusionStatus = Integer.valueOf(one.get("conclusion_status")==null?"0":(one.get("conclusion_status")+""));
            String conclusionStatusName = "";
            switch (conclusionStatus){
                case 1:conclusionStatusName="待补录";break;
                case 2:conclusionStatusName="已登记";break;
            }
            tmp.put("conclusionStatusName",conclusionStatusName);
            Integer statustemp = Integer.valueOf(one.get("status")+"");
            String statusName = "";
            switch (statustemp){
                case -1:statusName="已取消";break;
                case 1:statusName="待处置";break;
                case 2:statusName="前往居民定位";break;
                case 3:statusName="已签到";break;
                case 4:statusName="已登记小结";break;
                case 5:statusName="待补录";break;
                case 6:statusName="待评价";break;
                case 7:statusName="已完成";break;
            }
            tmp.put("statusName",statusName);
            result.add(tmp);
            Integer age  = IdCardUtil.getAgeForIdcard(tmp.getString("idcard"));
            tmp.put("age",age);
            //患者设备
            List<PatientDevice> devices = patientDeviceDao.findAllByUser(tmp.get("patientCode").toString());
            if (devices.size()>0){
                tmp.put("deviceFlag","1");
            }
            else {
                tmp.put("deviceFlag","0");
            }
        }
        return result;
    }
    /**
     * 系统更新医生上门服务工单状态
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusBySystem(String doctor, Integer dispatchOrderStatus) {
        SecurityMonitoringDoctorStatusDo doctorSwitch = doctorStatusDao.findByDoctor(doctor);
        if (null != doctorSwitch) {
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setUpdateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
        } else {
            doctorSwitch = new SecurityMonitoringDoctorStatusDo();
            doctorSwitch.setDoctor(doctor);
            doctorSwitch.setStatus(dispatchOrderStatus);
            doctorSwitch.setCreateTime(new Date());
            doctorSwitch.setCreateUser("System");
            doctorSwitch.setCreateUserName("System");
        }
        doctorStatusDao.save(doctorSwitch);
    }
    public SecurityMonitoringOrderDO acceptOrder1(String orderId,String doctor) throws Exception{
        SecurityMonitoringOrderDO doorServiceOrder = securityMonitoringOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
        }
        doorServiceOrder.setStatus(SecurityMonitoringOrderDO.Status.waitForArrive.getType()); //
        this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 3);//待服务
        doorServiceOrder.setServiceResponseTime(new Date());
        //新增工单医生关联关系
//        JSONObject jsonObjectParam = new JSONObject();
//        JSONObject doc = new JSONObject();
//        doc.put("doctor",doorServiceOrder.getDoctor());
//        doc.put("doctorName",doorServiceOrder.getDoctorName());
//        doc.put("hospitalLevel",hospitalLevel);
//        doc.put("doctorJobCode",jobCode);
//        doc.put("doctorJobName",jobCodeName);
//        JSONArray docArr = new JSONArray();
//        docArr.add(doc);
//        jsonObjectParam.put("doctorArr",docArr);
        // 无费用
//        if (wlyyDoorServiceOrderService.orderWithDoctorAdd(new JSONObject(), jsonObjectParam, doorServiceOrder)) return null;
        securityMonitoringOrderDao.save(doorServiceOrder);
        systemMessageDao.orderMessageDelByType(doorServiceOrder.getDoctor(),orderId,"607");
        if(doorServiceOrder.getType() == null|| doorServiceOrder.getType() != 3) {
//            //获取咨询
//            ConsultTeam consultTeam = consultTeamDao.queryByRelationCode(orderId);
//            consultTeam.setDoctor(doorServiceOrder.getDoctor());
//            consultTeam.setDoctorName(doorServiceOrder.getDoctorName());
//            consultTeamDao.save(consultTeam);
//
//            String sessionId = doorServiceOrder.getPatient() + "_" + consultTeam.getConsult() + "_" + doorServiceOrder.getNumber() + "_" + consultTeam.getType();
//            //成功创建服务工单后,居民所在机构调度员向居民发起一条通知服务消息
//
//            // 发送IM消息通知患者医生已接单
//            String noticeContent = "我已接受您的服务工单预约," + doorServiceOrder.getDoctorName() + "医生正在为您服务!";
////        imUtill.sendIntoTopicIM(doorServiceOrder.getDoctor(), sessionId, consultTeam.getConsult(), noticeContent, doorServiceOrder.getProxyPatient(), doorServiceOrder.getProxyPatientName());
//            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "1", noticeContent);
//            // 发送居民上门服务简要信息
//            JSONObject orderInfoContent = wlyyDoorServiceOrderService.queryOrderCardInfo(doorServiceOrder);
//            orderInfoContent.put("re_msg_type", 0);
//            wlyyDoorServiceOrderService.qucikSendIM(doorServiceOrder.getId(), doorServiceOrder.getDispatcher(), "智能助手", "2101", orderInfoContent.toJSONString());
        }
        return doorServiceOrder;
    }
    /**
     * 接单
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject acceptOrder(String orderId,String doctor) throws Exception {
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO doorServiceOrderDO = securityMonitoringOrderDao.findOne(orderId);
        if(null == doorServiceOrderDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前工单不存在,id:" + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        if (doorServiceOrderDO.getStatus()!=1){//待处置工单才可进行接单操作
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前工单已被取消或接收:" + orderId;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        SecurityMonitoringDoctorStatusDo doctorStatusDo = doctorStatusDao.findByDoctor(doctor);
        BaseDoctorDO doctorVO = baseDoctorDao.findById(doctor);
        if (null == doctorStatusDo) {
            doctorStatusDo =new SecurityMonitoringDoctorStatusDo();
            doctorStatusDo.setDoctor(doctor);
            doctorStatusDo.setStatus(2);
            doctorStatusDo.setCreateTime(new Date());
            doctorStatusDo.setCreateUser(doctor);
            doctorStatusDo.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
            doctorStatusDao.save(doctorStatusDo);
        }
        SecurityMonitoringDoctorStatusDo doorDoctorStatusDO = doctorStatusDao.queryByDoctorAndStatusIn(doctor,new Integer[]{SecurityMonitoringDoctorStatusDo.Status.waitForSend.getType(),
                SecurityMonitoringDoctorStatusDo.Status.waitForAccept.getType(),
                SecurityMonitoringDoctorStatusDo.Status.waitForServe.getType(),
                SecurityMonitoringDoctorStatusDo.Status.serving.getType(),
        });
        if(null == doorDoctorStatusDO){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前接单的医生不存在或禁止接单,doctor:" + doctor;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        BaseDoctorDO doctorDO= baseDoctorDao.findById(doctor);
        doorServiceOrderDO.setDoctor(doctor);
        doorServiceOrderDO.setDoctorName(doctorDO.getName());
        doorServiceOrderDO.setDoctorType("医生");
        doorServiceOrderDO.setStatus(SecurityMonitoringOrderDO.Status.waitForArrive.getType());//前往居民定位
        doorServiceOrderDO.setUpdateUser(doctor);
        doorServiceOrderDO.setUpdateUserName(doctorDO.getName());
        securityMonitoringOrderDao.save(doorServiceOrderDO);
        // 派单时,把医生拉入会话,作为其中一个成员,医生拒单时,退出会话
        //TODO 接单时创建两个人聊天
//        ConsultDo consult = consultDao.queryByRelationCode(orderId);
//        String sessionId = doorServiceOrderDO.getPatient() + "_" + consult.getId() + "_" + doorServiceOrderDO.getNumber() + "_" + consult.getType();
//        imUtill.updateParticipantNew(sessionId,doctor,null);
        // 工单状态变更记录
//        WlyyDoorProcessLogDO processLogDO = new WlyyDoorProcessLogDO();
//        processLogDO.setOrderId(orderId);
//        processLogDO.setStatus(WlyyDoorServiceOrderDO.Status.waitForAccept.getType());
//        processLogDO.setDispatcher(dispatcher);
//        processLogDO.setDispatcherName(dispathcherName);
//        processLogDO.setCreateTime(new Date());
//        wlyyDoorProcessLogDao.save(processLogDO);
        // 发送IM消息通知患者医生已派单
//        String noticeContent = "已转派"+doorServiceOrderDO.getDoctorName()+"医生为您服务,请耐心等待医生接单";
//        this.qucikSendIM(doorServiceOrderDO.getId(), dispatcher, "智能助手","1", noticeContent);
        SecurityMonitoringOrderDO doorServiceOrder = acceptOrder1(orderId, doctor);
        if(doorServiceOrder==null){
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            String failMsg = "当前接单的医生不存在或禁止接单,doctor:" + doctor;
            result.put(ResponseContant.resultMsg, failMsg);
            logger.error(failMsg);
            return result;
        }
        result.put(ResponseContant.resultFlag, ResponseContant.success);
        result.put(ResponseContant.resultMsg, doorServiceOrder);
        // 发送微信模板消息通知患者医生已接单
//        BasePatientDO patient = basePatientDao.findById(doorServiceOrder.getPatient());//
        // 获取微信模板
//        ConsultDo consult = consultDao.queryByRelationCode(orderId);
//        try {
//            JSONObject json = new JSONObject();
//            if(consult != null) {
//                json.put("consult", consult.getId());
//            }
//            String first = "key1,您好!您的上门预约服务已由【key2】医生接单了";
//            first = first.replace("key1",(patient.getName()==null?"":patient.getName()));
//            first = first.replace("key2", null != doorServiceOrder.getDoctorName() ? doorServiceOrder.getDoctorName() : "");
//            List<BasePatientWechatDo> basePatientWechatDos = basePatientWechatDao.findByWechatIdAndPatientId(wxId,patient.getId());
//            String openId = basePatientWechatDos.get(0).getOpenid();
//            messageUtil.putTemplateWxMessage(wxId,"template_process_feedback","smyyyjjd",openId,first,null,null,30,json,DateUtil.dateToChineseDate(new Date()),"上门服务已接单");
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.error(e.getMessage());
//        }
        //  待接单消息设为已操作, 434 医生接单-- 王五接受了服务工单12345678
        messageUtil.createMessage("医生接单","634",doorServiceOrder.getPatient(),doorServiceOrder.getPatientName(),
                doorServiceOrder.getId(), doorServiceOrder.getDoctor(),doorServiceOrder.getDoctorName() ,null, doorServiceOrder.getDoctorName() + "接受了服务工单"+ doorServiceOrder.getNumber());
        return result;
    }
    /**
     * 取消工单
     * @param orderId
     * @param reason
     * @return
     */
    public JSONObject cancelOrder(String orderId,int type,String reason,String doctor){
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO orderDO = securityMonitoringOrderDao.findOne(orderId);
        if(null == orderDO){
            String failMsg = "【取消工单】该工单不存在:," + orderId;
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        //接单前可取消工单
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        if (doctorDO==null){
            String failMsg = "【取消工单】操作医生不存在," + orderId;
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        if(orderDO.getStatus() > SecurityMonitoringOrderDO.Status.waitForSend.getType()){
            String failMsg = "只有医生接单前的工单才可取消:," + orderId;
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        orderDO.setDoctor(doctor);
        orderDO.setDoctorName(doctorDO.getName());
        orderDO.setCancelType(type);
        orderDO.setCancelTime(new Date());
        orderDO.setCancelReason(reason);
        orderDO.setStatus(SecurityMonitoringOrderDO.Status.cancel.getType());
        this.save(orderDO);
       if(type == SecurityMonitoringOrderDO.CancelType.patient.getType()){                   //居民取消,消息列表也应该不显示
           messageUtil.updateSecurityMonitoringOrderMessage(orderDO,new String[]{"602","603"},"patientCancel");
        }
        //保存取消记录
        SecurityMonitoringOrderCancelLog cancelLogDO = new SecurityMonitoringOrderCancelLog();
        cancelLogDO.setOrderId(orderId);
        cancelLogDO.setPatient(orderDO.getPatient());
        cancelLogDO.setCancelType(type);
        cancelLogDO.setCancelReason(reason);
        cancelLogDO.setTime(orderDO.getCancelTime());
        securityMonitoringOrderCancelLogDao.save(cancelLogDO);
        //保存居民确认取消记录
        JSONObject confirmInfo = new JSONObject();
        confirmInfo.put("orderId",orderId);
        confirmInfo.put("patient",orderDO.getPatient());
        confirmInfo.put("patientName",orderDO.getPatientName());
        confirmInfo.put("type",4);
        confirmInfo.put("description",reason);
        JSONObject confirmInfoJson = new JSONObject();
        confirmInfoJson.put("confirmInfo",confirmInfo);
        this.orderWithConfirmLogAdd(result,confirmInfo,orderId);
//        Consult consult = consultDao.queryByRelationCode(orderId);
//        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
//
//        Patient patient = patientInfoService.findByCode(orderDO.getPatient());
//        WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","smyyyqx");
//        String first = templateConfig.getFirst().replace("key1", null != patient.getName() ? patient.getName() : "");
//        org.json.JSONObject json = new org.json.JSONObject();
//        json.put("first", first);
//        json.put("keyword1", DateUtil.dateToStrShort(new Date()));
//        json.put("keyword2", "上门预约已取消");
//        json.put("url", templateConfig.getUrl());
//        json.put("remark", templateConfig.getRemark());
//        if(consult != null) {
//            json.put("consult", consult.getCode());
//        }else {
//            json.put("id", orderDO.getId());
//        }
//        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
        result.put("resultFlag", 1);
        result.put("resultMsg", orderDO);
        return result;
    }
    @Transactional(rollbackFor = Exception.class)
    public boolean orderWithConfirmLogAdd(JSONObject result, JSONObject jsonObjectParam, String orderId) {
        // 确认信息
        JSONObject confirmInfo = jsonObjectParam.getJSONObject("confirmInfo");
        if (null != confirmInfo) {
            SecurityMonitoringOrderPatientConfirmLog confirmLogDO = null;
            try {
                confirmLogDO = EntityUtils.jsonToEntity(confirmInfo.toString(), SecurityMonitoringOrderPatientConfirmLog.class);
            } catch (Exception e) {
                String failMsg = "工单关联【居民确认操作日志记录】时," + e.getMessage();
                result.put("resultFlag", 0);
                result.put("resultMsg", failMsg);
                logger.error(failMsg);
                return true;
            }
            confirmLogDO.setOrderId(orderId);
            confirmLogDO.setCreateTime(new Date());
            try {
                securityMonitoringOrderPatientConfirmLogDao.save(confirmLogDO);
            } catch (Exception e) {
                String failMsg = "保存工单关联的【居民确认操作日志记录】时:," + e.getMessage();
                result.put("resultFlag", 0);
                result.put("resultMsg", failMsg);
                logger.error(failMsg);
                return true;
            }
        }
        return false;
    }
    /**
     * 签到保存
     * @param orderId
     * @param signTime
     * @param signWay
     * @param signLocation
     * @param signImg
     * @return
     */
    public SecurityMonitoringOrderDO signIn(String orderId, String signTime, Integer signWay, String signLocation,
                                         String signImg, String twoDimensionalCode,String doctorId) throws Exception {
        SecurityMonitoringOrderDO doorServiceOrder = securityMonitoringOrderDao.findOne(orderId);
        doorServiceOrder.setDoctorSignTime(DateUtil.strToDate(signTime));
        doorServiceOrder.setDoctorSignWay(signWay);
        // 签到方式-2扫码时,需要去解析地址
        doorServiceOrder.setDoctorSignLocation(signLocation);
        doorServiceOrder.setDoctorSignImg(org.apache.commons.lang.StringUtils.isEmpty(signImg) ? null : signImg);
        doorServiceOrder.setStatus(SecurityMonitoringOrderDO.Status.signed.getType());
        if(signWay == 4 ){//扫码签到
            if (twoDimensionalCode.equals(doorServiceOrder.getNumber())){
                this.setUpdateColumnInfo(doorServiceOrder);
                doorServiceOrder = securityMonitoringOrderDao.save(doorServiceOrder);
                // 修改医生上门服务工单状态 4服务中
                this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 4);//服务中
                return doorServiceOrder;
            }else {
                logger.info("扫码签到失败");
                return null;
            }
        }else {
            this.setUpdateColumnInfo(doorServiceOrder);
            doorServiceOrder = securityMonitoringOrderDao.save(doorServiceOrder);
            // 修改医生上门服务工单状态 4服务中
            this.updateDispatchStatusBySystem(doorServiceOrder.getDoctor(), 4);
            return doorServiceOrder;
        }
    }
    /**
     * 根据接单医生code获取最近一次服务orderId
     * @param doctor
     * @return
     */
    public String getOrderIdByDoctor(String doctor) {
        String sql = "SELECT id as orderId from base_security_monitoring_order where doctor=? and status in(2,3,4,5,6,7) ORDER BY update_time desc,create_time desc, status ASC limit 1";
        String orderId = jdbcTemplate.queryForObject(sql, String.class, new Object[]{doctor});
        return orderId;
    }
    /**
     * 编辑保存服务工单小结
     * @return
     * @throws Exception
     */
    public SecurityMonitoringConclusionDO updateDoorConclusion(Integer manageStatus,String orderId,String conclusion,Integer examPapeStatus) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        SecurityMonitoringConclusionDO doorConclusion = new SecurityMonitoringConclusionDO();
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        if (one==null){
        }
        BaseDoctorDO doctorVO = baseDoctorDao.findById(one.getDoctor());
        if (doorConclusion != null && org.apache.commons.lang.StringUtils.isNotEmpty(doorConclusion.getId())) {
            doorConclusion.setUpdateTime(new Date());
            doorConclusion.setUpdateUser(one.getDoctor());
            doorConclusion.setUpdateUserName(null != doctorVO ? doctorVO.getName() : null);
        } else {
            doorConclusion.setCreateTime(new Date());
            doorConclusion.setUpdateTime(new Date());
            doorConclusion.setCreateUser(one.getDoctor());
            doorConclusion.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        }
        securityMonitoringConclusionDao.save(doorConclusion);
        // 设置是否需要上传补录报告
        one.setStatus(SecurityMonitoringOrderDO.Status.registerSummary.getType());//已登记服务小结
        one.setExamPaperStatus(examPapeStatus);
        one.setConclusionStatus(2);
        securityMonitoringOrderDao.save(one);
        return doorConclusion;
    }
    /**
     * 跳过登记服务小结
     * @param orderId
     */
    public void cancelConclusion(String orderId) {
        securityMonitoringOrderDao.updateConclusionStatus(orderId);
    }
    /**
     * 统计居民已经服务的次数
     * @param patient
     * @return
     */
    public Integer countPatientDoorTimes(String patient){
        Integer count = 0;
        String sql = "SELECT count(o.id) as count FROM base_security_monitoring_order o  where  o.patient = '" + patient + "' and status>3 ";
        count = jdbcTemplate.queryForObject(sql,Integer.class);
        return count;
    }
    /**
     * 根据orderId获取工单服务小结
     * @param orderId
     * @return
     */
    public SecurityMonitoringConclusionDO getDoorConclusion(String orderId){
        SecurityMonitoringConclusionDO doorConclusion = securityMonitoringConclusionDao.findByOrderId(orderId);
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        if (doorConclusion==null&&one!=null) {
            doorConclusion = new SecurityMonitoringConclusionDO();
            doorConclusion.setOrderId(one.getId());
            doorConclusion.setPatient(one.getPatient());
            doorConclusion.setPatientName(one.getPatientName());
            doorConclusion.setDoctor(one.getDoctor());
            doorConclusion.setDoctorName(one.getDoctorName());
        }
        return doorConclusion;
    }
    public SecurityMonitoringOrderDO saveOrderFinishBydoctor(String orderId ,String finishImg) throws Exception {
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        one.setDoctorConfirmFinishImg(finishImg);
        one.setStatus(SecurityMonitoringOrderDO.Status.complete.getType());
        one.setDoctorConfirmFinishTime(new Date());
        // 更新记录
        this.setUpdateColumnInfo(one);
        securityMonitoringOrderDao.save(one);
        SecurityMonitoringOrderDO doorServiceOrderDO = this.getDoorServiceOrderById(orderId);
        // 发送微信通知  待付款
        BasePatientDO patient = basePatientDao.findById(one.getPatient());
        // 获取微信模板 smfwdwk-上门服务待付款
//        Consult consult = consultDao.queryByRelationCode(orderId);
        try {
//            WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_process_feedback","fwyspf");
//            String first = templateConfig.getFirst();
//            first = first.replace("key1", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm"));
//            first = first .replace("key2", null != one.getDoctorName() ? one.getDoctorName() : "");
//            org.json.JSONObject json = new org.json.JSONObject();
//            json.put("first", first);
//            json.put("keyword1", DateUtil.dateToStrShort(new Date()));
//            json.put("keyword2", "服务医生评分");
//            json.put("url", templateConfig.getUrl());
//            json.put("remark", templateConfig.getRemark());
//            json.put("id",orderId);
//            //json.put("consult",consult.getCode());
//            WlyyDoorCommentDO wlyyDoorCommentDO = this.DoorCommentDao.selectCommentDoctor(patient.getCode(),orderId);
//            String finish="";
//            if(wlyyDoorCommentDO!=null){
//                finish = "0";
//                json.put("finish",finish);
//            }else {
//                finish = "1";
//                json.put("finish",finish);
//            }
//            pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 31, patient.getOpenid(), patient.getName(), json);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return doorServiceOrderDO;
    }
    /**
     * 根据id获取服务工单信息
     * @param id
     * @return
     */
    public SecurityMonitoringOrderDO getDoorServiceOrderById(String id) throws Exception {
        SecurityMonitoringOrderDO doorServiceOrder = securityMonitoringOrderDao.findOne(id);
        if (null == doorServiceOrder) {
            return null;
        }
        BasePatientDO patient = basePatientDao.findById(doorServiceOrder.getPatient());
        if (patient != null) {
            String sex = IdCardUtil.getSexForIdcard_new(patient.getIdcard());
            int age = IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday());
            doorServiceOrder.setSex("1".equals(sex) ? "男" : "2".equals(sex) ? "女" : "未知");
            doorServiceOrder.setAge(age);
            doorServiceOrder.setPhoto(patient.getPhoto());
//            String typeValues = this.getTypeValueByPatientCode(patient.getCode());
//            doorServiceOrder.setTypeValue(typeValues);
        }
        // 获取服务次数
        Integer count = 1;//本年服务次数 一年只能1次
        Integer times = countPatientDoorTimes(doorServiceOrder.getPatient());//服务次数
//        List<WlyyDoorDoctorDO> djDetailList = this.djDetailList(id,level,times);
//        doorServiceOrder.setDjDetailList(djDetailList);
//        List<Map<String, Object>> feeDetailDOS = this.getDoorFeeDetailGroupByStatus(id);
//        String jsonData = this.serverPackagePriceByOrderId(id);
//        if (null != feeDetailDOS && feeDetailDOS.size() > 0) {
//            // 设置服务项及费用信息
//            doorServiceOrder.setDoorFeeDetailList(feeDetailDOS);
//            //计算扣服务包后应付的服务项费用
//            /*Map<String, Object> map = this.countServerPackagePrice(jsonData, doorServiceOrder.getPatient());
//            BigDecimal cashPrice = this.calculateCash(String.valueOf(map.get("cashPrice")), id, level, times);
//            WlyyDoorServiceOrderDO wlyyDoorServiceOrderDO = this.doorServiceOrderDao.findOne(id);
//            if(wlyyDoorServiceOrderDO.getTotalFee()!=cashPrice){
//                wlyyDoorServiceOrderDO.setTotalFee(cashPrice);
//                wlyyDoorServiceOrderService.save(wlyyDoorServiceOrderDO);
//            }
//            map.put("cashPrice", cashPrice);
//            doorServiceOrder.setServiceCost(map);*/
//        }
        // 服务工单关联的医护人员
//        List<Map<String, Object>> doorServiceDoctors = this.getDoorServiceDoctor(id);
//        if (null != doorServiceDoctors && doorServiceDoctors.size() > 0) {
//            doorServiceOrder.setDoctors(doorServiceDoctors);
//        }
        // 设置医生出诊费信息,先获取工单出诊医生
        /*List<WlyyDoorDoctorDO> doorDoctorDOList = doorDoctorDao.findByOrderId(id);
        if (doorDoctorDOList != null && doorDoctorDOList.size() > 0) {
            Map<String,String> jobName = new HashMap<>();
            Map<String,String> jobCode = new HashMap<>();
            List<Integer> levels = new ArrayList<>();
            for(WlyyDoorDoctorDO doorDoctorDO : doorDoctorDOList){
                jobName.put(doorDoctorDO.getDoctor(),doorDoctorDO.getDoctorJobName());
                jobName.put(doorDoctorDO.getDoctor(),doorDoctorDO.getDoctorJobCode());
                levels.add(doorDoctorDO.getHospitalLevel());
            }
            List<Map<String, Object>> jobFeeList = dmJobService.getJobFeeList(jobCode, jobName, levels, times);
            doorServiceOrder.setVisitCost(jobFeeList);
        }*/
        //获取咨询 //TODO 获取咨询
//        Consult consult = consultDao.queryByRelationCode(id);
//        if (null != consult) {
//            doorServiceOrder.setSessionId(doorServiceOrder.getPatient() + "_" + consult.getCode() + "_"  + doorServiceOrder.getNumber() +  "_" +  consult.getType());
//        }
        // 设置服务小结
        SecurityMonitoringConclusionDO doorConclusion = this.getDoorConclusion(id);
        doorServiceOrder.setMonitoringConclusion(doorConclusion);
        return doorServiceOrder;
    }
    private String getRandomIntStr(){
        Random rand = new Random();
        int i = rand.nextInt(); //int范围类的随机数
        i = rand.nextInt(100); //生成0-100以内的随机数
        i = (int)(Math.random() * 100000000); //0-100以内的随机数,用Matn.random()方式
        return String.valueOf(i);
    }
    private void setUpdateColumnInfo(SecurityMonitoringOrderDO one) {
        one.setUpdateTime(new Date());
        one.setUpdateUser(one.getDoctor());
        one.setUpdateUserName(one.getDoctorName());
    }
}

+ 55 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/ArchiveService.java

@ -1,9 +1,14 @@
package com.yihu.jw.care.service.sign;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.apply.PatientBedApplyDao;
import com.yihu.jw.care.dao.sign.ArchiveDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.apply.PatientBedApplyDo;
import com.yihu.jw.entity.care.archive.ArchiveDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientMedicareCardDao;
@ -11,6 +16,7 @@ import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@ -37,6 +43,10 @@ public class ArchiveService extends BaseJpaService<ArchiveDO, ArchiveDao> {
    private BasePatientMedicareCardDao patientMedicareCardDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientBedApplyDao patientBedApplyDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    /**
@ -49,8 +59,25 @@ public class ArchiveService extends BaseJpaService<ArchiveDO, ArchiveDao> {
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }
    public PageEnvelop<List<Map<String,Object>>> archiveList(String doctorId, int page, int size,Integer signStatus){
        String sql = "SELECT a.archive_time,p.idcard,p.mobile,p.name,p.sex,p.id ";
    public JSONObject getArchiveTopNum(String doctorId){
        JSONObject json = new JSONObject();
        json.put("signTotal",0);
        json.put("unSignTotal",0);
        String sql = " SELECT COUNT(*) num,CAST(sign_status as char) sign_status  from wlyy_archive WHERE doctor_code =  '"+doctorId+"'GROUP BY sign_status";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:list){
            if("1".equals(String.valueOf(map.get("sign_status")))){
                json.put("signTotal",map.get("num"));
            }
            if("0".equals(String.valueOf(map.get("sign_status")))){
                json.put("unSignTotal",map.get("num"));
            }
        }
        return json;
    }
    public PageEnvelop<List<Map<String,Object>>> archiveList(String doctorId, int page, int size,Integer signStatus,String name){
        String sql = "SELECT a.create_time,p.idcard,p.mobile,p.name,p.sex,p.id ";
        String countSql = "SELECT count(*) ";
        String filters = "from wlyy_archive a,base_patient p " +
@ -59,14 +86,17 @@ public class ArchiveService extends BaseJpaService<ArchiveDO, ArchiveDao> {
        if(signStatus!=null){
            filters += " and a.sign_status = "+signStatus;
        }
        if(StringUtils.isNotBlank(name)){
            filters += " and p.name like '%"+name+"%'";
        }
        String orderBy = " ORDER BY a.archive_time DESC " +
        String orderBy = " ORDER BY a.create_time DESC " +
                "LIMIT "+ (page - 1) * size + "," + size;
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql+filters+orderBy);
        for (Map<String,Object> map :list){
            String idcard = map.get("idcard").toString();
            map.put("archiveTime", map.get("archive_time").toString().substring(0,19));
            map.put("createTime", map.get("create_time").toString().substring(0,19));
            map.put("age", IdCardUtil.getAgeForIdcard(idcard));
        }
        Long count = jdbcTemplate.queryForObject(countSql+filters,Long.class);
@ -104,7 +134,18 @@ public class ArchiveService extends BaseJpaService<ArchiveDO, ArchiveDao> {
        archiveDO.setSickName(patientDO.getName());
        archiveDO.setSignStatus(0);
        archiveDO.setIdcard(patientDO.getIdcard());
        archiveDO.setCreateTime(new Date());
        archiveDao.save(archiveDO);
        //床位申请修改状态
        List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByDoctorCode(doctorId);
        if (hospitalDOs.size()>0){
            PatientBedApplyDo bedApplyDo = patientBedApplyDao.findByPatientAndOrgCodeAndStatus(patientDO.getIdcard(),hospitalDOs.get(0).getOrgCode(),1);
            if (bedApplyDo!=null){
                bedApplyDo.setStatus(2);
                patientBedApplyDao.save(bedApplyDo);
            }
        }
        return 0;
    }
@ -121,7 +162,17 @@ public class ArchiveService extends BaseJpaService<ArchiveDO, ArchiveDao> {
        archiveDO.setSickName(patientDO.getName());
        archiveDO.setSignStatus(0);
        archiveDO.setIdcard(patientDO.getIdcard());
        archiveDO.setCreateTime(new Date());
        archiveDao.save(archiveDO);
        List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByDoctorCode(doctorId);
        if (hospitalDOs.size()>0){
            PatientBedApplyDo bedApplyDo = patientBedApplyDao.findByPatientAndOrgCodeAndStatus(patientDO.getIdcard(),hospitalDOs.get(0).getOrgCode(),1);
            if (bedApplyDo!=null){
                bedApplyDo.setStatus(2);
                patientBedApplyDao.save(bedApplyDo);
            }
        }
    }
}

+ 429 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/CapacityAssessmentRecordService.java

@ -1,23 +1,41 @@
package com.yihu.jw.care.service.sign;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.sign.CapacityAssessmentRecordDao;
import com.yihu.jw.care.dao.apply.PatientBedApplyDao;
import com.yihu.jw.care.dao.label.WlyyPatientLabelDao;
import com.yihu.jw.care.dao.sign.*;
import com.yihu.jw.care.service.common.DictService;
import com.yihu.jw.care.util.ConstantUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.care.sign.CapacityAssessmentRecordDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.apply.PatientBedApplyDo;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import com.yihu.jw.entity.care.sign.*;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.mysql.query.BaseJpaService;
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.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.Iterator;
import java.util.List;
import java.util.Map;
@ -37,7 +55,94 @@ public class CapacityAssessmentRecordService extends BaseJpaService<CapacityAsse
    private BaseDoctorDao doctorDao;
    @Autowired
    private BaseDoctorHospitalDao doctorHospitalDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private CapacityAssessmentBaseInfoDao CAbaseInfoDao;
    @Autowired
    private CapacityAssessmentCognitiveAbilityDao CACognitiveAbilityDao;
    @Autowired
    private CapacityAssessmentLivingAbilityDao CALivingAbilityDao;
    @Autowired
    private CapacityAssessmentSocialAbilityDao CASocialAbilityDao;
    @Autowired
    private WlyyPatientLabelDao patientLabelDao;
    @Autowired
    private DictService dictService;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private PatientBedApplyDao patientBedApplyDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    /**
     * 按id查找评估明细
     * @param patient
     * @return
     */
    public CapacityAssessmentRecordDO findAssessmentByPatientId(String patient)  {
        return capacityAssessmentRecordDao.findByPatient(patient);
    }
    /**
     * 按id查找评估明细
     * @param id
     * @return
     */
    public CapacityAssessmentRecordDO findAssessmentById(String id)  {
        CapacityAssessmentRecordDO recordDO = capacityAssessmentRecordDao.findOne(id);
        BasePatientDO basePatientDO = patientDao.findById(recordDO.getPatient());
        recordDO.setAge(IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        recordDO.setPhoto(basePatientDO.getPhoto());
        recordDO.setSexName(dictService.fingByNameAndCode(ConstantUtil.DICT_SEX,String.valueOf(recordDO.getSex())));
        recordDO.setServicePackageStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_SERVICEPACKAGESTATUS,String.valueOf(recordDO.getServicePackageStatus())));
        recordDO.setStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_CAPACITY_AGREE_STATUS,String.valueOf(recordDO.getStatus())));
        recordDO.setLevelConclusionName(dictService.fingByNameAndCode(ConstantUtil.DICT_LEVEL_CONCLUSION,String.valueOf(recordDO.getLevelConclusion())));
        recordDO.setLivingAbilityName(dictService.fingByNameAndCode(ConstantUtil.DICT_LEVEL_CONCLUSION,String.valueOf(recordDO.getLivingAbility())));
        recordDO.setCognitiveAbilityName(dictService.fingByNameAndCode(ConstantUtil.DICT_LEVEL_CONCLUSION,String.valueOf(recordDO.getCognitiveAbility())));
        recordDO.setComprehensiveAbilityName(dictService.fingByNameAndCode(ConstantUtil.DICT_LEVEL_CONCLUSION,String.valueOf(recordDO.getComprehensiveAbility())));
        recordDO.setSocialAbilityName(dictService.fingByNameAndCode(ConstantUtil.DICT_LEVEL_CONCLUSION,String.valueOf(recordDO.getSocialAbility())));
        return recordDO;
    }
    /**
     * 获取居民统计
     * @param doctorId
     * @return
     */
    public Map<String,Object> getPatientNum(String doctorId){
        Map<String,Object> res = new HashedMap();
        //能力完好(0级) 轻度失能(1级) 中度失能(2级) 重度失能(3级) 新生儿 10
        res.put("0",0);
        res.put("1",0);
        res.put("2",0);
        res.put("3",0);
        String sql = "SELECT COUNT(DISTINCT ar.patient),level_conclusion from  " +
                "base_capacity_assessment_record ar, " +
                "base_service_package_sign_record sr,base_service_package_record r,  " +
                "                base_service_package_item i,base_team_member m  " +
                "                WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id  " +
                "                and i.del = 1 and m.team_code = i.team_code and ar.patient = sr.patient " +
                "                and m.doctor_code = '"+doctorId+"' and m.del = '1' and sr.`status`=1 " +
                "GROUP BY ar.level_conclusion" ;
        List<Map<String,Object>> countMapList = jdbcTemplate.queryForList(sql);
        for(Map<String,Object> map:countMapList){
            int c = Integer.valueOf(map.get("count").toString());
            res.put(String.valueOf(map.get("status")),c);
        }
        String sql2 = "SELECT COUNT(DISTINCT ar.id) from base_patient ar, " +
                "base_service_package_sign_record sr,base_service_package_record r,  " +
                "                base_service_package_item i,base_team_member m  " +
                "                WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id  " +
                "                and i.del = 1 and m.team_code = i.team_code and ar.id = sr.patient and ar.archive_type = 2 " +
                "                and m.doctor_code = '"+doctorId+"' and m.del = '1' and sr.`status`=1";
        Integer count = jdbcTemplate.queryForObject(sql2,Integer.class);
        res.put("10",count);
        return res;
    }
    public PageEnvelop<List<Map<String,Object>>> assessmentPage(String doctorId,String name, int page, int size,
                    Integer status,Integer levelConclusion,Integer servicePackageStatus){
@ -70,6 +175,9 @@ public class CapacityAssessmentRecordService extends BaseJpaService<CapacityAsse
            String idcard = map.get("idcard").toString();
            map.put("assessmentTime", map.get("assessment_time").toString().substring(0,19));
            map.put("age", IdCardUtil.getAgeForIdcard(idcard));
            map.put("levelConclusionName",dictService.fingByNameAndCode(ConstantUtil.DICT_LEVEL_CONCLUSION,String.valueOf(map.get("levelConclusion"))));
            map.put("servicePackageStatusName",dictService.fingByNameAndCode(ConstantUtil.DICT_SERVICEPACKAGESTATUS,String.valueOf(map.get("servicePackageStatus"))));
            map.put("statusName",dictService.fingByNameAndCode(ConstantUtil.DICT_CAPACITY_AGREE_STATUS,String.valueOf(map.get("status"))));
        }
        Long count = jdbcTemplate.queryForObject(countSql+filters,Long.class);
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,count);
@ -93,11 +201,33 @@ public class CapacityAssessmentRecordService extends BaseJpaService<CapacityAsse
     * @param doctorId
     * @throws Exception
     */
    public void capacityAssessment(String jsonData,String doctorId) throws Exception{
    @Transactional(rollbackFor = Exception.class)
    public JSONObject capacityAssessment(String jsonData,String doctorId) throws Exception{
        JSONObject result = new JSONObject();
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        CapacityAssessmentRecordDO recordDO = objectMapper.readValue(jsonObject.getJSONObject("assessment").toJSONString(), CapacityAssessmentRecordDO.class);
        CapacityAssessmentRecordDO recordDO = JSONObject.parseObject(jsonObject.getJSONObject("assessment").toJSONString(), CapacityAssessmentRecordDO.class);
        if(isCapacityAssessment(recordDO.getPatient())==0){
            String year = DateUtil.getNowYear()+"";
            JSONObject obj = getAssessmentItemDetail(recordDO.getPatient(),0,year);
            net.sf.json.JSONObject objTmp = net.sf.json.JSONObject.fromObject(JSON.parseObject(obj.toJSONString()));
            Iterator<String> keys = objTmp.keys();
            boolean finishFlag=true;
            while (keys.hasNext()){
                String key = keys.next();
                net.sf.json.JSONObject tmp = objTmp.getJSONObject(key+"");
                String id = tmp.containsKey("id")?tmp.getString("id"):"";
                if (StringUtils.isBlank(id)){
                    result.put(ResponseContant.resultFlag, ResponseContant.fail);
                    result.put(ResponseContant.resultMsg,"患者存在未完成的评估表"+key);
                    finishFlag=false;
                    break;
                }
            }
            if (!finishFlag){
                return result;
            }
            BaseDoctorDO doctorDO = doctorDao.findById(doctorId);
            List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(doctorId);
            recordDO.setOrgCode(doctorHospitalDOs.get(0).getOrgCode());
@ -107,7 +237,132 @@ public class CapacityAssessmentRecordService extends BaseJpaService<CapacityAsse
            recordDO.setServicePackageStatus(0);
            recordDO.setStatus(0);
            capacityAssessmentRecordDao.save(recordDO);
            //生成居民标签
            patientLabelDao.deleteByPatientAndLabelType(recordDO.getPatient(),"1");
            WlyyPatientLabelDO patientLabelDO = new WlyyPatientLabelDO();
            patientLabelDO.setCzrq(new Date());
            patientLabelDO.setLabelType("1");
            patientLabelDO.setPatient(recordDO.getPatient());
            patientLabelDO.setLabelCode(String.valueOf(recordDO.getLevelConclusion()));
            patientLabelDO.setLabelName(dictService.fingByNameAndCode(ConstantUtil.DICT_SERVICE_TYPE,patientLabelDO.getLabelCode()));
            patientLabelDao.save(patientLabelDO);
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg,recordDO);
            return result;
        }
        return null;
    }
    /**
     * 通过患者id 生成当年评估报告
     * @param patient
     * @param doctorId
     * @throws Exception
     */
    public JSONObject capacityAssessmentByPatient(String patient,String doctorId) throws Exception {
        JSONObject result = new JSONObject();
        String year = DateUtil.getNowYear()+"";
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO!=null){
            CapacityAssessmentRecordDO recordDO = new CapacityAssessmentRecordDO();
            //判断患者是否评估表已填
            JSONObject obj = getAssessmentItemDetail(patient,0,year);
            net.sf.json.JSONObject objTmp = net.sf.json.JSONObject.fromObject(JSON.parseObject(obj.toJSONString()));
            Iterator<String> keys = objTmp.keys();
            boolean finishFlag=true;
            while (keys.hasNext()){
                String key = keys.next();
                net.sf.json.JSONObject tmp = objTmp.getJSONObject(key+"");
                String id = tmp.containsKey("id")?tmp.getString("id"):"";
                if (StringUtils.isBlank(id)){
                    result.put("status",-1);
                    result.put("message","患者存在未完成的评估表"+key);
                    finishFlag=false;
                    break;
                }
            }
            if (!finishFlag){
                return result;
            }
            if(isCapacityAssessment(recordDO.getPatient())==0&&finishFlag){
                List<CapacityAssessmentBaseInfoDo> baseInfoDoList = CAbaseInfoDao.findByPatientAndYear(patient,year);
                if (baseInfoDoList.size()>0){
                    CapacityAssessmentBaseInfoDo baseInfoDo = baseInfoDoList.get(0);
                    if (StringUtils.isNotBlank(baseInfoDo.getName())){
                        recordDO.setName(baseInfoDo.getName());
                    }
                    else {
                        recordDO.setName(patientDO.getName());
                    }
                    recordDO.setPatient(patientDO.getId());
                    if (StringUtils.isNotBlank(baseInfoDo.getIdcard())){
                        recordDO.setIdcard(baseInfoDo.getIdcard());
                        recordDO.setBirthday(IdCardUtil.getBirthdayForIdcard(recordDO.getIdcard()));
                    }
                    else {
                        recordDO.setIdcard(patientDO.getIdcard());
                        recordDO.setBirthday(patientDO.getBirthday());
                    }
                    if (StringUtils.isNotBlank(baseInfoDo.getPatientPhone())){
                        recordDO.setMobile(baseInfoDo.getPatientPhone());
                    }
                    else {
                        recordDO.setMobile(patientDO.getMobile());
                    }
                    //户籍所在地,居住地
                    if (StringUtils.isNotBlank(baseInfoDo.getDomicileStreetName())){
                        String registeredResidence =baseInfoDo.getDomicileCountyName()+baseInfoDo.getDomicileStreetName()
                                +baseInfoDo.getDomicileOrgName()+baseInfoDo.getDomicileBuilding()+baseInfoDo.getDomicileRoom();
                        recordDO.setRegisteredResidence(registeredResidence);
                    }
                    if (StringUtils.isNotBlank(baseInfoDo.getLiveStreetName())){
                        String liveAddress =baseInfoDo.getLiveCountyName()+baseInfoDo.getLiveStreetName()
                                +baseInfoDo.getLiveOrgName()+baseInfoDo.getLiveBuilding()+baseInfoDo.getLiveRoom();
                        recordDO.setLiveAddress(liveAddress);
                    }
                    //评估时间
                    recordDO.setAssessmentTime(baseInfoDo.getCreateTime());
                    BaseDoctorDO doctorDO = doctorDao.findById(doctorId);
                    List<BaseDoctorHospitalDO> doctorHospitalDOs = doctorHospitalDao.findByDoctorCode(doctorId);
                    recordDO.setOrgCode(doctorHospitalDOs.get(0).getOrgCode());
                    BaseOrgDO orgDO = baseOrgDao.findByCode(recordDO.getOrgCode());
                    recordDO.setAssessmentAddress(orgDO.getAddress());// 评估地点
                    recordDO.setOrgName(doctorHospitalDOs.get(0).getOrgName());
                    recordDO.setDoctorName(doctorDO.getName());
                    recordDO.setDoctor(doctorId);
                    recordDO.setServicePackageStatus(0);
                    recordDO.setStatus(0);
                    capacityAssessmentRecordDao.save(recordDO);
                    //生成居民标签
                    patientLabelDao.deleteByPatientAndLabelType(recordDO.getPatient(),"1");
                    WlyyPatientLabelDO patientLabelDO = new WlyyPatientLabelDO();
                    patientLabelDO.setCzrq(new Date());
                    patientLabelDO.setLabelType("1");
                    patientLabelDO.setPatient(recordDO.getPatient());
                    patientLabelDO.setLabelCode(String.valueOf(recordDO.getLevelConclusion()));
                    patientLabelDO.setLabelName(dictService.fingByNameAndCode(ConstantUtil.DICT_SERVICE_TYPE,patientLabelDO.getLabelCode()));
                    patientLabelDao.save(patientLabelDO);
                    result.put("status",1);
                    result.put("message","保存成功");
                    result.put("data",recordDO);
                }
                else {
                    result.put("status",-1);
                    result.put("message","未查询到患者基本信息");
                }
            }
            else {
                result.put("status",-1);
                result.put("message","患者已做过能力评估");
            }
        }
        else {
            result.put("status",-1);
            result.put("message","未找到该患者");
        }
        return result;
    }
    /**
@ -122,6 +377,176 @@ public class CapacityAssessmentRecordService extends BaseJpaService<CapacityAsse
        recordDO.setSignUrl(signUrl);
        recordDO.setSignTime(new Date());
        capacityAssessmentRecordDao.save(recordDO);
        //完成评估 修改床位生请状态为已完成
        PatientBedApplyDo bedApplyDo = patientBedApplyDao.findByPatientAndOrgCodeAndStatus(recordDO.getIdcard(),recordDO.getOrgCode(),2);
        if (bedApplyDo!=null) {
            bedApplyDo.setStatus(0);
            patientBedApplyDao.save(bedApplyDo);
        }
    }
    /**
     *
     * @param patient
     * @param item 0全部 1基本信息 2日常生活能力 3认知能力 4精神状态与社会交流能力
     * @param year
     * @return
     */
    public JSONObject getAssessmentItemDetail(String patient,Integer item,String year) throws Exception {
        JSONObject result = new JSONObject();
        String tableName = "";
        String objName="";
        String keyName="";
        Integer tmpItem=item;
        boolean allSearch=false;
        if(StringUtils.isBlank(year)){
            year = DateUtil.getNowYear()+"";
        }
        if (item==0){
            tmpItem++;
            allSearch=true;
        }
        for(;tmpItem<=4;) {
            if (tmpItem == 1) {
                tableName = "base_capacity_assessment_baseinfo";
                objName = "com.yihu.jw.entity.care.sign.CapacityAssessmentBaseInfoDo";
                keyName = "baseinfo";
            } else if (tmpItem == 2) {
                tableName = "base_capacity_assessment_living_ability";
                objName = "com.yihu.jw.entity.care.sign.CapacityAssessmentLivingAbilityDo";
                keyName = "living_ability";
            } else if (tmpItem == 3) {
                tableName = "base_capacity_assessment_cognitive_ability";
                objName = "com.yihu.jw.entity.care.sign.CapacityAssessmentCognitiveAbilityDo";
                keyName = "cognitive_ability";
            } else if (tmpItem == 4) {
                tableName = "base_capacity_assessment_social_ability";
                objName = "com.yihu.jw.entity.care.sign.CapacityAssessmentSocialAbilityDo";
                keyName = "social_ability";
            }
            Class c1 = Class.forName(objName);
            String sql = "select * from " + tableName + " where patient='" + patient + "' and assessment_year='" + year + "' and status=1";
            Object O1 = null;
            Boolean searchFlag = true;
            try {
                O1 = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper(c1));
            } catch (Exception e) {
                searchFlag = false;
                O1 = c1.newInstance();
            }
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(O1, SerializerFeature.WriteMapNullValue));
            jsonObject.put("patient",patient);
            if (item==1){
                if (StringUtils.isNotBlank(jsonObject.getString("idcard"))){
                    jsonObject.put("birthday",IdCardUtil.getBirthdayForIdcardStr(jsonObject.getString("idcard")));
                }
                jsonObject.put("birthday",null);
            }
            if (!searchFlag && item == 1) {//基本信息带入
                CapacityAssessmentBaseInfoDo obj = new CapacityAssessmentBaseInfoDo();
                BasePatientDO patientDo = patientDao.findById(patient);
                obj.setPatient(patient);
                if (patientDo != null) {
                    obj.setName(patientDo.getName());
                    obj.setSex(patientDo.getSex());
                    obj.setIdcard(patientDo.getIdcard());
                    obj.setAge(IdCardUtil.getAgeForIdcard(patientDo.getIdcard()) + "");
                    obj.setNation(patientDo.getNational() == null ? null : patientDo.getNational() + "");//名族
                    obj.setNationName(patientDo.getNationalName());
                    obj.setPatientPhone(patientDo.getMobile());//手机
                    obj.setResidencePhone(patientDo.getPhone());//住宅电话
                    obj.setDomicileCounty(patientDo.getTownCode());//户籍 区
                    obj.setDomicileCountyName(patientDo.getTownName());
                    obj.setDomicileStreet(patientDo.getStreetCode());//户籍 街道
                    obj.setDomicileStreetName(patientDo.getStreetName());
                    obj.setLiveCounty(patientDo.getLiveTownCode());
                    obj.setLiveCountyName(patientDo.getLiveTownName());
                    obj.setLiveStreet(patientDo.getLiveStreetCode());
                    obj.setLiveStreetName(patientDo.getLiveStreetName());
                    if (StringUtils.isNotBlank(obj.getIdcard())){
                        obj.setBirthday(IdCardUtil.getBirthdayForIdcardStr(obj.getIdcard()));
                    }
                    jsonObject = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
                }
            }
            result.put(keyName, jsonObject);
            if (allSearch){
                tmpItem++;
            }
            else{
                break;
            }
        }
        return result;
    }
    /**
     *
     * @param json
     * @param item 0全部 1基本信息 2日常生活能力 3认知能力 4精神状态与社会交流能力
     * @return
     */
    public JSONObject saveAssessmentItemDetail(String json,Integer item){
       String year = DateUtil.getNowYear()+"";
       JSONObject result  = new JSONObject();
       JSONObject jsonObj = JSONObject.parseObject(json);
       boolean saveAll = false;
       if (item==0){
           saveAll=true;
       }
       if (item==1||saveAll){
           String tmpStr = jsonObj.getString("baseinfo");
           CapacityAssessmentBaseInfoDo obj = JSON.parseObject(tmpStr,CapacityAssessmentBaseInfoDo.class);
           List<CapacityAssessmentBaseInfoDo> tmp = CAbaseInfoDao.findByPatientAndYear(obj.getPatient(),year);
           if (tmp.size()>0){
               obj.setId(tmp.get(0).getId());
           }
           obj.setStatus(1);
           obj.setAssessmentYear(year);
           CAbaseInfoDao.save(obj);
           JSONObject resultTmp = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
           result.put("baseinfo",resultTmp);
       }
       if (item==2||saveAll){
           String tmpStr = jsonObj.getString("living_ability");
           CapacityAssessmentLivingAbilityDo obj = JSON.parseObject(tmpStr,CapacityAssessmentLivingAbilityDo.class);
           List<CapacityAssessmentLivingAbilityDo> tmp = CALivingAbilityDao.findByPatientAndYear(obj.getPatient(),year);
           if (tmp.size()>0){
               obj.setId(tmp.get(0).getId());
           }
           obj.setStatus(1);
           obj.setAssessmentYear(year);
           CALivingAbilityDao.save(obj);
           JSONObject resultTmp = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
           result.put("living_ability",resultTmp);
       }
       if (item==3||saveAll){
           String tmpStr = jsonObj.getString("cognitive_ability");
           CapacityAssessmentCognitiveAbilityDo obj = JSON.parseObject(tmpStr,CapacityAssessmentCognitiveAbilityDo.class);
           List<CapacityAssessmentCognitiveAbilityDo> tmp = CACognitiveAbilityDao.findByPatientAndYear(obj.getPatient(),year);
           if (tmp.size()>0){
               obj.setId(tmp.get(0).getId());
           }
           obj.setStatus(1);
           obj.setAssessmentYear(year);
           CACognitiveAbilityDao.save(obj);
           JSONObject resultTmp = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
           result.put("cognitive_ability",resultTmp);
       }
       if (item==4||saveAll){
           String tmpStr = jsonObj.getString("social_ability");
           CapacityAssessmentSocialAbilityDo obj = JSON.parseObject(tmpStr,CapacityAssessmentSocialAbilityDo.class);
           List<CapacityAssessmentSocialAbilityDo> tmp = CASocialAbilityDao.findByPatientAndYear(obj.getPatient(),year);
           if (tmp.size()>0){
               obj.setId(tmp.get(0).getId());
           }
           obj.setStatus(1);
           obj.setAssessmentYear(year);
           CASocialAbilityDao.save(obj);
            JSONObject resultTmp = JSON.parseObject(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
           result.put("social_ability",resultTmp);
       }
       return result;
    }
}

+ 81 - 47
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/sign/ServicePackageService.java

@ -7,18 +7,19 @@ import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageItemDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageRecordDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSignRecordDO;
import com.yihu.jw.entity.care.archive.ArchiveDO;
import com.yihu.jw.entity.care.sign.CapacityAssessmentRecordDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientMedicardCardService;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -28,10 +29,8 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/**
 *
@ -47,7 +46,8 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
    private ServicePackageDao servicePackageDao;
    @Autowired
    private ServicePackageItemDao servicePackageItemDao;
    @Autowired
    private CapacityAssessmentRecordService capacityAssessmentRecordService;
    @Autowired
    private ServicePackageSignRecordDao servicePackageSignRecordDao;
    @Autowired
@ -81,7 +81,7 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
                " base_service_package_item i, " +
                " base_org o " +
                "WHERE " +
                " sr.id = r.sign_id and sr.patient = '"+patient+"'" +
                " sr.id = r.sign_id and sr.status=1 and sr.patient = '"+patient+"'" +
                "AND r.service_package_id = i.service_package_id " +
                "AND i.del = 1 " +
                "and i.org_code = o.code " +
@ -118,7 +118,9 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
            redisTemplate.delete(key);
        }
        List<String> res = fingServiceItemsCodeByPatientId(patientId);
        redisTemplate.opsForList().leftPushAll(key,res);
        if(res!=null&&res.size()>0){
            redisTemplate.opsForList().leftPushAll(key,res);
        }
    }
@ -129,7 +131,7 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
     */
    public List<Map<String,Object>> fingServiceItemsByPatientId(String patientId){
        String sql = "SELECT DISTINCT i.code,i.name from base_service_package_sign_record sr,base_service_package_record r, " +
                " base_service_package_item i  where  sr.id = r.sign_id and r.service_package_id = i.service_package_id " +
                " base_service_package_item i  where  sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id " +
                "  and i.del = 1 and sr.`status`=1 and  sr.patient  = '"+patientId+"' ";
        return jdbcTemplate.queryForList(sql);
    }
@ -141,7 +143,7 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
     */
    public List<String> fingServiceItemsCodeByPatientId(String patientId){
        String sql = "SELECT DISTINCT i.code from base_service_package_sign_record sr,base_service_package_record r, " +
                " base_service_package_item i  where  sr.id = r.sign_id and r.service_package_id = i.service_package_id " +
                " base_service_package_item i  where  sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id " +
                "  and i.del = 1 and sr.`status`=1 and  sr.patient  = '"+patientId+"' ";
        return jdbcTemplate.queryForList(sql,String.class);
    }
@ -154,29 +156,13 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
        JSONObject json = new JSONObject();
        ServicePackageSignRecordDO signRecordDO = servicePackageSignRecordDao.findOne(id);
        BasePatientDO patientDO = patientDao.findById(signRecordDO.getPatient());
        PatientMedicareCardDO card = basePatientMedicardCardService.findByTypeAndPatientCodeAndDel("A_01",signRecordDO.getPatient(),"1");
        if(card != null){
            patientDO.setSsc(card.getCode());
        }
        json.put("patient",patientDO);
        List<Map<String,Object>> packageList = fingdBySignId(id);
        List<Map<String,Object>> doctorList = fingdDoctorBySignId(id,"generalDoctor");
        List<Map<String,Object>> helperList = fingdDoctorBySignId(id,"helper");
        String doctorInfo = "";
        String helperInfo = "";
        String packageInfo = "";
        if(doctorList.size()>0){
            doctorInfo = doctorList.get(0).get("name").toString()+"等"+doctorList.size()+"名";
        }
        if(helperList.size()>0){
            helperInfo = doctorList.get(0).get("name").toString()+"等"+helperList.size()+"名";
        }
        if(packageList.size()>0){
            packageInfo = packageList.get(0).get("name").toString()+"等"+packageList.size()+"个";
        }
        signRecordDO.setDoctorInfo(doctorInfo);
        signRecordDO.setHelperInfo(helperInfo);
        signRecordDO.setPackageInfo(packageInfo);
        List<Map<String,Object>> doctorList = fingdDoctorBySignId(id,1);
        List<Map<String,Object>> helperList = fingdDoctorBySignId(id,2);
        signRecordDO.setDoctorList(doctorList);
        signRecordDO.setHelperList(helperList);
        signRecordDO.setPackageList(packageList);
        json.put("signRecordDO",signRecordDO);
        return json;
    }
@ -185,13 +171,27 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
     * 根据签约记录查找医生/助老员
     * @param signId
     */
    public List<Map<String,Object>> fingdDoctorBySignId(String signId,String role){
    public List<Map<String,Object>> fingdDoctorBySignId(String signId,Integer level){
        String sql = "SELECT DISTINCT d.id,d.name from base_service_package_sign_record sr,base_service_package_record r, " +
                "base_service_package_item i,base_team_member m,base_doctor d,base_doctor_role dr " +
                "WHERE sr.id = r.sign_id and r.service_package_id = i.service_package_id " +
                "base_service_package_item i,base_team_member m,base_doctor d " +
                "WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id " +
                "and i.del = 1 and m.team_code = i.team_code " +
                "and m.del = '1' and d.id = dr.doctor_code and dr.role_code = '"+role+"' " +
                "and sr.id = '"+signId+"' ";
                "and m.del = '1' and d.level = " + level+
                " and sr.id = '"+signId+"' ";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 根据服务包id查找医生/助老员
     * @param packageId
     */
    public List<Map<String,Object>> fingdDoctorByPackageId(String packageId,Integer level){
        String sql = "SELECT DISTINCT d.id,d.name from base_service_package_record r, " +
                "base_service_package_item i,base_team_member m,base_doctor d " +
                "WHERE r.service_package_id = i.service_package_id " +
                "and i.del = 1 and m.team_code = i.team_code " +
                "and m.del = '1' and d.level = " + level+
                " and r.id = '"+packageId+"' ";
        return jdbcTemplate.queryForList(sql);
    }
@ -221,7 +221,7 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
        String filters = " from base_service_package_sign_record sr,base_service_package_record r, " +
                "base_service_package_item i,base_team_member m,base_patient p " +
                "WHERE sr.id = r.sign_id and r.service_package_id = i.service_package_id " +
                "WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id " +
                "and i.del = 1 and m.team_code = i.team_code and p.id = sr.patient " +
                "and m.doctor_code = '"+doctorId+"' and m.del = '1' and sr.`status`=1 ";
@ -253,7 +253,7 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
    public int getSignTotal(String doctorId){
        String sql = "SELECT COUNT(DISTINCT sr.patient) from base_service_package_sign_record sr,base_service_package_record r, " +
                "base_service_package_item i,base_team_member m " +
                "WHERE sr.id = r.sign_id and r.service_package_id = i.service_package_id " +
                "WHERE sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id " +
                "and i.del = 1 and m.team_code = i.team_code " +
                "and m.doctor_code = '"+doctorId+"' and m.del = '1' and sr.`status`=1 ";
@ -266,10 +266,12 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
     * @param doctorId
     */
    @Transactional(rollbackFor = Exception.class)
    public ServicePackageSignRecordDO servicePackageSign(String jsonData,String doctorId) throws Exception{
    public ServicePackageSignRecordDO servicePackageSign(String jsonData,String doctorId,String patientId) throws Exception{
        ServicePackageSignRecordDO signRecordDO = objectMapper.readValue(jsonData, ServicePackageSignRecordDO.class);
        signRecordDO.setPatient(patientId);
        List<ServicePackageRecordDO> recordDOList = signRecordDO.getRecordDOList();
        String signId = signRecordDO.getId();
        List<String> idList = new ArrayList<>();
        if(StringUtil.isEmpty(signId)){
            List<ServicePackageSignRecordDO> signRecordDOs = servicePackageSignRecordDao.findByStatusAndPatient(1,signRecordDO.getPatient());
            if(signRecordDOs.size()==0){
@ -286,24 +288,39 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
                signId = signRecordDO.getId();
                //建档状态修改
                ArchiveDO archiveDO = archiveDao.findByPatientAndDoctorCode(signRecordDO.getPatient(),doctorId);
                ArchiveDO archiveDO = archiveDao.findByPatientAndDoctorCode(patientId,doctorId);
                if(archiveDO!=null){
                    archiveDO.setSignStatus(1);
                    archiveDao.save(archiveDO);
                }
            }else{
                signId = signRecordDOs.get(0).getId();
                List<ServicePackageRecordDO> existList = servicePackageRecordDao.findBySignId(signId);
                idList = existList.stream().map(ServicePackageRecordDO::getServicePackageId).collect(Collectors.toList());
            }
        }
        for (ServicePackageRecordDO recordDO:recordDOList){
            recordDO.setPatient(signRecordDO.getPatient());
        Iterator<ServicePackageRecordDO> iterator = recordDOList.iterator();
        while (iterator.hasNext()) {
            ServicePackageRecordDO recordDO = iterator.next();
            recordDO.setPatient(patientId);
            recordDO.setSignId(signId);
            if (idList.contains(recordDO.getServicePackageId())) {
                iterator.remove();//使用迭代器的删除方法删除
            }
        }
        if(recordDOList.size()>0){
            CapacityAssessmentRecordDO capacityAssessmentRecordDO = capacityAssessmentRecordService.findAssessmentByPatientId(patientId);
            capacityAssessmentRecordDO.setServicePackageStatus(1);
            capacityAssessmentRecordService.save(capacityAssessmentRecordDO);
        }
        servicePackageRecordDao.save(recordDOList);
        return signRecordDO;
    }
    public PageEnvelop<List<Map<String,Object>>> servicePackagePage(int page, int size){
        String sql = "SELECT p.id,p.`name`,p.type,p.introduce,p.num  ";
        String countSql = "SELECT count(*) ";
@ -319,14 +336,31 @@ public class ServicePackageService extends BaseJpaService<ServicePackageDO, Serv
        for (Map<String,Object> map :list){
            String id = map.get("id").toString();
            List<ServicePackageItemDO> itemDOList = servicePackageItemDao.findByServicePackageId(id);
            if(itemDOList.size()>0){
                map.put("detail",itemDOList.get(0).getName()+"等"+itemDOList.size()+"项服务");
            }else{
                map.put("detail","");
            }
            map.put("detail",itemDOList);
            List<Map<String,Object>> doctorList = fingdDoctorByPackageId(id,1);
            List<Map<String,Object>> helperList = fingdDoctorByPackageId(id,2);
            map.put("doctorList",doctorList);
            map.put("helperList",helperList);
        }
        Long count = jdbcTemplate.queryForObject(countSql+filters,Long.class);
        return PageEnvelop.getSuccessListWithPage("success",list,page,size,count);
    }
    public List<ServicePackageRecordDO> servicePackageByPatient(String patient,String packageType){
        //签约记录
        List<ServicePackageSignRecordDO> signs = servicePackageSignRecordDao.findByStatusAndPatient(1,patient);
        if (signs.size()>0){
            ServicePackageSignRecordDO tmp = signs.get(0);
            String sql = " select r.* from base_service_package_record r inner join base_service_package p on r.service_package_id = p.id " +
                    " and p.del=1  where r.sign_id='"+tmp.getId()+"' ";
            if (StringUtils.isNotBlank(packageType)){
                sql += " and p.type='"+packageType+"' ";
            }
            List<ServicePackageRecordDO> result = jdbcTemplate.query(sql,new BeanPropertyRowMapper(ServicePackageRecordDO.class));
            return result;
        }
        else return new ArrayList<>();
    }
}

+ 141 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsService.java

@ -0,0 +1,141 @@
package com.yihu.jw.care.service.statistics;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.util.ConstantUtil;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.Calendar;
/**
 *
 * Created by yeshijie on 2021/4/7.
 */
@Service
public class StatisticsService {
    Logger logger = LoggerFactory.getLogger(StatisticsService.class);
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 统计首页头部数据
     * @param area
     * @param startDate
     * @param endDate
     */
    public JSONObject indexTopNum(String area,String startDate,String endDate,Integer level){
        JSONObject re = new JSONObject();
        String signSql = " SELECT COUNT(sr.id) " +
                " FROM " +
                "  base_service_package_sign_record sr, " +
                "  base_service_package_record r, " +
                "  base_service_package_item i, " +
                "   base_org o " +
                " WHERE " +
                "  sr.id = r.sign_id " +
                " AND sr. STATUS = 1 " +
                " AND r.service_package_id = i.service_package_id " +
                " AND i.del = 1 and i.org_code = o.code";
        String capacitySql = "select count(sr.id) from base_capacity_assessment_record sr, " +
                "   base_org o " +
                " WHERE " +
                " sr.org_code = o.code" ;
        String filters = "";
        if(ConstantUtil.cityLevel.equals(level)){
            filters = " and o.city_code = '"+area+"'";
        }else if(ConstantUtil.townLevel.equals(level)){
            filters = " and o.town_code = '"+area+"'";
        }else if(ConstantUtil.orgLevel.equals(level)){
            filters = " and o.code = '"+area+"'";
        }
        if(StringUtils.isNotBlank(startDate)){
            filters += " and sr.create_time >='"+startDate+"'";
        }
        if(StringUtils.isNotBlank(endDate)){
            filters += " and sr.create_time <='"+endDate+"'";
        }
        //签约数 能力评估
        Integer signNum = jdbcTemplate.queryForObject(signSql+filters,Integer.class);
        Integer capacityNum = jdbcTemplate.queryForObject(capacitySql+filters,Integer.class);
        re.put("signNum",signNum);
        re.put("capacityNum",capacityNum);
        return re;
    }
    /**
     * 首页 养护服务
     * @param area
     * @param startDate
     * @param endDate
     * @param level
     * @param type 类型:1本周,2本月
     */
    public JSONObject indexMaintenanceServices(String area,String startDate,String endDate,Integer level,int type){
        JSONObject re = new JSONObject();
        String sql = "select count(sr.id) from base_life_care_order sr, " +
                "   base_org o " +
                " WHERE " +
                " sr.hospital = o.code" ;
        if(ConstantUtil.cityLevel.equals(level)){
            sql += " and o.city_code = '"+area+"'";
        }else if(ConstantUtil.townLevel.equals(level)){
            sql += " and o.town_code = '"+area+"'";
        }else if(ConstantUtil.orgLevel.equals(level)){
            sql += " and o.code = '"+area+"'";
        }
        String filters = "";
        String timefilters = "";
        if(StringUtils.isNotBlank(startDate)){
            filters += " and sr.create_time >='"+startDate+"'";
        }
        if(StringUtils.isNotBlank(endDate)){
            filters += " and sr.create_time <='"+endDate+"'";
        }
        String start = calStart(endDate,type);
        timefilters += " and sr.create_time >='"+start+"'";
        timefilters += " and sr.create_time <='"+endDate+"'";
        //生活照料
        Integer lifeCareNum = jdbcTemplate.queryForObject(sql+filters,Integer.class);
        Integer lifeCareNumAdd = jdbcTemplate.queryForObject(sql+timefilters,Integer.class);
        re.put("lifeCareNum",lifeCareNum);
        re.put("lifeCareNumAdd",lifeCareNumAdd);
        return re;
    }
    /**
     * 计算开始时间
     * @param endDate
     * @param type 1周,2月
     * @return
     */
    public String calStart(String endDate,int type){
        if(StringUtils.isEmpty(endDate)){
            return endDate;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.strToDate(endDate));
        if(1==type){
            if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
                cal.add(Calendar.DAY_OF_WEEK,-1);
            }
            cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
        }else{
            cal.set(Calendar.DAY_OF_MONTH,1);
        }
        return DateUtil.dateToStrShort(cal.getTime());
    }
}

+ 211 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/CommonUtil.java

@ -0,0 +1,211 @@
package com.yihu.jw.care.util;
import it.sauronsoftware.jave.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
@Component
public class CommonUtil {
    private Logger logger = LoggerFactory.getLogger(CommonUtil.class);
    public String getIdcardEncode(String idcard) {
        if (idcard != null) {
            if (idcard.length() == 18) {
                return idcard.substring(0, 9) + "*******" + idcard.substring(16, 18);
            } else if (idcard.length() == 15) {
                return idcard.substring(0, 8) + "***" + idcard.substring(11, 15);
            }
        }
        return idcard;
    }
    /**
     * 对象转数组
     *
     * @param obj
     * @return
     */
    public byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }
    /**
     * 数组转对象
     *
     * @param bytes
     * @return
     */
    public Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
    /**
     * double转字符串,在转int
     * double*100转int 有bug 34.3会会变成3429
     *
     * @param d
     * @return
     */
    public static Integer doubleToInt(Double d) {
        if (d == null) {
            return 0;
        }
        String currency = String.valueOf(d);
        int index = currency.indexOf(".");
        int length = currency.length();
        Integer amLong = 0;
        if (index == -1) {
            amLong = Integer.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Integer.valueOf((currency.substring(0, index + 3)).replace(".", ""));
            if (length - index > 3) {
                if (Integer.valueOf(currency.substring(index + 3, index + 4)) >= 5) {
                    amLong++;
                }
            }
        } else if (length - index == 2) {
            amLong = Integer.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Integer.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong;
    }
    /**
     * 校验健康指标是否正常
     *
     * @param curValue    当前值
     * @param standardMax 最大标准值
     * @param standardMin 最小标准值
     * @return 0正常,1高,-1低
     */
    public double checkHealthIndex(double curValue, double standardMax, double standardMin) {
        if (curValue <= 0) {
            return 0;
        }
        if (standardMax > 0 && curValue > standardMax) {
            return curValue;
        }
        return 0;
    }
    public void changeToMp3(String sourcePath, String targetPath) {
        File source = new File(sourcePath);
        File target = new File(targetPath);
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }
    /**
     * 传入身高体重,计算BMI值
     *
     * @param weightStr 体重
     * @param heightStr 身高
     * @return
     */
    public double getBMIByWeightAndHeight(String weightStr, String heightStr) {
        DecimalFormat df2 = new DecimalFormat("###.00");
        double weight = Double.parseDouble(weightStr);
        Integer heightCM = Integer.parseInt(heightStr);
        heightStr = df2.format(heightCM / 100d);
        double height = Double.parseDouble(heightStr);
        double bmi = weight / (height * height);
        return bmi;
    }
    public String request(String remote_url, MultipartFile file, String type) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        logger.info(file.getOriginalFilename());
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            if (!org.springframework.util.StringUtils.isEmpty(type)) {
                builder.addTextBody("type", type); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

+ 143 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ConcealUtil.java

@ -0,0 +1,143 @@
package com.yihu.jw.care.util;
/**
 * 数据脱敏工具
 * Created by zdm on 2019/4/2.
 */
public class ConcealUtil {
    private static final int SIZE = 6;
    private static final String SYMBOL = "*";
    /**
     * 电话号码脱敏,达到保密效果
     *
     * @param userName 用户名
     * @return 替换后的用户名
     */
    public static String phoneConceal(String userName) {
        String userNameAfterReplaced = "";
        if (userName == null) {
            userName = "";
        }
        int nameLength = userName.length();
        if (nameLength <= 1) {
            userNameAfterReplaced = "*";
        } else if (nameLength == 2) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{0})\\d(?=\\d{1})");
        } else if (nameLength >= 3 && nameLength <= 6) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{1})\\d(?=\\d{1})");
        } else if (nameLength >= 7 && nameLength <= 10) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{3})\\d(?=\\d{3})");
        } else if (nameLength >= 11) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{3})\\d(?=\\d{4})");
        }
        return userNameAfterReplaced;
    }
    /**
     * 实际替换动作
     *
     * @param username username
     * @param regular  正则
     * @return
     */
    private static String replaceAction(String username, String regular) {
        return username.replaceAll(regular, "*");
    }
    /**
     * 身份证号替换,保留前四位和后四位
     * <p>
     * 如果身份证号为空 或者 null ,返回null ;否则,返回替换后的字符串;
     *
     * @param idCard 身份证号
     * @return
     */
    public static String idCardConceal(String idCard) {
        if (idCard.isEmpty() || idCard == null) {
            return null;
        } else {
            return replaceAction(idCard, "(?<=\\d{6})\\d(?=\\d{4})");
        }
    }
    /**
     * 银行卡替换,保留后四位
     * <p>
     * 如果银行卡号为空 或者 null ,返回null ;否则,返回替换后的字符串;
     *
     * @param bankCard 银行卡号
     * @return
     */
    public static String bankCardConceal(String bankCard) {
        if (bankCard.isEmpty() || bankCard == null) {
            return null;
        } else {
            return replaceAction(bankCard, "(?<=\\d{0})\\d(?=\\d{4})");
        }
    }
    /**
     * 姓名及地址脱敏
     * @param value
     * @return
     */
    public static String nameOrAddrConceal(String value) {
        if (null == value || "".equals(value)) {
            return value;
        }
        int len = value.length();
        int pamaone = len / 2;
        int pamatwo = pamaone - 1;
        int pamathree = len % 2;
        StringBuilder stringBuilder = new StringBuilder();
        if (len <= 2) {
            if (pamathree == 1) {
                return SYMBOL;
            }
            stringBuilder.append(value.charAt(0));
            stringBuilder.append(SYMBOL);
        } else {
            if (pamatwo <= 0) {
                stringBuilder.append(value.substring(0, 1));
                stringBuilder.append(SYMBOL);
                stringBuilder.append(value.substring(len - 1, len));
            } else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
                int pamafive = (len - SIZE) / 2;
                stringBuilder.append(value.substring(0, pamafive));
                for (int i = 0; i < SIZE; i++) {
                    stringBuilder.append(SYMBOL);
                }
                if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) {
                    stringBuilder.append(value.substring(len - pamafive, len));
                } else {
                    stringBuilder.append(value.substring(len - (pamafive + 1), len));
                }
            } else {
                int pamafour = len - 2;
                stringBuilder.append(value.substring(0, 1));
                for (int i = 0; i < pamafour; i++) {
                    stringBuilder.append(SYMBOL);
                }
                stringBuilder.append(value.substring(len - 1, len));
            }
        }
        return stringBuilder.toString();
    }
/*    public static void main(String[] args) throws IOException {
        String strName= nameOrAddrConceal("张三");
        System.out.println(strName);
        String addr= nameOrAddrConceal("厦门市");
        System.out.println(addr);
        String idcard= idCardConceal("350825199012033283");
        System.out.println(idcard);
        String phone= phoneConceal("17689202624");
        System.out.println(phone);
    }*/
}

+ 57 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ConstantUtil.java

@ -0,0 +1,57 @@
package com.yihu.jw.care.util;
/**
 * 常量工具栏
 * Created by yeshijie on 2021/4/7.
 */
public class ConstantUtil {
    /**
     *  杭州市
     */
    public static final String CITY = "330100";
    /**
     * 统计level
     */
    public final static Integer doctorLevel = 6;
    public final static Integer deptLevel = 5;
    public final static Integer orgLevel = 4;
    public final static Integer townLevel = 3;
    public final static Integer cityLevel = 2;
    /**
     * 字典项定义
     *
     archiveType 档案类型
     archiveStatus 档案状态
     blood 血型
     marriage_status 婚姻状态
     national 民族
     doctor_level  医生类型
     serviceType 服务包类型
     patient_label 居民标签
     service_type 服务类型
     label_type 标签类型
     level_conclusion 评估结果
     servicePackageStatus 是否分配服务包
     capacity_agree_status 能力评估认可状态
     sex 性别
     */
    public static final String DICT_ARCHIVETYPE = "archiveType";
    public static final String DICT_ARCHIVESTATUS = "archiveStatus";
    public static final String DICT_BLOOD = "blood";
    public static final String DICT_MARRIAGE_STATUS = "marriage_status";
    public static final String DICT_NATIONAL = "national";
    public static final String DICT_DOCTOR_LEVEL = "doctor_level";
    public static final String DICT_SERVICETYPE = "serviceType";
    public static final String DICT_PATIENT_LABEL = "patient_label";
    public static final String DICT_SERVICE_TYPE = "service_type";
    public static final String DICT_LABEL_TYPE = "label_type";
    public static final String DICT_LEVEL_CONCLUSION = "level_conclusion";
    public static final String DICT_SERVICEPACKAGESTATUS= "servicePackageStatus";
    public static final String DICT_CAPACITY_AGREE_STATUS= "capacity_agree_status";
    public static final String DICT_SEX= "sex";
}

+ 33 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MessageUtil.java

@ -7,6 +7,7 @@ import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.care.lifeCare.LifeCareOrderDO;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
@ -305,6 +306,21 @@ public class MessageUtil {
        return messageDO;
    }
    public void createMessage(String title,String type,String sender,String senderName,String relationCode,String Receiver,String ReceiverName,String idCard,String msg){
        SystemMessageDO messageDO = new SystemMessageDO();
        messageDO.setTitle(title);
        messageDO.setType(type);//401为资质申请审核
        messageDO.setSender(sender);
        messageDO.setSenderName(senderName);
        messageDO.setRelationCode(relationCode);
        messageDO.setReceiver(Receiver);
        messageDO.setReceiverName(ReceiverName);
        messageDO.setOver("1");
        messageDO.setData(msg);
        messageDO.setDel("1");
        messageDO.setCreateTime(new Date());
        systemMessageDao.save(messageDO);
    }
    public void updateLifeCareMessage(LifeCareOrderDO orderDO, String[] type, String toType){
        String orderId=orderDO.getId();
@ -323,4 +339,21 @@ public class MessageUtil {
        }
    }
    public void updateSecurityMonitoringOrderMessage(SecurityMonitoringOrderDO orderDO, String[] type, String toType){
        String orderId=orderDO.getId();
        List<SystemMessageDO> messages = systemMessageDao.queryByRelationCodeAndTypeIn(orderId,type);
        if (toType.equals("patientCancel")){//居民取消 消息列表也应该不显示
            if(CollectionUtils.isEmpty(messages)){
                logger.error("当前安防工单没有系统消息!!orderId:" + orderId);
            } else {
                messages.forEach(
                        message -> {
                            message.setOver("0");
                            systemMessageDao.save(message);
                        }
                );
            }
        }
    }
}

+ 81 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MyJdbcTemplate.java

@ -0,0 +1,81 @@
package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * @author yeshijie on 2018/2/12.
 */
@Component
public class MyJdbcTemplate {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * jdbc查询返回json
     * @param sql
     * @param args
     * @return
     * @throws DataAccessException
     */
    public List<JSONObject> queryJson(String sql, Object[] args) throws DataAccessException {
        return jdbcTemplate.query(sql, args, new ResultSetExtractor<List<JSONObject>>() {
            @Override
            public List<JSONObject> extractData(ResultSet rs) throws SQLException, DataAccessException {
                ResultSetMetaData rsd = rs.getMetaData();
                int clength = rsd.getColumnCount();
                List<JSONObject> li = new ArrayList<JSONObject>();
                try {
                    while (rs.next()) {
                        JSONObject jo = new JSONObject();
                        for (int i = 0; i < clength; i++) {
                            String columnName = rsd.getColumnLabel(i + 1);
                            jo.put(columnName, rs.getObject(i + 1));
                        }
                        li.add(jo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return li;
            }
        });
    }
    public List<JSONObject> queryJson(String sql) throws DataAccessException {
        return jdbcTemplate.query(sql, new ResultSetExtractor<List<JSONObject>>() {
            @Override
            public List<JSONObject> extractData(ResultSet rs) throws SQLException, DataAccessException {
                ResultSetMetaData rsd = rs.getMetaData();
                int clength = rsd.getColumnCount();
                List<JSONObject> li = new ArrayList<JSONObject>();
                try {
                    while (rs.next()) {
                        JSONObject jo = new JSONObject();
                        for (int i = 0; i < clength; i++) {
                            String columnName = rsd.getColumnLabel(i + 1);
                            jo.put(columnName, rs.getObject(i + 1));
                        }
                        li.add(jo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return li;
            }
        });
    }
}

+ 168 - 0
svr/svr-statistics-es/doc/es/QuartzJobConfig.java

@ -0,0 +1,168 @@
package com.yihu.jw.entity.job;
import org.hibernate.annotations.GenericGenerator;
/**
 * 计划任务
 */
@Entity
@Table(name = "wlyy_job_config")
public class QuartzJobConfig implements java.io.Serializable {
	private String id;
	private String quotaId;//指标id
	private String jobName;//任务名称
	private String jobInfo;//任务描述
	private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
	private String jobClass;//任务执行的class
	private String quartzCron;//quartz表达式
	private String status;//1 启动 0停止
	private String del;//是否删除 1正常 0删除
	private String sql;
	private String sqlCount;
	private String sqlDay;
	private String sqlYear;
	private String cacheKey;//缓存的key
	/** minimal constructor */
	public QuartzJobConfig() {
	}
	/** full constructor */
	public QuartzJobConfig(String jobName, String jobInfo, String jobType,
                           String jobClass, String quartzCron, String status) {
		this.jobName = jobName;
		this.jobInfo = jobInfo;
		this.jobType = jobType;
		this.jobClass = jobClass;
		this.quartzCron = quartzCron;
		this.status = status;
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "job_name", length = 50)
	public String getJobName() {
		return this.jobName;
	}
	public void setJobName(String jobName) {
		this.jobName = jobName;
	}
	@Column(name = "job_info", length = 200)
	public String getJobInfo() {
		return this.jobInfo;
	}
	public void setJobInfo(String jobInfo) {
		this.jobInfo = jobInfo;
	}
	@Column(name = "job_type", length = 10)
	public String getJobType() {
		return this.jobType;
	}
	public void setJobType(String jobType) {
		this.jobType = jobType;
	}
	@Column(name = "job_class", length = 200)
	public String getJobClass() {
		return jobClass;
	}
	public void setJobClass(String jobClass) {
		this.jobClass = jobClass;
	}
	@Column(name = "quartz_cron", length = 200)
	public String getQuartzCron() {
		return this.quartzCron;
	}
	public void setQuartzCron(String quartzCron) {
		this.quartzCron = quartzCron;
	}
	@Column(name = "status", length = 1)
	public String getStatus() {
		return this.status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	@Column(name = "quota_id", length = 50)
	public String getQuotaId() {
		return quotaId;
	}
	public void setQuotaId(String quotaId) {
		this.quotaId = quotaId;
	}
	@Column(name = "del", length = 1)
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	public String getSql() {
		return sql;
	}
	public void setSql(String sql) {
		this.sql = sql;
	}
	public String getSqlCount() {
		return sqlCount;
	}
	public void setSqlCount(String sqlCount) {
		this.sqlCount = sqlCount;
	}
	public String getSqlDay() {
		return sqlDay;
	}
	public void setSqlDay(String sqlDay) {
		this.sqlDay = sqlDay;
	}
	public String getSqlYear() {
		return sqlYear;
	}
	public void setSqlYear(String sqlYear) {
		this.sqlYear = sqlYear;
	}
	public String getCacheKey() {
		return cacheKey;
	}
	public void setCacheKey(String cacheKey) {
		this.cacheKey = cacheKey;
	}
}

+ 127 - 0
svr/svr-statistics-es/doc/es/QuartzJobConfig1.java

@ -0,0 +1,127 @@
//package com.yihu.wlyy.entity.job;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.Id;
//import javax.persistence.Table;
//import org.hibernate.annotations.GenericGenerator;
//
///**
// * 计划任务
// */
//@Entity
//@Table(name = "wlyy_job_config")
//public class QuartzJobConfig implements java.io.Serializable {
//
//	private String id;
//	private String quotaId;//指标id
//	private String jobName;//任务名称
//	private String jobInfo;//任务描述
//	private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
//	private String jobClass;//任务执行的class
//	private String quartzCron;//quartz表达式
//	private String status;//1 启动 0停止
//	private String del;//是否删除 1正常 0删除
//
//	/** minimal constructor */
//	public QuartzJobConfig() {
//
//	}
//
//	/** full constructor */
//	public QuartzJobConfig(String jobName, String jobInfo, String jobType,
//                           String jobClass, String quartzCron, String status) {
//		this.jobName = jobName;
//		this.jobInfo = jobInfo;
//		this.jobType = jobType;
//		this.jobClass = jobClass;
//		this.quartzCron = quartzCron;
//		this.status = status;
//	}
//
//	// Property accessors
//	@GenericGenerator(name = "generator", strategy = "uuid")
//	@Id
//	@GeneratedValue(generator = "generator")
//	@Column(name = "id", unique = true, nullable = false, length = 50)
//	public String getId() {
//		return this.id;
//	}
//
//	public void setId(String id) {
//		this.id = id;
//	}
//
//	@Column(name = "job_name", length = 50)
//	public String getJobName() {
//		return this.jobName;
//	}
//
//	public void setJobName(String jobName) {
//		this.jobName = jobName;
//	}
//
//	@Column(name = "job_info", length = 200)
//	public String getJobInfo() {
//		return this.jobInfo;
//	}
//
//	public void setJobInfo(String jobInfo) {
//		this.jobInfo = jobInfo;
//	}
//
//	@Column(name = "job_type", length = 10)
//	public String getJobType() {
//		return this.jobType;
//	}
//
//	public void setJobType(String jobType) {
//		this.jobType = jobType;
//	}
//
//	@Column(name = "job_class", length = 200)
//	public String getJobClass() {
//		return jobClass;
//	}
//
//	public void setJobClass(String jobClass) {
//		this.jobClass = jobClass;
//	}
//
//	@Column(name = "quartz_cron", length = 200)
//	public String getQuartzCron() {
//		return this.quartzCron;
//	}
//
//	public void setQuartzCron(String quartzCron) {
//		this.quartzCron = quartzCron;
//	}
//
//	@Column(name = "status", length = 1)
//	public String getStatus() {
//		return this.status;
//	}
//
//	public void setStatus(String status) {
//		this.status = status;
//	}
//
//	@Column(name = "quota_id", length = 50)
//	public String getQuotaId() {
//		return quotaId;
//	}
//
//	public void setQuotaId(String quotaId) {
//		this.quotaId = quotaId;
//	}
//
//	@Column(name = "del", length = 1)
//	public String getDel() {
//		return del;
//	}
//
//	public void setDel(String del) {
//		this.del = del;
//	}
//}

+ 116 - 0
svr/svr-statistics-es/doc/es/统计新增索引.txt

@ -0,0 +1,116 @@
创建索引
POST  http://172.19.103.68:9200/hlw_quota_test
查询索引
GET http://172.19.103.68:9200/hlw_quota_test/
给索引加mapping
POST http://172.19.103.68:9200/hlw_quota_test/hlw_quota_test/_mapping
{
    "hlw_quota_test": {
            "properties": {
                "quotaCode": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "city": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "cityName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "town": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "townName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "hospital": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "hospitalName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "dept": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "deptName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "doctor": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "doctorName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey1": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey1Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey2": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey2Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey3": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey3Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey4": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey4Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "areaLevel": {
                    "type": "string",
                    "index": "not_analyzed"
                }, 
               "timeLevel": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "result1": {
                    "type": "double"
                },
                "result2": {
                    "type": "double"
                },
                "quotaDate": {
                    "type": "date"
                },
                "createTime": {
                    "type": "date"
                }
            }
        }
  }
增加索引搜索大小
PUT  http://172.19.103.68:9200/hlw_quota_test/_settings
{
  "index": {
    "max_result_window": 500000
  }
}

Datei-Diff unterdrückt, da er zu groß ist
+ 192 - 0
svr/svr-statistics-es/doc/sql/统计相关表数据备份20171121.txt


BIN
svr/svr-statistics-es/doc/业务文档/统计指标流程.docx


BIN
svr/svr-statistics-es/doc/部署文档/正式库/后台/tomcat部署.docx


+ 455 - 0
svr/svr-statistics-es/pom.xml

@ -0,0 +1,455 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-statistics-es</artifactId>
    <version>1.0.0</version>
    <modelVersion>4.0.0</modelVersion>
    <!--打成war包需要的配置-->
    <packaging>jar</packaging>
    <name>svr-statistics-es</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.commons-bean-utils>1.9.2</version.commons-bean-utils>
        <version.commons-codec>1.9</version.commons-codec>
        <version.commons-collections>3.2.1</version.commons-collections>
        <version.commons-compress>1.9</version.commons-compress>
        <version.commons-dbcp2>2.1.1</version.commons-dbcp2>
        <version.commons-dbutils>1.6</version.commons-dbutils>
        <version.commons-io>2.4</version.commons-io>
        <version.commons-lang3>3.2.1</version.commons-lang3>
        <version.commons-pool2>2.4.2</version.commons-pool2>
        <version.hibernate>5.0.12.Final</version.hibernate>
        <version.hibernate-annotations>4.0.5.Final</version.hibernate-annotations>
        <version.hibernate-jpa-api>1.0.0.Final</version.hibernate-jpa-api>
        <version.http-client>4.5.1</version.http-client>
        <version.http-core>4.4.3</version.http-core>
        <version.java>1.8</version.java>
        <version.jackson>2.6.6</version.jackson>
        <version.jedis>2.9.0</version.jedis>
        <version.jcl-over-slf4j>1.7.19</version.jcl-over-slf4j>
        <version.jul-over-slf4j>1.7.21</version.jul-over-slf4j>
        <version.joda-time>2.8.2</version.joda-time>
        <version.junit>4.12</version.junit>
        <version.log4j2>2.4.1</version.log4j2>
        <version.logback>1.1.7</version.logback>
        <version.mysql>5.1.38</version.mysql>
        <version.quartz>2.2.3</version.quartz>
        <version.servlet-api>3.1.0</version.servlet-api>
        <version.slf4j>1.7.21</version.slf4j>
        <version.tomcat-embed>8.0.28</version.tomcat-embed>
        <version.elasticsearch>2.4.6</version.elasticsearch>
        <version.jest>2.4.0</version.jest>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--Jackson library-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <!--elasticsearch start-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${version.elasticsearch}</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>${version.jest}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>shield</artifactId>
            <version>${version.elasticsearch}</version>
        </dependency>
        <!--elasticsearch end-->
        <!--Apache commons library-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${version.commons-lang3}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>${version.http-core}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${version.http-client}</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>${version.commons-bean-utils}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>${version.commons-pool2}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>${version.commons-dbutils}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${version.commons-dbcp2}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>${version.commons-collections}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>${version.commons-compress}</version>
        </dependency>
        <!--Hibernate framework-->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>${version.hibernate-jpa-api}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${version.hibernate}</version>
        </dependency>
        <!--Miscellaneous-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>${version.quartz}</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>${version.quartz}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${version.servlet-api}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${version.mysql}</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${version.joda-time}</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>${version.commons-codec}</version>
        </dependency>
        <!--Log framework-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <!--Log framework to SLF4J bridge: x-over-slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${version.jcl-over-slf4j}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-jdk14</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${version.jul-over-slf4j}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--SLF4J api-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <!--The single log BACKEND-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${version.logback}</version>
        </dependency>
        <!--Spring framework family-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <!--Spring integration family-->
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-jmx</artifactId>
        </dependency>
        <!--Spring batch family-->
        <!--Spring boot family-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-devtools</artifactId>-->
        <!--<version>${version.spring-boot}</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>de.codecentric</groupId>-->
        <!--<artifactId>spring-boot-admin-starter-client</artifactId>-->
        <!--<version>1.3.5</version>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20151123</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>delete-by-query</artifactId>
            <version>2.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->
        <!--<version>1.3.5.RELEASE</version>-->
        <!--</dependency>-->
        <!--oracle驱动-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.3</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-statistics-es</finalName>
        <plugins>
            <!--打成war包需要的配置-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <version>3.1</version>
            </plugin>
        </plugins>
    </build>
</project>

+ 120 - 0
svr/svr-statistics-es/readme.MD

@ -0,0 +1,120 @@
[es-sql](http://172.19.103.68:9200/_plugin/sql/) 例子
[elasticsearch-sql文档](https://github.com/NLPchina/elasticsearch-sql/wiki/Functions-support)
**重命名配置支持**
{elasticsearch_home}/config/elasticsearch.yml
```
script.inline: on
script.indexed: on
script.engine.groovy.inline.aggs: on
```
**目前2.4.2 es-sql不支持update delete**
6.x 系列的es支持delete
**查询表**
```SELECT * FROM wlyy_quota_test```
**条件查询表**
```SELECT * FROM wlyy_quota_test where townName='湖里区'```
**模糊查询**
SELECT * FROM wlyy_quota_test where townName like '%湖里%'
**查询返回单个字段**
```SELECT city FROM wlyy_quota_test```
**查询返回单个字段并且重命名**
```SELECT city as slavename FROM wlyy_quota_test```
**查询根据某个字段聚合**
```SELECT city  FROM wlyy_quota_test group by city```
**查询根据某个字段聚合并且重命名**
```SELECT city as slavename  FROM wlyy_quota_test group by slavename```
**条件查询并且排序表**
```SELECT * FROM wlyy_quota_test where townName='湖里区' order by createTime desc ```
**分页查询(分页查询不能与group by 同时使用)**
```SELECT city as slavename  FROM wlyy_quota_test limit 0,10```
**分页查询带条件(分页查询不能与group by 同时使用)**
```SELECT townName as slavename  FROM wlyy_quota_test where townName='湖里区' limit 0,10```
**count使用**
```SELECT count(*) num FROM wlyy_quota_test where townName='湖里区'```
**count distinct使用**
```select count( distinct town) from wlyy_quota_test```
**max使用**
```SELECT max(result1) FROM wlyy_quota_test where townName='湖里区'```
**min使用**
```SELECT min(result1) FROM wlyy_quota_test where townName='湖里区'```
**sum使用**
```select sum(result1) from wlyy_quota_test```
**按照年龄分组使用**
```SELECT count(age) FROM account GROUP BY range(age, 20,25,30,35,40)```
**时间聚合使用**
```select town,townName,sum(result1) result1 from wlyy_quota_test group by town,townName,date_histogram(field='quotaDate','interval'='month')```
interval例子
```
1天    date_histogram(field='quotaDate','interval'='1d')
每周   date_histogram(field='quotaDate','interval'='week')
每月   date_histogram(field='quotaDate','interval'='month')
每季度 date_histogram(field='quotaDate','interval'='quarter')
每年   date_histogram(field='quotaDate','interval'='year')
```
**子字段(nested)查询**
```SELECT townName.name FROM wlyy_quota_test where townName.name like '%湖里%'```
**join(只支持2个表,简单的查询 不支持分组)**
```select  table1.town town1 ,table2.townName townName2 from wlyy_quota_test table1 join wlyy_quota_test table2 on table1.town=table2.town```

+ 56 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/Application.java

@ -0,0 +1,56 @@
package com.yihu.jw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.support.ErrorPageFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
 * Created by Administrator on 2016.10.12.
 */
@SpringBootApplication
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager")
@EnableAutoConfiguration(exclude = {
        ElasticsearchAutoConfiguration.class,
        ElasticsearchRepositoriesAutoConfiguration.class,
        ElasticsearchDataAutoConfiguration.class,
        RedisRepositoriesAutoConfiguration.class
})
public class Application {
    public static ApplicationContext ctx = null;
    public static void main(String[] args) {
        ctx = SpringApplication.run(Application.class, args);
    }
    /**
     * start 解决如下问题
     * Cannot forward to error page for
     * request [/strategy/list/] as the response has already been committed. As a
     * result, the response may have the wrong status code. If your application is
     * running on WebSphere Application Server you may be able to resolve this
     * problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false
     */
    @Bean
    public ErrorPageFilter errorPageFilter() {
        return new ErrorPageFilter();
    }
    @Bean
    public FilterRegistrationBean disableSpringBootErrorFilter(ErrorPageFilter filter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(filter);
        filterRegistrationBean.setEnabled(false);
        return filterRegistrationBean;
    }
    //end
}

+ 49 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/AsyncConfig.java

@ -0,0 +1,49 @@
package com.yihu.jw.statistics.config;
import java.util.concurrent.Executor;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
 * Created by Administrator on 2016.10.18.
 * 启用多綫程
 */
@Configuration
@EnableAsync
public class AsyncConfig  {
    /** 如果池中的实际线程数小于corePoolSize,无论是否其中有空闲的线程,都会给新的任务产生新的线程 */
    private int corePoolSize = 5;
    /** 如果池中的线程数=maximumPoolSize,则有空闲线程使用空闲线程,否则新任务放入queueCapacity. */
    private int maxPoolSize = 20;
    /** 缓冲队列. */
    private int queueCapacity = 10;
    @Bean
    public Executor dbExtractExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    @Bean
    public Executor dbStorageExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

+ 240 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/DataSourceConfig.java

@ -0,0 +1,240 @@
package com.yihu.jw.statistics.config;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
 * Created by Administrator on 2016.10.20.
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize}")
    private Integer initialSize;
    @Value("${spring.datasource.minIdle}")
    private Integer minIdle;
    @Value("${spring.datasource.maxActive}")
    private Integer maxActive;
    @Value("${spring.datasource.maxWait}")
    private Integer maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle}")
    private Boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow}")
    private Boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn}")
    private Boolean testOnReturn;
    @Value("${spring.datasource.poolPreparedStatements}")
    private Boolean poolPreparedStatements;
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private Integer maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.removeAbandoned}")
    private Boolean removeAbandoned;
    @Value("${spring.datasource.removeAbandonedTimeout}")
    private Integer removeAbandonedTimeout;
    @Value("${spring.datasource.logAbandoned}")
    private Boolean logAbandoned;
    @Value("${spring.datasource.filters")
    private String filters;
    @Value("${spring.datasource.primaryReadWrite.url}")
    private String primaryReadWriteUrl;
    @Value("${spring.datasource.primaryReadWrite.username}")
    private String primaryReadWriteUsername;
    @Value("${spring.datasource.primaryReadWrite.password}")
    private String primaryReadWritePassword;
    /**
     * 主数据源
     *
     * @return
     */
    @Bean(name = "primaryReadWrite")
    @Primary//主库 默认不写名字用这个
    public DataSource primaryReadWriteDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(primaryReadWriteUrl);
        datasource.setUsername(primaryReadWriteUsername);
        datasource.setPassword(primaryReadWritePassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    @Value("${spring.datasource.primaryRead.url}")
    private String primaryReadUrl;
    @Value("${spring.datasource.primaryRead.username}")
    private String pprimaryReadUsername;
    @Value("${spring.datasource.primaryRead.password}")
    private String primaryReadPassword;
    @Bean(name = "primaryRead")
    public DataSource primaryReadDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(primaryReadUrl);
        datasource.setUsername(pprimaryReadUsername);
        datasource.setPassword(primaryReadPassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    @Value("${spring.datasource.im.url}")
    private String imUrl;
    @Value("${spring.datasource.im.username}")
    private String imUsername;
    @Value("${spring.datasource.im.password}")
    private String imPassword;
    @Bean(name = "imData")
    public DataSource imDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(imUrl);
        datasource.setUsername(imUsername);
        datasource.setPassword(imPassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    private Properties properties() {
        Properties properties = new Properties();
        properties.put("druid.stat.mergeSql", "true");
        properties.put("slowSqlMillis", "1000");
        return properties;
    }
    //------------------------------------druid 监控----------------------------------------------
    @Bean
    public ServletRegistrationBean statViewServlet() {
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //设置ip白名单
        //servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
        // servletRegistrationBean.addInitParameter("deny","192.168.0.19");
        //设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "jkzl");
        servletRegistrationBean.addInitParameter("loginPassword", "jkzlehr");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean filterRegistrationBean(WebStatFilter webStatFilter) {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(webStatFilter);
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
    @Bean
    public StatFilter statFilter() {
        return new StatFilter();
    }
    @Bean
    public WebStatFilter webStatFilter() {
        return new WebStatFilter();
    }
    //------------------------------------druid 监控----------------------------------------------
}

+ 30 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/MVCConfig.java

@ -0,0 +1,30 @@
package com.yihu.jw.statistics.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
 * Created by chenweida on 2017/7/17.
 */
@Configuration
public class MVCConfig extends WebMvcConfigurerAdapter {
    /**
     * 为null的数据不返回
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(mappingJackson2HttpMessageConverter);
    }
}

+ 61 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/SwaggerConfig.java

@ -0,0 +1,61 @@
package com.yihu.jw.statistics.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    private static final String PUBLIC_API = "Default";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Bean
    public Docket publicAPI() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(PUBLIC_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(or(
                        regex("/job/.*"),
                        regex("/quotaQuery/.*"),
                        regex("/extractDataToEs/.*")
                ))
                .build()
                .apiInfo(publicApiInfo());
    }
    private ApiInfo publicApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台统计分析API",
                "统计分析接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
}

+ 55 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/WebSecurityConfig.java

@ -0,0 +1,55 @@
package com.yihu.jw.statistics.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * Created by Administrator on 2016.10.17.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${security.basic.username}")
    String username;
    @Value("${security.basic.password}")
    String password;
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/metrics/**").permitAll()
                .antMatchers("/health/**").permitAll()
                .antMatchers("/env/**").permitAll()
                .antMatchers("/dump/**").permitAll()
                .antMatchers("/trace/**").permitAll()
                .antMatchers("/mappings/**").permitAll()
                .antMatchers("/actuator/**").permitAll()
                .antMatchers("/beans/**").permitAll()
                .antMatchers("/configprops/**").permitAll()
                .antMatchers("/docs/**").permitAll()
                .antMatchers("/info/**").permitAll()
                .antMatchers("/configuration/**").permitAll()
                .antMatchers("/jolokia/**").permitAll()
                .antMatchers("/job/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().defaultSuccessUrl("/swagger-ui.html").failureUrl("/login") //登录成功之后的跳转
                .permitAll()
                .and()
                .logout().logoutSuccessUrl("/login")
                .permitAll();
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                .withUser(username).password(password).roles("USER");
    }
}

+ 0 - 0
svr/svr-statistics-es/src/main/java/com/yihu/jw/statistics/config/jpa/HibernateProperties.java


Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.