浏览代码

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

wangzhinan 1 年之前
父节点
当前提交
ab0f53baeb
共有 100 个文件被更改,包括 71 次插入19293 次删除
  1. 4 5
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/dao/OutpatientDao.java
  2. 15 1
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/DsyyPrescriptionService.java
  3. 12 4
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java
  4. 7 1
      business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java
  5. 31 1
      common/common-entity/src/db/2023.sql
  6. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java
  7. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderDO.java
  8. 0 330
      svr/svr-after-diagnosis/pom.xml
  9. 0 6
      svr/svr-after-diagnosis/readme.MD
  10. 0 24
      svr/svr-after-diagnosis/src/mian/java/com/yihu/SvrAfterDiagnosisApplication.java
  11. 0 20
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DeviceCategoryDao.java
  12. 0 21
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DeviceDao.java
  13. 0 128
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DevicePatientHealthIndexDao.java
  14. 0 10
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DeviceWxMessageDao.java
  15. 0 27
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DoctorHealthStandardDao.java
  16. 0 12
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientAimBloodPressureDao.java
  17. 0 13
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientAimBloodSuggerDao.java
  18. 0 23
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientAimSportsDao.java
  19. 0 14
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientBloodSuggerDao.java
  20. 0 57
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientDeviceDao.java
  21. 0 20
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientDeviceLogDao.java
  22. 0 27
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientHealthStandardDao.java
  23. 0 35
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientHealthTimeDao.java
  24. 0 18
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/dict/DmDrugsGroupItemDao.java
  25. 0 146
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowUpDao.java
  26. 0 23
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowupContentDao.java
  27. 0 22
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowupDrugsDao.java
  28. 0 15
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowupSignDao.java
  29. 0 17
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionAdjustDao.java
  30. 0 12
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionAdjustReasonDao.java
  31. 0 41
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionDispensaryCodeDao.java
  32. 0 29
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionFollowupContentDao.java
  33. 0 20
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionPayDao.java
  34. 0 20
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionReviewedDao.java
  35. 0 21
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/FrequencyDao.java
  36. 0 15
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/GuidanceMessageLogDao.java
  37. 0 17
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientDiagnosisInformationDao.java
  38. 0 26
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientDischargeDao.java
  39. 0 29
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientDiseaseServerDao.java
  40. 0 12
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientHospitalRecordDao.java
  41. 0 18
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientMedicalRecordsRehabilitationDao.java
  42. 0 56
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientRehabilitationPlanDao.java
  43. 0 11
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientRehabilitationPlanLogDao.java
  44. 0 20
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationAdviceDao.java
  45. 0 13
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationDetailAppointmentDao.java
  46. 0 94
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationDetailDao.java
  47. 0 14
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationGuidanceDao.java
  48. 0 17
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationGuidancePatientDao.java
  49. 0 38
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationOperateRecordsDao.java
  50. 0 19
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationPlanTemplateDao.java
  51. 0 16
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationServiceItemDao.java
  52. 0 18
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationTemplateDetailDao.java
  53. 0 24
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialDiseaseMessagesDao.java
  54. 0 16
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistEvaluateDao.java
  55. 0 15
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistEvaluateLabelDao.java
  56. 0 15
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistEvaluateScoreDao.java
  57. 0 22
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistHospitalServiceItemDao.java
  58. 0 41
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistPatientRelationDao.java
  59. 0 27
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistServiceItemDao.java
  60. 0 17
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistServiceItemOperateLogDao.java
  61. 0 843
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/BaseController.java
  62. 0 387
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/device/DoctorDeviceController.java
  63. 0 365
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/device/PatientDeviceController.java
  64. 0 740
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorFollowUpController.java
  65. 0 80
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorFollowupDrugsController.java
  66. 0 79
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorPhthisisFollowupController.java
  67. 0 344
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorVisitDetailController.java
  68. 0 691
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/health/DoctorHealthController.java
  69. 0 564
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/health/PatientHealthController.java
  70. 0 292
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionController.java
  71. 0 77
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionFollowupContentController.java
  72. 0 204
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionInfoController.java
  73. 0 106
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionLogController.java
  74. 0 362
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionPayController.java
  75. 0 80
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionAdjustController.java
  76. 0 131
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionCodeController.java
  77. 0 148
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionExpressageController.java
  78. 0 671
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionInfoController.java
  79. 0 140
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionLogController.java
  80. 0 93
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorDiagnosisInformationController.java
  81. 0 212
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorRehabilitaionInfoController.java
  82. 0 1134
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorRehabilitationManageController.java
  83. 0 264
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorRehabilitationPlanController.java
  84. 0 537
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/PatientRehabilitationManageController.java
  85. 0 189
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/DeviceDetailService.java
  86. 0 51
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/DeviceService.java
  87. 0 93
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/DeviceWxMessageService.java
  88. 0 129
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/PatientDeviceLogService.java
  89. 0 653
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/PatientDeviceService.java
  90. 0 1934
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/PatientHealthIndexService.java
  91. 0 3411
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/FollowUpService.java
  92. 0 105
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/FollowupDrugsService.java
  93. 0 217
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/PhthisisFollowupService.java
  94. 0 1051
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/VisitDetailService.java
  95. 0 276
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PatientPrescriptionPayService.java
  96. 0 217
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionAdjustService.java
  97. 0 110
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionAdressService.java
  98. 0 163
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionDiagnosisService.java
  99. 0 376
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionDispensaryCodeService.java
  100. 0 0
      svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionFollowupContentService.java

+ 4 - 5
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/dao/OutpatientDao.java

@ -5,7 +5,6 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@ -18,12 +17,12 @@ public interface OutpatientDao extends JpaRepository<WlyyOutpatientDO, String>,
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and a.outpatientType <> '3' and a.outpatientType <> '4' and a.status in(0,1,2)")
    List<WlyyOutpatientDO> findByPatientList(String patient);
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and  a.outpatientType = '3' and a.status in(0,1,2)")
    List<WlyyOutpatientDO> findByPatientAndDoctorList(String patient);
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and  a.outpatientType = ?2 and a.status in('0','1','2')")
    List<WlyyOutpatientDO> findByPatientAndDoctorList(String patient,String outpatientType);
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and a.outpatientType <> '3' and a.status in(3) order by a.createTime desc ")
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and a.outpatientType <> '3' and a.status in('3') order by a.createTime desc ")
    List<WlyyOutpatientDO> findByPatientListByStatus(String patient);
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and a.outpatientType = ?2  and a.status in(3) order by a.createTime desc ")
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and a.outpatientType = ?2  and a.status in('3') order by a.createTime desc ")
    List<WlyyOutpatientDO> findByPatientListByStatusAndType(String patient,String outpatientType);
    @Query("from WlyyOutpatientDO a where a.patient = ?1 and a.hisStatus=1 and a.createTime>=?2 and a.createTime<=?3")

+ 15 - 1
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/DsyyPrescriptionService.java

@ -263,11 +263,25 @@ public class DsyyPrescriptionService extends BaseJpaService<WlyyPrescriptionDO,
         * @return
         * @throws Exception
         */
    public JSONArray findCardNo(String patient) throws Exception {
    public JSONArray findCardNo(String patient,boolean demoFlag) throws Exception {
        BasePatientDO patientDO = patientDao.getOne(patient);
        if (patientDO==null){
            throw new Exception("不存在该患者!");
        }
        if(demoFlag){
            JSONArray rs =new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("PAT_NO","P5616242-0");
            jsonObject.put("CARD_NO","D40136791");
            jsonObject.put("CARD_STAT","激活");
            jsonObject.put("OP_DATE","2011-09-27 15:35:57");
            jsonObject.put("CARD_TYPE","2");
            jsonObject.put("CARD_TYPE_NAME","社保卡");
            jsonObject.put("social_no","350211198411053024");
            jsonObject.put("name","白海灵");
            rs.add(jsonObject);
            return rs;
        }
        patientMedicareCardDao.deleteByPatientId(patient);
        JSONArray array = dsyyEntranceService.findCardNo(patientDO.getIdcard());
        for (int i=0;i<array.size();i++){

+ 12 - 4
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java

@ -1166,6 +1166,8 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
            businessOrderService.recharge(outpatient.getId(), "协同复诊-诊查费", "5", "协同复诊-诊查费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }else if ("3".equalsIgnoreCase(outpatient.getOutpatientType())){
            BusinessOrderDO businessOrderDO = businessOrderService.recharge(outpatient.getId(), "专家咨询费", "1", "专家咨询费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }else if ("4".equalsIgnoreCase(outpatient.getOutpatientType())){
            BusinessOrderDO businessOrderDO = businessOrderService.recharge(outpatient.getId(), "康复咨询费", "6", "康复咨询费", outpatient.getConsumer(), outpatient.getConsumerName(), outpatient.getDoctor(), price);
        }
@ -1182,7 +1184,7 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        } catch (Exception e) {
            throw new RuntimeException("号源已经被预约,请选择其他号源");
        }
        if (!outpatientDO.getOutpatientType().equalsIgnoreCase("3")){
        if (!outpatientDO.getOutpatientType().equalsIgnoreCase("3")&&!outpatientDO.getOutpatientType().equalsIgnoreCase("4")){
            if (1==expressageDO.getOneselfPickupFlg()){
                if("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
                    String drugCode= expressageDO.getHospitalCode()==null?"5550":expressageDO.getHospitalCode();
@ -1526,8 +1528,8 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        //2.判断是否有未结束的
        List<WlyyOutpatientDO> list = new ArrayList<>();
        if(StringUtils.isNotBlank(outpatientType)&&outpatientType.equalsIgnoreCase("3")){
            list = outpatientDao.findByPatientAndDoctorList(patient);
        if(StringUtils.isNotBlank(outpatientType)&&(outpatientType.equalsIgnoreCase("3")||outpatientType.equalsIgnoreCase("4"))){
            list = outpatientDao.findByPatientAndDoctorList(patient,outpatientType);
        }else {
            list = outpatientDao.findByPatientList(patient);
        }
@ -6006,7 +6008,10 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
    }
    public List<WlyyHospitalSysDictDO> findCancelReasonList() {
    public List<WlyyHospitalSysDictDO> findCancelReasonList(String type) {
        if("28".equals(type)){
            return sysDictDao.findByDictName("PatientCancel28");
        }
        return sysDictDao.findByDictName("PatientCancel");
    }
@ -6143,6 +6148,9 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
        } else if (4==type){
            //专家咨询
            sql += " AND room.reservation_type=3 AND room.consult_type =1";
        } else if (5==type){
            //康复咨询
            sql += " AND room.reservation_type=4 AND room.consult_type =1";
        } else if (1==type) {
            //在线复诊
            sql += " AND room.reservation_type=1 AND room.consult_type =1";

+ 7 - 1
business/im-service/src/main/java/com/yihu/jw/im/service/ImService.java

@ -1569,6 +1569,7 @@ public class ImService {
        }else if("4".equals(wlyyOutpatientDO.getOutpatientType())){
            users.put(patient, 0);
            ct.setType(28);
            consultTitle = "申请康复咨询";
        } else {
            users.put(patient, 0);
@ -4248,7 +4249,9 @@ public class ImService {
                sql += " AND op.type =2 and op.outpatient_type = 3";
            } else if (type.equalsIgnoreCase("12")) {
                sql += " AND op.outpatient_type = 2";
            } else {
            } else if (type.equalsIgnoreCase("28")) {
                sql += " AND op.outpatient_type = 4";
            }else {
                sql += " AND op.type in (1,2,3) ";
            }
        }
@ -4299,6 +4302,9 @@ public class ImService {
                if ("2".equalsIgnoreCase(map.get("outpatientType").toString())) {
                    map.put("type", 12);
                }
                if ("4".equalsIgnoreCase(map.get("outpatientType").toString())) {
                    map.put("type", 28);
                }
            }
            if (map.get("id") != null) {
                if ("1".equals(type) || "15".equals(type) || type.contains(",") || "17".equals(type)) {

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

@ -461,4 +461,34 @@ CREATE TABLE `wlyy_patient_device_log` (
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12773 DEFAULT CHARSET=utf8mb4;
ALTER table wlyy_patient_health_index add COLUMN `is_upload` tinyint(1) DEFAULT NULL COMMENT '是否上传物联网 0和null否 1是,2失败';
ALTER table wlyy_patient_health_index add COLUMN `is_upload` tinyint(1) DEFAULT NULL COMMENT '是否上传物联网 0和null否 1是,2失败';
-- 2023-12-25 ysj
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('PatientCancel28', NULL, 'PatientCancel28', '1', '咨询信息填写错误', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('PatientCancel281', NULL, 'PatientCancel28', '2', '临时有事,无法按时复诊', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
INSERT INTO `base`.`wlyy_hospital_sys_dict` (`id`, `saas_id`, `dict_name`, `dict_code`, `dict_value`, `py_code`, `sort`, `hospital`, `create_time`, `create_user`, `create_user_name`, `update_time`, `update_user`, `update_user_name`, `img_url`, `model_name`) VALUES ('PatientCancel282', NULL, 'PatientCancel28', '3', '其他', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
CREATE TABLE `wlyy_patient_aim_sports` (
   `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id主键,与业务主键无关',
   `code` varchar(50) NOT NULL COMMENT '业务主键UUID',
   `patientcode` varchar(50) DEFAULT NULL COMMENT '患者CODE',
   `daily_step_count` int(11) DEFAULT NULL COMMENT '每日步数',
   `bmi_max` varchar(10) DEFAULT NULL COMMENT '体重指数BMI标准值上限',
   `bmi_min` varchar(10) DEFAULT NULL COMMENT '体重指数BMI标准值下限',
   `create_date` varchar(10) DEFAULT NULL COMMENT '上传日期',
   `create_time` datetime DEFAULT NULL COMMENT '创建时间',
   PRIMARY KEY (`id`),
   UNIQUE KEY `code` (`patientcode`,`create_date`) USING BTREE
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COMMENT='患者-运动目标';
INSERT INTO `dm_sports_type` (`id`, `code`, `name`, `del`) VALUES ('1', '1', '轻度运动', '1');
INSERT INTO `dm_sports_type` (`id`, `code`, `name`, `del`) VALUES ('2', '2', '中度运动', '1');
INSERT INTO `dm_sports_type` (`id`, `code`, `name`, `del`) VALUES ('3', '3', '稍强运动', '1');
INSERT INTO `dm_sports_type` (`id`, `code`, `name`, `del`) VALUES ('4', '4', '强度运动', '1');
INSERT INTO `dm_sports` (`id`, `code`, `name`, `type`, `del`) VALUES ('1', '1', '购物', NULL, '1');
INSERT INTO `dm_sports` (`id`, `code`, `name`, `type`, `del`) VALUES ('2', '2', '散步', NULL, '1');
INSERT INTO `dm_sports` (`id`, `code`, `name`, `type`, `del`) VALUES ('3', '3', '做操', NULL, '1');
INSERT INTO `dm_sports` (`id`, `code`, `name`, `type`, `del`) VALUES ('4', '4', '太极拳', NULL, '1');
INSERT INTO `dm_sports` (`id`, `code`, `name`, `type`, `del`) VALUES ('5', '5', '气功', NULL, '1');
INSERT INTO `dm_sports` (`id`, `code`, `name`, `type`, `del`) VALUES ('6', '6', '跑步', NULL, '1');

+ 1 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/im/ConsultTeamDo.java

@ -27,6 +27,7 @@ public class ConsultTeamDo extends UuidIdentityEntity {
	// 23 新生儿在线咨询
	// 24 老人在线咨询
	// 25
	// 28 康复咨询
	private String patient;         // 提问者标识
	private String name;            // 患者姓名
	private Integer sex;            // 患者性别

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/order/BusinessOrderDO.java

@ -27,7 +27,7 @@ public class BusinessOrderDO extends IntegerIdentityEntity {
     */
    private Integer orderType;
    /**
     * 互联网医院- 1:专家咨询|2:图文诊室|3:视频诊室|4处方结算|5就诊卡充值)
     * 互联网医院- 1:专家咨询|2:图文诊室|3:视频诊室|4处方结算|5就诊卡充值 6康复咨询)
     * 医养项目 订单分类 orderType=1 时 1招生,2 课程,3 上门辅导托幼) 4 生活照料
     */
    private String orderCategory;

+ 0 - 330
svr/svr-after-diagnosis/pom.xml

@ -1,330 +0,0 @@
<?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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.4.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-after-diagnosis</artifactId>
    <packaging>jar</packaging>
    <version>${project.parent.version}</version>
    <dependencies>
        <!-- 支持Tomcat启动 -->
        <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>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--注释掉就不会读取git的配置,只会读取yml中的配置-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>
        <dependency>
            <groupId>com.ylz.dmrh</groupId>
            <artifactId>ehcsdk-java-sdk-base</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity-es</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>wxpay-sdk</artifactId>
            <version>3.0.9</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-request-mapping</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-exception</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-util</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <!-- 文件服务器 -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>fastdfs-starter</artifactId>
        </dependency>
        <!-- Jzkl Starter -->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>swagger-starter</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>${version.yihu-common}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <!-- <scope>runtime</scope> -->
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>elasticsearch-starter</artifactId>
            <version>${version.wlyy-common}</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>mailapi</artifactId>
                    <groupId>javax.mail</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--   poi xml导入导出工具 start-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>com.yihu.ehr</groupId>
                    <artifactId>commons-util</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.commons</groupId>
                    <artifactId>commons-collections4</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
        </dependency>
        <!-- xlsx  依赖这个包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <!--   poi xml导入导出工具 end -->
        <!--基础业务组件-->
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>base-service</artifactId>
            <version>${version.wlyy-common}</version>
            <exclusions>
                <exclusion>
                    <groupId>xalan</groupId>
                    <artifactId>xalan</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--缩略图-->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>${version.json-lib}</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>
            <version>${version.wlyy-common}</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>sms-service</artifactId>
            <version>${version.wlyy-common}</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>es-service</artifactId>
            <version>${version.wlyy-common}</version>
        </dependency>
        <!--oracle驱动-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>${version.oracle}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>svr-after-diagnosis</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <!-- 生成的jar中,不要包含pom.xml和pom.properties这两个文件 -->
                        <addMavenDescriptor>false</addMavenDescriptor>
                        <manifest>
                            <!-- 是否要把第三方jar加入到类构建路径 -->
                            <addClasspath>true</addClasspath>
                            <!-- 外部依赖jar包的最终位置 -->
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.yihu.SvrInternetHospitalApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!--拷贝依赖到jar外面的lib目录-->
            <plugin>
                <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>
                    <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>
</project>

+ 0 - 6
svr/svr-after-diagnosis/readme.MD

@ -1,6 +0,0 @@
svr-after-diagnosies 互联网医院 诊后服务
包括
慢病管理
随访管理
处方续方
康复管理

+ 0 - 24
svr/svr-after-diagnosis/src/mian/java/com/yihu/SvrAfterDiagnosisApplication.java

@ -1,24 +0,0 @@
package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
 * Created by yeshijie on 2023/2/10.
 */
@SpringBootApplication
@EnableJpaAuditing
public class SvrAfterDiagnosisApplication extends SpringBootServletInitializer {
    public static void main(String[] args)  {
        SpringApplication.run(SvrAfterDiagnosisApplication.class, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SvrAfterDiagnosisApplication.class);
    }
}

+ 0 - 20
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DeviceCategoryDao.java

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

+ 0 - 21
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DeviceDao.java

@ -1,21 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.afterDiagnosis.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();
}

+ 0 - 128
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DevicePatientHealthIndexDao.java

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

+ 0 - 10
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DeviceWxMessageDao.java

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

+ 0 - 27
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/DoctorHealthStandardDao.java

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

+ 0 - 12
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientAimBloodPressureDao.java

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

+ 0 - 13
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientAimBloodSuggerDao.java

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

+ 0 - 23
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientAimSportsDao.java

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

+ 0 - 14
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientBloodSuggerDao.java

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

+ 0 - 57
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientDeviceDao.java

@ -1,57 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.device;
import com.yihu.jw.entity.patient.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);
    @Query("select pd from PatientDevice pd where pd.deviceSn = ?1 ")
    List<PatientDevice> findByDeviceSn2(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,BasePatientDO p where a.userIdcard=p.idcard")
    List<PatientDevice> findWithArrdess();
    @Query("select a from PatientDevice a")
    List<PatientDevice> findAll();
}

+ 0 - 20
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientDeviceLogDao.java

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

+ 0 - 27
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientHealthStandardDao.java

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

+ 0 - 35
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/device/PatientHealthTimeDao.java

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

+ 0 - 18
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/dict/DmDrugsGroupItemDao.java

@ -1,18 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.afterDiagnosis.dao.dict;
import com.yihu.jw.entity.base.dict.DmDrugsGroupItem;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DmDrugsGroupItemDao extends PagingAndSortingRepository<DmDrugsGroupItem, Long>, JpaSpecificationExecutor<DmDrugsGroupItem> {
    @Query(value = "select b.* from wlyy_followup_class_drugs a,dm_drugs_group_item b left join dm_drugs_group c on c.group_code = b.group_code and c.status='1' where a.drugs_code=b.drugs_code and a.followup_class=?1 and b.status='1' order by c.order,b.order",nativeQuery = true)
    List<DmDrugsGroupItem> findByFollowupClass(String followupClass) throws Exception;
}

+ 0 - 146
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowUpDao.java

@ -1,146 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.afterDiagnosis.dao.followup;
import com.yihu.jw.entity.followup.Followup;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
import java.util.Set;
public interface FollowUpDao extends PagingAndSortingRepository<Followup, Long>, JpaSpecificationExecutor<Followup> {
    @Query("select a.followupDate from Followup a where a.doctorCode = ?1 and a.patientCode = ?2 and a.followupClass = '9'" )
    List<Date> findFollowupDateList(String doctor,String patientCode) throws Exception;
    @Query("select a.status from Followup a where a.doctorCode = ?1 and a.patientCode = ?2 and a.followupClass = '9'" )
    Set findStatusList(String doctor, String patientCode) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.patientCode = ?2 and a.followupClass = '9' order by a.followupPlanDate asc")
    List<Followup> findFollowupList(String doctor,String patientCode) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.patientCode = ?2 and a.followupDate = ?3 and a.followupClass = '9'")
    Followup findFollowupByDate(String doctor,String patientCode,Date followupDate) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupDate between ?2 and ?3 and a.status <> '0'")
    List<Followup> findByDoctor(String doctor, Date begin, Date end) throws Exception;
    //查询未完成有效随访记录
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupDate between ?2 and ?3 and a.status NOT IN ('0', '1') ")
    List<Followup> getByDoctor(String doctor, Date begin, Date end) throws Exception;
    //查询未完成有效随访计划记录
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupPlanDate between ?2 and ?3 and a.status NOT IN ('0', '1') ")
    List<Followup> getByDoctorPlan(String doctor, Date begin, Date end) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupPlanDate between ?2 and ?3 and a.status <> '0' and a.followupClass=?4 and a.patientName like ?5 order by a.followupPlanDate DESC")
    List<Followup> findAllDoctorPlan(String doctor, Date begin, Date end,String followupClass,String patientName) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupPlanDate between ?2 and ?3 and a.status <> '0' and a.patientCode = ?4 and a.followupClass = ?5 and a.patientName like ?6 order by a.followupPlanDate DESC")
    List<Followup> findAllDoctorPlan(String doctor, Date begin, Date end,String patientCode,String followupClass,String patientName) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupPlanDate between ?2 and ?3 and a.status <> '0' and a.patientCode = ?4 and a.followupClass = ?5 and a.patientName like ?6 and a.followupClass in('5','6','7','8','9') order by a.followupPlanDate DESC")
    List<Followup> findAllDoorDoctorPlan(String doctor, Date begin, Date end,String patientCode,String followupClass,String patientName) throws Exception;
    @Query("select a from Followup a where a.doctorCode = ?1 and a.followupPlanDate between ?2 and ?3 and a.status <> '0' and a.followupClass=?4 and a.patientName like ?5 and a.followupClass in('5','6','7','8','9') order by a.followupPlanDate DESC")
    List<Followup> findAllDoorDoctorPlan(String doctor, Date begin, Date end,String followupClass,String patientName) throws Exception;
    @Query("select a from Followup a where a.patientCode = ?1 and a.status <> '0' and a.doctorCode = ?2 order by a.followupPlanDate DESC")
    List<Followup> findAllPatientPlan(String patientCode,String doctorCode) throws Exception;
    @Query("select a from Followup a where a.creater = ?1 and a.followupDate between ?2 and ?3 and a.status <> '0'")
    List<Followup> findByCreater(String creater, Date begin, Date end, Pageable pageRequest) throws Exception;
    @Query(value = "select a.* from wlyy_followup a where a.doctor_code in ?1 and a.patient_code = ?2 and a.followup_class=?3 and a.status ='1' order by a.followup_date DESC limit 1",nativeQuery = true)
    Followup findLastFollowup(String[] doctors,String patientCode,String followClass) throws Exception;
    /**
     * 查找所有的随访数据
     * @param patient
     * @param teamCode
     * @param pageable
     * @return
     */
    @Query("select distinct d.id,d.name,d.photo,a.followupType,a.followupClass,a.status,a.createTime,a.updateTime,a.followupManagerStatus,c.id,c.name,c.photo" + ",a.followupDate,a.followupPlanDate,a.followupNextDate,a.id,a.followupNo,a.prescriptionCode,a.type from Followup a, BaseDoctorDO d, BaseDoctorDO c where a.doctorCode = d.id and a.creater = c.id and a.patientCode = ?1 and (a.adminTeamCode = ?2 or a.doctorCode=?3) and a.status > '0'")
    Page<Object> findByPatientAndTeam(String patient, Long teamCode, String doctor,Pageable pageable);
    /**
     * 查找所有的随访数据
     * @param patient
     * @param pageable
     * @return
     */
    @Query("select d.id,d.name,d.photo,a.followupType,a.followupClass,a.status,a.createTime,a.updateTime,a.followupManagerStatus,c.id,c.name,c.photo" + ",a.followupDate,a.followupPlanDate,a.followupNextDate,a.id,a.followupNo,a.prescriptionCode from Followup a, BaseDoctorDO d, BaseDoctorDO c where a.doctorCode = d.id and a.creater = c.id and a.patientCode = ?1  and a.status > '0'")
    Page<Object> findByPatient(String patient, Pageable pageable);
    /**
     * 查找所有的随访计划(未开始的归类为计划)
     * @param patient
     * @param pageable
     * @return
     */
    @Query("select d.id,d.name,d.photo,a.followupType,a.followupClass,a.status,a.createTime,a.updateTime,a.followupManagerStatus,c.id,c.name,c.photo" + ",a.followupDate,a.followupPlanDate,a.followupNextDate,a.id,a.followupNo,a.prescriptionCode from Followup a, BaseDoctorDO d, BaseDoctorDO c where a.doctorCode = d.id and a.creater = c.id and a.patientCode = ?1 and a.status = '2'")
    Page<Object> findPlanByPatient(String patient, Pageable pageable);
    /**
     * 查找所有的随访记录(进行中的,已完整的的归类为计划)
     * @param patient
     * @param pageable
     * @return
     */
    @Query("select d.id,d.name,d.photo,a.followupType,a.followupClass,a.status,a.createTime,a.updateTime,a.followupManagerStatus,c.id,c.name,c.photo" + ",a.followupDate,a.followupPlanDate,a.followupNextDate,a.id,a.followupNo,a.prescriptionCode from Followup a, BaseDoctorDO d, BaseDoctorDO c where a.doctorCode = d.id and a.creater = c.id and a.patientCode = ?1 and (a.status = '1' or a.status = '3')")
    Page<Object> findRecordByPatient(String patient, Pageable pageable);
    
    /**
     * 查找所有的随访计划(未开始的归类为计划)
     * @param patient
     * @param teamCode
     * @param pageable
     * @return
     */
    @Query("select distinct d.id,d.name,d.photo,a.followupType,a.followupClass,a.status,a.createTime,a.updateTime,a.followupManagerStatus,c.id,c.name,c.photo" + ",a.followupDate,a.followupPlanDate,a.followupNextDate,a.id,a.followupNo,a.prescriptionCode,a.type from Followup a, BaseDoctorDO d, BaseDoctorDO c where a.doctorCode = d.id and a.creater = c.id and a.patientCode = ?1 and (a.adminTeamCode = ?2 or a.doctorCode=?3) and a.status = '2'")
    Page<Object> findPlanByPatientAndTeam(String patient, Long teamCode,String doctor, Pageable pageable);
    /**
     * 查找所有的随访记录(进行中的,已完整的的归类为计划)
     * @param patient
     * @param teamCode
     * @param pageable
     * @return
     */
    @Query("select distinct d.id,d.name,d.photo,a.followupType,a.followupClass,a.status,a.createTime,a.updateTime,a.followupManagerStatus,c.id,c.name,c.photo" + ",a.followupDate,a.followupPlanDate,a.followupNextDate,a.id,a.followupNo,a.prescriptionCode,a.type from Followup a, BaseDoctorDO d, BaseDoctorDO c where a.doctorCode = d.id and a.creater = c.id and a.patientCode = ?1 and (a.adminTeamCode = ?2 or a.doctorCode=?3) and (a.status = '1' or a.status = '3')")
    Page<Object> findRecordByPatientAndTeam(String patient, Long teamCode,String doctor, Pageable pageable);
    
    /**
     * 根据续方CODE获取随访记录
     * @param prescriptionCode
     * @return
     */
    @Query("select a from Followup a where a.prescriptionCode = ?1 and a.status <> '0'")
	Followup getFollowupByPrescriptionCode(String prescriptionCode);
    
    @Modifying
    @Query("update Followup a set a.status=?2 where a.prescriptionCode = ?1 ")
    void updateStatusByPrescriptionCode(String prescriptionCode, String status);
    @Query("select a from Followup a where a.patientCode = ?1 and a.followupClass = ?2 and a.status = '1' order by a.followupDate desc")
    List<Followup> findAllByPatientCodeAndClass(String patientCode, String followupClass);
    @Query("select a from Followup a where a.patientCode = ?1 and a.type = ?2 order by a.visitCount asc")
    List<Followup> findAllByPatientCodeAndType(String patientCode, Integer type);
    @Query("select a from Followup a where a.patientCode = ?1 and a.type = ?2 and a.status=?3 order by a.visitCount asc")
    List<Followup> findListByPatientAndType(String patientCode, Integer type,String status);
}

+ 0 - 23
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowupContentDao.java

@ -1,23 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.afterDiagnosis.dao.followup;
import com.yihu.jw.entity.followup.FollowupContent;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FollowupContentDao extends PagingAndSortingRepository<FollowupContent, Long>, JpaSpecificationExecutor<FollowupContent> {
    @Query("select distinct a.followupProject from FollowupContent a where a.followupId=?1")
    List<String> findProjectByFollowupId(Long followupId) throws Exception;
    List<FollowupContent> findByFollowupIdAndFollowupProject(Long followupId,String followupProject);
    List<FollowupContent> findByFollowupId(Long followupId);
}

+ 0 - 22
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowupDrugsDao.java

@ -1,22 +0,0 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.afterDiagnosis.dao.followup;
import com.yihu.jw.entity.followup.FollowupDrugs;
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 FollowupDrugsDao extends PagingAndSortingRepository<FollowupDrugs, Long>, JpaSpecificationExecutor<FollowupDrugs> {
    @Modifying
    @Query("delete from FollowupDrugs a where a.followupId=?1")
    int deleteByFollowupId(Long followupId) throws Exception;
    List<FollowupDrugs> findByFollowupId(Long followupId) throws Exception;
}

+ 0 - 15
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/followup/FollowupSignDao.java

@ -1,15 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.followup;
import com.yihu.jw.entity.followup.FollowupSign;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2019/4/22.
 */
public interface FollowupSignDao extends PagingAndSortingRepository<FollowupSign, Long>, JpaSpecificationExecutor<FollowupSign> {
    List<FollowupSign> findByFollowupIdAndDel(Long followupId,Integer del);
}

+ 0 - 17
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionAdjustDao.java

@ -1,17 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.prescription;
import com.yihu.jw.entity.hospital.prescription.PrescriptionAdjust;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2017/8/2.
 */
public interface PrescriptionAdjustDao extends PagingAndSortingRepository<PrescriptionAdjust, Long>,JpaSpecificationExecutor<PrescriptionAdjust> {
    List<PrescriptionAdjust> findByPrescriptionCode(String code);
    List<PrescriptionAdjust> findByPrescriptionCodeOrderByIdDesc(String code);
}

+ 0 - 12
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionAdjustReasonDao.java

@ -1,12 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.prescription;
import com.yihu.jw.entity.hospital.prescription.PrescriptionAdjustReason;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2017/8/26.
 */
public interface PrescriptionAdjustReasonDao extends PagingAndSortingRepository<PrescriptionAdjustReason, Long>, JpaSpecificationExecutor<PrescriptionAdjustReason> {
}

+ 0 - 41
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionDispensaryCodeDao.java

@ -1,41 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.prescription;
import com.yihu.jw.entity.hospital.prescription.PrescriptionDispensaryCode;
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 Administrator on 2017/7/21.
 * 处方取码
 */
public interface PrescriptionDispensaryCodeDao extends PagingAndSortingRepository<PrescriptionDispensaryCode, Long>, JpaSpecificationExecutor<PrescriptionDispensaryCode> {
    @Query(nativeQuery = true, value = "select * from wlyy_prescription_dispensary_code  where code=?1 order by create_time desc limit 0,1 ")
    PrescriptionDispensaryCode finByCode(String code);
    List<PrescriptionDispensaryCode> findByPrescriptionCode(String prescriptionCode);
    @Query("select count(1) from PrescriptionDispensaryCode a where a.code= ?1 and a.isUse =0")
    Integer getResidentQRCodeCount(String code);
    @Query("select a.code from PrescriptionDispensaryCode a where a.prescriptionCode= ?1 and a.type =?2 ")
    String getCodeByPrescriptionCodeAndType(String prescriptionCode, Integer type);
    /**
     * 更新处方某一类型的编码为使用
     *
     * @param prescriptionCode
     * @param type
     */
    @Modifying
    @Query("update PrescriptionDispensaryCode a set a.isUse=1 where a.prescriptionCode= ?1 and a.type = ?2 and a.isUse=0 ")
    void updateToUse(String prescriptionCode, Integer type);
    PrescriptionDispensaryCode findByCodeAndIsUse(String code, Integer isUse);
    PrescriptionDispensaryCode findByPrescriptionCodeAndIsUseAndType(String prescriptionCode, Integer isUse,Integer type);
}

+ 0 - 29
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionFollowupContentDao.java

@ -1,29 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.prescription;
import com.yihu.jw.entity.hospital.prescription.PrescriptionFollowupContent;
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;
/**
 * 续方咨询问卷相关方法
 * @author huangwenjie
 * @date 2017/11/2 09:07
 */
public interface PrescriptionFollowupContentDao extends
		PagingAndSortingRepository<PrescriptionFollowupContent, Long>,
		JpaSpecificationExecutor<PrescriptionFollowupContent> {
	
	@Query("from PrescriptionFollowupContent p where p.prescriptionCode=?1 and p.followupProject=?2")
	List<PrescriptionFollowupContent> findByPrescriptionCodeAndFollowupProject(String prescriptionCode, String followupProject);
	
	@Modifying
	@Query("delete PrescriptionFollowupContent p where p.prescriptionCode=?1 and p.followupProject=?2")
	void deleteByPrescriptioncodeAndFollowupProject(String prescriptioncode, String followupProject);
	
	@Query("from PrescriptionFollowupContent p where p.prescriptionCode=?1")
	List<PrescriptionFollowupContent> findByPrescriptionCode(String prescriptioncode);
}

+ 0 - 20
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionPayDao.java

@ -1,20 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.prescription;
import com.yihu.jw.entity.hospital.prescription.PrescriptionPay;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by chenweida on 2017/7/27.
 */
public interface PrescriptionPayDao extends PagingAndSortingRepository<PrescriptionPay, Long>, JpaSpecificationExecutor<PrescriptionPay> {
    //    查询已经支付成功的支付记录
    @Query("from PrescriptionPay p where p.prescriptionCode=?1 and p.tradeStatus='1'")
    PrescriptionPay findByPrescriptionPay(String prescriptionCode);
    //查询支付记录
    @Query("from PrescriptionPay p where p.code=?1 ")
    PrescriptionPay findByCode(String code);
}

+ 0 - 20
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/prescription/PrescriptionReviewedDao.java

@ -1,20 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.prescription;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionReviewedDO;
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 Trick on 2017/8/4.
 */
public interface PrescriptionReviewedDao extends PagingAndSortingRepository<WlyyPrescriptionReviewedDO, Long>, JpaSpecificationExecutor<WlyyPrescriptionReviewedDO> {
    @Query(value = "select p from WlyyPrescriptionReviewedDO p where p.prescriptionId=?1 order by p.reviewedTime desc")
    WlyyPrescriptionReviewedDO findByPrescriptionCode(String prescriptionCode);
    @Query("select p from WlyyPrescriptionReviewedDO p where p.prescriptionId=?1 and p.status=?2")
    List<WlyyPrescriptionReviewedDO> findByPrescriptionCodeAndStatus(String prescriptionCode, Integer status);
}

+ 0 - 21
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/FrequencyDao.java

@ -1,21 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.hospital.doctor.Frequency;
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 wzn54 on 2019/1/17.
 */
public interface FrequencyDao extends PagingAndSortingRepository<Frequency, Long>, JpaSpecificationExecutor<Frequency> {
    @Query("select f from Frequency f where  f.del=1")
    List<Frequency> findByDel();
    @Query("select f from Frequency  f where f.del=1 and f.code=?1 ")
    Frequency findByCode(String code);
}

+ 0 - 15
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/GuidanceMessageLogDao.java

@ -1,15 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.GuidanceMessageLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by 刘文彬 on 2018/8/23.
 */
public interface GuidanceMessageLogDao extends PagingAndSortingRepository<GuidanceMessageLogDO, Long>,JpaSpecificationExecutor<GuidanceMessageLogDO> {
    List<GuidanceMessageLogDO> findByPlanDetailId(String planDetailId);
}

+ 0 - 17
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientDiagnosisInformationDao.java

@ -1,17 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.PatientDiagnosisInformationDO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PatientDiagnosisInformationDao extends PagingAndSortingRepository<PatientDiagnosisInformationDO, Long>,
        JpaSpecificationExecutor<PatientDiagnosisInformationDO> {
    PatientDiagnosisInformationDO findByPlanId(String planId);
    @Query("select d from PatientDiagnosisInformationDO d where d.patient = ?1 order by d.dischargeTime,d.createTime desc")
    Page<PatientDiagnosisInformationDO> findByPatient(String patient, Pageable pageRequest);
}

+ 0 - 26
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientDischargeDao.java

@ -1,26 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.rehabilitation.PatientDischargeDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientDischargeDao extends PagingAndSortingRepository<PatientDischargeDO, Long>, JpaSpecificationExecutor<PatientDischargeDO> {
    List<PatientDischargeDO> findAllByType(Integer type);
    List<PatientDischargeDO> findAllByTypeAndIdcardAndCreateUser(Integer type, String idcard, String createUser);
    List<PatientDischargeDO> findAllByTypeAndCreateUser(Integer type, String createUser);
    List<PatientDischargeDO> findAllByIdcardAndCreateUser(String idcard, String createUser);
    List<PatientDischargeDO> findAllByCreateUser(String createUser);
    List<PatientDischargeDO> queryByCreateUserAndPatientIn(String createUser,String[] patient);
    // //查询下转是否存在该患者 :sign_status=1(包括type==null,type==2) 1.6.8后新增未家签的也能添加患者判断条件(d.type=2 and sign_status=0)
    @Query(value = "select count(1) from PatientDischargeDO p where p.idcard = ?1 and p.createUser=?2 and (p.signStatus=1 and ( p.type is null or p.type=2) or (p.type=2 and p.signStatus=0))")
    int isPatientExist(String idcard, String createUser);
}

+ 0 - 29
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientDiseaseServerDao.java

@ -1,29 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.PatientDiseaseServer;
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 Trick on 2018/7/4.
 */
public interface PatientDiseaseServerDao extends
        PagingAndSortingRepository<PatientDiseaseServer, Long>,
        JpaSpecificationExecutor<PatientDiseaseServer> {
    List<PatientDiseaseServer> findByPatientAndDel(String patient,String del);
    List<PatientDiseaseServer> findBySpecialistRelationCodeAndDel(String code,String del);
    @Query(value = "select  p from PatientDiseaseServer p where p.specialistRelationCode=?1 and p.disease=?2 and p.del=?3")
    PatientDiseaseServer findBySpecialistRelationCodeAndDiseaseAndCode(String specialistRelationCode,String disease,String del);
    @Modifying
    @Query("update PatientDiseaseServer pds set pds.del=0 where pds.specialistRelationCode=?1")
    void updateBySpecialistRelationCodeAndDel(String code);
}

+ 0 - 12
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientHospitalRecordDao.java

@ -1,12 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.PatientHospitalRecordDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/4/25.
 */
public interface PatientHospitalRecordDao extends PagingAndSortingRepository<PatientHospitalRecordDO, String>,
        JpaSpecificationExecutor<PatientHospitalRecordDO> {
}

+ 0 - 18
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientMedicalRecordsRehabilitationDao.java

@ -1,18 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientMedicalRecordsRehabilitationDao extends PagingAndSortingRepository<PatientMedicalRecordsDO, String>, JpaSpecificationExecutor<PatientMedicalRecordsDO> {
    @Query("select p from PatientMedicalRecordsDO p where p.code = ?1")
    PatientMedicalRecordsDO findByCode(String code);
    
    List<PatientMedicalRecordsDO> findByPatient(String patient);
    
    
}

+ 0 - 56
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientRehabilitationPlanDao.java

@ -1,56 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanDO;
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.Date;
import java.util.List;
/**
 * Created by 刘文彬 on 2018/8/16.
 */
public interface PatientRehabilitationPlanDao extends PagingAndSortingRepository<PatientRehabilitationPlanDO, String>,JpaSpecificationExecutor<PatientRehabilitationPlanDO> {
    @Query(" select p from PatientRehabilitationPlanDO p where p.patient=?1 and p.createUser=?2 order by p.createTime desc ")
    List<PatientRehabilitationPlanDO> findByPatientAndCreateUser(String patient, String doctor);
    @Query(" select p from PatientRehabilitationPlanDO p where p.patient=?1 and p.createUser=?2 and p.teamCode=?3 order by p.createTime desc ")
    List<PatientRehabilitationPlanDO> findByPatientAndCreateUserAndTeamCode(String patient, String doctor,Integer teamCode);
    @Query(" select p from PatientRehabilitationPlanDO p where p.patient=?1 order by p.createTime desc ")
    List<PatientRehabilitationPlanDO> findByPatients(String patientCode);
    @Query("update PatientRehabilitationPlanDO a set a.status=?1 where a.id =?2 ")
    @Modifying
    int updateStatusById(Integer status,String id);
    //插入服务包id
    @Modifying
    @Query("update PatientRehabilitationPlanDO p set p.servicePackageId = ?2 where p.id = ?1")
    void updateServicePackageId(String planId, String servicePackageId);
    @Query("select count(distinct p.patient) from PatientRehabilitationPlanDO p where p.createUser=?1  and p.status>0 ")
    Integer patientCount(String doctorCode);
    @Query("select count(distinct p.patient) from PatientRehabilitationPlanDO p where p.createUser=?1  and p.status=2 ")
    Integer getFinishPatientCount(String doctorCode);
//    @Query("update PatientRehabilitationPlanDO a set a.status=0,a.abortReason=?1,a.abortTime=?3 where a.id =?2 ")
//    @Modifying
//    int abortPlanById(String abortReason, String id, Date abortTime);
    @Query("select p from PatientRehabilitationPlanDO p where p.disease =?1 and p.status=1 and p.patient=?2")
    List<PatientRehabilitationPlanDO> selectByDiseaseAndPatient(String disease,String patient);
    @Modifying
    @Query("update PatientRehabilitationPlanDO t set t.patientImg = ?2 where t.id=?1 ")
    int updatePatientImgById(String planId, String patientImg);
    @Query("update PatientRehabilitationPlanDO a set a.status=?1,a.abortTime= ?3 where a.id =?2 ")
    @Modifying
    int updateStatusAndTimeById(Integer status, String id, Date date);
}

+ 0 - 11
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/PatientRehabilitationPlanLogDao.java

@ -1,11 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by liub on 2021/1/12.
 */
public interface PatientRehabilitationPlanLogDao extends PagingAndSortingRepository<PatientRehabilitationPlanLogDO,Long>, JpaSpecificationExecutor<PatientRehabilitationPlanLogDO> {
}

+ 0 - 20
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationAdviceDao.java

@ -1,20 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
// create by hmf on 2020/02/27
public interface RehabilitationAdviceDao extends
        PagingAndSortingRepository<RehabilitationAdviceDO, Long>,
        JpaSpecificationExecutor<RehabilitationAdviceDO> {
    RehabilitationAdviceDO findByCode(String code);
    @Query("select a from RehabilitationAdviceDO a where a.createUser = ?1 or a.createUser is null order by a.createUser, a.createTime desc")
    List<RehabilitationAdviceDO> findByDoctor(String doctorCode);
}

+ 0 - 13
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationDetailAppointmentDao.java

@ -1,13 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationDetailAppointmentDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by ysj on 2020/7/10.
 */
public interface RehabilitationDetailAppointmentDao extends PagingAndSortingRepository<RehabilitationDetailAppointmentDO, String>,JpaSpecificationExecutor<RehabilitationDetailAppointmentDO> {
}

+ 0 - 94
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationDetailDao.java

@ -1,94 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationDetailDO;
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.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by 刘文彬 on 2018/8/20.
 */
public interface RehabilitationDetailDao extends PagingAndSortingRepository<RehabilitationDetailDO, Long>,JpaSpecificationExecutor<RehabilitationDetailDO> {
    @Query("select count(1) from RehabilitationDetailDO where status=?1 and planId=?2 ")
    Integer findByStatusAndPlanId(Integer status,String planId);
    @Query("select count(1) from RehabilitationDetailDO where planId=?1 ")
    Integer findAllByPlanId(String planId);
    @Query("select count(1) from RehabilitationDetailDO where planId=?1 and executeTime>=?2 and executeTime<=?3 ")
    Integer todayBacklogCount(String programId,Date executeStartTime,Date executeEndTime);
    @Query("select count(1) from RehabilitationDetailDO where status =?1 and planId=?2 and executeTime>=?3 and executeTime<=?4 ")
    Integer completenessCount(Integer status,String planId,Date executeStartTime,Date executeEndTime);
    @Query("select d from RehabilitationDetailDO d where d.planId=?1 order by d.executeTime desc")
    List<RehabilitationDetailDO> getAllRehabilitationDetail(String programId);
    @Query("select d from RehabilitationDetailDO d where d.executeTime<=?1 and d.executeTime>=?2 and d.planId=?3")
    List<RehabilitationDetailDO> findByPlanId(Date executeStartTime,Date executeEndTime,String planId);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor=?1 and p.patient=?2  and d.status!=?3",nativeQuery = true)
    Integer unfinishItemByDoctor(String doctor,String patient,Integer status);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor in (?1,?2) and p.patient=?3  and d.status!=?4",nativeQuery = true)
    Integer unfinishItemByDoctor(String generalDoctor,String healthDoctor,String patient,Integer status);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor=?1 and p.patient=?2",nativeQuery = true)
    Integer findItemByDoctor(String doctor,String patient);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor in (?1,?2) and p.patient=?3",nativeQuery = true)
    Integer findItemByDoctor(String generalDoctor,String healthDoctor,String patient);
//    @Query("select count(distinct serviceItemId) from RehabilitationDetailDO d left join PatientRehabilitationPlanDO p on d.planId=p.id where doctor=?1 and p.patient=?2 ")
//    Integer finishItemByDoctor(String doctor,String patient);
//
    @Query(value ="select count(1) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where doctor=?1 and p.patient=?2  and d.status=?3",nativeQuery = true)
    Integer completeServiceByDoctor(String doctor,String patient,Integer status);
    @Query(value ="select count(1) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where doctor in (?1,?2) and p.patient=?3  and d.status=?4",nativeQuery = true)
    Integer completeServiceByDoctor(String generalDoctor,String healthDoctor,String patient,Integer status);
    RehabilitationDetailDO findById(String planDetailId);
    @Query(value ="select d.doctor,p.patient,count(1) as num from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.status!=1 and d.execute_time>=?1 and d.execute_time<=?2 GROUP BY d.doctor,p.patient",nativeQuery = true)
    List<Map> dailyJob(String startTime,String endTime);
    @Query(value = "select d.id from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.status!=1 and d.execute_time>=?1 and d.execute_time<=?2 and d.doctor=?3 and p.patient=?4",nativeQuery = true)
    List<String> findByPatientAndDoctor(String startTime,String endTime,String doctorCode,String patientCode);
    @Modifying
    @Query("update RehabilitationDetailDO t set t.status = ?1 where t.id=?2 ")
    int updateStatusById(Integer status,String id);
    @Modifying
    @Query("update RehabilitationDetailDO t set t.status = ?1,t.relationCode=?3 where t.id=?2 ")
    int updateStatusAndRelationCodeById(Integer status,String id,String relationCode);
    @Query(value ="select p.patient from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.id=?1",nativeQuery = true)
    List<String> findPatientById(String planDetailId);
    @Query
    List<RehabilitationDetailDO> findByPlanIdAndStatus(String planId,int status);
    @Modifying
    @Query("update RehabilitationDetailDO t set t.executeTime = ?1 where t.id=?2 ")
    int updateExecuteTime(Date executeTime,String id);
    @Modifying
    @Query("delete from RehabilitationDetailDO t where t.planId = ?1 and t.hospitalServiceItemId = ?2 and (t.executeTime > ?3 OR t.executeTime is null OR t.executeTime<>'')  and t.status <> 1 ")
    void deleteDetailByPlanIdAndHospitalServiceItemId(String planId, String hospitalServiceItemId, Date dateShort);
    @Modifying
    @Query("delete from RehabilitationDetailDO t where t.planId = ?1 and (t.executeTime > ?2 OR t.executeTime is null OR t.executeTime<>'')  and t.status <> 1 ")
    void deleteDetailByPlanId(String planId, Date dateShort);
    @Query("select d from RehabilitationDetailDO d where d.planId = ?1 and d.type=?2 and d.doctor=?3 and d.status<>?4 ")
    List<RehabilitationDetailDO> findByPlanIdAndTypeAndDoctorAndStatusNot(String planId,Integer type,String doctor,Integer status);
}

+ 0 - 14
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationGuidanceDao.java

@ -1,14 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidanceDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface RehabilitationGuidanceDao extends PagingAndSortingRepository<RehabilitationguidanceDO, Long>, JpaSpecificationExecutor<RehabilitationguidanceDO> {
    @Query("select p from RehabilitationguidanceDO p where p.code = ?1 and p.del=1")
    RehabilitationguidanceDO findByCode(String code);
}

+ 0 - 17
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationGuidancePatientDao.java

@ -1,17 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidancePatientDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface RehabilitationGuidancePatientDao extends PagingAndSortingRepository<RehabilitationguidancePatientDO, Long>, JpaSpecificationExecutor<RehabilitationguidancePatientDO> {
    @Query("select p from RehabilitationguidancePatientDO p where p.patient = ?1 and p.doctor=?2 ")
    List<RehabilitationguidancePatientDO> findByPatientAndDoctor(String patient, String doctor);
    @Query("select p from RehabilitationguidancePatientDO p where  p.relationCode=?1")
    List<RehabilitationguidancePatientDO> findByRelationCode(String relationCode);
}

+ 0 - 38
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationOperateRecordsDao.java

@ -1,38 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
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 刘文彬 on 2018/8/29.
 */
public interface RehabilitationOperateRecordsDao extends PagingAndSortingRepository<RehabilitationOperateRecordsDO, Long>,JpaSpecificationExecutor<RehabilitationOperateRecordsDO> {
    List<RehabilitationOperateRecordsDO> findByRehabilitationDetailId(String rehabilitationDetailId);
    List<RehabilitationOperateRecordsDO> findByRehabilitationDetailIdAndId(String rehabilitationDetailId,String id);
    @Modifying
    @Query("update RehabilitationOperateRecordsDO a set a.status=?1 where a.rehabilitationDetailId =?2 ")
    int updateStatus(Integer status,String rehabilitationDetailId);
    @Modifying
    @Query("update RehabilitationOperateRecordsDO a set a.node=?1,a.relationRecordImg=?2,a.status=1 where a.rehabilitationDetailId =?3 ")
    int updateNodeAndRelationRecordImg(String node,String rehabilitationRecordImg,String rehabilitataioDetailId);
    @Modifying
    @Query("update RehabilitationOperateRecordsDO a set a.node=?1,a.status=1 where a.rehabilitationDetailId =?2 ")
    int updateNodeByPlanDetailId(String node,String rehabilitataioDetailId);
    @Modifying
    @Query("update RehabilitationOperateRecordsDO a set a.relationRecordImg=?1,a.status=1 where a.rehabilitationDetailId =?2 ")
    int updateImagByPlanDetailId(String image,String rehabilitataioDetailId);
    @Query("select a from RehabilitationOperateRecordsDO a where a.rehabilitationDetailId=?1 and a.doctorCode=?2 and a.status<>?3")
    List<RehabilitationOperateRecordsDO> findByRehabilitationDetailIdAndDoctorCodeAndStatusNot(String rehabilitationDetailId,String doctorCode,Integer status);
}

+ 0 - 19
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationPlanTemplateDao.java

@ -1,19 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPlanTemplateDO;
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 RehabilitationPlanTemplateDao extends PagingAndSortingRepository<RehabilitationPlanTemplateDO, Long>,JpaSpecificationExecutor<RehabilitationPlanTemplateDO> {
    @Query("select t from RehabilitationPlanTemplateDO t where (t.adminTeamCode = ?1 or t.adminTeamCode is null) and t.del = 1 ORDER BY t.adminTeamCode,t.createTime DESC ")
    List<RehabilitationPlanTemplateDO> findByAdminTeamCode(Long adminTeamCode);
    @Modifying
    @Query("update RehabilitationPlanTemplateDO t set t.del = 0 where t.id = ?1")
    void updateDelById(String id);
}

+ 0 - 16
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationServiceItemDao.java

@ -1,16 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface RehabilitationServiceItemDao extends PagingAndSortingRepository<RehabilitationServiceItemDO, Long>,JpaSpecificationExecutor<RehabilitationServiceItemDO> {
    RehabilitationServiceItemDO findByCode(String itemId);
    @Query("SELECT a FROM RehabilitationServiceItemDO a ")
    List<RehabilitationServiceItemDO> findList();
}

+ 0 - 18
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/RehabilitationTemplateDetailDao.java

@ -1,18 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationTemplateDetailDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface RehabilitationTemplateDetailDao extends PagingAndSortingRepository<RehabilitationTemplateDetailDO, Long>,JpaSpecificationExecutor<RehabilitationTemplateDetailDO> {
    List<RehabilitationTemplateDetailDO> findTemplateDetailByTemplateId(String templateId);
    void deleteByTemplateId(String templateId);
    @Query("SELECT r.hospitalServiceItemId FROM RehabilitationTemplateDetailDO r where r.templateId = ?1")
    List<String> findHospitalServiceItemIdByTemplateId(String templateId);
}

+ 0 - 24
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialDiseaseMessagesDao.java

@ -1,24 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.SpecialDiseaseMessages;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/***
 * @ClassName: SpecialDiseaseMessagesDao
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/4/20 9:44
 */
public interface SpecialDiseaseMessagesDao extends PagingAndSortingRepository<SpecialDiseaseMessages,Long>, JpaSpecificationExecutor<SpecialDiseaseMessages> {
    @Query("select m from SpecialDiseaseMessages m where m.createTime>?1 and m.createTime<?2 order by m.createTime desc")
    Page<SpecialDiseaseMessages> findByTime(String createTime, String endTime, Pageable pageRequest);
    @Query("select count(1) from SpecialDiseaseMessages m where m.createTime>?1 and m.createTime<?2")
    Integer findCountsByTime(String createTime,String endTime);
}

+ 0 - 16
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistEvaluateDao.java

@ -1,16 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;/**
 * Created by nature of king on 2018/8/21.
 */
import com.yihu.jw.entity.specialist.SpecialistEvaluateDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author wangzhinan
 * @create 2018-08-21 16:41
 * @desc 评论表
 **/
public interface SpecialistEvaluateDao extends PagingAndSortingRepository<SpecialistEvaluateDO, String>, JpaSpecificationExecutor<SpecialistEvaluateDO> {
}

+ 0 - 15
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistEvaluateLabelDao.java

@ -1,15 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;/**
 * Created by nature of king on 2018/8/22.
 */
import com.yihu.jw.entity.specialist.SpecialistEvaluateLabelDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author wangzhinan
 * @create 2018-08-22 9:38
 * @desc 评论标签
 **/
public interface SpecialistEvaluateLabelDao extends PagingAndSortingRepository<SpecialistEvaluateLabelDO, String>, JpaSpecificationExecutor<SpecialistEvaluateLabelDO> {
}

+ 0 - 15
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistEvaluateScoreDao.java

@ -1,15 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;/**
 * Created by nature of king on 2018/8/22.
 */
import com.yihu.jw.entity.specialist.SpecialistEvaluateScoreDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author wangzhinan
 * @create 2018-08-22 9:39
 * @desc 评论得分
 **/
public interface SpecialistEvaluateScoreDao extends PagingAndSortingRepository<SpecialistEvaluateScoreDO, String>, JpaSpecificationExecutor<SpecialistEvaluateScoreDO> {
}

+ 0 - 22
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistHospitalServiceItemDao.java

@ -1,22 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;/**
 * Created by nature of king on 2018/8/28.
 */
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * @author wangzhinan
 * @create 2018-08-28 19:54
 * @desc 机构服务项目
 **/
public interface SpecialistHospitalServiceItemDao extends PagingAndSortingRepository<HospitalServiceItemDO, String>,
        JpaSpecificationExecutor<HospitalServiceItemDO> {
    @Query("select p from HospitalServiceItemDO  p where p.hospital =?1 and p.serviceItemId =?2")
    public List<HospitalServiceItemDO> findByHospitalAndServiceItemId(String hospital,String serviceItemId);
}

+ 0 - 41
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistPatientRelationDao.java

@ -1,41 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
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 Trick on 2018/4/25.
 */
public interface SpecialistPatientRelationDao extends PagingAndSortingRepository<SpecialistPatientRelationDO, String>,
        JpaSpecificationExecutor<SpecialistPatientRelationDO> {
    List<SpecialistPatientRelationDO> findByDoctorAndStatus(String doctor,String status);
    @Query("select p from SpecialistPatientRelationDO p where p.doctor=?1 and p.patient =?2  and p.status>=0 and p.signStatus=1")
    SpecialistPatientRelationDO findByDoctorAndPatient(String doctor,String patient);
    @Query("select p from SpecialistPatientRelationDO p where p.doctor=?1 and (p.patient=?2 or p.healthAssistant=?2) and p.signStatus='1' and p.status>=0 ")
    SpecialistPatientRelationDO findByPatientAndDoctor(String doctor, String patient);
    List<SpecialistPatientRelationDO> findAllBySignStatus(String signStatus);
    @Modifying
    @Query("update SpecialistPatientRelationDO p set p.doctor = ?2, p.doctorName=?3 where p.patient=?1 and p.signStatus='1' and p.status>=0 ")
    void updateSpecialistByPatient(String patient, String doctor, String doctorName);
    @Query("select p from SpecialistPatientRelationDO p where p.teamCode=?1 and p.patient =?2 and p.status>=0 and p.signStatus=1")
    SpecialistPatientRelationDO findByTeamCodeAndPatient(Integer teamCode,String patient);
    @Query("select p from SpecialistPatientRelationDO p where p.doctor=?1 and p.patient =?2 and p.teamCode =?3 and p.status>=0 and p.signStatus=1")
    SpecialistPatientRelationDO findByDoctorAndPatientAndTeamCode(String doctor,String patient,Integer teamCode);
    @Query("select p from SpecialistPatientRelationDO p where p.teamCode=?1 and p.patient=?2 and p.doctor=?3 and p.status>=0 and p.status >=0 and p.signStatus=1")
    List<SpecialistPatientRelationDO> findListByTeamCodeAndPatientAndDoctor(Integer teamCode,String patient,String doctor);
    @Query("select p from SpecialistPatientRelationDO p where p.teamCode=?1 and p.patient=?2 and p.status>=0 and p.status >=0 and p.signStatus=1")
    List<SpecialistPatientRelationDO> findListByTeamAndPatient(Integer teamCode,String patient);
}

+ 0 - 27
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistServiceItemDao.java

@ -1,27 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;/**
 * Created by nature of king on 2018/8/16.
 */
import com.yihu.jw.entity.specialist.SpecialistServiceItemDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * @author wangzhinan
 * @create 2018-08-16 10:58
 * @desc 服务项目Dao
 **/
public interface SpecialistServiceItemDao extends PagingAndSortingRepository<SpecialistServiceItemDO, String>,
        JpaSpecificationExecutor<SpecialistServiceItemDO> {
    @Query("select p from SpecialistServiceItemDO p where p.title =?1")
    public List<SpecialistServiceItemDO> findByTitle(String title);
    @Query("select p from SpecialistServiceItemDO p where p.title =?1 and p.content=?2")
    public List<SpecialistServiceItemDO> findByTitleAndContent(String title,String content);
}

+ 0 - 17
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/dao/rehabilitation/SpecialistServiceItemOperateLogDao.java

@ -1,17 +0,0 @@
package com.yihu.jw.afterDiagnosis.dao.rehabilitation;/**
 * Created by nature of king on 2018/8/16.
 */
import com.yihu.jw.entity.specialist.SpecialistServiceItemOperateLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author wangzhinan
 * @create 2018-08-16 11:04
 * @desc 服务项目操作日志
 **/
public interface SpecialistServiceItemOperateLogDao  extends PagingAndSortingRepository<SpecialistServiceItemOperateLogDO, String>,
        JpaSpecificationExecutor<SpecialistServiceItemOperateLogDO> {
}

+ 0 - 843
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/BaseController.java

@ -1,843 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.IdEntity;
import com.yihu.jw.entity.base.dict.BaseExceptionDictDO;
import com.yihu.jw.restmodel.exception.dao.BaseExceptionDictDao;
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.io.PrintWriter;
import java.io.StringWriter;
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;
    @Autowired
    private BaseExceptionDictDao baseExceptionDictDao;
    @Autowired
    protected ObjectMapper objectMapper;
    /**
     * 獲取髮送請求用戶的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");
        } 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;
        }
    }
    /**
     * 获取当前用户的角色级别
     * @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 error(Exception e,String method,String key,String param) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            String exception = sw.toString();
            if(StringUtils.isNotBlank(exception)){
                exception = exception.length()>30000? exception.substring(0,30000):exception;
            }
        }catch (Exception e1){
            e1.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;
        }
    }
    public String errorResult(Exception e) {
        try {
            e.printStackTrace();
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            BaseExceptionDictDO baseExceptionDictDO =baseExceptionDictDao.findByExceptionInfo(e.getClass().toString());
            if (baseExceptionDictDO!=null){
                map.put("status", Integer.parseInt(baseExceptionDictDO.getCode()));
                map.put("msg", baseExceptionDictDO.getRemindContent());
            }else {
                map.put("status", -10000);
                map.put("msg", "系统繁忙,请稍后再试");
            }
            return mapper.writeValueAsString(map);
        } catch (Exception e1) {
            e.printStackTrace();
            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   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list,String key2,Object value) {
        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);
            map.put(key2, value);
            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;
    }
    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;
    }
    /**
     * 无效用户消息返回
     *
     * @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 errorResult(e);
        } catch (Exception e2) {
            return null;
        }
    }
}

+ 0 - 387
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/device/DoctorDeviceController.java

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

+ 0 - 365
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/device/PatientDeviceController.java

@ -1,365 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.device;
import com.yihu.jw.afterDiagnosis.dao.device.PatientDeviceDao;
import com.yihu.jw.afterDiagnosis.dao.device.PatientHealthTimeDao;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.device.DeviceDetailService;
import com.yihu.jw.afterDiagnosis.service.device.PatientDeviceLogService;
import com.yihu.jw.afterDiagnosis.service.device.PatientDeviceService;
import com.yihu.jw.afterDiagnosis.service.device.PatientHealthIndexService;
import com.yihu.jw.entity.base.device.PatientHealthTime;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.patient.PatientDevice;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.message.service.WxMessageUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import 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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 患者端:设备管理控制类
 *
 * @author George
 */
@RestController
@RequestMapping(value = "patient/device")
@Api(value = "患者设备管理", description = "患者设备管理")
public class PatientDeviceController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(PatientDeviceController.class);
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private PatientHealthIndexService patientHealthIndexService;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    @Autowired
    private PatientDeviceLogService patientDeviceLogService;
    @Autowired
    private SystemMessageDao messageDao;
    @ApiOperation("获取居民标准体征预警值")
    @RequestMapping(value = "getDeviceStandard", method = RequestMethod.GET)
    public String getDeviceStandard(@ApiParam(name = "type", value = "类型1血糖,2血压", defaultValue = "1")
                                    @RequestParam(value = "type", required = true) Integer type){
        try {
            JSONObject json = patientHealthIndexService.getealthStandard(type,getRepUID());
            return write(200,"获取成功","data",json);
        } catch (Exception ex) {
            error(ex);
            return error(-1,"获取失败");
        }
    }
    /**
     * 设置及修改血糖仪时间段
     * 默认时间段如下
     * fasting: 00:00-07:59
     * afterBreakfast: 08:00-09:59
     * beforeLunch: 10:00-11:59
     * afterLunch: 12:00-13:59
     * beforeDinner: 14:00-17:59
     * afterDinner: 18:00-19:59
     * beforeSleep: 20:00-23:59
     */
    @ApiOperation("设置修改血糖仪时间段")
    @RequestMapping(value = "/setBloodTime", method = RequestMethod.GET)
    public String setBloodTime(@RequestParam(required = false) String fastingStart,
                               @RequestParam(required = false) String fastingEnd,
                               @RequestParam(required = false) String afterBreakfastStart,
                               @RequestParam(required = false) String afterBreakfastEnd,
                               @RequestParam(required = false) String beforeLunchStart,
                               @RequestParam(required = false) String beforeLunchEnd,
                               @RequestParam(required = false) String afterLunchStart,
                               @RequestParam(required = false) String afterLunchEnd,
                               @RequestParam(required = false) String beforeDinnerStart,
                               @RequestParam(required = false) String beforeDinnerEnd,
                               @RequestParam(required = false) String afterDinnerStart,
                               @RequestParam(required = false) String afterDinnerEnd,
                               @RequestParam(required = false) String beforeSleepStart,
                               @RequestParam(required = false) String beforeSleepEnd,
                               @RequestParam(required = false) String sim,
                               @RequestParam String deviceSN,
                               @RequestParam String categoryCode,
                               @RequestParam String userType,
                               @RequestParam(required = false) String newDeviceSN,
                               @RequestParam(required = false) String hospital,
                               @RequestParam(required = false) String hospitalName,
                               @RequestParam(required = false) String checkDoctorName) {
        try {
            String user = getRepUID();
            if (StringUtils.isNotEmpty(newDeviceSN)) {
//                校验新的sn码 1.是否被占用 2.是否是真的设备码
                if(!newDeviceSN.equals(deviceSN)){
                    //有改sn码
                    PatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(newDeviceSN, userType);
                    if (device != null) {
                        throw new Exception("sn码" + newDeviceSN + "已被使用!");
                    }
                    if(!patientDeviceService.checkDeviceSn(newDeviceSN)){
                        return error(-1,"设备不存在");
                    }
                }
                if ("1".equals(categoryCode)) {
//                        先修改患者设备绑定表
                    int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType,sim,hospital,hospitalName,checkDoctorName);
                    if (rows != 0) {
                        //                只更换设备编码,不更改时间值
//                1.先查询是否自定义时间段,没有则新增,有则修改
                        PatientHealthTime healthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
                        if (healthTime == null) {
                            patientDeviceService.setBloodTime(user, newDeviceSN, "null", "null", "null", "null", "null", "null",
                                    "null", "null", "null", "null", "null", "null", "null", "null");
                        } else {
                            patientDeviceService.updateDeviceSN(user, deviceSN, newDeviceSN);
                        }
                    }
                }else {
                    int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType,sim,hospital,hospitalName,checkDoctorName);
                }
                return write(200, "更改sv码成功!");
            }
            patientDeviceService.setBloodTime(user, deviceSN, fastingStart, fastingEnd, afterBreakfastStart, afterBreakfastEnd, beforeLunchStart, beforeLunchEnd,
                    afterLunchStart, afterLunchEnd, beforeDinnerStart, beforeDinnerEnd, afterDinnerStart, afterDinnerEnd, beforeSleepStart, beforeSleepEnd);
            return write(200, "设置成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            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()).orElse(null);
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
                device.setAgentName(patient.getName());
            }
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                patientDeviceService.saveDevice(device);
                patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),2,1);
            }
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            try {
                String openId = patient.getOpenid();
                String name = patient.getName();
                String first = "";
                String deviceName = device.getDeviceName();
                WxTemplateConfigDO templateConfig = wxMessageUtil.findByWechatIdAndTemplateNameAndSceneAndStatus(null,"template_patient_bind_device","bdsb",1);
                WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
                BeanUtils.copyProperties(templateConfig,newConfig);
                first = newConfig.getFirst();
                first = first.replace("key1",(deviceName==null?"":deviceName));
                newConfig.setFirst(first);
                newConfig.setKeyword1(deviceName);
                newConfig.setKeyword2(DateUtil.dateToStrLong(device.getCzrq()));
                wxMessageUtil.putWxMsg(null,openId,newConfig,22,new com.alibaba.fastjson.JSONObject());
            }catch (Exception e){
                logger.info("设备绑定微信模板消息发送失败:"+e.getMessage());
            }
            return success("设备保存成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    public String getDeviceByPatient(@ApiParam(name = "id", value = "分页起始id", defaultValue = "0")
                                     @RequestParam(value = "id", required = true) long id,
                                     @ApiParam(name = "pagesize", value = "每页条数", defaultValue = "10")
                                     @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            if (id < 0) {
                id = 0L;
            }
            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)
    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);
            String deviceSN = device.getDeviceSn();
            String user = device.getUser();
            if(!device.getCategoryCode().equals("4")) {
                Map map = patientDeviceService.getBloodSuggerTime(user, deviceSN);
                mapList.put("time", map);
            }
            mapList.put("device", device);
            return write(200, "查询成功", "data", mapList);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 通过sn码获取设备绑定情况
     */
    @ApiOperation("通过sn码获取设备绑定情况")
    @RequestMapping(value = "PatientDeviceIdcard", method = RequestMethod.GET)
    public String getDeviceUser(@ApiParam(name = "type", value = "设备类型", defaultValue = "1")
                                @RequestParam(value = "type", required = true) String type,
                                @ApiParam(name = "device_sn", value = "设备SN码", defaultValue = "15L000002")
                                @RequestParam(value = "device_sn", required = true) String deviceSn) {
        try {
            if (deviceDetailService.findByDeviceSn(deviceSn)==null){
                return write(-1,"设备不存在!");
            }
            List<Map<String, String>> list = patientDeviceService.getDeviceUser(getRepUID(), deviceSn, type);
            return write(200, "获取设备绑定信息成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    
    /**
     * 发送设备审核系统消息
     */
    @ApiOperation("发送设备审核系统消息")
    @RequestMapping(value = "sendDeviceReviewMessage",method = RequestMethod.POST)
    public String sendDeviceReviewMessage(@ApiParam(name = "id", value = "删除设备关联ID")
                                              @RequestParam(value = "id", required = true) String id,
                                          @ApiParam(name = "reson", value = "解绑理由")
                                          @RequestParam(value = "reson", required = true) String reson){
        try {
            PatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
//                if (!StringUtils.equals(pd.getUser(), getUID())) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                pd.setApplyStatus(1);//审核中
                pd.setApplyReason(reson);
                patientDeviceDao.save(pd);
                
                return success("申请成功!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备删除
     */
    @ApiOperation("设备删除")
    @RequestMapping(value = "DeletePatientDevice",method = {RequestMethod.GET,RequestMethod.POST})
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            PatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getRepUID());
                //全部解绑后去判断就更新设备表中是否绑定字段
                patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),2,2);
                deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
                return success("设备已删除!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @ApiOperation("获取居民的设备任务信息")
    @RequestMapping(value = "getPatientDeviceTaskInfo",method = RequestMethod.POST)
    public String getPatientDeviceTaskInfo(@ApiParam(name = "patientCode",value = "患者code")@RequestParam(value = "patientCode",required = true)String patientCode){
        try {
            return write(200,"执行成功","data",patientDeviceService.getPatientDeviceTaskInfo(patientCode));
        }catch (Exception e){
            return write(-1,"执行失败!");
        }
    }
}

+ 0 - 740
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorFollowUpController.java

@ -1,740 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.followup;
import com.alibaba.fastjson.JSON;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.followup.FollowUpService;
import com.yihu.jw.afterDiagnosis.service.followup.FollowupDrugsService;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.followup.FollowupContentESDO;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
 * 医生端:随访接口
 *
 * @author hzp add 2016-12-07
 */
@RestController
@RequestMapping(value = "/doctor/followup")
@Api(description = "医生端-随访接口")
public class DoctorFollowUpController extends BaseController {
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private FollowupDrugsService followupDrugsService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /*************************************** 随访计划 ****************************************************************************/
    @ApiOperation("获取随访列表")
    @RequestMapping(value = "/list", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2016-12-07 00:00:00")
                          @RequestParam(value = "startTime", required = true) String startTime,
                          @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2016-12-14 00:00:00")
                          @RequestParam(value = "endTime", required = true) String endTime) {
        try {
            List<Map<String, Object>> result = followUpService.getListByDoctor(getUID(), startTime, endTime);     //"64de9952-5b15-11e6-8344-fa163e8aee56"
            return write(200, "获取随访列表成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访列表失败!" + e.getMessage());
        }
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/list_by_team", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询居民随访列表")
    public String getListByPatientAndTeam(@RequestParam @ApiParam(value = "居民Code") String patient,
                                          @RequestParam @ApiParam(value = "医生Code") String doctor,
                                          @RequestParam @ApiParam(value = "团队code") Long teamCode,
                                          @RequestParam @ApiParam(value = "第几页") int page,
                                          @RequestParam @ApiParam(value = "页大小") int pagesize,
                                          @RequestParam(value = "type",required = false) @ApiParam(value = "类型:放空为全部,1计划,2记录",defaultValue = "0") String type) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            if (teamCode == null || teamCode < 1) {
                return error(-1, "请输入需查询的居民的团队");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = followUpService.getListByPatientAndTeam(patient,doctor, teamCode, page, pagesize,type);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "/list_by", method = {RequestMethod.GET,RequestMethod.POST})
    @ApiOperation(value = "查询居民随访列表")
    public String getListByPatient(@RequestParam @ApiParam(value = "居民Code") String patient,
                                          @RequestParam @ApiParam(value = "第几页") int page,
                                          @RequestParam @ApiParam(value = "页大小") int pagesize,
                                          @RequestParam(value = "type",required = false) @ApiParam(value = "类型:放空为全部,1计划,2记录",defaultValue = "0") String type) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "请输入需查询的居民");
            }
            page = page > 0 ? page - 1 : 0;
            JSONArray result = followUpService.getListByPatient(patient, page, pagesize,type);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @ApiOperation("获取随访列表(创建者)")
    @RequestMapping(value = "/createrList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getCreaterList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2016-12-07 00:00:00")
                                 @RequestParam(value = "startTime", required = true) String startTime,
                                 @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2016-12-14 00:00:00")
                                 @RequestParam(value = "endTime", required = true) String endTime,
                                 @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                 @RequestParam(value = "page", required = true) String page,
                                 @ApiParam(name = "pageSize", value = "每页几行", defaultValue = "10")
                                 @RequestParam(value = "pageSize", required = true) String pageSize) {
        try {
            List<Map<String, String>> result = followUpService.getListByCreater(getUID(), startTime, endTime, page, pageSize);     //"64de9952-5b15-11e6-8344-fa163e8aee56"
            return write(200, "获取随访列表成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访列表失败!" + e.getMessage());
        }
    }
    @ApiOperation("新增随访计划(批量)")
    @RequestMapping(value = "/addFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String addFollowupPlan(@ApiParam(name = "patient", value = "患者代码", defaultValue = "443a196ef8744536a531260eb26c05d7")
                                  @RequestParam(value = "patient", required = true) String patient,
                                  @ApiParam(name = "data", value = "随访计划列表json", defaultValue = "[{\"date\":\"2016-12-16 20:00:00\",\"type\":\"10\",\"doctor\":\"64de9952-5b15-11e6-8344-fa163e8aee56\"},{\"date\":\"2016-12-17 15:00:00\",\"type\":\"3\",\"doctor\":\"64de9952-5b15-11e6-8344-fa163e8aee56\"}]")
                                  @RequestParam(value = "data", required = true) String data) {
        try {
            Iterable<Followup> followups = followUpService.addFollowupPlan(getUID(), patient, data);
            return write(200, "新增随访计划成功!","data",followups);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("编辑随访计划")
    @RequestMapping(value = "/editFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String editFollowupPlan(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                   @RequestParam(value = "id", required = true) String id,
                                   @ApiParam(name = "planDate", value = "随访计划时间", defaultValue = "2016-12-14 20:00:00")
                                   @RequestParam(value = "planDate", required = true) String planDate,
                                   @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                   @RequestParam(value = "followupType", required = true) String followupType) {
        try {
            followUpService.editFollowupPlan(getUID(), id, planDate, followupType);
            return write(200, "编辑随访计划成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "编辑随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("开始随访记录")
    @RequestMapping(value = "/startFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String startFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                @RequestParam(value = "id", required = true) String id,
                                @ApiParam(name = "followupNo", value = "随访记录编码")
                                @RequestParam(value = "followupNo", required = false) String followupNo,
                                @ApiParam(name = "date", value = "随访时间", defaultValue = "2016-12-14 20:00:00")
                                @RequestParam(value = "date", required = true) String date,
                                @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                @RequestParam(value = "followupType", required = true) String followupType,
                                @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病,3高糖】", defaultValue = "1")
                                @RequestParam(value = "followupClass", required = true) String followupClass,
                                @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                                @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus,
                                @ApiParam(name = "plandate", value = "下次随访时间", defaultValue = "2016-12-14 20:00:00")
                                @RequestParam(value = "plandate", required = false) String plandate,
                                @ApiParam(name = "prescriptioncode", value = "续方CODE", defaultValue = "")
                                    @RequestParam(value = "prescriptioncode", required = false) String prescriptioncode) {
        try {
            Followup followup = followUpService.startFollowup( id, followupNo, date, followupType, followupClass, followupManagerStatus,plandate,prescriptioncode);
            followUpService.getNotStartFollowup(getUID(), followup.getFollowupPlanDate());
            return write(200, "开始随访记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "开始随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("新增临时随访记录(返回ID)")
    @RequestMapping(value = "/addFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String addFollowup(@ApiParam(name = "patient", value = "患者代码", defaultValue = "443a196ef8744536a531260eb26c05d7")
                              @RequestParam(value = "patient", required = true) String patient,
                              @ApiParam(name = "date", value = "下次随访时间", defaultValue = "2016-12-15 20:00:00")
                              @RequestParam(value = "date", required = true) String date,
                              @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                              @RequestParam(value = "followupType", required = true) String followupType,
                              @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病 3高糖】", defaultValue = "1")
                              @RequestParam(value = "followupClass", required = true) String followupClass,
                              @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                              @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus,
                              @ApiParam(name = "plandate", value = "下次随访时间", defaultValue = "2016-12-14 20:00:00")
                              @RequestParam(value = "plandate", required = false) String plandate,
                              @ApiParam(name = "prescriptioncode", value = "续方CODE", defaultValue = "续方CODE")
                              @RequestParam(value = "prescriptioncode", required = false) String prescriptioncode,
                              @ApiParam(name = "type", value = "随访类型", defaultValue = "0")
                              @RequestParam(value = "type", required = false) Integer type) {
        try {
            String response = followUpService.addFollowup(getUID(), patient, date, followupType, followupClass, followupManagerStatus,plandate,prescriptioncode,type);
            return write(200, "新增临时随访记录成功!", "data", response);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "新增临时随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("取消随访计划")
    @RequestMapping(value = "/cancelFollowupPlan", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String cancelFollowupPlan(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                     @RequestParam(value = "id", required = true) String id) {
        try {
            followUpService.cancelFollowupPlan(id);
            return write(200, "取消随访计划成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "取消随访计划失败!" + e.getMessage());
        }
    }
    @ApiOperation("完成随访记录")
    @RequestMapping(value = "/finishFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String finishFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                 @RequestParam(value = "id", required = true) String id) {
        try {
            followUpService.finishFollowup(id);
            return write(200, "完成随访记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "完成随访记录失败!" + e.getMessage());
        }
    }
    /*********************************** 随访详情 *******************************************************************/
    @ApiOperation("获取随访信息")
    @RequestMapping(value = "/getFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowup(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                              @RequestParam(value = "id", required = true) String id) {
        try {
            Map<String, String> response = followUpService.getFollowup(id);
            try {
                String sql = "UPDATE `wlyy`.`wlyy_followup` SET `doctor_read_status`='1' WHERE (`id`='"+id+"') ";
                jdbcTemplate.update(sql);
            }catch (Exception e){
                e.printStackTrace();
            }
            return write(200, "获取随访信息成功!", "data", response);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访信息失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取随访项目列表")
    @RequestMapping(value = "/getFollowupProject", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupProject(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                     @RequestParam(value = "id", required = true) String id) {
        try {
            List<Map<String, String>> list = followUpService.getFollowupProject(id);
            return write(200, "获取随访项目列表成功!", "data", list);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访项目列表失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取随访项目数据")
    @RequestMapping(value = "/getFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                         @RequestParam(value = "id", required = true) String id,
                                         @ApiParam(name = "followupProject", value = "随访项目")
                                         @RequestParam(value = "followupProject", required = false) String followupProject) {
        try {
            FollowupContentESDO followupContentESDO = followUpService.esGetFollowupProjectDataList(id, followupProject);
             String jsonString = JSON.toJSONString(followupContentESDO);
            Map maps = (Map)JSON.parse(jsonString);
            return write(200, "获取随访项目数据成功!", "data", maps);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访项目数据失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存随访项目数据")
    @RequestMapping(value = "/saveFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "4")
                                          @RequestParam(value = "id", required = true) String id,
                                          @ApiParam(name = "followupProject", value = "随访项目", defaultValue = "2")
                                          @RequestParam(value = "followupProject", required = false) String followupProject,
                                          @ApiParam(name = "followupProjectData", value = "随访项目数据", defaultValue = "{\"BLOOD_SUGAR\":\"33.3\",\"BLOOD_SUGAR_TYPE\":\"1\",\"WEIGHT\":\"76\",\"WEIGHT_EXP\":\"60\",\"BMI\":\"11\"}")
                                          @RequestParam(value = "followupProjectData", required = true) String followupProjectData) {
        try {
            followUpService.esSaveFollowupProjectData(id, followupProject, followupProjectData);
            return write(200, "保存随访项目数据成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存随访项目数据失败!" + e.getMessage());
        }
    }
    /*********************************** 电话随访 *****************************************************************/
    @ApiOperation("获取电话随访内容")
    @RequestMapping(value = "/getFollowupPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupPhone(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                   @RequestParam(value = "id", required = true) String id) {
        try {
            String response = followUpService.getFollowupPhone(id);
            return write(200, "获取电话随访内容成功!", "data", response);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取电话随访内容失败!" + e.getMessage());
        }
    }
    @ApiOperation("记录电话随访内容")
    @RequestMapping(value = "/saveFollowupPhone", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveFollowupPhone(@ApiParam(name = "id", value = "随访记录ID", defaultValue = "")
                                    @RequestParam(value = "id", required = true) String id,
                                    @ApiParam(name = "content", value = "电话随访内容", defaultValue = "")
                                    @RequestParam(value = "content", required = true) String content) {
        try {
            followUpService.saveFollowupPhone(id, content);
            return write(200, "记录电话随访内容成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "记录电话随访内容失败!" + e.getMessage());
        }
    }
    /*************************************** 上次随访 ********************************************/
    @ApiOperation("获取上次随访")
    @RequestMapping(value = "/getLastFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getLastFollowup(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20161008001")
                                  @RequestParam(value = "patient", required = true) String patient,
                                  @ApiParam(name = "followClass", value = "随访类别", defaultValue = "1")
                                  @RequestParam(value = "followClass", required = true) String followClass) {
        try {
            Map<String, String> response = followUpService.getLastFollowup(getUID(), patient, followClass);
            return write(200, "获取上次随访成功!", "data", response);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取上次随访失败!" + e.getMessage());
        }
    }
    @ApiOperation("复制上次随访数据")
    @RequestMapping(value = "/copyFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String copyFollowup(@ApiParam(name = "id", value = "本地随访ID", defaultValue = "")
                               @RequestParam(value = "id", required = true) Long id,
                               @ApiParam(name = "fromId", value = "拷贝随访记录ID", defaultValue = "")
                               @RequestParam(value = "fromId", required = true) Long fromId) {
        try {
            followUpService.copyFollowup(id, fromId);
            return write(200, "复制上次随访成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "复制上次随访失败!" + e.getMessage());
        }
    }
    /*************************************** 发送随访计划消息 ********************************************/
    @ApiOperation("发送随访计划消息")
    @RequestMapping(value = "/sendMessage", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String sendMessage(@ApiParam(name = "date", value = "日期", defaultValue = "2017-01-05")
                              @RequestParam(value = "date", required = true) String date) {
        try {
            followUpService.sendMessage(date);
            return write(200, "发送随访计划消息成功!");
        } catch (Exception e) {
            return invalidUserException(e, -1, "发送随访计划消息失败!" + e.getMessage());
        }
    }
    
    
    @RequestMapping(value = "/checkfollowupcontent", method = RequestMethod.GET)
    @ApiOperation("检查续方关联的随访记录是否对应的详情记录")
    public String getfollowupcontent(
            @ApiParam(name = "followupid", value = "随访ID", defaultValue = "")
            @RequestParam(value = "followupid", required = true) String followupid,
            @ApiParam(name = "type", value = "支持传多个以英文逗号连接,drug为药品,1-9为随访分类", defaultValue = "")
            @RequestParam(value = "type", required = true) String type){
        try {
            int count = followUpService.getfollowupcontent(followupid,type);
            return write(200, "操作成功!","data",count);
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    
    @RequestMapping(value = "/checkfollowupcompleted", method = RequestMethod.GET)
    @ApiOperation("检查续方关联的随访记录是否对应的详情记录")
    public String checkfollowupcompleted(
            @ApiParam(name = "followupid", value = "随访ID", defaultValue = "")
            @RequestParam(value = "followupid", required = true) String followupid){
        try {
            boolean completed = followUpService.checkfollowupcompleted(followupid);
            return write(200, "操作成功!","data",completed);
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    //=======================1.5.7上门访视相关接口====================================
    @RequestMapping(value = "/findFollowupByMonth",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取访视计划按月日历形式")
    public String findFollowupByMonth(@ApiParam(name = "doctor", value = "医生", defaultValue = "zjm20190214")
                                          @RequestParam(value = "doctor", required = true) String doctor,
                                      @ApiParam(name = "patient", value = "居民")
                                          @RequestParam(value = "patient", required = false) String patient,
                                      @ApiParam(name = "followupClass", value = "随访类别,多类别“,”分割")
                                          @RequestParam(value = "followupClass", required = false) String followupClass,
                                      @ApiParam(name = "patientName", value = "居民姓名")
                                          @RequestParam(value = "patientName", required = false) String patientName,
                                      @ApiParam(value = "开始时间,格式(yyyy-MM-dd)", name = "startDate",required = false)
                                          @RequestParam(value = "startDate", required = false) String startDate,
                                      @ApiParam(value = "结束时间,格式(yyyy-MM-dd)", name = "endDate",required = false)
                                          @RequestParam(value = "endDate", required = false) String endDate,
                                      @ApiParam(name = "flag", value = "区分上门访视(1-是)")
                                          @RequestParam(value = "flag", required = false) String flag,
                                      @ApiParam(name = "type", value = "区分随访计划1、新增随访2、临时随访3、入户随访")
                                          @RequestParam(value = "type", required = false) Integer type,
                                      @ApiParam(name = "status", value = "随访状态")
                                          @RequestParam(value = "status", required = false) String status){
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupByMonth(doctor,patient,followupClass,patientName,startDate,endDate,flag,type,status));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowupList",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取访视列表形式")
    public String findFollowupList(@ApiParam(name = "doctor", value = "医生", defaultValue = "zjm20190214")
                                       @RequestParam(value = "doctor", required = true) String doctor,
                                   @ApiParam(name = "patient", value = "居民")
                                       @RequestParam(value = "patient", required = false) String patient,
                                   @ApiParam(name = "followupClass", value = "随访类别,多类别“,”分割")
                                       @RequestParam(value = "followupClass", required = false) String followupClass,
                                   @ApiParam(name = "patientName", value = "居民姓名")
                                       @RequestParam(value = "patientName", required = false) String patientName,
                                   @ApiParam(value = "开始时间,格式(yyyy-MM-dd)", name = "startDate",required = false)
                                       @RequestParam(value = "startDate", required = false) String startDate,
                                   @ApiParam(value = "结束时间,格式(yyyy-MM-dd)", name = "endDate",required = false)
                                       @RequestParam(value = "endDate", required = false) String endDate,
                                   @ApiParam(name = "flag", value = "区分上门访视(1-是)")
                                       @RequestParam(value = "flag", required = false) String flag,
                                   @ApiParam(name = "type", value = "")
                                       @RequestParam(value = "type", required = false) Integer type,
                                   @ApiParam(name = "status", value = "随访状态")
                                       @RequestParam(value = "status", required = false) String status){
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupList(null,doctor,patient,followupClass,patientName,startDate,endDate,flag,type,status));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findLabelListWithCount",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取随访标签列表带居民数")
    public String findLabelListWithCount(){
        try {
            return write(200, "操作成功!","data",followUpService.findLabelListWithCount());
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowupLabel",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取随访标签列表")
    public String findFollowupLabel(){
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupLabel());
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowUpPatient",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取可随访居民列表")
    public String findFollowUpPatient(@ApiParam(name = "namekey", value = "居民姓名模糊", defaultValue = "")
                                      @RequestParam(value = "namekey", required = false)String namekey,
                                      @ApiParam(name = "labelCode", value = "标签code", defaultValue = "1")
                                      @RequestParam(value = "labelCode", required = false)String labelCode,
                                      @ApiParam(name = "doctor", value = "医生", defaultValue = "zjm20190214")
                                      @RequestParam(value = "doctor", required = true)String doctor,
                                      @ApiParam(name = "page", value = "页数,1开始", defaultValue = "1")
                                      @RequestParam(value = "page", required = true)Integer page,
                                      @ApiParam(name = "size", value = "每页大小", defaultValue = "10")
                                      @RequestParam(value = "size", required = true)Integer size)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.findFollowUpPatient(namekey,doctor,labelCode,page,size));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findPatientInfo",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取居民单条信息")
    public String findPatientInfo(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                  @RequestParam(value = "patient", required = true)String patient) {
        try {
            return write(200, "操作成功!","data",followUpService.findPatientInfo(patient));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findPatientFollowList",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取居民随访列表")
    public String findPatientFollowList(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                        @RequestParam(value = "patient", required = true)String patient,
                                        @ApiParam(name = "doctor", value = "医生code", defaultValue = "")
                                        @RequestParam(value = "doctor", required = true)String doctor){
        try {
            return write(200, "操作成功!","data",followUpService.findPatientFollowList(patient,doctor));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/saveFollowup",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("保存随访访视")
    public String saveFollowup(@ApiParam(name = "jsonFollowup", value = "创建访视json", defaultValue = "")
                               @RequestParam(value = "jsonFollowup", required = true)String jsonFollowup){
        try {
            return write(200, "操作成功!","data",followUpService.saveFollowup(jsonFollowup));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/delFollowup",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("删除随访访视")
    public String delFollowup(@ApiParam(name = "followupId", value = "随访ID", defaultValue = "")
                               @RequestParam(value = "followupId", required = true)Long followupId)throws Exception {
        try {
            Followup followup = followUpService.delFollowup(followupId);
            followUpService.getNotStartFollowup(getUID(), followup.getFollowupPlanDate());
            return write(200, "操作成功!","data", true);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findFollowupInfo",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("获取随访详情")
    public String findFollowupInfo(@ApiParam(name = "followupId", value = "随访ID", defaultValue = "")
                                   @RequestParam(value = "followupId", required = true)Long followupId) {
        try {
            return write(200, "操作成功!","data",followUpService.findFollowupInfo(followupId));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/saveFollowupSign",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("签到")
    public String saveFollowupSign(@ApiParam(name = "jsonSign", value = "签到", defaultValue = "")
                                   @RequestParam(value = "jsonSign", required = true)String jsonSign)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.saveFollowupSign(jsonSign));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/updateFollowupSign",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("更新签到")
    public String updateFollowupSign(@ApiParam(name = "jsonSign", value = "签到", defaultValue = "")
                                     @RequestParam(value = "jsonSign", required = true)String jsonSign)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.updateFollowupSign(jsonSign));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/urlAnalysis",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("门牌解析上门地址")
    public String urlAnalysis(@ApiParam(name = "url", value = "地址解析", defaultValue = "")
                              @RequestParam(value = "url", required = true)String url)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.urlAnalysis(url));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/updateFollowStatus",produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("完成随访")
    public String  updateFollowStatus(@ApiParam(name = "followupId", value = "随访ID", defaultValue = "")
                                      @RequestParam(value = "followupId", required = true)Long followupId,
                                      @ApiParam(name = "isFlag", value = "标识第一次还是N次肺结核(第一次0,n次为1)", defaultValue = "")
                                      @RequestParam(value = "isFlag", required = false)Integer isFlag)throws Exception {
        try {
            return write(200, "操作成功!","data",followUpService.updateFollowStatus(followupId,isFlag));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findByFollowupId",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("签约详情")
    public String findByFollowupId(@ApiParam(name = "followupId", value = "签到", defaultValue = "")
                                   @RequestParam(value = "followupId", required = true)Long followupId) {
        try {
            return write(200, "操作成功!","data",followUpService.findByFollowupId(followupId));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/isFirstTimeFollowup",produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("判断居民该类别随访是否为第一次")
    public String isFirstTimeFollowup(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                      @RequestParam(value = "patient", required = true)String patient,
                                      @ApiParam(name = "followupClass", value = "随访类别", defaultValue = "")
                                      @RequestParam(value = "followupClass", required = true)String followupClass,
                                      @ApiParam(name = "followupId", value = "随访类别", defaultValue = "")
                                      @RequestParam(value = "followupId", required = true)Integer followupId) {
        try {
            return write(200, "操作成功!","data",followUpService.isFirstTimeFollowup(getUID(),patient,followupClass,followupId));
        }catch (Exception e){
            //日志文件中记录异常信息
            //返回接口异常信息处理结果
            return errorResult(e);
        }
    }
    //=======================end ==================================================
    @ApiOperation("保存全部随访表单数据")
    @RequestMapping(value = "/saveAllFollowupProjectData", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveAllFollowupProjectData(@ApiParam(name = "id", value = "随访记录ID")
                                                 @RequestParam(value = "id", required = true) String id,
                                             @ApiParam(name = "followupNo", value = "随访记录编码")
                                             @RequestParam(value = "followupNo", required = false) String followupNo,
                                             @ApiParam(name = "date", value = "随访时间", defaultValue = "2016-12-14 20:00:00")
                                                 @RequestParam(value = "date", required = false) String date,
                                             @ApiParam(name = "followupType", value = "随访方式【字典FOLLOWUP_WAY_DICT】", defaultValue = "12")
                                                 @RequestParam(value = "followupType", required = false) String followupType,
                                             @ApiParam(name = "followupClass", value = "随访类别【1.高血压 2.糖尿病,3高糖】", defaultValue = "1")
                                                 @RequestParam(value = "followupClass", required = false) String followupClass,
                                             @ApiParam(name = "followupManagerStatus", value = "随访管理状态【字典FOLLOWUP_MANAGER_STATUS】", defaultValue = "1")
                                                 @RequestParam(value = "followupManagerStatus", required = false) String followupManagerStatus,
                                             @ApiParam(name = "plandate", value = "下次随访时间", defaultValue = "2016-12-14 20:00:00")
                                                 @RequestParam(value = "plandate", required = false) String plandate,
                                             @ApiParam(name = "prescriptioncode", value = "续方CODE")
                                                 @RequestParam(value = "prescriptioncode", required = false) String prescriptioncode,
                                          @ApiParam(name = "followupProjectData", value = "随访项目数据", defaultValue = "{\"WEIGHT\":\"76\",\"WEIGHT_EXP\":\"60\",\"BMI\":\"11\"}")
                                          @RequestParam(value = "followupProjectData", required = true) String followupProjectData) {
        try {
            JSONObject jsonObject = new JSONObject(followupProjectData);
            Followup followup = followUpService.startFollowup(id, followupNo, date, followupType, followupClass, followupManagerStatus, plandate, prescriptioncode);
            followUpService.finishFollowup(id);
            followUpService.saveAllFollowupProjectData(id, jsonObject.getJSONObject("followupProjectData").toString());
            followupDrugsService.saveFollowupDrugs(id,jsonObject.getJSONArray("drugsData").toString());
            return write(200, "保存随访项目数据成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存随访项目数据失败!" + e.getMessage());
        }
    }
}

+ 0 - 80
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorFollowupDrugsController.java

@ -1,80 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.followup;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.followup.FollowupDrugsService;
import com.yihu.jw.entity.base.dict.DmDrugsGroupItem;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * 医生端:随访接口
 * 
 * @author hzp add 2016-12-07
 *
 */
@RestController
@RequestMapping(value = "/doctor/followup/drugs")
@Api(description = "医生端-随访用药接口")
public class DoctorFollowupDrugsController extends BaseController {
	@Autowired
	private FollowupDrugsService followupDrugsService;
	@ApiOperation("获取面访用药数据")
	@RequestMapping(value = "/getFollowupDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public String getFollowupDrugs(@ApiParam(name="id",value="随访记录ID",defaultValue = "")
									@RequestParam(value="id",required = true) String id)
	{
		try {
			Map<String,Object> response = followupDrugsService.getFollowupDrugs(id);
			return write(200, "获取面访用药数据成功!","data",response);
		} catch (Exception e) {
			return invalidUserException(e, -1, "获取面访用药数据失败!"+e.getMessage());
		}
	}
	@ApiOperation("保存面访用药数据")
	@RequestMapping(value = "/saveFollowupDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String saveFollowupDrugs(@ApiParam(name="id",value="随访记录ID",defaultValue = "")
										  @RequestParam(value="id",required = true) String id,
									      @ApiParam(name="drugsData",value="面访用药数据",defaultValue = "[]")
										  @RequestParam(value="drugsData",required = true) String drugsData)
	{
		try {
			followupDrugsService.saveFollowupDrugs(id,drugsData);
			return write(200, "保存面访用药数据成功!");
		} catch (Exception e) {
			return invalidUserException(e, -1, "保存面访用药数据失败!"+e.getMessage());
		}
	}
	@ApiOperation("获取随访类别用药列表")
	@RequestMapping(value = "/getFollowupClassDrugs", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	public String getFollowupClassDrugs(@ApiParam(name="followupClass",value="随访类别:1.高血压 2.糖尿病",defaultValue = "")
									@RequestParam(value="followupClass",required = true) String followupClass)
	{
		try {
			List<DmDrugsGroupItem> list = followupDrugsService.getFollowupClassDrugs(followupClass);
			return write(200, "获取随访类别用药列表成功!","data",list);
		} catch (Exception e) {
			return invalidUserException(e, -1, "获取随访类别用药列表失败!"+e.getMessage());
		}
	}
}

+ 0 - 79
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorPhthisisFollowupController.java

@ -1,79 +0,0 @@
//package com.yihu.jw.afterDiagnosis.endpoint.followup;
//
//import com.alibaba.fastjson.JSONObject;
//import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
//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;
//
///**
// * 医生端:肺结核随访服务控制器
// *
// * @author lith on 2019-05-05
// */
//@RestController
//@RequestMapping(value = "/doctor/phthisis")
//@Api(value = "医生端-肺结核随访记录服务")
//public class DoctorPhthisisFollowupController extends BaseController {
//    @Autowired
//    private PhthisisFollowupService phthisisFollowupService;
//
//    @PostMapping(value = "/saveFirst")
//    @ApiOperation(value = "保存第一次肺结核随访数据")
//    public String saveFirstFollowup(@ApiParam(name = "jsonData", value = "随访json") @RequestParam(value = "jsonData", required = true) String jsonData) {
//        StringBuilder errMsg = new StringBuilder();
//        try {
//            if(!phthisisFollowupService.saveFirstFollowup(jsonData,errMsg)){
//                return error( -1, "保存第一次肺结核随访数据失败," + errMsg);
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//        return write(200, "保存第一次肺结核随访数据成功!");
//    }
//
//    @PostMapping(value = "/saveNTimes")
//    @ApiOperation("保存第n次肺结核随访数据")
//    public String saveNTimesFollowup(@ApiParam(name = "jsonData", value = "随访json") @RequestParam(value = "jsonData", required = true) String jsonData) {
//        StringBuilder errMsg = new StringBuilder();
//        try {
//            if(!phthisisFollowupService.saveNTimesFollowup(jsonData,errMsg)){
//                return error( -1, "保存第n次肺结核随访数据失败," + errMsg);
//            }
//        } catch (Exception e) {
//            error(e);
//            return error(-1, "保存第n次肺结核随访数据失败," + e.getMessage());
//        }
//        return write(200, "保存第n次肺结核随访数据成功!");
//    }
//
//    @GetMapping(value = "/getFirst")
//    @ApiOperation("查询第一次肺结核随访数据详情")
//    public String queryFirst(@ApiParam(name = "followupId", value = "随访记录ID")
//                                         @RequestParam(value = "followupId", required = true) String followupId) {
//        try {
//            JSONObject firstFollowupES = phthisisFollowupService.queryFirstByFollowupId(followupId);
//            return write(200, "查询成功!", "data", firstFollowupES);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!" + e.getMessage());
//        }
//    }
//
//    @GetMapping(value = "/getNTimes")
//    @ApiOperation("查询第n次肺结核随访数据详情")
//    public String queryNTimes(@ApiParam(name = "followupId", value = "随访记录ID")
//                                         @RequestParam(value = "followupId", required = true) String followupId) {
//        try {
//            List<JSONObject> ntimesFollowups = phthisisFollowupService.queryNTimesByFollowupId(followupId);
//            return write(200, "查询成功!", "data", ntimesFollowups);
//        } catch (Exception e) {
//            return invalidUserException(e, -1, "查询失败!" + e.getMessage());
//        }
//    }
//
//}

+ 0 - 344
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/followup/DoctorVisitDetailController.java

@ -1,344 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.followup;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.followup.VisitDetailService;
import com.yihu.jw.followup.FollowupSevereMentalDisorderES;
import com.yihu.jw.followup.NewbornFamilyVisitRecordES;
import com.yihu.jw.followup.OlderPeopleHealthCheckRecordES;
import com.yihu.jw.followup.PostpartumVisitRecordES;
import com.yihu.jw.util.entity.ServiceException;
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.*;
/**
 * 医生端:访视详情表单接口
 *
 * @author hmf on 2019-04-23
 */
@RestController
@RequestMapping(value = "/doctor/visitDetail")
@Api(description = "医生端-访视详情表单接口")
public class DoctorVisitDetailController extends BaseController {
    @Autowired
    private VisitDetailService visitDetailService;
    @ApiOperation("保存孕产妇访视详情")
    @RequestMapping(value = "/savePostpartumVisitDetails", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String savePostpartumVisitDetails(@ApiParam(name = "followupId", value = "随访记录ID")
                                             @RequestParam(value = "followupId", required = true) String followupId,
                                             @ApiParam(name = "followupProject", value = "随访项目")
                                             @RequestParam(value = "followupProject", required = false) String followupProject,
                                             @ApiParam(name = "postpartumVisitDetails", value = "孕产妇访视详情数据")
                                             @RequestParam(value = "postpartumVisitDetails", required = true) String postpartumVisitDetails) {
        try {
            visitDetailService.savePostpartumVisitDetails(followupId, followupProject, postpartumVisitDetails, getUID());
            return write(200, "保存孕产妇访视详情数据成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存孕产妇访视详情数据失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取孕产妇访视详情")
    @RequestMapping(value = "/getPostpartumVisitDetails", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupProjectData(@ApiParam(name = "followupId", value = "随访记录ID")
                                         @RequestParam(value = "followupId", required = true) String followupId,
                                         @ApiParam(name = "followupProject", value = "随访项目")
                                         @RequestParam(value = "followupProject", required = false) String followupProject) {
        try {
            PostpartumVisitRecordES postpartumVisitRecord = visitDetailService.getPostpartumVisitRecord(followupId, followupProject);
            return write(200, "获取孕产妇访视详情成功!", "data", postpartumVisitRecord);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取孕产妇访视详情失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存严重精神障碍患者随访记录")
    @RequestMapping(value = "/saveFollowupSevereMentalDisorder", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveFollowupSevereMentalDisorder(@ApiParam(name = "followupId", value = "随访记录ID")
                                             @RequestParam(value = "followupId", required = true) String followupId,
                                             @ApiParam(name = "followupProject", value = "随访项目")
                                             @RequestParam(value = "followupProject", required = false) String followupProject,
                                             @ApiParam(name = "severeMentalDisorderData", value = "严重精神障碍患者详情数据")
                                             @RequestParam(value = "severeMentalDisorderData", required = true) String severeMentalDisorderData) {
        try {
            visitDetailService.saveFollowupSevereMentalDisorder(followupId, followupProject, severeMentalDisorderData, getUID());
            return write(200, "保存严重精神障碍患者随访记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存严重精神障碍患者随访记录数据失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取严重精神障碍患者随访记录")
    @RequestMapping(value = "/getFollowupSevereMentalDisorder", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getFollowupSevereMentalDisorder(@ApiParam(name = "followupId", value = "随访记录ID")
                                         @RequestParam(value = "followupId", required = true) String followupId,
                                         @ApiParam(name = "followupProject", value = "随访项目")
                                         @RequestParam(value = "followupProject", required = false) String followupProject) {
        try {
            FollowupSevereMentalDisorderES severeMentalDisorderES = visitDetailService.getFollowupSevereMentalDisorder(followupId, followupProject);
            return write(200, "获取严重精神障碍患者随访记录成功!", "data", severeMentalDisorderES);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取严重精神障碍患者随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存老人健康体检随访记录")
    @RequestMapping(value = "/saveOlderPeopleHealthCheckRecord", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveOlderPeopleHealthCheckRecord(@ApiParam(name = "followupId", value = "随访记录ID")
                                             @RequestParam(value = "followupId", required = true) String followupId,
                                             @ApiParam(name = "followupProject", value = "随访项目")
                                             @RequestParam(value = "followupProject", required = false) String followupProject,
                                             @ApiParam(name = "olderPeopleHealthCheckData", value = "老人健康体检随访记录")
                                             @RequestParam(value = "olderPeopleHealthCheckData", required = true) String olderPeopleHealthCheckData,
                                             @ApiParam(name = "bdStatus", value = "登记健康体检表状态(0-可编辑  1-不可编辑)")
                                             @RequestParam(value = "bdStatus", required = false) Integer bdStatus,
                                             @ApiParam(name = "pgStatus", value = "老年人生活自理能力评估表状态(0-可编辑  1-不可编辑)")
                                             @RequestParam(value = "pgStatus", required = false) Integer pgStatus ) {
        try {
            visitDetailService.saveOlderPeopleHealthCheckRecord(followupId, followupProject, olderPeopleHealthCheckData, getUID(),bdStatus,pgStatus);
            return write(200, "保存老人健康体检随访记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存老人健康体检随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取老人健康体检随访记录")
    @RequestMapping(value = "/getOlderPeopleHealthCheckRecord", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getOlderPeopleHealthCheckRecord(@ApiParam(name = "followupId", value = "随访记录ID")
                                         @RequestParam(value = "followupId", required = true) String followupId,
                                         @ApiParam(name = "followupProject", value = "随访项目")
                                         @RequestParam(value = "followupProject", required = false) String followupProject) {
        try {
            OlderPeopleHealthCheckRecordES olderPeopleHealthCheckRecord = visitDetailService.getOlderPeopleHealthCheckRecord(followupId, followupProject);
            return write(200, "获取老人随访服务随访成功!", "data", olderPeopleHealthCheckRecord);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取老人随访服务随访失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存新生儿家庭访视记录")
    @RequestMapping(value = "/saveNewbornFamilyVisitRecord", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public String saveNewbornFamilyVisitRecord(@ApiParam(name = "followupId", value = "随访记录ID")
                                                   @RequestParam(value = "followupId", required = true) String followupId,
                                                   @ApiParam(name = "followupProject", value = "随访项目")
                                                   @RequestParam(value = "followupProject", required = false) String followupProject,
                                                   @ApiParam(name = "newbornFamilyVisitRecordData", value = "新生儿家庭访视记录")
                                                   @RequestParam(value = "newbornFamilyVisitRecordData", required = true) String newbornFamilyVisitRecordData) {
        try {
            visitDetailService.saveNewbornFamilyVisitRecord(followupId, followupProject, newbornFamilyVisitRecordData, getUID());
            return write(200, "保存新生儿家庭访视记录成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存新生儿家庭访视记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取新生儿家庭访视记录")
    @RequestMapping(value = "/getNewbornFamilyVisitRecord", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getNewbornFamilyVisitRecord(@ApiParam(name = "followupId", value = "随访记录ID")
                                                  @RequestParam(value = "followupId", required = true) String followupId,
                                                  @ApiParam(name = "followupProject", value = "随访项目")
                                                  @RequestParam(value = "followupProject", required = false) String followupProject) {
        try {
            NewbornFamilyVisitRecordES newbornFamilyVisitRecordES = visitDetailService.getNewbornFamilyVisitRecord(followupId, followupProject);
            return write(200, "获取新生儿家庭访视记录成功!", "data", newbornFamilyVisitRecordES);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取新生儿家庭访视记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取上次填写内容")
    @RequestMapping(value = "/getLastVisitRecord", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getLastVisitRecord(@ApiParam(name = "patientCode", value = "居民code")
                                         @RequestParam(value = "patientCode", required = true) String patientCode,
                                         @ApiParam(name = "followupClass", value = "随访类别(5.产后 6.新生儿 7.严重精神病 8.80岁以上老人 9.肺结核)")
                                         @RequestParam(value = "followupClass") String followupClass) {
        try {
            JSONObject jsonObject = visitDetailService.getLastVisitRecord(patientCode, followupClass);
            return write(200, "获取上次随访记录成功!", "data", jsonObject);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取上次随访记录失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存慢性妇科炎症日常随访")
    @RequestMapping(value = "/saveGynecologicalInflammationDaily", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveGynecologicalInflammationDaily(@ApiParam(name = "followupId", value = "随访记录ID")
                                                         @RequestParam(value = "followupId", required = true) String followupId,
                                                     @ApiParam(name = "jsonData", value = "随访表单数据", defaultValue = "{\"followup\":{\"followupDate\":\"2020-03-17\"},\"content\":{\"referralHospital\":\"2\",\"hospitalOrg\":\"\",\"hospitalOrgName\":\"医院\",\"illnessBetter\":\"1\",\"currentStatus\":\"2\",\"followClass\":\"1\"}}")
                                                   @RequestParam(value = "jsonData", required = true) String jsonData) {
        try {
            return write(200, "保存慢性妇科炎症日常随访成功!", "data", visitDetailService.saveGynecologicalInflammationDaily(followupId, jsonData, getUID()));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存慢性妇科炎症日常随访失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取慢性妇科炎症日常随访")
    @RequestMapping(value = "/getGynecologicalInflammationDaily", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getGynecologicalInflammationDaily(@ApiParam(name = "followupId", value = "随访记录ID")
                                              @RequestParam(value = "followupId", required = true) String followupId) {
        try {
            JSONObject jsonObject = visitDetailService.getGynecologicalInflammationDaily(followupId);
            return write(200, "获取慢性妇科炎症日常随访成功!", "data", jsonObject);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取慢性妇科炎症日常随访失败!" + e.getMessage());
        }
    }
    /**
     * type:
     * BreastFollowup //4.慢性乳腺疾病日常随访
     * CerebralApoplexyFollowup //7.脑卒中日常随访
     * CoronaryFollowup//1.冠心病日常随访
     * FattyLiverFollowUp//8.脂肪肝日常随访
     * NephropathyFollowup//5.慢性肾病日常随访
     * ProstateFollowup//3.慢性前列腺疾病日常随访
     * @param followupId
     * @param type
     * @return
     */
    @ApiOperation("获取随访病种日常随访")
    @RequestMapping(value = "/selectFollowupDiseaseById", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String selectFollowupDiseaseById(@ApiParam(name = "followupId", value = "随访记录ID")
                                                    @RequestParam(value = "followupId", required = true) String followupId,
                                                    @ApiParam(name = "type", value = "病种类型")
                                                    @RequestParam(value = "type", required = true) String type) {
        try {
            JSONObject jsonObject = visitDetailService.selectFollowupDiseaseById(followupId,type);
            return write(200, "获取随访病种日常随访成功!", "data", jsonObject);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取随访病种日常随访失败!" + e.getMessage());
        }
    }
    /**
     *
     * type:
     * BreastFollowup //4.慢性乳腺疾病日常随访
     * CerebralApoplexyFollowup //7.脑卒中日常随访
     * CoronaryFollowup//1.冠心病日常随访
     * FattyLiverFollowUp//8.脂肪肝日常随访
     * NephropathyFollowup//5.慢性肾病日常随访
     * ProstateFollowup//3.慢性前列腺疾病日常随访
     *
     * @param followupId
     * @param jsonData
     * @param type
     * @return
     */
    @ApiOperation("保存各类病种日常随访")
    @RequestMapping(value = "/saveFollowupDiseaseArchives", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveFollowupDiseaseArchives(@ApiParam(name = "followupId", value = "随访记录ID")
                                                     @RequestParam(value = "followupId", required = true) String followupId,
                                                     @ApiParam(name = "jsonData", value = "随访表单数据", defaultValue = "{\"followup\":{\"followupDate\":\"2020-03-17\"},\"content\":{\"referralHospital\":\"2\",\"hospitalOrg\":\"\",\"hospitalOrgName\":\"医院\",\"illnessBetter\":\"1\",\"currentStatus\":\"2\",\"followClass\":\"1\"}}")
                                                     @RequestParam(value = "jsonData", required = true) String jsonData,
                                                     @ApiParam(name = "type", value = "随访记录类型")
                                                         @RequestParam(value = "type", required = true) String type) {
        try {
            visitDetailService.saveFollowupDiseaseArchives(followupId, jsonData, getUID(),type);
            return write(200, "保存日常随访成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存日常随访失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存慢性妇科炎症随访档案")
    @RequestMapping(value = "/saveGynecologicalInflammationFollowupArchives", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveGynecologicalInflammationFollowupArchives(@ApiParam(name = "followupId", value = "随访记录ID")
                                                     @RequestParam(value = "followupId", required = true) String followupId,
                                                     @ApiParam(name = "jsonData", value = "随访表单数据", defaultValue = "{\"followup\":{\"followupDate\":\"2020-03-17\"},\"content\":{\"referralHospital\":\"2\",\"hospitalOrg\":\"\",\"hospitalOrgName\":\"医院\",\"illnessBetter\":\"1\",\"currentStatus\":\"2\",\"followClass\":\"1\"}}")
                                                     @RequestParam(value = "jsonData", required = true) String jsonData) {
        try {
            return write(200, "保存慢性妇科炎症随访档案成功!", "data", visitDetailService.saveGynecologicalInflammationFollowupArchives(followupId, jsonData, getUID()));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存慢性妇科炎症随访档案失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取慢性妇科炎症随访档案")
    @RequestMapping(value = "/getGynecologicalInflammationFollowupArchives", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getGynecologicalInflammationFollowupArchives(@ApiParam(name = "followupId", value = "随访记录ID")
                                                    @RequestParam(value = "followupId", required = true) String followupId) {
        try {
            JSONObject jsonObject = visitDetailService.getGynecologicalInflammationFollowupArchives(followupId);
            return write(200, "获取慢性妇科炎症随访档案成功!", "data", jsonObject);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取慢性妇科炎症随访档案失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存慢性阻塞性肺病--首次问卷")
    @RequestMapping(value = "/saveCOPDFirstTimeQuestionnaire", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveCOPDFirstTimeQuestionnaire(@ApiParam(name = "followupId", value = "随访记录ID")
                                                     @RequestParam(value = "followupId", required = true) String followupId,
                                                     @ApiParam(name = "jsonData", value = "随访表单数据")
                                                     @RequestParam(value = "jsonData", required = true) String jsonData) {
        try {
            return write(200, "保存慢性阻塞性肺病--首次问卷成功!", "data", visitDetailService.saveCOPDFirstTimeQuestionnaire(followupId, jsonData, getUID()));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存慢性阻塞性肺病--首次问卷失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取慢性阻塞性肺病--首次问卷")
    @RequestMapping(value = "/getCOPDFirstTimeQuestionnaire", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getCOPDFirstTimeQuestionnaire(@ApiParam(name = "followupId", value = "随访记录ID")
                                                    @RequestParam(value = "followupId", required = true) String followupId) {
        try {
            JSONObject jsonObject = visitDetailService.getCOPDFirstTimeQuestionnaire(followupId);
            return write(200, "获取慢性阻塞性肺病--首次问卷成功!", "data", jsonObject);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取慢性阻塞性肺病--首次问卷失败!" + e.getMessage());
        }
    }
    @ApiOperation("保存慢性阻塞性肺病--日常随访")
    @RequestMapping(value = "/saveCOPDDailyFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public String saveCOPDDailyFollowup(@ApiParam(name = "followupId", value = "随访记录ID")
                                                 @RequestParam(value = "followupId", required = true) String followupId,
                                                 @ApiParam(name = "jsonData", value = "随访表单数据")
                                                 @RequestParam(value = "jsonData", required = true) String jsonData) {
        try {
            return write(200, "保存慢性阻塞性肺病--日常随访成功!", "data", visitDetailService.saveCOPDDailyFollowup(followupId, jsonData, getUID()));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return invalidUserException(e, -1, "保存慢性阻塞性肺病--日常随访失败!" + e.getMessage());
        }
    }
    @ApiOperation("获取慢性阻塞性肺病--日常随访")
    @RequestMapping(value = "/getCOPDDailyFollowup", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public String getCOPDDailyFollowup(@ApiParam(name = "followupId", value = "随访记录ID")
                                                @RequestParam(value = "followupId", required = true) String followupId) {
        try {
            JSONObject jsonObject = visitDetailService.getCOPDDailyFollowup(followupId);
            return write(200, "获取慢性阻塞性肺病--日常随访成功!", "data", jsonObject);
        } catch (Exception e) {
            return invalidUserException(e, -1, "获取慢性阻塞性肺病--日常随访失败!" + e.getMessage());
        }
    }
}

+ 0 - 691
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/health/DoctorHealthController.java

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

+ 0 - 564
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/health/PatientHealthController.java

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

+ 0 - 292
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionController.java

@ -1,292 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionDispensaryCodeService;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionInfoService;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionPayService;
import com.yihu.jw.afterDiagnosis.service.prescription.WlyyPrescriptionService;
import com.yihu.jw.entity.hospital.prescription.*;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageDao;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by Administrator on 2017/7/21.
 */
@RestController("patientPrescriptionController")
@RequestMapping(value = "/patient/prescription")
@Api(description = "患者端-长处方接口")
public class PatientPrescriptionController extends BaseController {
    @Autowired
    private PrescriptionDispensaryCodeService prescriptionDispensaryCodeService;
    @Autowired
    private WlyyPrescriptionService prescriptionService;
    @Autowired
    private PrescriptionInfoService prescriptionInfoService;
    @Autowired
    private PrescriptionPayService prescriptionPayService;
    @Autowired
    private PrescriptionExpressageDao prescriptionExpressageDao;
    /**
     * 生成取药码
     */
    @RequestMapping(value = "/dispensaryCode/saveQRCode", method = RequestMethod.POST)
    public String saveQRCode2(
            @ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            prescriptionDispensaryCodeService.saveQRCode(prescriptionCode);
            return write(200, "生成二维码成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成居民取药码
     *
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/savePatientQRCode", method = RequestMethod.GET)
    public String saveQRCode(
            @ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeService.savePatientQRCode(prescriptionCode);
            if (prescriptionDispensaryCode == null) {
                return error(-1, "生成居民取药码失败!");
            } else {
                return write(200, "生成居民取药码成功!", "code", prescriptionDispensaryCode.getCode());
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "生成居民取药码失败!");
        }
    }
    /**
     * 生成配送员取药码
     *
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/saveDoctorQRCode", method = RequestMethod.GET)
    public String saveDoctorQRCode(
            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
            @RequestParam(value = "code", required = true) String code) {
        try {
            PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeService.saveQRCode(code,prescriptionCode, 2);
            if (prescriptionDispensaryCode == null) {
                return error(-1, "生成配送员取药码失败!");
            } else {
                return write(200, "生成配送员取药码成功!", "code", prescriptionDispensaryCode.getCode());
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "生成配送员取药码失败!");
        }
    }
    /**
     * 生成配送员配送码
     *
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/saveDoctorQRDeliveryCode", method = RequestMethod.GET)
    public String saveDoctorQRDeliveryCode(
            @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode,
            @RequestParam(value = "code", required = true) String code) {
        try {
            PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeService.saveQRCode(code,prescriptionCode, 3);
            if (prescriptionDispensaryCode == null) {
                return error(-1, "生成配送员配送码失败!");
            } else {
                return write(200, "生成配送员配送码成功!", "code", prescriptionDispensaryCode.getCode());
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "生成配送员配送码失败!");
        }
    }
    /**
     * 居民端获取取药码
     *
     * @param prescriptionCode
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/getPatientQrcode", method = RequestMethod.GET)
    public String getPatientQrcode(@RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            Map<String, Object> map = prescriptionDispensaryCodeService.getQrcode(prescriptionCode, getRepUID(), 1);
            return write(200, "获取居民取药码成功!", "data", map);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "获取取药码失败!");
        }
    }
    /**
     * 居民端获取智慧药柜取药码
     *
     * @param prescriptionCode
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/getJumiQrcode", method = RequestMethod.GET)
    public String getJumiQrcode(@RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
        try {
            Map<String, Object> map = prescriptionDispensaryCodeService.getJumiQrcode(prescriptionCode);
            return write(200, "获取居民取药码成功!", "data", map);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "获取取药码失败!");
        }
    }
    /**
     * 显示居民所有的取药码列表
     *
     * @param status
     * @param timeType
     * @param page
     * @param pagesize type 1、居民端扫码列表 2、配送员(健管师)扫码列表
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/list", method = RequestMethod.GET)
    public String list(
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "timeType", required = false) Integer timeType,
            @RequestParam(value = "page", required = true) Integer page,
            @RequestParam(value = "pagesize", required = true) Integer pagesize) {
        try {
            JSONArray result = prescriptionDispensaryCodeService.findByStatusAndTime(timeType, getRepUID(), status, page, pagesize, 1);
            return write(200, "获取信息成功!", "result", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 订单跟踪 包含处方药品信息 订单记录  支付记录
     * 根据处方code获取处方流程
     *
     * @param prescriptionCode
     * @return
     */
    @RequestMapping(value = "/prescriptionFollow", method = RequestMethod.GET)
    @ApiOperation(value = "获取处方订单详情")
    public String prescriptionFollow(
            @RequestParam(required = true) @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode) {
        try {
            JSONObject jo = new JSONObject();
            //获取处方信息
            WlyyPrescriptionDO prescription = prescriptionService.findByCode(prescriptionCode);
            //获取处方药品信息
            List<WlyyPrescriptionInfoDO> prescriptionInfos = prescriptionInfoService.getPrescriptionInfo(prescriptionCode);
            //获取付款信息
            PrescriptionPay prescriptionPay = prescriptionPayService.findByPrescriptionCode(prescriptionCode);
            //获取配送信息
            WlyyPrescriptionExpressageDO prescriptionExpressage = prescriptionExpressageDao.findByPrescriptionCode(prescriptionCode);
            jo.put("prescriptionExpressage", prescriptionExpressage);
            jo.put("prescriptionPay", prescriptionPay);
            jo.put("prescriptionInfos", prescriptionInfos);
            if (prescription != null) {
                jo.put("createTime", prescription.getCreateTime());//创建时间
                jo.put("doctorName", prescription.getDoctorName());//审核医生
                jo.put("prescriptionHospital", prescription.getHospitalName());//出药机构
                jo.put("dispensaryDispensaryType", prescription.getDispensaryType());//处方配送方式
                jo.put("prescriptionStatus", prescription.getStatus());//处方状态
                jo.put("ssc",prescription.getSsc());//医保卡号
                jo.put("payTime",prescription.getPayTime());//支付时间
            }
            return write(200, "查询成功", "data", jo);
        } catch (Exception e) {
            return error(-1, "获取失败");
        }
    }
    /**
     * 续方确认收药接口
     *
     * @param prescriptionCode 续方code原状态为60
     * @param type 1:确认收药 2:延长收药
     * @return
     */
    @RequestMapping(value = "/confirmReceipt", method = RequestMethod.POST)
    @ApiOperation(value = "续方确认收药接口")
    public String confirmReceipt(
            @RequestParam(required = true) @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode,
            @RequestParam(required = true) @ApiParam(value = "收药方式", name = "type") Integer type) {
        try {
            Map<String,Object> result = prescriptionService.confirmReceipt(prescriptionCode,type);
            int code = Integer.parseInt(result.get("code").toString());
            String msg = result.get("msg").toString();
            return write(code, msg);
        } catch (Exception e) {
            return error(-1, "确认失败");
        }
    }
    @RequestMapping(value = "/fadeRecipe", method = RequestMethod.POST)
    @ApiOperation(value = "挂号作废处方接口")
    public String fadeRecipe(
            @RequestParam(required = true) @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode){
        try {
//            String result = jwPrescriptionService.fadeRecipe(prescriptionCode);
            return write(200, "挂号作废成功!", "result", "");
        } catch (ServiceException se){
            return error(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "挂号作废失败+"+e.getMessage());
        }
    }
    /**
     *
     * @param prescriptionCode
     * @return
     */
    @RequestMapping(value = "/checkRecipeNoPay",method = RequestMethod.POST)
    @ApiOperation(value = "查询待结算订单是否作废,如果作废更新本地数据为线下取消")
    public String checkRecipeNoPay(@ApiParam(value = "处方业务主键",name = "prescriptionCode")@RequestParam(value = "prescriptionCode")String prescriptionCode){
        try{
            JSONObject object = prescriptionService.checkRecipeNoPay(2,prescriptionCode);
            return write(200,"操作成功!","result",object);
        }catch (Exception e){
            error(e);
            return error(-1,"操作失误!"+e.getMessage());
        }
    }
}

+ 0 - 77
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionFollowupContentController.java

@ -1,77 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionFollowupContentService;
import com.yihu.jw.entity.hospital.prescription.PrescriptionFollowupContent;
import com.yihu.jw.util.entity.ServiceException;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 患者端-续方咨询问卷相关方法
 * @author huangwenjie
 * @date 2017/11/1 22:50
 */
@RestController
@RequestMapping(value = "/patient/prescription/followupcontent/")
@Api(description = "患者-续方咨询问卷相关接口")
public class PatientPrescriptionFollowupContentController extends BaseController {
	@Autowired
	private PrescriptionFollowupContentService prescriptionFollowupContentService;
	
	@RequestMapping(value = "/getinfo", method = RequestMethod.GET)
	@ApiOperation("根据续方CODE、类型CODE,获取随访调查分类数据")
	public String getinfoByPrescriptionCodeAndFollowupProject(
			@ApiParam(name = "prescriptioncode", value = "续方CODE", defaultValue = "续方CODE")
			@RequestParam(value = "prescriptioncode", required = true) String prescriptioncode,
			@ApiParam(name = "followupProject", value = "续方CODE", defaultValue = "问卷类型(症状、体征和问卷)")
			@RequestParam(value = "followupProject", required = true) String followupProject){
		try {
			List<PrescriptionFollowupContent> result = prescriptionFollowupContentService.getByPrescriptionCodeAndFollowupProject(prescriptioncode,followupProject);
			Map<String, String> datamap = new HashMap<>();
			if(!result.isEmpty()){
				for (PrescriptionFollowupContent prescriptionFollowupContent: result) {
					datamap.put(prescriptionFollowupContent.getFollowupKey(),prescriptionFollowupContent.getFollowupValue());
				}
			}
			return write(200, "请求成功!","data",datamap);
		}catch (Exception e){
			//日志文件中记录异常信息
			error(e);
			//返回接口异常信息处理结果
			return error(-1, "请求失败,地址不可派送!");
		}
	}
	
	@RequestMapping(value = "/saveinfo", method = RequestMethod.POST)
	@ApiOperation("保存随访调查分类数据")
	public String saveInfo(@ApiParam(name = "prescriptioncode", value = "续方CODE", defaultValue = "续方CODE")
	                       @RequestParam(value = "prescriptioncode", required = true) String prescriptioncode,
	                       @ApiParam(name = "followupProjectData", value = "调查分类数据", defaultValue = "[{\"followupProject\":\"1\",\"projectData\":{\"WEIGHT\":\"76\",\"WEIGHT_EXP\":\"60\",\"BMI\":\"11\"}}]")
	                       @RequestParam(value = "followupProjectData", required = true) String followupProjectData,
	                       @ApiParam(name = "sendIM", value = "是否发送IM消息", defaultValue ="false")
	                       @RequestParam(value = "sendIM", required = true) boolean sendIM){
		try {
			prescriptionFollowupContentService.saveInfo(prescriptioncode,followupProjectData,getRepUID(),sendIM);
			return write(200, "请求成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e){
			//日志文件中记录异常信息
			error(e);
			//返回接口异常信息处理结果
			return error(-1, "请求失败!"+e.getMessage());
		}
	}
}

+ 0 - 204
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionInfoController.java

@ -1,204 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionDispensaryCodeService;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionInfoService;
import com.yihu.jw.entity.hospital.prescription.PrescriptionDispensaryCode;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Trick on 2017/7/25.
 */
@RestController
@RequestMapping(value = "/patient/prescriptionInfo")
@Api(description = "患者端-长处方接口")
public class PatientPrescriptionInfoController extends BaseController {
    @Autowired
    private PrescriptionInfoService prescriptionInfoService;
    @Autowired
    private PrescriptionDispensaryCodeService prescriptionDispensaryCodeService;
    /**
     * 获取处方列表
     * @param type
     * @return
     */
    @RequestMapping(value = "/getPrescriptionInfos" , method = RequestMethod.GET)
    @ApiOperation(value = "获取长处方信息列表")
    public String getPrescriptionInfos(@RequestParam(required = true)@ApiParam(name="type",value="1:查询处方;2我的续方;3:续方记录")String type,
                                       @RequestParam(required = false)@ApiParam(name="isRenewal",value="处方是否可续方:1.是;2.无过滤")String isRenewal,
                                       @RequestParam(required = false)@ApiParam(name="recipeNo",value="医嘱号,第一次获取上一方时传入0,第二次获取上一方时传入第一次返回的医嘱号,以此类推")String recipeNo,
                                       @RequestParam(required = false)@ApiParam(name="startDate",value="开始时间")String startDate,
                                       @RequestParam(required = false)@ApiParam(name="endDate",value="结束时间")String endDate,
                                       @RequestParam(required = false,defaultValue = "0")@ApiParam(name="diagnosisCode",value="所有诊断(0 全部 1高血压 2糖尿病)")String diagnosisCode,
                                       @RequestParam(required = false)@ApiParam(name="page",value="起始页")Integer page,
                                       @RequestParam(required = false)@ApiParam(name="size",value="每页记录数")Integer size,
                                       @RequestParam(required = true)@ApiParam(name="hospital",value="社区CODE")String hospital){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getPrescriptionInfos(type,recipeNo,diagnosisCode,startDate,endDate,getRepUID(),isRenewal,page,size,hospital));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "getRecipeMasterList" , method = RequestMethod.GET)
    @ApiOperation(value = "获取智业长处方信息列表")
    public String getRecipeMasterList(@RequestParam(required = false)@ApiParam(name="isRenewal",value="处方是否可续方:1.是;2.无过滤")String isRenewal,
                                      @RequestParam(required = false)@ApiParam(name="startDate",value="开始时间")String startDate,
                                      @RequestParam(required = false)@ApiParam(name="endDate",value="结束时间")String endDate,
                                      @RequestParam(required = false,defaultValue = "0")@ApiParam(name="diagnosisCode",value="所有诊断(0 全部 1高血压 2糖尿病)")String diagnosisCode,
                                      @RequestParam(required = false)@ApiParam(name="page",value="起始页")Integer page,
                                      @RequestParam(required = false)@ApiParam(name="size",value="每页记录数")Integer size,
                                      @RequestParam(required = false)@ApiParam(name="size",value="社区CODE")String hospital
    ){
        try {
            com.alibaba.fastjson.JSONObject json = prescriptionInfoService.getRecipeMasterList(getRepUID(),startDate,endDate,isRenewal,diagnosisCode,page,size,hospital);
            return write(200, "查询成功!", "data",json);
        }catch (Exception e){
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "/getPrescription" ,method = RequestMethod.GET)
    @ApiOperation(value = "获取长处方详细信息")
    public String getPrescription(@RequestParam(required = true)@ApiParam(name="code",value="处方CODE")String code,
                                  @RequestParam(required = false)@ApiParam(name="preCode",value="续方CODE")String preCode,
                                  @RequestParam(required = false)@ApiParam(name="hospital",value="社区CODE")String hospital){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getPrescription(code,getRepUID(),preCode,hospital));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "/getContinuedPrescription", method = RequestMethod.GET)
    @ApiOperation(value = "获取续方详细信息")
    public String getContinuedPrescription(@RequestParam(required = true)@ApiParam(name="code",value="续方CODE")String code){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getContinuedPrescription(code));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "/getPrescriptionProcess" ,method = RequestMethod.GET)
    @ApiOperation(value = "获取续方记录详细信息")
    public String getPrescriptionProcess(@RequestParam(required = true)@ApiParam(name="code",value="续方CODE")String code){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getPrescriptionProcess(code));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    @RequestMapping(value = "/cancelPrescriotion" , method = RequestMethod.POST)
    @ApiOperation(value = "取消续方")
    public String cancelPrescriotion(@RequestParam(required = true)@ApiParam(name="code",value="续方CODE")String code,
                                     @RequestParam(required = true)@ApiParam(name="reason",value="原因")String reason){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.cancelPrescriotion(code,reason));
        } catch (ServiceException se){
            return error(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "取消失败!");
        }
    }
    @ApiOperation("判断患者是否有续方记录")
    @RequestMapping(value = "checkPatientWithPrescription", method = RequestMethod.GET)
    public String checkPatientWithPrescription(){
        try {
            return write(200, "获取信息成功!", "data",prescriptionInfoService.checkPatientWithPrescription(getUID()));
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    
    @RequestMapping(value = "/getPatientLastPrescriptionProcess" ,method = RequestMethod.GET)
    @ApiOperation(value = "获取当前居民的上一条续方详情")
    public String getPatientLastPrescriptionProcess(){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getPatientLastPrescriptionProcess(getRepUID()));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    
    
    @RequestMapping(value = "/getPatientLastPrescriptionExpressInfo" ,method = RequestMethod.GET)
    @ApiOperation(value = "获取当前居民的上一条续方的派送地址")
    public String getPatientLastPrescriptionExpressInfo(@RequestParam(required = true)@ApiParam(name="dispensaryType",value="派送方式")Integer dispensaryType){
        try {
            return write(200, "查询成功!", "data", prescriptionInfoService.getPatientLastPrescriptionExpressInfo(getRepUID(),dispensaryType));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    
    /**
     * 扫码
     * @param code
     * @return
     */
    @RequestMapping(value = "/dispensaryCode/scanQrcode",method = RequestMethod.GET)
    public String scanQrcode(
            @RequestParam(value = "code",required = true) String code,
            @RequestParam(value = "patientCode",required = true) String patientCode
    ){
        try {
            PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeService.scanQrcode(code,getUID());
            return write(200, "扫码成功!", "data", prescriptionDispensaryCode);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    
    
    @RequestMapping(value = "/getTodayPrescriptionCount", method = RequestMethod.GET)
    @ApiOperation(value = "获取居民今天已发起的有效续方数量")
    public String getTodayPrescriptionCount(@RequestParam(required = true)
                                            @ApiParam(value = "居民CODE", name = "patientCode") String patientCode,
                                            @RequestParam(required = false)
                                            @ApiParam(value = "开始时间", name = "start_date") String start_date) {
        try {
            if(StringUtils.isBlank(start_date)){
                start_date = DateUtil.getStringDateShort();
            }
            return write(200, "查询成功!", "data", prescriptionInfoService.getTodayPrescriptionCount(patientCode,start_date));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
}

+ 0 - 106
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionLogController.java

@ -1,106 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionExpressageLogDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionLogDO;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageLogDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionLogService;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * Created by chenweida on 2017/7/27.
 */
@RestController
@RequestMapping(value = "/patient/prescriptionlog")
@Api(description = "患者端-处方日志")
public class PatientPrescriptionLogController extends BaseController {
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private PrescriptionExpressageLogDao prescriptionExpressageLogDao;
    /**
     * 订单跟踪
     * 根据处方code获取处方流程
     *
     * @param prescriptionCode
     * @return
     */
    @RequestMapping(value = "/orderFollow", method = RequestMethod.GET)
    @ApiOperation(value = "订单状态跟踪")
    public String orderFollow(
            @ApiParam(value = "处方code", name = "prescriptionCode") @RequestParam(required = true, name = "prescriptionCode") String prescriptionCode) {
        try {
            // (-3 支付过期 -2 患者自己取消 -1 审核不通过 , 0 待审核, 2调整中 10 审核通过/开方中  , 20开方完成/待支付, 21 支付失败 , 30 支付成功/待配药 ,
            // 40配药成功/待配送  41配送失败 42分配健管师 45配送中   49配送到服务站  100配送到患者手中/已完成)
            Integer[] status = new Integer[]{
                    WlyyPrescriptionLogDO.PrescriptionLogStatus.pay_success.getValue(),
                    WlyyPrescriptionLogDO.PrescriptionLogStatus.wait_expressage.getValue(),
                    WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageing.getValue(),
                    WlyyPrescriptionLogDO.PrescriptionLogStatus.finish.getValue()};
            List<WlyyPrescriptionLogDO> prescriptionLogs = prescriptionLogService.findPrescriptionLogsByPrescriptionCode(prescriptionCode, status);
            //加上快递的log
            List<WlyyPrescriptionExpressageLogDO> expressageLogs = prescriptionExpressageLogDao.findByPrescriptionCode(prescriptionCode);
            for (int i = 0; i < expressageLogs.size(); i++) {
                WlyyPrescriptionExpressageLogDO prescriptionExpressageLog = expressageLogs.get(i);
                WlyyPrescriptionLogDO prescriptionLog = new WlyyPrescriptionLogDO();
                prescriptionLog.setStatus(WlyyPrescriptionLogDO.PrescriptionLogStatus.expressage2hospital.getValue());
                prescriptionLog.setCreateTime(prescriptionExpressageLog.getCreateTime());
//                prescriptionLog.setHospital(prescriptionExpressageLog.getAcceptHospital());
//                prescriptionLog.setHospitalName(prescriptionExpressageLog.getAcceptHospitalName());
                prescriptionLog.setUserCode(prescriptionExpressageLog.getExpressageUserCode());
                prescriptionLog.setUserName(prescriptionExpressageLog.getExpressageUserName());
                prescriptionLogs.add(prescriptionLog);
            }
            //排序
            prescriptionLogs.sort((o1, o2) -> {
                long map1value = o1.getCreateTime().getTime();
                long map2value = o2.getCreateTime().getTime();
                if (map1value - map2value > 0) {
                    return -1;
                } else if (map1value - map2value < 0) {
                    return 1;
                } else {
                    return 0;
                }
            });
            if (prescriptionLogs != null && prescriptionLogs.size() > 0) {
                JSONArray ja = new JSONArray();
                for (int i = 0; i < prescriptionLogs.size(); i++) {
                    WlyyPrescriptionLogDO one = prescriptionLogs.get(i);
                    JSONObject jo = new JSONObject();
                    jo.put("createTime", DateUtil.dateToStrLong(one.getCreateTime()));
//                    jo.put("statusName", one.getStatusName());
                    ja.put(jo);
                }
                return write(200, "获取处方流程成功", "data", ja);
            } else {
                return error(-1, "获取失败");
            }
        } catch (
                Exception e
                )
        {
            return error(-1, "获取失败");
        }
    }
}

+ 0 - 362
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PatientPrescriptionPayController.java

@ -1,362 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PatientPrescriptionPayService;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionAdressService;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionNoticesService;
import com.yihu.jw.entity.order.PayLog;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
 * Created by Reece on 2017/7/28.
 */
@RestController("patientPrescriptionPayController")
@RequestMapping(value = "/patient/prescription/pay")
@Api(description = "患者端-长处方支付接口")
public class PatientPrescriptionPayController extends BaseController {
    @Autowired
    private PatientPrescriptionPayService payService;
    @Autowired
    private PrescriptionService prescriptionService;
    @Autowired
    private PrescriptionNoticesService noticesService;
    @Autowired
    private PrescriptionAdressService prescriptionAdressService;
    /**
     * 患者长处方支付接口 可配送方式查询
     *
     * @param orgCode          居民签约社区code
     * @param prescriptionCode 续方code
     * @return
     * @
     */
    @RequestMapping(value = "/dispatch", method = RequestMethod.POST)
    @ApiOperation(value = "配送方式查询接口")
    public String dispatch(
            @RequestParam(required = true) @ApiParam(value = "续方code", name = "prescriptionCode") String prescriptionCode,
            @RequestParam(required = true) @ApiParam(value = "居民签约社区code", name = "orgCode") String orgCode)  {
        try {
            com.alibaba.fastjson.JSONObject result = payService.dispatch(prescriptionCode, orgCode);
            return write(200, "获取成功!", "data", result);
        } catch (Exception e) {
            return error(-1, "获取失败!");
        }
    }
    /**
     * 患者长处方支付接口
     *
     * @param orgCode          患者签约医院code
     * @param prescriptionCode 续方code
     * @param type             配送方式 1:自取 2:快递 3:健管师配送
     * @param addressJson      配送信息json
     * @param totalAmount      订单总金额
     * @return
     * @
     */
    @RequestMapping(value = "/recipeCharge", method = RequestMethod.POST)
    @ApiOperation(value = "患者长处方支付接口")
    public String recipeCharge(
            @RequestParam(required = true) @ApiParam(value = "居民社区code", name = "orgCode") String orgCode,
            @RequestParam(required = true) @ApiParam(value = "续方code", name = "prescriptionCode") String prescriptionCode,
            @RequestParam(required = true) @ApiParam(value = "配送方式", name = "type") int type,
            @RequestParam(required = true) @ApiParam(value = "配送地址json", name = "addressJson", defaultValue = "{\"townName\":\"海沧区\",\"code\":\"3502050100\",\"address\":" +
                    "\"冰岛\",\"cityName\":\"厦门市\",\"townCode\":\"350205\",\"provinceCode\":\"350000\",\"cityCode\":\"350200\",\"name\":\"海沧区嵩屿街道社区卫生服务中心\"," +
                    "\"provinceName\":\"福建省\",\"streeCode\":\"35020501\",\"streeName\":\"皇后大道东\",\"phone\":\"13253541190\"}") String addressJson,
            @RequestParam(required = true) @ApiParam(value = "页面回调地址", name = "returnUrl") String returnUrl,
            @RequestParam(required = true) @ApiParam(value = "订单总金额", name = "totalAmount") int totalAmount,
            @RequestParam(required = false) @ApiParam(value = "送达时间", name = "deliveryTime") String deliveryTime)  {
        try {
            String patient = getUID();
            String repUid = getRepUID();
            if(!patient.equals(repUid)){
                return error(-1, "目前不支持在线共济支付,请使用居民本人账号登陆支付,或者到社区进行线下支付!");
            }
            
            Map result = payService.charge(type, addressJson, orgCode, prescriptionCode, totalAmount, patient, repUid, null, returnUrl, deliveryTime);
            if ("-1".equals(result.get("status").toString())) {
                return error(-1, "续方居民信息与微信支付身份信息不一致!");
            } else if ("-2".equals(result.get("status").toString())) {
                return error(-1, "续方居民信息挂号号或处方号不存在!");
            } else if ("-3".equals(result.get("status").toString())) {
                return error(-1, "您没有需要待结算的信息!");
            } else if ("-4".equals(result.get("status").toString())) {
                return error(-1, "附属卡未绑定!");
            } else {
                return write(200, "支付成功!", "data", result);
            }
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return error(-1, "支付失败!");
        }
    }
    /**
     * 患者家签及长处方支付结果查询接口
     *
     * @param outChargeNo
     * @return
     */
    @RequestMapping(value = "/recipeChargeQuery", method = RequestMethod.GET)
    @ApiOperation(value = "患者支付结果查询接口")
    public String chargeQuery(@RequestParam(required = true) @ApiParam(value = "支付应用流水号", name = "outChargeNo") String outChargeNo)  {
        try {
            String result = payService.chargeQuery(outChargeNo, null);
            return write(200, "获取成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return error(-1, "获取失败!");
        }
    }
    /**
     *易联众支付结果查询
     * @param outChargeNo
     * @returnc
     */
    @RequestMapping(value = "/getChargeQuery", method = RequestMethod.GET)
    @ApiOperation(value = "患者支付结果查询接口")
    public String getChargeQuery(@RequestParam(required = true) @ApiParam(value = "支付应用流水号", name = "outChargeNo") String outChargeNo)  {
        try {
            String result = payService.getChargeQuery(outChargeNo, null);
            return write(200, "获取成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return error(-1, "获取失败!");
        }
    }
    /**
     * 查询家庭签约支付结果
     *
     * @return
     */
    @RequestMapping(value = "/getSignFamilyPayResult", method = RequestMethod.GET)
    @ApiOperation(value = "查询家庭签约支付结果")
    public String getSignFamilyPayResult(
            @RequestParam(required = true)
            @ApiParam(value = "支付应用流水号", name = "outChargeNo") String outChargeNo,
            @RequestParam(required = true)
            @ApiParam(value = "易联众appid", name = "appId") String appId,
            @RequestParam(required = true)
            @ApiParam(value = "易联众app secret", name = "appSecret") String appSecret) {
        try {
            String result = payService.getSignFamilyPayResult(outChargeNo, null, appId, appSecret);
            return write(200, "获取成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!");
        }
    }
    /**
     * 长处方支付成功前端页面回调接口
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/recipeReturnUrl", method = RequestMethod.POST)
    @ApiOperation(value = "支付成功前端页面回调接口")
    public String recipeReturnUrl(HttpServletRequest request, HttpServletResponse response)  {
        try {
            Map result = payService.recipeReturnUrl(request, response, null);
            return write(200, "页面回调成功!", "data", result);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return error(-1, "页面回调失败!");
        }
    }
    /**
     * 测试长处方相关模板通知消息
     *
     * @param patient   要发送对象居民code
     * @param doctName  相关医生姓名(type=1审核医生、type=2 null、type=3配送健管师、type=4审核医生)
     * @param ordenTime 订单完成时间(type=1 null、type=2 null、type=3 null、type=4 订单完成时间)
     * @param type      1:续方审核通知 2:取药代办通知 3:配送中信息变更 4:已完成服务结果
     * @param status    续方通知状态 0不通过 1通过 2调整处方  其余状态均为0
     * @param url       带参数的模板跳转链接
     */
    @RequestMapping(value = "/testSendMassages", method = RequestMethod.POST)
    @ApiOperation(value = "测试长处方相关模板通知消息")
    public String testSendMassages(
            @ApiParam(name = "patient", value = "要发送对象居民code")
            @RequestParam(value = "patient", required = true) String patient,
            @ApiParam(name = "doctName", value = "相关医生姓名(type=1审核医生、type=2 null、type=3配送健管师、type=4审核医生)")
            @RequestParam(value = "doctName", required = false) String doctName,
            @ApiParam(name = "ordenTime", value = "订单完成时间(type=1 null、type=2 null、type=3 null、type=4 订单完成时间)")
            @RequestParam(value = "ordenTime", required = false) String ordenTime,
            @ApiParam(name = "type", value = "1:续方审核通知 2:取药代办通知 3:配送中信息变更 4:已完成服务结果")
            @RequestParam(value = "type", required = true) int type,
            @ApiParam(name = "status", value = "续方通知状态 0不通过 1通过 2调整处方  其余状态均为0")
            @RequestParam(value = "status", required = true) int status,
            @ApiParam(name = "url", value = "带参数的模板跳转链接")
            @RequestParam(value = "url", required = true) String url) {
        try {
            noticesService.sendMessages(patient, doctName, ordenTime, type, status, url);
            return write(200, "发送成功!");
        } catch (Exception e) {
            return error(-1, "发送失败!");
        }
    }
    //===========================v1.3.9======================================================================
    @RequestMapping(value = "/getAddressList", method = RequestMethod.POST)
    @ApiOperation(value = "获取患者所有地址")
    public String getAdressList(@ApiParam(name = "patient", value = "居民code")
                                @RequestParam(value = "patient", required = true) String patient) {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.getAdressList(patient));
        } catch (Exception e) {
            return error(-1, "获取失败!");
        }
    }
    @RequestMapping(value = "/getDefAddress", method = RequestMethod.POST)
    @ApiOperation(value = "获取患者默认地址")
    public String getDefAdress(String patient) {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.getDefAdress(patient));
        } catch (Exception e) {
            error(e);
            return error(-1, "发送失败!");
        }
    }
    @RequestMapping(value = "/saveAddress", method = RequestMethod.POST)
    @ApiOperation(value = "保存地址")
    public String saveAdress(@ApiParam(name = "addressJson", value = "实体json串")
                             @RequestParam(value = "addressJson", required = true) String addressJson) {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.saveAdress(addressJson));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!");
        }
    }
    @RequestMapping(value = "/delAddress", method = RequestMethod.POST)
    @ApiOperation(value = "删除地址")
    public String delAdress(@ApiParam(name = "id", value = "主键")
                            @RequestParam(value = "id", required = true) String id) {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.delAdress(id));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!");
        }
    }
    @RequestMapping(value = "/getProvince", method = RequestMethod.POST)
    @ApiOperation(value = "获取省会")
    public String getProvince() {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.getProvince());
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!");
        }
    }
    @RequestMapping(value = "/getCityByProvince", method = RequestMethod.POST)
    @ApiOperation(value = "根据省会获取城市")
    public String getCityByProvince(@ApiParam(name = "province", value = "省会code")
                                    @RequestParam(value = "province", required = true) String province) {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.getCityByProvince(province));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!");
        }
    }
    @RequestMapping(value = "/getTowmByCity", method = RequestMethod.POST)
    @ApiOperation(value = "根据城市获取区")
    public String getTowmByCity(@ApiParam(name = "city", value = "城市code")
                                @RequestParam(value = "city", required = true) String city) {
        try {
            return write(200, "获取成功!", "data", prescriptionAdressService.getTowmByCity(city));
        } catch (Exception e) {
            error(e);
            return error(-1, "获取失败!");
        }
    }
    /**
     * 查询缴费居民手机绑定情况
     *
     * @return
     */
    @RequestMapping(value = "/getPatientMobile", method = RequestMethod.GET)
    @ApiOperation(value = "查询缴费居民手机绑定情况")
    public String getPatientMobile() {
        try {
            String status = "1";
            String mobile = payService.getPatientMobile(getRepUID());
            if (StringUtils.isEmpty(mobile)){
                status = "0";
            }
            return write(200, "查询成功!", "data", status);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    
    /**
     * 根据长处方代码查询支付日志
     * @param prescriptionCode
     * @return
     */
    @RequestMapping(value = "/getPayLogsByPrescriptionCode", method = RequestMethod.GET)
    @ApiOperation(value = "根据长处方代码查询支付日志")
    public String getPayLogsByPrescriptionCode(@ApiParam(name = "prescriptionCode", value = "处方CODE")
                                               @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode){
        try {
            List<PayLog> result = payService.getPayLogsByPrescriptionCode(prescriptionCode);
            return write(200, "查询成功!", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
        
    }
}

+ 0 - 80
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionAdjustController.java

@ -1,80 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionAdjustService;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by yeshijie on 2017/8/17.
 */
@RestController
@RequestMapping(value = "/doctor/prescriptionAdjust")
@Api(description = "医生端-长处方线下调整相关接口接口")
public class PrescriptionAdjustController extends BaseController {
	@Autowired
	private PrescriptionDao prescriptionDao;
	@Autowired
	private PrescriptionAdjustService prescriptionAdjustService;
	
	@RequestMapping(value = "adjustPrescription",method = RequestMethod.POST)
	@ApiOperation("线下调整处方")
	public String adjustPrescription(@ApiParam(name = "code", value = "续方code", defaultValue = "10")
	                                 @RequestParam(value = "code", required = true) String code,
	                                 @ApiParam(value = "科室", name = "dept") @RequestParam(required = true) String dept,
	                                 @ApiParam(value = "诊金", name = "registerFee") @RequestParam(required = true) String registerFee,
	                                 @ApiParam(value = "诊金类型", name = "rateTypeCode") @RequestParam(required = true) String rateTypeCode,
									 @RequestParam(required = false) @ApiParam(value = "科室code(智业校正减库存使用)", name = "deptCode") String deptCode,
									 @RequestParam(required = false) @ApiParam(value = "药房地址(顺丰取药使用)", name = "orgAddress") String orgAddress){
		try{
			//1、保存科室和挂号信息
			prescriptionAdjustService.saveDept(code,dept,rateTypeCode,registerFee,deptCode);
			//2、调整处方
			JSONObject json = prescriptionAdjustService.adjustPrescription(code,deptCode,orgAddress);
			if(json.getInteger("status")==-1){
				return error(-1,json.getString("msg"));
			}
			return write(200,"请求调整成功");
		}catch (Exception e){
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "uploadCaDigital",method = RequestMethod.POST)
	@ApiOperation("上传基位ca认证信息")
	public String uploadCaDigital(@ApiParam(name = "code", value = "续方code", defaultValue = "10")
	                              @RequestParam(value = "code", required = true) String code){
		try{
			JSONObject json = prescriptionAdjustService.uploadCaDigital(code);
			if(json.getInteger("status")==-1){
				return error(-1,json.getString("msg"));
			}
			return write(200,"上传ca认证信息成功");
		}catch (Exception e){
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "getPrescriptionStatus",method = RequestMethod.GET)
	@ApiOperation("获取续方状态")
	public String getPrescriptionStatus(@ApiParam(name = "code", value = "续方code", defaultValue = "10")
	                                    @RequestParam(value = "code", required = true) String code){
		try {
			WlyyPrescriptionDO prescription = prescriptionDao.findById(code).orElse(null);
			
			return write(200,"success","data",prescription.getStatus());
		}catch (Exception e){
			return errorResult(e);
		}
	}
}

+ 0 - 131
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionCodeController.java

@ -1,131 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionDispensaryCodeService;
import com.yihu.jw.afterDiagnosis.service.prescription.WlyyPrescriptionExpressageService;
import com.yihu.jw.entity.hospital.prescription.PrescriptionDispensaryCode;
import com.yihu.jw.util.entity.ServiceException;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
 * Created by Trick on 2017/7/25.
 */
@RestController
@RequestMapping(value = "/doctor/prescriptionCode")
@Api(description = "医生端-长处方接口")
public class PrescriptionCodeController extends BaseController {
	
	
	@Autowired
	private PrescriptionDispensaryCodeService prescriptionDispensaryCodeService;
	
	@Autowired
	private WlyyPrescriptionExpressageService prescriptionExpressageService;
	
	/**
	 * 确认配送 二维码方式
	 * 根据处方code获取处方流程
	 *
	 * @param code wlyy_prescription_dispensary_code的code
	 * @return
	 */
	@RequestMapping(value = "/expressage", method = RequestMethod.POST)
	@ApiOperation(value = "确认配送")
	public String expressage(
			@ApiParam(required = true, name = "code", value = " 二维码code") @RequestParam(value = "code", required = true) String code) {
		try {
			Integer status = prescriptionExpressageService.expressage(code, getUID());
			if (status == -1) {
				return error(-1, "取药码错误");
			} else if (status == -2) {
				return error(-1, "编码已使用");
			} else if (status == -3) {
				return error(-1, "编码类型错误");
			}else if (status == -6) {
				throw new ServiceException("发药错误");
			}else if (status == -7) {
				throw new ServiceException("已无待取药品");
			}
			return write(200, "配送成功");
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 医生端获取取药码
	 *
	 * @param prescriptionCode
	 * @return
	 */
	@RequestMapping(value = "/dispensaryCode/getDoctorDispensaryQrcode", method = RequestMethod.GET)
	@ApiOperation("医生端获取取药码")
	public String getDoctorDispensaryQrcode(
			@ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
		
		try{
			Map<String, Object> map = prescriptionDispensaryCodeService.getQrcode(prescriptionCode,getUID(),2);//xh1D2017031503333
			return write(200, "获取配送员取药码成功!", "data", map);
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 医生端获取配送码
	 *
	 * @param prescriptionCode
	 * @return
	 */
	@RequestMapping(value = "/dispensaryCode/getDoctorDeliveryQrcode", method = RequestMethod.GET)
	@ApiOperation("医生端获取配送码")
	public String getDoctorDeliveryQrcode(
			@ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) {
		
		try{
			Map<String, Object> map = prescriptionDispensaryCodeService.getQrcode(prescriptionCode,getUID(),3);
			if(map!=null&&map.size()>0){
				
				return write(200, "获取配送员配送码成功!", "data", map);
			}else{
				return error(-1, "获取配送员配送码失败!");
			}
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 扫码
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/dispensaryCode/scanQrcode",method = RequestMethod.GET)
	public String scanQrcode(
			@RequestParam(value = "code",required = true) String code){
		try {
			PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeService.scanQrcode(code,getUID());
			return write(200, "扫码成功!", "data", prescriptionDispensaryCode);
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
}

+ 0 - 148
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionExpressageController.java

@ -1,148 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.WlyyPrescriptionExpressageService;
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 Reece on 2017/7/28.
 */
@RestController
@RequestMapping(value = "/doctor/prescription/expressage")
@Api(description = "医生端-长处配送相关接口")
public class PrescriptionExpressageController extends BaseController {
	
	@Autowired
	private WlyyPrescriptionExpressageService expressageService;
	/**
	 * 确认接收 药品
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/expressage2Hospital", method = RequestMethod.POST)
	@ApiOperation(value = "确认药品被服务站接收")
	public String expressage2Hospital(
			@ApiParam(required = true, name = "hospital", value = "机构code") @RequestParam(value = "hospital", required = true) String hospital,
			@ApiParam(required = true, name = "hospitalName", value = "机构名称") @RequestParam(value = "hospitalName", required = true) String hospitalName,
			@ApiParam(required = true, name = "hospitalAddress", value = "机构地址") @RequestParam(value = "hospitalAddress", required = true) String hospitalAddress,
			@ApiParam(required = true, name = "userCode", value = "接收人code") @RequestParam(value = "userCode", required = true) String userCode,
			@ApiParam(required = true, name = "userName", value = "接收人Name") @RequestParam(value = "userName", required = true) String userName,
			@ApiParam(required = true, name = "mobile", value = "电话号码") @RequestParam(value = "mobile", required = true) String mobile,
			@ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode", required = true) String prescriptionCode) throws Exception {
		try {
			expressageService.expressage2Hospital(hospital, hospitalName, hospitalAddress, userCode, userName, mobile, prescriptionCode);
			return success("接收成功");
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getDrugDeliveryState", method = RequestMethod.GET)
	@ApiOperation(value = "获取异常原因列表")
	public String getDrugDeliveryState(){
		try {
			return write(200, "获取成功", "data", expressageService.getDrugDeliveryState());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getEsListByIDCardOrSSC", method = RequestMethod.GET)
	@ApiOperation(value = "根据医保号和身份证查询订单")
	public String getEsListByIDCardOrSSC(@ApiParam(required = true, name = "keyWord", value = "医保号或身份证") @RequestParam(required = true)String keyWord,
	                                     @ApiParam(required = true, name = "page", value = "起始页,重1开始") @RequestParam(required = true)Integer page,
	                                     @ApiParam(required = true, name = "pageSize", value = "每页大小") @RequestParam(required = true)Integer pageSize){
		try {
			return write(200, "获取成功", "data", expressageService.getEsListByIDCardOrSSC( keyWord, page, pageSize));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/saveDrugDelivery", method = RequestMethod.POST)
	@ApiOperation(value = "异常出药操作")
	public String saveDrugDelivery(@ApiParam(required = true, name = "prescriptionCode", value = "续方code") @RequestParam(required = true)String prescriptionCode,
	                               @ApiParam(required = true, name = "reasonCode", value = "原因code") @RequestParam(required = true)String reasonCode,
	                               @ApiParam(required = true, name = "reasonName", value = "原因名称") @RequestParam(required = true)String reasonName,
	                               @ApiParam(required = true, name = "reason", value = "详细原因") @RequestParam(required = true)String reason){
		try {
			return write(200, "获取成功", "data", expressageService.saveDrugDelivery( getUID(), prescriptionCode, reasonCode, reasonName, reason));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPresStatesList", method = RequestMethod.GET)
	@ApiOperation(value = "获取续方状态原因列表")
	public String getPresStatesList(){
		try {
			return write(200, "获取成功", "data", expressageService.getPresStatesList());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPresEsPayList", method = RequestMethod.GET)
	@ApiOperation(value = "获取订单列表")
	public String getPresEsPayList(@ApiParam(name = "keyWord", value = "订单号,接收人,医保号或身份证") @RequestParam(required = false)String keyWord,
	                               @ApiParam(name = "state", value = "续方状态") @RequestParam(required = false)String state,
	                               @ApiParam(name = "type", value = "1 自取 2快递配送 3健管师配送 4网格员派送") @RequestParam(required = false)String type,
	                               @ApiParam(name = "startDate", value = "开始时间yyyy-MM--dd") @RequestParam(required = false)String startDate,
	                               @ApiParam(name = "endDate", value = "结束时间yyyy-MM-dd") @RequestParam(required = false)String endDate,
	                               @ApiParam(name = "operator", value = "操作人") @RequestParam(required = false)String operator,
	                               @ApiParam(name = "flag", value = "1为异常出药,0为正常") @RequestParam(required = false)String flag,
	                               @ApiParam(name = "page", value = "页面") @RequestParam(required = true)Integer page,
	                               @ApiParam(name = "pageSize", value = "页面大小") @RequestParam(required = true)Integer pageSize){
		try {
			return write(200, "获取成功", "data", expressageService.getPresEsPayList(getUID(),keyWord,state,type,startDate,endDate,operator,flag,page,pageSize));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPresEsList", method = RequestMethod.GET)
	@ApiOperation(value = "获取出药记录列表")
	public String getPresEsList(@ApiParam(name = "keyWord", value = "订单号,接收人,医保号或身份证") @RequestParam(required = false)String keyWord,
	                            @ApiParam(name = "state", value = "续方状态") @RequestParam(required = false)String state,
	                            @ApiParam(name = "type", value = "1 自取 2快递配送 3健管师配送") @RequestParam(required = false)String type,
	                            @ApiParam(name = "startDate", value = "开始时间yyyy-MM--dd") @RequestParam(required = false)String startDate,
	                            @ApiParam(name = "endDate", value = "结束时间yyyy-MM-dd") @RequestParam(required = false)String endDate,
	                            @ApiParam(name = "operator", value = "操作人") @RequestParam(required = false)String operator,
	                            @ApiParam(name = "flag", value = "1为异常出药,0为正常") @RequestParam(required = false)String flag,
	                            @ApiParam(name = "page", value = "页面") @RequestParam(required = true)Integer page,
	                            @ApiParam(name = "pageSize", value = "页面大小") @RequestParam(required = true)Integer pageSize){
		try {return write(200, "获取成功", "data", expressageService.getPresEsList(getUID(),keyWord,state,type,startDate,endDate,operator,flag,page,pageSize));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getHospitalOperator", method = RequestMethod.GET)
	@ApiOperation(value = "获取操作人员下拉列表")
	public String getHospitalOperator(){
		try {
			return write(200, "获取成功", "data", expressageService.getHospitalOperator(getUID()));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	
	
	@RequestMapping(value = "/getPrescriptionExpressInfo" ,method = RequestMethod.GET)
	@ApiOperation(value = "获取处方的配送地址")
	public String getPrescriptionExpressInfo(@RequestParam(required = true)@ApiParam(name="code",value="续方CODE")String code){
		try {
			return write(200, "查询成功!", "data", expressageService.findByPrescriptionCode(code));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
}

+ 0 - 671
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionInfoController.java

@ -1,671 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionInfoService;
import com.yihu.jw.afterDiagnosis.service.prescription.PrescriptionPayService;
import com.yihu.jw.afterDiagnosis.service.prescription.WlyyPrescriptionService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.prescription.PrescriptionPay;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionExpressageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by Trick on 2017/7/25
 */
@RestController
@RequestMapping(value = "/doctor/prescriptionInfo")
@Api(description = "医生端-长处方接口")
public class PrescriptionInfoController extends BaseController {
	
	@Autowired
	private PrescriptionInfoService prescriptionInfoService;
	@Autowired
	private PrescriptionExpressageDao prescriptionExpressageDao;
	@Autowired
	private WlyyPrescriptionService prescriptionService;
	@Autowired
	private PrescriptionPayService prescriptionPayService;
	@Autowired
	private BasePatientDao patientDao;
	
	@RequestMapping(value = "getRecipeMasterList" , method = RequestMethod.GET)
	@ApiOperation(value = "获取智业长处方信息列表")
	public String getRecipeMasterList(@RequestParam(required = true)@ApiParam(name="patient",value="居民code",defaultValue = "ec7572875d27446cb4f067b13a85d72a")String patient,
	                                  @RequestParam(required = false)@ApiParam(name="isRenewal",value="处方是否可续方:1.是;2.无过滤")String isRenewal,
	                                  @RequestParam(required = false)@ApiParam(name="startDate",value="开始时间")String startDate,
	                                  @RequestParam(required = false)@ApiParam(name="endDate",value="结束时间")String endDate,
	                                  @RequestParam(required = false,defaultValue = "0")@ApiParam(name="diagnosisCode",value="所有诊断(0 全部 1高血压 2糖尿病 3高血压和糖尿病)")String diagnosisCode,
	                                  @RequestParam(required = false)@ApiParam(name="page",value="起始页")Integer page,
	                                  @RequestParam(required = false)@ApiParam(name="size",value="每页记录数")Integer size,
	                                  @RequestParam(required = false)@ApiParam(name="hospital",value="社区CODE")String hospital){
		try {
			JSONObject json = prescriptionInfoService.getRecipeMasterList(patient,startDate,endDate,isRenewal,diagnosisCode,page,size,hospital);
			return write(200, "查询成功!", "data",json);
		}catch (Exception e){
			return errorResult(e);
		}
	}
	
	/**
	 * 获取长处方信息列表
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/getPrescriptionInfos" , method = RequestMethod.GET)
	@ApiOperation(value = "获取长处方信息列表")
	public String getPrescriptionInfos(@RequestParam(required = true)@ApiParam(name="type",value="1:查询处方;2我的续方;3:续方记录")String type,
	                                   @RequestParam(required = false)@ApiParam(name="isRenewal",value="处方是否可续方:1.是;2.无过滤")String isRenewal,
	                                   @RequestParam(required = false)@ApiParam(name="recipeNo",value="医嘱号,第一次获取上一方时传入0,第二次获取上一方时传入第一次返回的医嘱号,以此类推")String recipeNo,
	                                   @RequestParam(required = false)@ApiParam(name="startDate",value="开始时间")String startDate,
	                                   @RequestParam(required = false)@ApiParam(name="endDate",value="结束时间")String endDate,
	                                   @RequestParam(required = false,defaultValue = "0")@ApiParam(name="diagnosisCode",value="所有诊断(0 全部 1高血压 2糖尿病 3高血压或糖尿病)")String diagnosisCode,
	                                   @RequestParam(required = false)@ApiParam(name="page",value="起始页")Integer page,
	                                   @RequestParam(required = false)@ApiParam(name="size",value="每页记录数")Integer size,
	                                   @RequestParam(required = true)@ApiParam(name="patientCode",value="居民CODE")String patientCode,
	                                   @RequestParam(required = false)@ApiParam(name="hospital",value="社区CODE")String hospital){
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getPrescriptionInfos(type,recipeNo,diagnosisCode,startDate,endDate,patientCode,isRenewal,page,size,hospital));
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPrescriptionFilter", method = RequestMethod.GET)
	@ApiOperation(value = "获取过滤规则信息列表")
	public String getPrescriptionFilter(@RequestParam(required = false) @ApiParam(value = "团队code", name = "teamCode")Integer teamCode,
										@RequestParam(required = false) @ApiParam(value = "医生code", name = "doctorCode") String doctorCode,
	                                    @RequestParam(required = false) @ApiParam(value = "居民code", name = "patient")String patient) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getPrescriptionFilter(teamCode,patient,doctorCode));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getDoctorPrescription", method = RequestMethod.GET)
	@ApiOperation(value = "获取全科医生/建管师续方列表/搜索")
	public String getDoctorPrescription(@RequestParam(required = false) @ApiParam(value = "团队code", name = "teamCode") Integer teamCode,
										@RequestParam(required = false) @ApiParam(value = "医生code", name = "doctorCode") String doctorCode,
	                                    @RequestParam(required = false) @ApiParam(value = "续方状态", name = "state") String state,
	                                    @RequestParam(required = false) @ApiParam(value = "所有诊断:1 糖尿病 2高血压,3其他", name = "diseases") String diseases,
	                                    @RequestParam(required = false) @ApiParam(name = "startDate", value = "开始时间") String startDate,
	                                    @RequestParam(required = false) @ApiParam(name = "endDate", value = "结束时间") String endDate,
	                                    @RequestParam(required = false) @ApiParam(name = "nameKeyword", value = "患者姓名模糊匹配") String nameKeyword,
	                                    @RequestParam(required = false) @ApiParam(name = "patient", value = "患者Code") String patient,
	                                    @RequestParam(required = false) @ApiParam(name = "page", value = "起始页") Integer page,
	                                    @RequestParam(required = false) @ApiParam(name = "size", value = "每页条数") Integer size) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getDoctorPrescription(teamCode,doctorCode , state, diseases, startDate, endDate, nameKeyword, patient, page, size));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/getDoctorPrescriptionTotal", method = RequestMethod.GET)
	@ApiOperation(value = "获取全科医生数目/建管师续方列表数目/搜索数目")
	public String getDoctorPrescriptionTotal(@RequestParam(required = false) @ApiParam(value = "团队code", name = "teamCode") Integer teamCode,
	                                         @RequestParam(required = false) @ApiParam(value = "续方状态", name = "state") String state,
	                                         @RequestParam(required = false) @ApiParam(value = "所有诊断:1 糖尿病 2高血压,3其他", name = "dispensary") String diseases,
	                                         @RequestParam(required = false) @ApiParam(name = "startDate", value = "开始时间") String startDate,
	                                         @RequestParam(required = false) @ApiParam(name = "endDate", value = "结束时间") String endDate,
	                                         @RequestParam(required = false) @ApiParam(name = "nameKeyword", value = "患者姓名模糊匹配") String nameKeyword,
	                                         @RequestParam(required = false) @ApiParam(name = "patient", value = "患者Code") String patient) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getDoctorPrescriptionTotal(teamCode, state, diseases, startDate, endDate, nameKeyword, patient));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	
	@RequestMapping(value = "/getContinuedPrescriptionAsDoctor", method = RequestMethod.GET)
	@ApiOperation(value = "续方详情")
	public String getContinuedPrescriptionAsDoctor(@RequestParam(required = true) @ApiParam(value = "续方CODE", name = "code") String code,
	                                               @RequestParam(required = true) @ApiParam(value = "团队长标识:1:是;2否", name = "type") String type) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getContinuedPrescriptionAsDoctor(code));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
    @RequestMapping(value = "/getOrgAddress", method = RequestMethod.GET)
    @ApiOperation(value = "获取医生所属机构药房")
    public String getOrgAddress(@RequestParam(required = true) @ApiParam(value = "所属机构CODE", name = "code") String code) {
        try {
            return write(200, "查询成功!","data",prescriptionInfoService.getOrgAddress(code));
        } catch (Exception e) {
			return errorResult(e);
        }
    }
	@RequestMapping(value = "/reviewPrescription", method = RequestMethod.POST)
	@ApiOperation(value = "续方审核")
	public String reviewPrescription(@RequestParam(required = true) @ApiParam(value = "续方CODE", name = "code") String code,
	                                 @RequestParam(required = false) @ApiParam(value = "不同意原因", name = "reason") String reason,
	                                 @RequestParam(required = false) @ApiParam(value = "不同意原因CODE", name = "reasonCode") String reasonCode,
	                                 @RequestParam(required = false) @ApiParam(value = "1同意,2不同意", name = "state") String state,
	                                 @RequestParam(required = false) @ApiParam(value = "科室", name = "dept") String dept,
	                                 @RequestParam(required = false) @ApiParam(value = "诊金", name = "registerFee") String registerFee,
	                                 @RequestParam(required = false) @ApiParam(value = "诊金类型", name = "rateTypeCode") String rateTypeCode,
									 @RequestParam(required = false) @ApiParam(value = "备注", name = "remark") String remark,
									 @RequestParam(required = false) @ApiParam(value = "科室code(智业校正减库存使用)", name = "deptCode") String deptCode,
									 @RequestParam(required = false) @ApiParam(value = "药房地址(顺丰取药使用)", name = "orgAddress") String orgAddress) {
		try {
			int rs = prescriptionInfoService.reviewPrescription(code, reason,reasonCode, state, dept, registerFee, rateTypeCode,remark,deptCode,orgAddress);
			if (rs == 0) {
				return write(200, "开方失败!", "data", rs);
			} else {
				return write(200, "成功提交开方", "data", rs);
			}
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/updatePresInfo", method = RequestMethod.POST)
	@ApiOperation(value = "调整处方")
	public String updatePresInfo(@RequestParam(required = true) @ApiParam(value = "续方CODE", name = "code") String code,
	                             @RequestParam(required = true) @ApiParam(value = "续方药品JSON", name = "infos") String infos,
	                             @RequestParam(required = false) @ApiParam(value = "疾病JSON", name = "diagnosis") String diagnosis,
	                             @RequestParam(required = false) @ApiParam(value = "调整原因", name = "reason") String reason,
	                             @RequestParam(required = false) @ApiParam(value = "调整原因标签Code,用,分割", name = "reasonCode") String reasonCode) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.updatePresInfo(code, infos, diagnosis, reason,reasonCode));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getInfoTitle", method = RequestMethod.POST)
	@ApiOperation(value = "调整处方-药品分类及种类数目")
	public String getInfoTitle() {
		try {
			return write(200, "操作成功!", "data", "");
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getInfoListByParentCode", method = RequestMethod.POST)
	@ApiOperation(value = "药品类别获取药品")
	private String getInfoListByParentCode(@RequestParam(required = true) @ApiParam(value = "药品类别Code", name = "code") String code) {
		try {
			return write(200, "操作成功!", "data", "");
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 订单跟踪 包含处方药品信息 订单记录  支付记录
	 * 根据处方code获取处方流程
	 *
	 * @param prescriptionCode
	 * @return
	 */
	@RequestMapping(value = "/prescriptionFollow", method = RequestMethod.GET)
	@ApiOperation(value = "获取处方订单详情")
	public String prescriptionFollow(
			@RequestParam(required = true) @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode) {
		try {
			JSONObject jo = new JSONObject();
			//获取处方信息
			WlyyPrescriptionDO prescription = prescriptionService.findByCode(prescriptionCode);
			
			//获取处方药品信息
			List<WlyyPrescriptionInfoDO> prescriptionInfos = prescriptionInfoService.getPrescriptionInfo(prescriptionCode);
			//获取付款信息
			PrescriptionPay prescriptionPay = prescriptionPayService.findByPrescriptionCode(prescriptionCode);
			//获取配送信息
			WlyyPrescriptionExpressageDO prescriptionExpressage = prescriptionExpressageDao.findByPrescriptionCode(prescriptionCode);
			
			jo.put("prescriptionInfos", prescriptionInfos);
			jo.put("prescriptionPay", prescriptionPay);
			jo.put("prescriptionExpressage", prescriptionExpressage);
			if (prescription != null) {
				jo.put("createTime", prescription.getCreateTime());//创建时间
				jo.put("doctorName", prescription.getDoctorName());//审核医生
				jo.put("prescriptionHospital", prescription.getHospitalName());//出药机构
				jo.put("dispensaryDispensaryType", prescription.getDispensaryType());//处方配送方式
//				jo.put("dispensaryDispensaryTypeName", prescription.getDispensaryTypeName());//处方配送方式
				jo.put("prescriptionStatus", prescription.getStatus());//处方状态
//				jo.put("prescriptionStatusName", prescription.getStatusName(prescription.getStatus(), "",""));//处方状态名称
				BasePatientDO p =  patientDao.findById(prescription.getPatientCode()).orElse(null);
				jo.put("patient",p.getId());
				jo.put("patientName",p.getName());
				jo.put("IdCard",p.getIdcard());
				jo.put("ssc",p.getSsc());
//				jo.put("orgAddress",prescription.getOrgAddress());
//				jo.put("deptCode",prescription.getDeptCode());
//				jo.put("deptCodeName",prescription.getDeptCodeName());
			}
			return write(200, "查询成功", "data", jo);
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getHDoctorPrescriptionExpressage", method = RequestMethod.GET)
	@ApiOperation(value = "获取健康管理师续方订单列表")
	public String getHDoctorPrescriptionExpressage
			(@RequestParam(required = false) @ApiParam(value = "团队Code", name = "teamCode") String teamCode,
			 @RequestParam(required = false) @ApiParam(value = "1:需跟踪;2:已接收", name = "type") String type,
			 @RequestParam(required = false) @ApiParam(value = "患者姓名关键字", name = "nameKey") String nameKey,
			 @RequestParam(required = false) @ApiParam(value = "开始时间", name = "startDate") String startDate,
			 @RequestParam(required = false) @ApiParam(value = "结束时间", name = "endDate") String endDate,
			 @RequestParam(required = false) @ApiParam(value = "服务站", name = "hospital") String hospital,
			 @RequestParam(required = false) @ApiParam(value = "配送状态", name = "state") String state,
			 @RequestParam(required = false) @ApiParam(value = "页数", name = "page") Integer page,
			 @RequestParam(required = false) @ApiParam(value = "每页大小", name = "size") Integer size) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getHDoctorPrescriptionExpressage(teamCode, type, getRepUID(), nameKey, startDate, endDate, hospital, state, page, size));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getHDoctorPrescriptionExpressageTotal", method = RequestMethod.GET)
	@ApiOperation(value = "获取健康管理师续方订单列表数目")
	public String getHDoctorPrescriptionExpressageTotal
			(@RequestParam(required = false) @ApiParam(value = "团队Code", name = "teamCode") String teamCode,
			 @RequestParam(required = false) @ApiParam(value = "1:需跟踪;2:已接收", name = "type") String type,
			 @RequestParam(required = false) @ApiParam(value = "患者姓名关键字", name = "nameKey") String nameKey,
			 @RequestParam(required = false) @ApiParam(value = "开始时间", name = "startDate") String startDate,
			 @RequestParam(required = false) @ApiParam(value = "结束时间", name = "endDate") String endDate,
			 @RequestParam(required = false) @ApiParam(value = "服务站", name = "hospital") String hospital,
			 @RequestParam(required = false) @ApiParam(value = "配送状态", name = "state") String state) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getHDoctorPrescriptionExpressageTotal(teamCode, type, getUID(), nameKey, startDate, endDate, hospital, state));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPrescriptionExpressageFilter", method = RequestMethod.GET)
	@ApiOperation(value = "获取健康管理师续方订单列表过滤条件")
	public String getPrescriptionExpressageFilter() {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getPrescriptionExpressageFilter(getUID()));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPrescriptionExpressageAsdoctorFilter", method = RequestMethod.GET)
	@ApiOperation(value = "获取全科医生续方订单列表过滤条件")
	public String getPrescriptionExpressageAsdoctorFilter() {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getPrescriptionExpressageAsdoctorFilter());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getDoctorPrescriptionExpressage", method = RequestMethod.GET)
	@ApiOperation(value = "获取全科医生续方订单列表")
	public String getDoctorPrescriptionExpressage
			(@RequestParam(required = false) @ApiParam(value = "团队Code", name = "teamCode") Integer teamCode,
			 @RequestParam(required = false) @ApiParam(value = "居民搜素关键字", name = "nameKey") String nameKey,
			 @RequestParam(required = false) @ApiParam(value = "开始时间", name = "startDate") String startDate,
			 @RequestParam(required = false) @ApiParam(value = "结束时间", name = "endDate") String endDate,
			 @RequestParam(required = false) @ApiParam(value = "机构", name = "hospital") String hospital,
			 @RequestParam(required = false) @ApiParam(value = "配送状态", name = "state") String state,
			 @RequestParam(required = false) @ApiParam(value = "配送方式:1 自取 2快递配送 3健管师配送", name = "dispensaryType") String
					 dispensaryType,
			 @RequestParam(required = false) @ApiParam(value = "传1为未分配健管师", name = "AllocationType") String
					 allocationType,
			 @RequestParam(required = false) @ApiParam(value = "起始页", name = "page") Integer page,
			 @RequestParam(required = false) @ApiParam(value = "每页大小", name = "size") Integer size) {
		try {
			return write(200, "操作成功!", "data",
					prescriptionInfoService.
							getDoctorPrescriptionExpressage(teamCode, nameKey, startDate, endDate, hospital, state, dispensaryType, allocationType, page, size));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getDoctorPrescriptionExpressageTotal", method = RequestMethod.GET)
	@ApiOperation(value = "获取全科医生续方订单列表数目")
	public String getDoctorPrescriptionExpressageTotal
			(@RequestParam(required = false) @ApiParam(value = "团队Code", name = "teamCode") Integer teamCode,
			 @RequestParam(required = false) @ApiParam(value = "居民搜素关键字", name = "nameKey") String nameKey,
			 @RequestParam(required = false) @ApiParam(value = "开始时间", name = "startDate") String startDate,
			 @RequestParam(required = false) @ApiParam(value = "结束时间", name = "endDate") String endDate,
			 @RequestParam(required = false) @ApiParam(value = "机构", name = "hospital") String hospital,
			 @RequestParam(required = false) @ApiParam(value = "配送状态", name = "state") String state,
			 @RequestParam(required = false) @ApiParam(value = "配送方式:1 自取 2快递配送 3健管师配送", name = "dispensaryType") String
					 dispensaryType,
			 @RequestParam(required = false) @ApiParam(value = "传1为未分配健管师", name = "AllocationType") String
					 allocationType) {
		try {
			return write(200, "操作成功!", "data",
					prescriptionInfoService.
							getDoctorPrescriptionExpressageTotal(teamCode, nameKey, startDate, endDate, hospital, state, dispensaryType, allocationType));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getCountExpressage", method = RequestMethod.GET)
	@ApiOperation(value = "获取指定团队未分配建管师订单数目")
	public String getCountExpressage
			(@RequestParam(required = true) @ApiParam(value = "团队Code", name = "teamCode") String teamCode) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getCountExpressage(teamCode));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getHospitalListTitle", method = RequestMethod.GET)
	@ApiOperation(value = "获取服务站列表")
	public String getHospitalListTitle
			(@RequestParam(required = true) @ApiParam(value = "团队Code", name = "teamCode") String teamCode) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getHospitalListTitle(teamCode));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/distributionHealthDoctor", method = RequestMethod.POST)
	@ApiOperation(value = "配置建管师")
	public String distributionHealthDoctor
			(@RequestParam(required = true) @ApiParam(value = "续方Code字符串用','分割", name = "codes") String codes,
			 @RequestParam(required = true) @ApiParam(value = "健康管理师Code", name = "healthDoctor") String
					 healthDoctor) {
		try {
			return write(200, "操作成功!", "data", 1);
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getIcd10Info", method = RequestMethod.GET)
	@ApiOperation(value = "获取诊断结果")
	public String getIcd10Info(@RequestParam(required = true) @ApiParam(value = "诊断结果关键字", name = "nameKey") String
			                           nameKey) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getIcd10Info(nameKey));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPrescriptionTemp", method = RequestMethod.GET)
	@ApiOperation(value = "获取调整处方模板")
	public String getPrescriptionTemp() {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.getPrescriptionTemp(getUID()));
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/initDrugData", method = RequestMethod.GET)
	@ApiOperation(value = "刷入redis平次数据")
	public String initDrugData() {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.initDrugData());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/drugToRate", method = RequestMethod.GET)
	@ApiOperation(value = "频次翻译")
	public String drugToRate(@RequestParam(required = true) @ApiParam(name = "code", value = "频次CODE") String code) {
		try {
			return write(200, "操作成功!", "data", prescriptionInfoService.drugToRate(code));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPrescription", method = RequestMethod.GET)
	@ApiOperation(value = "获取长处方详细信息")
	public String getPrescription(@RequestParam(required = true) @ApiParam(name = "code", value = "处方CODE") String code
			,@RequestParam(required = true) @ApiParam(name = "patient", value = "居民CODE") String  patient,
			                      @RequestParam(required = false) @ApiParam(name = "preCode", value = "续方CODE")String preCode,
			                      @RequestParam(required = false) @ApiParam(name = "hospital", value = "社区CODE")String hospital) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getPrescription(code,patient,preCode,hospital));
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getRateList", method = RequestMethod.GET)
	@ApiOperation(value = "查询频次列表")
	public String getRateList() {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getRateList());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getRegisterRee", method = RequestMethod.GET)
	@ApiOperation(value = "获取挂号费+诊察费下拉列表")
	public String getRegisterRee
			(@RequestParam(required = true) @ApiParam(name = "jwHospital", value = "开方机构") String jwHospital,
			 @RequestParam(required = true) @ApiParam(name = "jwDoctorCode", value = "开方医生Code") String jwDoctorCode) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getRegisterRee(jwHospital, jwDoctorCode));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getDeptList", method = RequestMethod.GET)
	@ApiOperation(value = "获取医生科室列表")
	public String getDeptList(@RequestParam(required = true) @ApiParam(name = "jwHospital", value = "开方机构") String
			                          jwHospital,
	                          @RequestParam(required = true) @ApiParam(name = "jwDoctorCode", value = "开方医生Code") String jwDoctorCode) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getDeptList(jwHospital, jwDoctorCode));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getUsageDict", method = RequestMethod.GET)
	@ApiOperation(value = "获取药品用法列表")
	public String getUsageDict() {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getUsageDict());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPhysicDays", method = RequestMethod.GET)
	@ApiOperation(value = "获取药品用法天数")
	public String getPhysicDays() {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getPhysicDays());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getPhysicInfo", method = RequestMethod.GET)
	@ApiOperation(value = "获取药品信息")
	public String getPhysicInfo(@RequestParam(required = true) @ApiParam(name = "code", value = "药品code") String code) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getPhysicInfo(code,getUID()));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	@RequestMapping(value = "/getReasonByType", method = RequestMethod.GET)
	@ApiOperation(value = "获取原因")
	public String getReasonByType(@RequestParam(required = true) @ApiParam(name = "code", value = "类型:0 审核原因标签;1 调整原因标签") Integer type) {
		try {
			return write(200, "查询成功!", "data", prescriptionInfoService.getReasonByType(type));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 长处方统计--长处方记录筛选
	 * @Author zhangdan
	 * @param level 地区级别
	 * @param area 地区编号
	 * @param disease 疾病 高血压1 糖尿病2
	 * @param status 状态 1.总量,2.已完成,3.居民取消,4.审核不通过,5.进行中,6.其他原因取消(没有选择的情况传1)
	 * @param type 取药方式 1.自取,2快递配送,3健管师配送
	 * @param startTime 开始日期
	 * @param endTime 结束日期
	 * @return
	 */
	@RequestMapping(value = "/getPrescriptionByCondition", method = RequestMethod.GET)
	public String getPrescriptionByCondition(
			@RequestParam(required = true)String level,
			@RequestParam(required = true)String area,
			@RequestParam(required = false)String disease,
			@RequestParam(required = false,defaultValue = "1")String status,
			@RequestParam(required = false)String type,
			@RequestParam(required = false)String startTime,
			@RequestParam(required = false)String endTime,
			@RequestParam(required = true,defaultValue = "1")String pageNo,
			@RequestParam(required = false)String pageSize){
		try{
			if (StringUtils.isNotBlank(startTime)){
				if (StringUtils.isNotBlank(endTime)){
					Date startDate = DateUtil.strToDate(startTime,"yyyy-MM-dd");
					Date endDate = DateUtil.strToDate(endTime,"yyyy-MM-dd");
					if (startDate.after(endDate)){
						return  error(-2,"参数错误");
					}
				}
			}
			if (StringUtils.isBlank(pageSize)){
				pageSize="10";
			}
			return write(200, "查询成功", "data", prescriptionService.getPrescriptionByCondition(level,area,disease,status,type,startTime,endTime,Integer.valueOf(pageNo),Integer.valueOf(pageSize)));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 长处方统计--上方模糊搜索
	 * @Author zhangdan
	 * @param keyWord 模糊搜索关键字
	 * @return
	 */
	@RequestMapping(value = "/getPrescriptionByKeyWord", method = RequestMethod.GET)
	public String getPrescriptionByKeyWord(
			@RequestParam(required = true)String keyWord,
			@RequestParam(required = true,defaultValue = "1")String pageNo,
			@RequestParam(required = false)String pageSize){
		try{
			if (StringUtils.isBlank(pageSize)){
				pageSize="10";
			}
			return write(200, "查询成功", "data", prescriptionService.getPrescriptionByKeyWord(keyWord,Integer.valueOf(pageNo),Integer.valueOf(pageSize)));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 长处方-修改审核检查步骤
	 * @param viewTag 模糊搜索关键字
	 * @param status 模糊搜索关键字
	 * @param prescriptionCode 处方CODE
	 * @return
	 */
	@RequestMapping(value = "/updatePrescriptionViewStatus", method = RequestMethod.POST)
	public String updatePrescriptionViewStatus(@RequestParam(required = true) @ApiParam(name = "viewTag", value = "审核步骤")String viewTag,
	                                           @RequestParam(required = true) @ApiParam(name = "status", value = "0未完成,1已完成")Integer status,
	                                           @RequestParam(required = true) @ApiParam(name = "prescriptionCode", value = "处方CODE")String prescriptionCode
	                                           ){
		try{
//			prescriptionService.updatePrescriptionViewStatus(viewTag,status,prescriptionCode);
			return write(200, "操作成功");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 续方确认收药接口
	 *
	 * @param prescriptionCode 续方code原状态为60
	 * @param type 1:确认收药 2:延长收药
	 * @return
	 */
	@RequestMapping(value = "/confirmReceipt", method = RequestMethod.POST)
	@ApiOperation(value = "续方确认收药接口")
	public String confirmReceipt(
			@RequestParam(required = true) @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode,
			@RequestParam(required = true) @ApiParam(value = "收药方式", name = "type") Integer type) {
		try {
			Map<String,Object> result = prescriptionService.confirmReceipt(prescriptionCode,type);
			int code = Integer.parseInt(result.get("code").toString());
			String msg = result.get("msg").toString();
			return write(code, msg);
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 修改处方收货地址
	 *
	 * @param prescriptionCode 续方code原状态为60
	 * @param addressJson
	 * @return
	 */
	@RequestMapping(value = "/updateAddress", method = RequestMethod.POST)
	@ApiOperation(value = "修改处方收货地址")
	public String updateAddress(
			@RequestParam(required = true) @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode,
			@RequestParam(required = true) @ApiParam(value = "派送方式", name = "dispensaryType") Integer dispensaryType,
			@RequestParam(required = true) @ApiParam(value = "配送地址json", name = "addressJson", defaultValue = "{\"townName\":\"海沧区\",\"code\":\"3502050100\",\"address\":" +
					"\"冰岛\",\"cityName\":\"厦门市\",\"townCode\":\"350205\",\"provinceCode\":\"350000\",\"cityCode\":\"350200\",\"name\":\"海沧区嵩屿街道社区卫生服务中心\"," +
					"\"provinceName\":\"福建省\",\"streeCode\":\"35020501\",\"streeName\":\"皇后大道东\",\"phone\":\"13253541190\"}") String addressJson) {
		try {
			prescriptionService.updateAddress(prescriptionCode,addressJson,dispensaryType);
			return write(200, "操作成功");
		} catch (Exception e) {
			return errorResult(e);
		}
	}
}

+ 0 - 140
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/prescription/PrescriptionLogController.java

@ -1,140 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.prescription;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionExpressageLogDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionLogDO;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageLogDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionLogService;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * Created by chenweida on 2017/7/27.
 */
@RestController("doctorPrescriptionLogController")
@RequestMapping(value = "/doctor/prescriptionlog")
@Api(description = "医生端-处方日志")
public class PrescriptionLogController extends BaseController {
	@Autowired
	private PrescriptionLogService prescriptionLogService;
	@Autowired
	private PrescriptionExpressageLogDao prescriptionExpressageLogDao;
	@Autowired
	private PrescriptionDao prescriptionDao;
	
	@RequestMapping(value = "/getPrescriptionLogs", method = RequestMethod.GET)
	@ApiOperation(value = "获取处方流程")
	public String addReply(
			@RequestParam(required = true, name = "prescriptionCode") @ApiParam(value = "处方code", name = "prescriptionCode") String prescriptionCode) {
		try {
			// (-3 支付过期 -2 患者自己取消 -1 审核不通过 , 0 待审核, 2调整中 10 审核通过/开方中  , 20开方完成/待支付, 21 支付失败 , 30 支付成功/待配药 ,
			//  40配药成功/待配送  41配送失败  42配送中   43配送到服务站  100配送到患者手中/已完成)
			Integer[] status = new Integer[]{
					WlyyPrescriptionLogDO.PrescriptionLogStatus.revieweding.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.changeing.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.reviewed_success.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.wait_pay.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.pay_success.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.wait_expressage.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageing.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.finish.getValue()};
			List<WlyyPrescriptionLogDO> prescriptionLogs = prescriptionLogService.findPrescriptionLogsByPrescriptionCode(prescriptionCode, status);
			if (prescriptionLogs != null) {
				JSONArray ja = new JSONArray();
				
				prescriptionLogs.stream().forEach(one -> {
					JSONObject jo = new JSONObject();
					jo.put("createTime", DateUtil.dateToStrLong(one.getCreateTime()));
//					jo.put("statusName", one.getStatusName());
					ja.put(jo);
				});
				return write(200, "获取处方流程成功", "data", ja);
			} else {
				return error(-1, "获取失败");
			}
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	
	/**
	 * 根据处方code获取处方流程
	 *
	 * @param prescriptionCode
	 * @return
	 */
	@RequestMapping(value = "/orderFollow", method = RequestMethod.GET)
	@ApiOperation(value = "订单状态跟踪")
	public String orderFollow(
			@ApiParam(value = "处方code", name = "prescriptionCode") @RequestParam(required = true, name = "prescriptionCode") String prescriptionCode) {
		try {
			
			// (-3 支付过期 -2 患者自己取消 -1 审核不通过 , 0 待审核, 2调整中 10 审核通过/开方中  , 20开方完成/待支付, 21 支付失败 , 30 支付成功/待配药 ,
			//  40配药成功/待配送  41配送失败  42配送中   43配送到服务站  100配送到患者手中/已完成)
			Integer[] status = new Integer[]{
					WlyyPrescriptionLogDO.PrescriptionLogStatus.reviewed_success.getValue(),
//                    WlyyPrescriptionLogDO.PrescriptionLogStatus.adding.getValue(), //暂无此状态
					WlyyPrescriptionLogDO.PrescriptionLogStatus.pay_success.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.wait_expressage.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageing.getValue(),
					WlyyPrescriptionLogDO.PrescriptionLogStatus.finish.getValue()};
			List<WlyyPrescriptionLogDO> prescriptionLogs = prescriptionLogService.findPrescriptionLogsByPrescriptionCode(prescriptionCode, status);
			
			//加上快递的log
			List<WlyyPrescriptionExpressageLogDO> expressageLogs = prescriptionExpressageLogDao.findByPrescriptionCode(prescriptionCode);
			for (int i = 0; i < expressageLogs.size(); i++) {
				WlyyPrescriptionExpressageLogDO prescriptionExpressageLog = expressageLogs.get(i);
				WlyyPrescriptionLogDO prescriptionLog = new WlyyPrescriptionLogDO();
				prescriptionLog.setStatus(WlyyPrescriptionLogDO.PrescriptionLogStatus.expressage2hospital.getValue());
				prescriptionLog.setCreateTime(prescriptionExpressageLog.getCreateTime());
//				prescriptionLog.setHospital(prescriptionExpressageLog.getAcceptHospital());
//				prescriptionLog.setHospitalName(prescriptionExpressageLog.getAcceptHospitalName());
				prescriptionLog.setUserCode(prescriptionExpressageLog.getAcceptUser());
				prescriptionLog.setUserName(prescriptionExpressageLog.getAcceptUserName());
				prescriptionLogs.add(prescriptionLog);
			}
			//排序
			prescriptionLogs.sort((o1, o2) -> {
				long map1value = o1.getCreateTime().getTime();
				long map2value = o2.getCreateTime().getTime();
				
				if (map1value - map2value > 0) {
					return -1;
				} else if (map1value - map2value < 0) {
					return 1;
				} else {
					return 0;
				}
			});
			if (prescriptionLogs != null && prescriptionLogs.size() > 0) {
				JSONArray ja = new JSONArray();
				for (int i = 0; i < prescriptionLogs.size(); i++) {
					WlyyPrescriptionLogDO one = prescriptionLogs.get(i);
					JSONObject jo = new JSONObject();
					jo.put("createTime", DateUtil.dateToStrLong(one.getCreateTime()));
//					jo.put("statusName", one.getStatusName());
					jo.put("drugDeliveryflag", "0");
					ja.put(jo);
				}
				return write(200, "获取处方流程成功", "data", ja);
			} else {
				return error(-1, "获取失败");
			}
		} catch (Exception e){
			return errorResult(e);
		}
	}
}

+ 0 - 93
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorDiagnosisInformationController.java

@ -1,93 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.rehabilitation;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.DiagnosisInformationService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.entity.ServiceException;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by humingfen on 2019/2/11.
 */
@RestController
@RequestMapping(value = "/doctor/specialist/diagnosisInformation")
@Api(description = "医生端-诊疗信息管理")
public class DoctorDiagnosisInformationController extends BaseController {
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DiagnosisInformationService diagnosisInformationService;
    @RequestMapping(value = "/createDiagnosisInformation", method = RequestMethod.POST)
    @ApiOperation(value = "创建诊疗信息")
    public String createDiagnosisInformation(@ApiParam(name = "patient", value = "居民code")
                                 @RequestParam String patient,
                                 @ApiParam(name = "patientName", value = "居民姓名")
                                 @RequestParam String patientName,
                                 @ApiParam(name = "planId", value = "康复计划id")
                                     @RequestParam String planId,
                                 @ApiParam(name = "hospital", value = "诊疗医院code")
                                     @RequestParam(required = false) String hospital,
                                 @ApiParam(name = "hospitalName", value = "诊疗医院名称")
                                     @RequestParam String hospitalName,
                                 @ApiParam(name = "department", value = "入院科室")
                                     @RequestParam String department,
                                 @ApiParam(name = "attendingDoctorName", value = "主治医生名称")
                                     @RequestParam String attendingDoctorName,
                                 @ApiParam(name = "admittingDiagnosis", value = "入院诊断")
                                     @RequestParam String admittingDiagnosis,
                                 @ApiParam(name = "dischargeDiagnosis", value = "出院诊断")
                                     @RequestParam String dischargeDiagnosis,
                                 @ApiParam(name = "advice", value = "医嘱小结")
                                     @RequestParam String advice,
                                 @ApiParam(name = "dischargeTime", value = "出院时间")
                                     @RequestParam String dischargeTime){
        try {
            BaseDoctorDO d = doctorDao.findByIdAndDel(getUID());
            return write(200, "保存成功", "data", diagnosisInformationService.createDiagnosisInformation(patient, patientName, planId, hospital, hospitalName, department,
                    attendingDoctorName, admittingDiagnosis, dischargeDiagnosis, advice, dischargeTime, d));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findDiagnosisInformationByPlanId", method = RequestMethod.GET)
    @ApiOperation(value = "根据康复计划id获取诊疗信息")
    public ObjEnvelop findDiagnosisInformationByPlanId(@ApiParam(name = "planId", value = "康复计划id")
                                                   @RequestParam String planId){
        try {
            return diagnosisInformationService.findDiagnosisInformationByPlanId(planId);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage());
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "/findDiagnosisInformationByPatient", method = RequestMethod.GET)
    @ApiOperation(value = "根据居民获取诊疗信息")
    public PageEnvelop findDiagnosisInformationByPatient(@ApiParam(name = "patient", value = "居民code")
                                                        @RequestParam(value = "patient") String patient,
                                                         @ApiParam(name = "page", value = "第几页,page从0开始")
                                                        @RequestParam(value = "page") Integer page,
                                                         @ApiParam(name = "size", value = "行数")
                                                        @RequestParam(value = "size") Integer size){
        try {
            return diagnosisInformationService.findDiagnosisInformationByPatient(patient, page, size);
        } catch (Exception e) {
            return PageEnvelop.getError("获取失败",-1);
        }
    }
}

+ 0 - 212
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorRehabilitaionInfoController.java

@ -1,212 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.rehabilitation;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.RehabilitationInfoService;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/doctor/rehabilitation", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-康复下转管理")
public class DoctorRehabilitaionInfoController extends BaseController {
    @Autowired
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private ObjectMapper objectMapper;
    @RequestMapping(value = "createAdvice", method = RequestMethod.POST)
    @ApiOperation("创建/编辑康复建议模板")
    public String createAdvice(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                               @RequestParam(value = "doctorCode", required = false) String doctorCode,
                               @ApiParam(name = "code", value = "模板code")
                               @RequestParam(value = "code", required = false) String code,
                               @ApiParam(name = "name", value = "模板名称", required = true)
                               @RequestParam(value = "name", required = true) String name,
                               @ApiParam(name = "content", value = "模板内容", required = true)
                               @RequestParam(value = "content", required = true) String content) {
        try {
            if (StringUtils.isBlank(doctorCode)) {
                doctorCode = getUID();
            }
            rehabilitationInfoService.createAdvice(doctorCode, code, name, content);
            return write(200, "更新成功");
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "deleteAdvice", method = RequestMethod.POST)
    @ApiOperation("删除康复建议模板")
    public String deleteAdvice(@ApiParam(name = "id", value = "模板id")
                               @RequestParam(value = "id", required = false) Long id) {
        try {
            rehabilitationInfoService.deleteAdvice(id);
            return write(200, "删除成功");
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getAdviceListByDoctor", method = RequestMethod.GET)
    @ApiOperation("获取医生创建康复建议模板及系统模板")
    public String getAdviceListByDoctor(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                        @RequestParam(value = "doctorCode", required = false) String doctorCode) {
        try {
            if (StringUtils.isBlank(doctorCode)) {
                doctorCode = getUID();
            }
            List<RehabilitationAdviceDO> list = rehabilitationInfoService.getAdviceListByDoctor(doctorCode);
            return write(200, "请求成功", "data", list);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "createMedicalRecords", method = RequestMethod.POST)
    @ApiOperation("添加编辑住院病历")
    public String createMedicalRecords(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                       @RequestParam(value = "doctorCode", required = false) String doctorCode,
                                       @ApiParam(name = "patient", value = "居民code")
                                       @RequestParam String patient,
                                       @ApiParam(name = "patientName", value = "居民姓名")
                                       @RequestParam String patientName,
                                       @ApiParam(name = "jsonData", value = "住院病历相关数据")
                                       @RequestParam(value = "jsonData", required = true) String jsonData,
                                       @ApiParam(name = "id", value = "模板id,编辑时传入")
                                           @RequestParam(value = "id", required = false) String id) {
        try {
            if (StringUtils.isBlank(doctorCode)) {
                doctorCode = getUID();
            }
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO = objectMapper.readValue(jsonData, PatientMedicalRecordsDO.class);
            return write(200, "添加成功", "data", rehabilitationInfoService.createMedicalRecords(doctorCode, patient, patientName, patientMedicalRecordsDO, id));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getMedicalHistoryList", method = RequestMethod.GET)
    @ApiOperation("获取厦心出院就诊记录信息")
    public String getMedicalHistoryList(@ApiParam(name = "code", value = "居民code", required = true)
                                        @RequestParam(value = "code", required = true) String code,
                                        @ApiParam(name = "page", value = "page", required = true)
                                        @RequestParam(value = "page", required = true) Integer page,
                                        @ApiParam(name = "size", value = "size", required = true)
                                        @RequestParam(value = "size", required = true) Integer size) {
        try {
            List<Map<String,Object>> list = rehabilitationInfoService.getMedicalHistoryList(code,page,size);
            return write(200, "请求成功", "data", list);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getDischargePatientList", method = RequestMethod.GET)
    @ApiOperation("获取即将出院居民列表,区分家签非家签")
    public String getDischargePatientList(@ApiParam(name = "hospital", value = "机构code", required = false)
                                          @RequestParam(value = "hospital", required = true) String hospital) {
        try {
            JSONObject result = rehabilitationInfoService.getDischargePatientList(hospital, getUID());
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getRehabilitationPatientList", method = RequestMethod.GET)
    @ApiOperation("获取康复下转居民列表")
    public String getRehabilitationPatientList(@ApiParam(name = "idcard", value = "身份证", required = false)
                                               @RequestParam(value = "idcard", required = false) String idcard,
                                               @ApiParam(name = "isTurnDown", value = "是否已下转 -2:未下转未家签,-1未下转 0未下转全部,;1已下转(未接收);2已下转(已接收);3已下转全部;03已下转全部+未下转全部", defaultValue = "0",required = false)
                                               @RequestParam(value = "isTurnDown", required = false,defaultValue = "3") String isTurnDown ,
                                               @ApiParam(name = "page", value = "起始页", required = false) @RequestParam(value = "page", required = false,defaultValue = "1") Integer page,
                                               @ApiParam(name = "pagesize", value = "每页显示数据条数", required = false) @RequestParam(value = "pagesize", required = false,defaultValue = "10") Integer pagesize
    ) {
        try {
            if(page==null){
                page = 1;
            }
            if(pagesize==null){
                pagesize = 10;
            }
            JSONObject result = rehabilitationInfoService.getRehabilitationPatientList(idcard, getUID(),isTurnDown,page,pagesize);
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "remindDoctorReceive", method = RequestMethod.POST)
    @ApiOperation("提醒家医接收")
    public String remindDoctorReceive(@ApiParam(name = "diseaseName", value = "疾病名称", required = true)
                                      @RequestParam(value = "diseaseName", required = true) String diseaseName,
                                      @ApiParam(name = "doctorCode", value = "全科医生", required = true)
                                      @RequestParam(value = "doctorCode", required = true) String doctorCode){
        try {
            rehabilitationInfoService.remindDoctorReceive(diseaseName,getUID() , doctorCode);
            return success("请求成功");
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getDeorsumvergenceCount", method = RequestMethod.GET)
    @ApiOperation("康复下转已下转顶头数据")
    public String getDeorsumvergenceCount(){
        try {
            JSONObject result = rehabilitationInfoService.getDeorsumvergenceCount(getUID());
            return write(200, "请求成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getPatientByIdcardOrSsc", method = RequestMethod.POST)
    @ApiOperation("根据患者身份证或社保卡号进行搜索添加出院记录")
    public String getPatientByIdcardOrSsc(@ApiParam(name = "patientInfo", value = "居民身份证或者社保卡", required = true)
                                              @RequestParam(value = "patientInfo")String patientInfo,
                                          @ApiParam(name = "type", value = "1患者家签列表 2康复下转列表", required = true)
                                          @RequestParam(value = "type") Integer type) {
        try {
            JSONObject object = rehabilitationInfoService.getPatientByIdcardOrSsc(patientInfo, type, getUID());
            if(object.getInteger("status") == 200) {
                return write(200, "添加成功!", "data", object.get("data"));
            }else {
                return write(-1, "添加失败!", "data", object.getString("msg"));
            }
        } catch (ServiceException se){
            return error(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
}

+ 0 - 1134
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorRehabilitationManageController.java

@ -1,1134 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.rehabilitation;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidancePatientDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.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.List;
import java.util.Map;
/**
 * Created by 刘文彬 on 2018/8/30.
 */
@RestController
@RequestMapping(value = "/doctor/specialist/rehabilitation", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-康复管理")
public class DoctorRehabilitationManageController extends BaseController {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private WlyyRehabilitationManageService wlyyRehabilitationManageService;
    @Autowired
    private WlyyRehabilitationPlanService wlyyRehabilitationPlanService;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private RehabilitationGuidanceService rehabilitationGuidanceService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BaseDoctorDao doctorDao;
    @RequestMapping(value = "findRehabilitationPlanList", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划列表")
    public MixEnvelop findRehabilitationPlanList(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                             @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                                 @ApiParam(name = "patientCondition", value = "居民条件,可以按身份证或者居民名称模糊匹配", required = false)
                                             @RequestParam(value = "patientCondition", required = false)String patientCondition,
                                                 @ApiParam(name = "diseaseCode", value = "疾病类型code", required = false)
                                             @RequestParam(value = "diseaseCode", required = false)String diseaseCode,
                                                 @ApiParam(name = "planType", value = "安排类型(1康复计划,2转社区医院,3转家庭病床)", required = false)
                                             @RequestParam(value = "planType", required = false)Integer planType,
                                                 @ApiParam(name = "todaybacklog", value = "今日待办(1、今日待办,2、全部)", required = false)
                                             @RequestParam(value = "todaybacklog", required = false,defaultValue = "1")Integer todaybacklog,
                                                 @ApiParam(name = "page", value = "第几页,从1开始", required = true)
                                             @RequestParam(value = "page", required = false,defaultValue = "1")Integer page,
                                                 @ApiParam(name = "pageSize", value = "每页分页大小", required = true)
                                             @RequestParam(value = "pageSize", required = false,defaultValue = "10")Integer pageSize) {
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.findRehabilitationPlan(doctorCode,diseaseCode,planType,todaybacklog,patientCondition,page,pageSize);
        } catch (ServiceException se) {
            return MixEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return MixEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "selectBySpecialistDoctor", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取签约专科居民")
    public String selectBySpecialistDoctor(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                             @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                           @ApiParam(name = "doctorType", value = "医生类型(1专科2家医)", required = false)
                                           @RequestParam(value = "doctorType", required = false)String doctorType,
                                           @ApiParam(name = "patientInfo", value = "身份证或者姓名", required = false)
                                               @RequestParam(value = "patientInfo", required = false)String patientInfo,
                                           @ApiParam(name = "diseaseCode", value = "疾病类型code", required = false)
                                             @RequestParam(value = "diseaseCode", required = false)String diseaseCode,
                                           @ApiParam(name = "level", value = "1市2区3社区", required = false)
                                             @RequestParam(value = "level", required = false)String level,
                                           @ApiParam(name = "area", value = "区域", required = false)
                                             @RequestParam(value = "area", required = false)String area,
                                           @ApiParam(name = "page", value = "第几页,从1开始", required = true)
                                             @RequestParam(value = "page", required = false,defaultValue = "1")Integer page,
                                           @ApiParam(name = "pageSize", value = "每页分页大小", required = true)
                                             @RequestParam(value = "pageSize", required = false,defaultValue = "10")Integer pageSize,
                                           @ApiParam(name = "filterPlan", value = "是否过滤康复计划,1过滤,0或者放空不过滤", required = false)
                                               @RequestParam(value = "filterPlan", required = false)String filterPlan,
                                           @ApiParam(name = "turnDownState", value = "下转状态 0全部;1已下转;2已接受;3未下转", required = false)
                                           @RequestParam(value="turnDownState", required = false,defaultValue = "0")String turnDownState
                                           ) {
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            com.alibaba.fastjson.JSONObject result = wlyyRehabilitationManageService.selectBySpecialistDoctor(level,area,doctorCode,diseaseCode,page,pageSize,doctorType,patientInfo,filterPlan,turnDownState);
            com.alibaba.fastjson.JSONArray showList = result.getJSONArray("showList");
            com.alibaba.fastjson.JSONObject turnDownStateObj = result.getJSONObject("turnDownState");
            return write(200, "获取成功", "data", showList,"data2",turnDownStateObj);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "findRehabilitationPlanDetailList", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划详情列表")
    public ObjEnvelop findRehabilitationPlanDetailList(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                                   @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                                       @ApiParam(name = "patientCode", value = "居民code", required = true)
                                                   @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.findRehabilitationPlanDetailList(doctorCode,patientCode);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "getPrescriptionFulfil",method = RequestMethod.GET)
    @ApiOperation("获取已完成处方续方")
    public String getPrescriptionFulfil(@ApiParam(name = "patient", value = "居民code", required = false)
                                        @RequestParam(value = "patient", required = false)String patient,
                                        @ApiParam(name = "doctor", value = "医生code", required = false)
                                        @RequestParam(value = "doctor", required = false)String doctor
    ){
        try {
            return write(200, "获取成功!", "data", wlyyRehabilitationManageService.getPrescriptionFulfil(patient,doctor));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "getRehabilitationConsultationList",method = RequestMethod.GET)
    @ApiOperation("康复咨询")
    public String getRehabilitationConsultationList(@ApiParam(name = "patient",value = "居民code",required = false)
                                                    @RequestParam(value = "patient",required = false)String patient,
                                                    @ApiParam(name = "doctor",value = "医生code",required = false)
                                                    @RequestParam(value = "doctor",required = false)String doctor,
                                                    @ApiParam(name = "brief ",value = "简介 (1综合 0列表 2详细)",required = false)
                                                    @RequestParam(value = "brief",required = false)String brief
    ){
        try {
            return write(200,"获取成功!","data",wlyyRehabilitationManageService.getRehabilitationConsultationList(patient,doctor,brief));
        } catch (Exception e) {
            error(e);
            return error(-1,"请求失败");
        }
    }
    @RequestMapping(value = "getFollowupPlan",method = RequestMethod.GET)
    @ApiOperation("随访计划")
    public String getFollowupPlan(@ApiParam(name = "patient",value = "居民code",required = true)
                                  @RequestParam(value = "patient",required = true)String patient,
                                  @ApiParam(name="doctor",value = "医生code",required = true)
                                  @RequestParam(value = "doctor",required = true)String doctor,
                                  @ApiParam(name = "id",value = "随访id",required = false)
                                  @RequestParam(value = "id",required = false)String id,
                                  @ApiParam(name = "biref",value = "简介",required = false)
                                  @RequestParam(value = "biref",required = false)String biref){
        try {
            return write(200,"获取成功","data",wlyyRehabilitationManageService.getFollowupPlan(doctor,patient,id,biref));
        } catch (Exception e) {
            error(e);
            return error(-1,"请求失败");
        }
    }
    @ApiOperation("获取居民最近的一次住院病历")//wlyy_patient_medical_records_rehabilitation
    @RequestMapping(value = "getNewRehabilitation", method = RequestMethod.GET)
    public String getNewRehabilitation(
                                           @ApiParam(name = "patientCode", value = "居民code", required = true)
                                           @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            List<PatientMedicalRecordsDO> result = wlyyRehabilitationManageService.getNewRehabilitation(patientCode,getRepUID());
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectByGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据计划查询指导留言")
    public String selectByGuidance(@ApiParam(name = "planId", value = "计划id", required = false)
                                                   @RequestParam(value = "planId", required = true)String planId,
                                                   @ApiParam(name = "itemCode", value = "服务项目code", required = true)
                                                   @RequestParam(value = "itemCode", required = true)String itemCode){
        try {
            List<Map<String,Object>> mapList = wlyyRehabilitationManageService.selectByGuidance(planId,itemCode);
            return write(200, "获取成功", "data", mapList);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "calendarPlanDetail", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按日历展示")
    public ObjEnvelop calendarPlanDetail(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)")
                                     @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                     @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)")
                                     @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                     @ApiParam(name = "planId", value = "计划id", required = true)
                                     @RequestParam(value = "planId")String planId,
                                     @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                     @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                     @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                     @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                     @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                     @RequestParam(value = "status", required = false)Integer status,
                                     @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                     @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.calendarPlanDetail(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode,taskExecutor);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "calendarPlanDetailBypatient", method = RequestMethod.GET)
    @ApiOperation("康复管理--某患者的康复计划按日历展示")
    public ObjEnvelop calendarPlanDetailBypatient(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                                  @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                                  @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                                  @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                                  @ApiParam(name = "patient", value = "患者code", required = true)
                                                  @RequestParam(value = "patient", required = true)String patient,
                                                  @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                                  @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                                  @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                                  @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                                  @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                                  @RequestParam(value = "status", required = false)Integer status,
                                                  @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                                  @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            //居民康复计划
            List<Map<String,Object>> planList = wlyyRehabilitationManageService.getPatientAllRehabilitationPlan(patient,doctorCode);
            StringBuilder planIds = new StringBuilder();
            planIds.append(planList.get(0).get("id").toString());
            for (int i =1;i<planList.size();i++){
                planIds.append(","+planList.get(i).get("id").toString());
            }
            return rehabilitationManageService.calendarPlanDetail(executeStartTime,executeEndTime,planIds.toString(),searchTask,status,doctorCode,taskExecutor);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "calendarPlanDetailList", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按列表展示-限定频次")
    public ObjEnvelop calendarPlanDetailList(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                     @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                     @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                     @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                     @ApiParam(name = "planId", value = "计划id", required = true)
                                     @RequestParam(value = "planId", required = true)String planId,
                                     @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                     @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                     @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                     @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                     @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                     @RequestParam(value = "status", required = false)Integer status,
                                     @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                     @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.calendarPlanDetailList(planId,searchTask,status,doctorCode,executeStartTime,executeEndTime,taskExecutor);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "calendarPlanDetailListBypatient", method = RequestMethod.GET)
    @ApiOperation("康复管理--某患者的康复计划按列表展示")
    public ObjEnvelop calendarPlanDetailListBypatient(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                         @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                         @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                         @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                         @ApiParam(name = "patient", value = "患者code", required = true)
                                         @RequestParam(value = "patient", required = true)String patient,
                                         @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                         @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                         @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                         @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                         @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                         @RequestParam(value = "status", required = false)Integer status,
                                         @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                         @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            List<Map<String,Object>> planList = wlyyRehabilitationManageService.getPatientAllRehabilitationPlan(patient,doctorCode);
            StringBuilder planIds = new StringBuilder();
            planIds.append(planList.get(0).get("id").toString());
            for (int i =1;i<planList.size();i++){
                planIds.append(","+planList.get(i).get("id").toString());
            }
            return rehabilitationManageService.calendarPlanDetailList(planIds.toString(),searchTask,status,doctorCode,executeStartTime,executeEndTime,taskExecutor);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "calendarPlanDetailItems", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目按列表展示")
    public String calendarPlanDetailItems(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                          @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                          @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                          @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                          @ApiParam(name = "planId", value = "计划id", required = true)
                                          @RequestParam(value = "planId", required = true)String planId,
                                          @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、健康指导,4、随访,5、复诊)", required = false)
                                          @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                          @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                          @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                          @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            List<Map<String,Object>> result = wlyyRehabilitationManageService.calendarPlanDetailItems(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode);
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectByPlanDetaiId", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取操作记录-不限定频次")
    public String selectByPlanDetaiId(
            @ApiParam(name = "patient", value = "居民code", required = false)
            @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(name = "planId", value = "计划id", required = true)
            @RequestParam(value = "planId", required = true) String planId,
            @ApiParam(name = "code", value = "服务项目code", required = true)
            @RequestParam(value = "code", required = true) String code,
            @ApiParam(name = "page", value = "", required = false)
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pagesize", value = "", required = false)
            @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        try {
            return write(200, "获取成功", "data", wlyyRehabilitationManageService.selectByPlanDetaiId(patient,planId,code,page,pagesize));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectPlanByPatient", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据居民code查找康复计划")
    public String calendarPlanDetailItems(@ApiParam(name = "patient", value = "居民code", required = false)
                                              @RequestParam(value = "patient", required = false)String patient,
                                          @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status,
                                          @ApiParam(name = "planId", value = "计划id", required = false)
                                              @RequestParam(value = "planId", required = false)String planId){
        try {
            List<Map<String,Object>> result = wlyyRehabilitationManageService.selectPlanByPatient(patient,status,planId,getUID());
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectAllPlaneByPatient",method = RequestMethod.GET)
    @ApiOperation("获取居民所有康复计划")
    public String getPatientAllRehabilitationPlan(@ApiParam(name = "patient",value = "居民Code", required = true)
                                                  @RequestParam(value = "patient",required = true)String patient){
        try {
            return write(200, "获取成功", "data", wlyyRehabilitationManageService.getPatientAllRehabilitationPlan(patient,getUID()));
        }catch (Exception e){
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectAllCompleteServiceItemsByPatient",method = RequestMethod.GET)
    @ApiOperation("康复计划主页动态")
    public String selectAllCompleteServiceItemsByPatient(@ApiParam(name = "patient",value = "居民Code", required = true)
                                                  @RequestParam(value = "patient",required = true)String patient){
        try {
            return write(200, "获取成功", "data", wlyyRehabilitationManageService.selectAllCompleteServiceItemsByPatient(patient));
        }catch (Exception e){
            return errorResult(e);
        }
    }
    @RequestMapping(value = "manageAllPlanByPatient",method = RequestMethod.POST)
    @ApiOperation("一键确认管理居民所有的康复计划")
    public String manageAllPlanByPatient(@ApiParam(name="patient",value = "患者code",required = true)
                                         @RequestParam(value = "patient",required = true)String patient){
        try {
            return write(200,"操作成功","data",wlyyRehabilitationManageService.manageAllPlanByPatient(patient,getRepUID()));
        } catch (ServiceException se) {
            return error(-1,se.getMessage());
        } catch (Exception e){
            return errorResult(e);
        }
    }
    @RequestMapping(value = "serviceItemList", method = RequestMethod.GET)
    @ApiOperation("康复管理-多个康复计划服务项目内容列表")
    public ObjEnvelop serviceItemList(@ApiParam(name = "planDetailIds", value = "康复计划多个服务项目id(多个‘,’分隔)", required = true)
                                                   @RequestParam(value = "planDetailIds", required = true)String planDetailIds,
                                  @ApiParam(name = "doctorCode", value = "医生code", required = false)
                                  @RequestParam(value = "doctorCode", required = false)String doctorCode){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.serviceItemList(planDetailIds,doctorCode);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "serviceItem", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目确认详情页")
    public ObjEnvelop serviceItem(@ApiParam(name = "planDetailId", value = "康复计划服务项目id", required = true)
                              @RequestParam(value = "planDetailId", required = true)String planDetailId,
                              @ApiParam(name = "doctorCode", value = "医生code", required = false)
                              @RequestParam(value = "doctorCode", required = false)String doctorCode,
                              @ApiParam(name = "recordId", value = "记录id", required = false)
                              @RequestParam(value = "recordId", required = false)String recordId){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.serviceItem(planDetailId,doctorCode,recordId);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "saveGuidanceMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-保存指导留言")
    public String saveGuidanceMessage(@ApiParam(name = "messageId", value = "消息id", required = true)
                                      @RequestParam(value = "messageId", required = true)String messageId,
                                      @ApiParam(name = "doctorCode", value = "医生code", required = false)
                                      @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                      @ApiParam(name = "content", value = "聊天内容", required = true)
                                      @RequestParam(value = "content", required = true)String content,
                                      @ApiParam(name = "planDetailId", value = "服务项目id", required = true)
                                      @RequestParam(value = "planDetailId", required = true)String planDetailId,
                                      @ApiParam(name = "contentType", value = "内容类型(1,6,8 - 文本, 2,9- 图片, 3 - 语音, 4-文章, 5,7系统消息。12-语音 18-居民名片, 19-聊天记录)", required = true)
                                      @RequestParam(value = "contentType", required = true)Integer contentType){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            BaseDoctorDO doctor = doctorDao.findByIdAndDel(doctorCode);
            Integer doctorType = doctor.getLevel();
            rehabilitationManageService.saveGuidanceMessage(messageId,doctorCode,doctorType,content,planDetailId,contentType);
            return write(200, "保存成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updateStatusRehabilitationOperate", method = RequestMethod.POST)
    @ApiOperation("康复管理-更新康复计划操作完成日志状态")
    public String updateStatusRehabilitationOperate(@ApiParam(name = "planDetailId", value = "服务项目id", required = true)
                                                    @RequestParam(value = "planDetailId", required = true)String planDetailId,
                                                    @ApiParam(name = "status", value = "状态", required = true)
                                                    @RequestParam(value = "status", required = true)Integer status){
        try {
            rehabilitationManageService.updateStatusRehabilitationOperate(status,planDetailId);
            return write(200, "更新成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "planDetailAfterCall", method = RequestMethod.POST)
    @ApiOperation("康复管理-电话关怀拨打后生成记录对应怪坏记录")
    public String planDetailAfterCall(@ApiParam(name = "planDetailId", value = "服务项目id", required = true)
                                      @RequestParam(value = "planDetailId", required = true)String planDetailId,
                                      @ApiParam(name = "doctorCode", value = "执行任务的doctorCode", required = true)
                                      @RequestParam(value = "doctorCode", required = false)String doctorCode){
        try {
            if (StringUtils.isBlank(doctorCode)){
                doctorCode = getRepUID();
            }
            RehabilitationOperateRecordsDO recordsDO = rehabilitationManageService.planDetailAfterCall(planDetailId,doctorCode);
            return write(200, "电话关怀记录生成成功!", "data", recordsDO);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "patientRehabilitationDetail", method = RequestMethod.GET)
    @ApiOperation("康复管理-居民详情页")
    public ObjEnvelop patientRehabilitationDetail(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                              @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            return rehabilitationManageService.patientRehabilitationDetail(patientCode);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "recentPlanDetailRecord", method = RequestMethod.GET)
    @ApiOperation("康复管理-近期康复相关记录")
    public ObjEnvelop recentPlanDetailRecord(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                         @RequestParam(value = "patientCode", required = true)String patientCode,
                                         @ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                         @RequestParam(value = "startTime", required = false)String startTime,
                                         @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                         @RequestParam(value = "endTime", required = false)String endTime,
                                         @ApiParam(name = "page", value = "第几页,从1开始", required = true)
                                         @RequestParam(value = "page", required = false,defaultValue = "1")Integer page,
                                         @ApiParam(name = "pageSize", value = "每页分页大小", required = true)
                                        @RequestParam(value = "pageSize", required = false,defaultValue = "10")Integer pageSize){
        try {
            return rehabilitationManageService.recentPlanDetailRecord(patientCode,startTime,endTime,page,pageSize);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "createServiceQrCode", method = RequestMethod.POST)
    @ApiOperation("康复管理-根据康复计划明细id和医生code生成服务码")
    public String createServiceQrCode(@ApiParam(name = "planDetailId", value = "康复计划项目明细ID")@RequestParam(value = "planDetailId", required = true)String planDetailId,
                                      @ApiParam(name = "doctorCode", value = "医生code")@RequestParam(value = "doctorCode", required = true)String doctorCode){
        try {
            return write(200, "获取二维码成功!", "data", wlyyRehabilitationManageService.createServiceQrCode(planDetailId,doctorCode));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    
    @RequestMapping(value = "createSpecialDoctorQrCode", method = RequestMethod.POST)
    @ApiOperation("康复管理-生成康复下转专科医生二维码")
    public String createSpecialDoctorQrCode(
            @ApiParam(name = "doctorCode", value = "医生code")@RequestParam(value = "doctorCode", required = true)String doctorCode,
            @ApiParam(name = "teamCode", value = "团队CODE")@RequestParam(value = "teamCode", required = true)String teamCode,
            @ApiParam(name = "teamName", value = "团队名称")@RequestParam(value = "teamName", required = true)String teamName
                                             ){
        
        try {
            return write(200, "获取二维码成功!", "data", wlyyRehabilitationManageService.createSpecialDoctorQrCode(doctorCode,teamCode,teamName));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "checkAfterQrCode", method = RequestMethod.POST)
    @ApiOperation("康复管理-居民扫码后验证是否是关联的居民扫码")
    public String checkAfterQrCode(@ApiParam(name = "planDetailId", value = "康复计划项目明细ID")@RequestParam(value = "planDetailId", required = true)String planDetailId,
                                      @ApiParam(name = "patientCode", value = "居民端登录的居民code")@RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            Map<String,Object> result = rehabilitationPlanService.checkAfterQrCode(planDetailId,patientCode);
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "serviceDoctorList", method = RequestMethod.GET)
    @ApiOperation("康复管理-医生端居民详情服务医生列表")
    public ObjEnvelop serviceDoctorList(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                    @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            return rehabilitationManageService.serviceDoctorList(patientCode);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "appCalendarPlanDetailList", method = RequestMethod.GET)
    @ApiOperation("康复管理-app端、微信端计划的服务项目列表")
    public ObjEnvelop appCalendarPlanDetailList(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                            @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                            @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                            @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                            @ApiParam(name = "planId", value = "计划id", required = true)
                                            @RequestParam(value = "planId", required = true)String planId,
                                            @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、随访,3、复诊,4、健康教育)", required = false)
                                            @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                            @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                            @RequestParam(value = "status", required = false)Integer status){
        try {
            return rehabilitationManageService.appCalendarPlanDetailList(planId,searchTask,status,executeStartTime,executeEndTime);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "saveRehabilitationOperateRecord", method = RequestMethod.POST)
    @ApiOperation("康复管理-新增operateRecord")
    public String saveRehabilitationOperateRecord(@ApiParam(name = "dataJson", value = "实体json",defaultValue = "{\"rehabilitationDetailId\":\"402803f6657f195301657f4fbd3c0001\",\"patientCode\":\"00\",\"patientName\":\"11\",\"doctorCode\":\"22\",\"doctorName\":\"33\",\"node\":\"jjjjjj\",\"relationRecordType\":\"4\",\"relation_record_code\":\"55\",\"relationRecordImg\":\"666666\",\"status\":\"0\"}")@RequestParam(value = "dataJson", required = true)String dataJson){
        try {
            return write(200, "新增康复计划日志成功!", "data", rehabilitationPlanService.saveRehabilitationOperateRecord(dataJson));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updateNoteAndImageRehabilitationOperate", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划完成时更新服务完成笔记和图片接口并且确认完成")
    public String updateNoteAndImageRehabilitationOperate(@ApiParam(name = "planDetailId", value = "康复计划项目明细ID")@RequestParam(value = "planDetailId", required = true)String planDetailId,
                                                          @ApiParam(name = "node", value = "服务完成笔记", required = false)@RequestParam(value = "node", required = false)String node,
                                                          @ApiParam(name = "image", value = "相关记录图片,json格式", required = false)@RequestParam(value = "image", required = false)String image,
                                                          @ApiParam(name = "relationCode", value = "业务关联code", required = false)@RequestParam(value = "relationCode", required = false)String relationCode,
                                                          @ApiParam(name = "status", value = "是否确认完成 0未确认 1确认", required = false)@RequestParam(value = "status", required = false)String status){
        try {
            if (StringUtils.isNotBlank(image)){
                try{
                    com.alibaba.fastjson.JSONArray jsonImg = com.alibaba.fastjson.JSONArray.parseArray(image);//json格式
                    image = jsonImg.toJSONString();
                }catch (Exception e){
                    com.alibaba.fastjson.JSONArray jsonImg = new com.alibaba.fastjson.JSONArray();
                    String[] images = image.split(",");
                    for (String tmp:images){
                        jsonImg.add(tmp);
                    }
                    image = jsonImg.toJSONString();
                }
            }
            rehabilitationManageService.updateNodeAndRelationRecordImg(node, image,status,planDetailId, relationCode);
            return write(200, "更新日志成功!");
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updateRelationCodeByDetailId", method = RequestMethod.POST)
    @ApiOperation("康复管理-服务项目关联关系")
    public String updateRelationCodeByDetailId(@ApiParam(name = "planDetailId", value = "康复计划项目明细ID")@RequestParam(value = "planDetailId", required = true)String planDetailId,
                                                          @ApiParam(name = "relationCode", value = "业务关联code", required = false)@RequestParam(value = "relationCode", required = false)String relationCode){
        try {
            Integer result = wlyyRehabilitationManageService.updateRelationCodeByDetailId(planDetailId,relationCode);
            if (result==1){
                return write(200, "更新日志成功!");
            }else {
                return error(-1, "更新日志失败");
            }
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectPlanServerDoctor", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划的服务医生")
    public String selectPlanServerDoctor(@ApiParam(name = "planId", value = "康复计划ID")@RequestParam(value = "planId", required = true)String planId){
        try {
            String doctorCode = getRepUID();
            return write(200, "查询成功!","data",wlyyRehabilitationManageService.selectPlanServerDoctor(planId,doctorCode));
        } catch (ServiceException se) {
            return error(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updatePlanDetailStatusById", method = RequestMethod.POST)
    @ApiOperation("康复管理-更新康复计划服务项目状态")
    public String updatePlanDetailStatusById(@ApiParam(name = "planDetailId", value = "服务项目id", required = true)
                                             @RequestParam(value = "planDetailId", required = true)String planDetailId,
                                             @ApiParam(name = "status", value = "状态(0未完成,1已完成,2已预约)", required = true)
                                             @RequestParam(value = "status", required = true)Integer status){
        try {
            rehabilitationManageService.updatePlanDetailStatusById(status,planDetailId);
            return write(200, "更新成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updatePlanDetailExecuteTimeById", method = RequestMethod.POST)
    @ApiOperation("康复管理-修改康复计划服务项目执行时间")
    public String updatePlanDetailExecuteTimeById(@ApiParam(name = "planDetailId", value = "服务项目id", required = true)
                                             @RequestParam(value = "planDetailId", required = true)String planDetailId,
                                             @ApiParam(name = "executeTime", required = true)
                                             @RequestParam(value = "executeTime", required = true)String executeTime){
        try {
            rehabilitationManageService.updatePlanDetailExecuteTimeById(DateUtil.strToDateLong(executeTime),planDetailId);
            return write(200, "更新成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updatePlanStatusById", method = RequestMethod.POST)
    @ApiOperation("康复管理-更新计划的状态")
    public String updatePlanStatusById(@ApiParam(name = "planId", value = "服务项目id", required = true)
                                             @RequestParam(value = "planId", required = true)String planId,
                                             @ApiParam(name = "status", value = "状态(0已中止,1进行中,2已完成)", required = true)
                                             @RequestParam(value = "status", required = true)Integer status,
                                             @ApiParam(name = "abortReason", value = "中止原因")
                                             @RequestParam(value = "abortReason",defaultValue = "",required = false)String abortReason){
        try {
            wlyyRehabilitationPlanService.updatePlanStatusById(planId,status,abortReason);
            return write(200, "更新成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "planSchedule", method = RequestMethod.GET)
    @ApiOperation("康复管理-计划总进度")
    public ObjEnvelop planSchedule(@ApiParam(name = "planId", value = "计划id", required = true)
                               @RequestParam(value = "planId", required = true)String planId,
                               @ApiParam(name = "patientCode", value = "居民code", required = true)
                               @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            return rehabilitationManageService.planSchedule(planId,patientCode,1);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "selectByMedicalCode", method = RequestMethod.GET)
    @ApiOperation("获取医院病历")
    public String selectByMedicalCode(@ApiParam(name = "medical", value = "住院code", required = true)
                               @RequestParam(value = "medical", required = true)String medical){
        try {
            List<PatientMedicalRecordsDO> result = wlyyRehabilitationManageService.selectByMedicalCode(medical);
            try {
                String sql = "UPDATE `wlyy`.`wlyy_patient_medical_records_rehabilitation` SET `doctor_read_status`='1' WHERE (`code`='"+medical+"') ";
                jdbcTemplate.update(sql);
            }catch (Exception e){
                e.printStackTrace();
            }
            return write(200, "获取成功!", "data", result);
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "patientCount", method = RequestMethod.GET)
    @ApiOperation("医生已计划数,已完成计划数(居民数)")
    public ObjEnvelop patientCount(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                                   @RequestParam(value = "doctorCode", required = false)String doctorCode){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getRepUID();
            }
            return rehabilitationManageService.patientCount(doctorCode);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "sendToFamilyDoctor", method = RequestMethod.POST)
    @ApiOperation(value = "给家医发送居民的康复计划.")
    public String sendBusinessCard(@ApiParam(name = "doctorCode", value = "专医code")
                                   @RequestParam(value = "doctorCode", required = true) String doctorCode,
                                   @ApiParam(name = "doctorName", value = "专医名字")
                                   @RequestParam(value = "doctorName", required = true) String doctorName,
                                   @ApiParam(name = "sessionId", value = "会话id", defaultValue = "")
                                   @RequestParam(value = "sessionId", required = true) String sessionId,
                                   @ApiParam(name = "businessType", value = "businessType", defaultValue = "1")
                                   @RequestParam(value = "businessType", required = true) String businessType,
                                   @ApiParam(name = "contentJsonStr", value = "contentJsonStr")
                                   @RequestParam(value = "contentJsonStr", required = true) String contentJsonStr){
        try {
            imUtill.sendImMsg(doctorCode,doctorName,sessionId,ImUtil.ContentType.Rehabilitation.getValue(),contentJsonStr,businessType,null);
            return write(200,"发送消息成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e){
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getServiceItemsAfterStop", method = RequestMethod.GET)
    @ApiOperation("康复管理-已执行项目清单")
    public ObjEnvelop getServiceItemsAfterStop(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                @RequestParam(value = "planId", required = true)String planId){
        try {
            return rehabilitationManageService.getServiceItemsAfterStop(planId);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    /**
     * 康复管理-频次列表
     *
     * @return
     */
    @RequestMapping(value = "selectFrequencys", method = RequestMethod.GET)
    @ApiOperation("康复管理-频次列表")
    public String selectFrequencys(){
        try {
            return write(200, "操作成功!","data",wlyyRehabilitationManageService.selectFrequences());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getServiceItemList", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取服务项目列表")
    public String getServiceItemList(@ApiParam(name = "name", value = "服务项目名称", required = false)
                                     @RequestParam(value = "name", required = false) String name) {
        try {
            return write(200, "请求成功!", "data", wlyyRehabilitationManageService.getServiceItemList(name));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public String selectType(@ApiParam(name = "type", value = "康复指导类型", required = false)
                                 @RequestParam(value = "type", required = false) Integer type,
                             @ApiParam(name = "id", value = "康复指导模板id", required = false)
                            @RequestParam(value = "id", required = false) String id,
                             @ApiParam(name = "title", value = "康复指导名称", required = false)
                                 @RequestParam(value = "title", required = false) String title,
                             @ApiParam(name = "planId", value = "计划id", required = false)
                                 @RequestParam(value = "planId", required = false) String planId,
                             @ApiParam(name = "page", value = "页码", required = false)
                                 @RequestParam(value = "page", required = false, defaultValue ="1") Integer page,
                             @ApiParam(name = "pagesize", value = "每页大小", required = false)
                                 @RequestParam(value = "pagesize", required = false,defaultValue = "15") Integer pagesize) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.select(title,type,id,planId,page,pagesize));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectPatientGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public String selectPatientGuidances(@ApiParam(name = "patient", value = "居民code", required = false)
                             @RequestParam(value = "patient", required = false) String patient,
                             @ApiParam(name = "code", value = "康复指导模板code", required = false)
                             @RequestParam(value = "code", required = false) String code,
                             @ApiParam(name = "doctor", value = "医生code", required = false)
                             @RequestParam(value = "doctor", required = false) String doctor,
                             @ApiParam(name = "page", value = "页码", required = false)
                             @RequestParam(value = "page", required = false) Integer page,
                             @ApiParam(name = "pagesize", value = "每页大小", required = false)
                             @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,code,page,pagesize));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectType", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表标题")
    public String selectType(@ApiParam(name="planId",value = "根据计划id取该计划对应疾病的指导",required = false)
                             @RequestParam(value = "planId",required = false)String planId) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.selectType(planId));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectByRelationCode", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据业务code查找康复指导")
    public String selectByRelationCode(@ApiParam(name = "relationCode", value = "业务关联code", required = false)
                             @RequestParam(value = "relationCode", required = false) String relationCode,
                             @ApiParam(name = "patient", value = "居民code", required = false)
                            @RequestParam(value = "patient", required = false) String patient,
                             @ApiParam(name = "doctor", value = "医生code", required = false)
                                 @RequestParam(value = "doctor", required = false) String doctor) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.selectByRelationCode(patient,doctor,relationCode));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "sendGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-发送康复指导")
    public String selectType(@ApiParam(name = "json", value = "康复指导json", required = true)
                             @RequestParam(value = "json", required = true) String json,
                             @ApiParam(name = "planId", value = "计划ID", required = true)
                             @RequestParam(value = "planId", required = true) String planId) {
        try {
            com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(json);
            List<RehabilitationguidancePatientDO> rehabilitationguidancePatientDOS = new ArrayList<>();
            for (int i=0;i<array.size();i++){
                com.alibaba.fastjson.JSONObject object = array.getJSONObject(i);
                RehabilitationguidancePatientDO rehabilitationguidancePatientDO = objectMapper.readValue(object.toJSONString(),RehabilitationguidancePatientDO.class);
                rehabilitationguidancePatientDOS.add(rehabilitationguidancePatientDO);
            }
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.sendGuidanceToPatient(rehabilitationguidancePatientDOS,planId));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "confirmManage", method = RequestMethod.GET)
    @ApiOperation("康复管理-确认管理")
    public String confirmManage(@ApiParam(name = "doctor", value = "签约医生code", required = true)
                             @RequestParam(value = "doctor", required = true) String signDoctor,
                             @ApiParam(name = "patient", value = "居民code", required = true)
                             @RequestParam(value = "patient", required = true) String patient,
                             @ApiParam(name = "specialist", value = "专医code", required = true)
                             @RequestParam(value = "specialist", required = true) String specialist,
                             @ApiParam(name = "relationId", value = "签约关系id", required = true)
                             @RequestParam(value = "relationId", required = false) String relationId,
                             @ApiParam(name = "planId", value = "计划id", required = true)
                             @RequestParam(value = "planId", required = false) String planId) {
        try {
            wlyyRehabilitationManageService.confirmManage(patient,signDoctor,specialist,relationId,planId);
            return write(200, "请求成功!");
        } catch (ServiceException se) {
            return error(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectPlanDetailByPlanId", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看其它服务计划")
    public String selectPlanDetailByPlanId(@ApiParam(name = "planId", value = "计划id", required = true)
                                @RequestParam(value = "planId", required = true) String planId,
                                @ApiParam(name = "planDetailId", value = "计划详情id", required = true)
                                    @RequestParam(value = "planDetailId", required = true) String planDetailId,
                                @ApiParam(name = "itemId", value = "服务项目code", required = true)
                                    @RequestParam(value = "itemId", required = true) String itemId) {
        try {
            return write(200, "请求成功!","data",wlyyRehabilitationManageService.selectPlanDetailByPlan(planId,planDetailId,itemId));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "selectReservationRecord", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看复诊记录")
    public String selectReservationRecord(@ApiParam(name = "patient", value = "居民code", required = true)
                                           @RequestParam(value = "patient", required = true) String patient,
                                          @ApiParam(name = "doctor", value = "医生code", required = false)
                                          @RequestParam(value = "doctor", required = false) String doctor,
                                          @ApiParam(name = "page", value = "页码", required = false)
                                              @RequestParam(value = "page", required = false) Integer page,
                                          @ApiParam(name = "pageSize", value = "条数", required = false)
                                              @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        try {
            if (doctor==null||doctor==""){
                   doctor=getUID();
            }
            return write(200, "请求成功!","data",wlyyRehabilitationManageService.selectReservationRecord(patient,doctor,page,pageSize));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    /**
     *
     * @param patient 居民code
     * @param doctor 专科医生code
     * @param type 1康复指导2康复下转3复诊提醒4上门服务提醒5家签提醒
     * @param relationCode 业务关联code
     * @param planId 计划id
     * @return
     */
    @RequestMapping(value = "sendSpecialistWeixinMessage", method = RequestMethod.GET)
    @ApiOperation("康复管理-发送微信模板消息")
    public String sendSpecialistWeixinMessage(@ApiParam(name = "patient", value = "居民code", required = true)
                                           @RequestParam(value = "patient", required = true) String patient,
                                           @ApiParam(name = "doctor", value = "医生code", required = true)
                                           @RequestParam(value = "doctor", required = true) String doctor,
                                           @ApiParam(name = "type", value = "发送类型", required = true)
                                           @RequestParam(value = "type", required = true) Integer type,
                                           @ApiParam(name = "relationCode", value = "业务code", required = false)
                                           @RequestParam(value = "relationCode", required = true) String relationCode,
                                           @ApiParam(name = "planId", value = "计划id", required = false)
                                           @RequestParam(value = "planId", required = true) String planId,
                                           @ApiParam(name = "reservationType", value = "复诊类型:1线上,2线下,3远程", required = false)
                                           @RequestParam(value = "reservationType", required = false) String reservationType) {
        try {
            rehabilitationGuidanceService.sendSpecialistWeixinMessage(patient,doctor,type,relationCode,planId,reservationType);
            return write(200, "请求成功!");
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @GetMapping(value = "appointmentConsultation")
    @ApiOperation("预约协诊")
    public String appointmentConsultation(@ApiParam(name = "patient", value = "居民code", required = true)
                                                @RequestParam(value = "patient", required = true) String patient,
                                            @ApiParam(name = "doctor", value = "医生code-家医", required = true)
                                                @RequestParam(value = "doctor", required = true) String doctor,
                                            @ApiParam(name = "doctorName", value = "医生姓名-家医", required = true)
                                                @RequestParam(value = "doctorName", required = true) String doctorName,
                                          @ApiParam(name = "appointmentDoctor", value = "医生code-专科", required = true)
                                              @RequestParam(value = "appointmentDoctor", required = true) String appointmentDoctor,
                                          @ApiParam(name = "appointmentDoctorName", value = "医生姓名-专科", required = true)
                                              @RequestParam(value = "appointmentDoctorName", required = true) String appointmentDoctorName,
                                            @ApiParam(name = "sendTime", value = "发送时间", required = true)
                                                @RequestParam(value = "sendTime", required = true) String sendTime,
                                            @ApiParam(name = "planDetailId", value = "计划明细id", required = true)
                                                @RequestParam(value = "planDetailId", required = true) String planDetailId){
        try {
            rehabilitationManageService.appointmentConsultation(patient,doctor,doctorName,appointmentDoctor,appointmentDoctorName,sendTime,planDetailId,getUID());
            return write(200, "请求成功!","data","");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    /**
     * 获取为某患者创建康复计划的专科医生列表,家庭医生,
     * @param patientCode 患者code
     * @return
     */
    @RequestMapping(value = "getPatientSpecialAndFamilyDoctor",method = RequestMethod.GET)
    @ApiOperation("获取为某患者创建康复计划的医生专科列表、家庭医生")
    public String getConsultDoctorForConsulting(@RequestParam("patientCode")String patientCode){
        try {
            return write(200,"查询成功","data",wlyyRehabilitationManageService.getPatientSpecialAndFamilyDoctor(patientCode));
        }catch (Exception e){
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getPlanDetailForModifing",method = RequestMethod.GET)
    @ApiOperation(value = "根据planId、模板id获取计划列表")
    public String getPlanDetailForModifing(@ApiParam(name = "planId",value = "康复计划id",required = true)
                                           @RequestParam(value = "planId",required = true) String planId,
                                           @ApiParam(name = "templateId",value = "模板Id,不传默认为系统模板",required = false)
                                           @RequestParam(value = "templateId",required = false) String templateId){
        try {
            return write(200,"查询成功","data",wlyyRehabilitationManageService.getPlanDetailForModifing(planId, templateId));
        }catch (Exception e){
            return errorResult(e);
        }
    }
}

+ 0 - 264
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/DoctorRehabilitationPlanController.java

@ -1,264 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.rehabilitation;
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.RehabilitationManageService;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.WlyyRehabilitationPlanService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashSet;
import java.util.Set;
/**
 * Created by humingfen on 2018/8/22.
 */
@RestController
@RequestMapping(value = "/doctor/specialist/rehabilitationPlan")
@Api(description = "医生端-康复服务套餐管理")
public class DoctorRehabilitationPlanController extends BaseController {
    @Autowired
    private WlyyRehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @RequestMapping(value = "/findTemplateList", method = RequestMethod.GET)
    @ApiOperation(value = "获取康复服务套餐模板列表")
    public String templateList(@ApiParam(name = "doctor", value = "医生标识")
                               @RequestParam(required = false)String doctor,
                               @ApiParam(name = "patient", value = "居民标识")
                               @RequestParam(required = false)String patient,
                               @ApiParam(name = "adminTeamCode", value = "居民签约的专科行政团队id")
                                   @RequestParam(value = "adminTeamCode", required = false)Long adminTeamCode){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            return write(200, "获取成功", "data", rehabilitationPlanService.findTemplateInfo(doctor, patient, adminTeamCode));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/findTemplateDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取康复服务套餐模板明细")
    public String findTemplateDetail(@ApiParam(name = "templateId", value = "模板id")
                                     @RequestParam(required = true)String templateId){
        try {
            return write(200, "获取成功", "data", rehabilitationPlanService.findTemplateDetailInfo(templateId));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/createTemplate", method = RequestMethod.POST)
    @ApiOperation(value = "创建康复服务套餐模板")
    public String createTemplate(@ApiParam(name = "doctor", value = "医生标识")
                                 @RequestParam(required = false)String doctor,
                                 @ApiParam(name = "adminTeamCode", value = "团队id")
                                 @RequestParam(required = false)Long adminTeamCode,
                                 @ApiParam(name = "title", value = "康复服务模板名称")
                                 @RequestParam(required = true) String title){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            BaseDoctorDO d = doctorDao.findByIdAndDel(doctor);
            return write(200, "获取成功", "data", rehabilitationPlanService.createTemplate(title,d,adminTeamCode));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/createTemplateDetail", method = RequestMethod.POST)
    @ApiOperation(value = "创建康复服务套餐模板明细")
    public String createTemplateDetail(@ApiParam(name = "doctor", value = "医生标识")
                                       @RequestParam(required = false)String doctor,
                                       @ApiParam(name = "json", value = "康复服务模板明细")
                                       @RequestParam(required = true) String json,
                                       @ApiParam(name = "type", value = "create或者edit")
                                       @RequestParam(required = true) String type){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            BaseDoctorDO d = doctorDao.findByIdAndDel(doctor);
            return write(200, "获取成功", "data", rehabilitationPlanService.createTemplateDetail(json, type, d));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/deleteTemplate", method = RequestMethod.POST)
    @ApiOperation(value = "删除康复服务套餐模板")
    public String deleteTemplate(@ApiParam(name = "templateId", value = "模板id")
                                 @RequestParam(required = true)String templateId){
        try {
            return write(200, "获取成功", "data", rehabilitationPlanService.deleteTemplate(templateId));
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/createRehabilitationPlan", method = RequestMethod.POST)
    @ApiOperation(value = "创建居民康复计划")
    public String createRehabilitationPlan(@ApiParam(name = "doctor", value = "医生标识")
                                           @RequestParam(required = false)String doctor,
                                           @ApiParam(name = "json", value = "康复计划json")
                                           @RequestParam(required = true) String json){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            BaseDoctorDO d = doctorDao.findByIdAndDel(doctor);
            JSONObject object = new JSONObject(json);
            JSONArray array = object.getJSONArray("detail");
            Set<String> list = new HashSet<>();
            for(int i=0;i<array.length();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String hospitalServiceItemId = jsonObject.getString("hospitalServiceItemId");
                String frequencyCode = jsonObject.getString("frequencyCode");
                Long timeType = jsonObject.getLong("timeType");
                String executeTimes =jsonObject.getString("executeTimes");
                String str[] = executeTimes.split(",");
                for (int j=i+1;j<array.length();j++){
                    JSONObject jsonObject1 = array.getJSONObject(j);
                    String hospitalServiceItemId1 = jsonObject1.getString("hospitalServiceItemId");
                    String frequencyCode1 = jsonObject1.getString("frequencyCode");
                    Long timeType1 = jsonObject1.getLong("timeType");
                    String executeTimes1 =jsonObject1.getString("executeTimes");
                    if (hospitalServiceItemId.equalsIgnoreCase(hospitalServiceItemId1)&&frequencyCode.equalsIgnoreCase(frequencyCode1)&&timeType.equals(timeType1)){
                        for (int z=0;z<str.length;z++){
                            if (executeTimes1.contains(str[z])){
                                list.add(hospitalServiceItemId);
                            }
                        }
                    }
                }
            }
            if (list != null && list.size()!=0){
                return write(-1, "计划创建失败!您设置了重复项目时间,请修改后生成!", "data", list);
            }
            return write(200, "获取成功", "data", rehabilitationPlanService.createRehabilitationPlan(json,d));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "updatePatientImgById", method = RequestMethod.POST)
    @ApiOperation("更新康复计划居民签名照/证件照")
    public String updatePatientImgById(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                       @RequestParam(value = "planId")String planId,
                                       @ApiParam(name = "patientImg", value = "居民签名/证件照地址")
                                       @RequestParam(value = "patientImg")String patientImg){
        try {
            rehabilitationPlanService.updatePatientImgById(planId, patientImg);
            return write(200, "更新成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "sendWxMsg", method = RequestMethod.POST)
    @ApiOperation("发送微信模板消息")
    public String sendWxTemplate(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                       @RequestParam(value = "planId")String planId){
        try {
            ObjEnvelop jsonObject = rehabilitationManageService.getServiceItemsAfterStop(planId);
            rehabilitationPlanService.sendWxTemplate(planId, getUID(), jsonObject);
            return write(200, "发送成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "/updateRehabilitationPlan", method = RequestMethod.POST)
    @ApiOperation(value = "编辑居民康复计划")
    public String updateRehabilitationPlan(@ApiParam(name = "doctor", value = "医生标识")
                                           @RequestParam(required = false)String doctor,
                                           @ApiParam(name = "json", value = "康复计划json")
                                           @RequestParam(required = true) String json,
                                           @ApiParam(name = "updateStatus", value = "修改类型:0单个服务的修改(默认),1整个计划修改")
                                           @RequestParam(required = false,defaultValue = "0") String updateStatus){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            BaseDoctorDO d = doctorDao.findByIdAndDel(doctor);
            JSONObject object = new JSONObject(json);
            JSONArray array = object.getJSONArray("detail");//获取服务内容
            Set<String> list = new HashSet<>();
            for(int i=0;i<array.length();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String hospitalServiceItemId = jsonObject.getString("hospitalServiceItemId");//服务id
                String frequencyCode = jsonObject.getString("frequencyCode");
                Long timeType = jsonObject.getLong("timeType");
                String executeTimes =jsonObject.getString("executeTimes");
                String str[] = executeTimes.split(",");
                for (int j=i+1;j<array.length();j++){
                    JSONObject jsonObject1 = array.getJSONObject(j);
                    String hospitalServiceItemId1 = jsonObject1.getString("hospitalServiceItemId");
                    String frequencyCode1 = jsonObject1.getString("frequencyCode");
                    Long timeType1 = jsonObject1.getLong("timeType");
                    String executeTimes1 =jsonObject1.getString("executeTimes");
                    if (hospitalServiceItemId.equalsIgnoreCase(hospitalServiceItemId1)&&frequencyCode.equalsIgnoreCase(frequencyCode1)&&timeType.equals(timeType1)){
                        for (int z=0;z<str.length;z++){
                            if (executeTimes1.contains(str[z])){//时间与之前项目时间相同
                                list.add(hospitalServiceItemId);
                            }
                        }
                    }
                }
            }
            if (list != null && list.size()!=0){
                return write(-1, "计划创建失败!您设置了重复项目时间,请修改后生成!", "data", list);
            }
            return write(200, "获取成功", "data", rehabilitationPlanService.updateRehabilitationPlan(json,d,updateStatus));
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @RequestMapping(value = "getRehabilitationPlanLog",method = RequestMethod.GET)
    @ApiOperation(value = "获取康复计划修改记录")
    public String getRehabilitationPlanLog(@ApiParam(name = "planId",value = "康复计划Id",required = true)
                                           @RequestParam(value = "planId",required = true) String planId){
        try {
            return write(200,"获取成功","data",rehabilitationPlanService.getRehabilitationPlanLog(planId));
        }catch (Exception e){
            return errorResult(e);
        }
    }
}

+ 0 - 537
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/endpoint/rehabilitation/PatientRehabilitationManageController.java

@ -1,537 +0,0 @@
package com.yihu.jw.afterDiagnosis.endpoint.rehabilitation;
/**
 * Created by 刘文彬 on 2018/8/31.
 */
import com.yihu.jw.afterDiagnosis.endpoint.BaseController;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.RehabilitationGuidanceService;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.RehabilitationManageService;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.RehabilitationPlanService;
import com.yihu.jw.afterDiagnosis.service.rehabilitation.WlyyRehabilitationManageService;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by 刘文彬 on 2018/8/30.
 */
@RestController
@RequestMapping(value = "/patient/specialist/rehabilitation")
@Api(description = "居民端-康复管理")
public class PatientRehabilitationManageController extends BaseController {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private RehabilitationGuidanceService rehabilitationGuidanceService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyRehabilitationManageService wlyyRehabilitationManageService;
    @RequestMapping(value = "patientRehabilitationDetail", method = RequestMethod.GET)
    @ApiOperation("康复管理-微信端-居民详情页")
    public ObjEnvelop patientRehabilitationDetail(){
        try {
            String patient = null;
            if (StringUtils.isNoneBlank(getRepresentedUID())){
                patient = getRepresentedUID();
            }else {
                patient = getUID();
            }
            return rehabilitationManageService.patientRehabilitationDetail(patient);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "getPatientInfo", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取居民信息")
    public String getPatientInfo(@ApiParam(name = "patient", value = "居民信息", required = true)
                                     @RequestParam(value = "patient", required = true)String patient,
                                     @ApiParam(name = "planId", value = "计划id", required = true)
                                     @RequestParam(value = "planId", required = true)String planId){
        try {
            return write(200, "获取成功", "data", wlyyRehabilitationManageService.getPatientInfo(planId,patient));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectByMedicalCode", method = RequestMethod.GET)
    @ApiOperation("获取医院病历")
    public String selectByMedicalCode(@ApiParam(name = "medical", value = "住院code", required = true)
                                      @RequestParam(value = "medical", required = true)String medical){
        try {
            List<PatientMedicalRecordsDO> result = wlyyRehabilitationManageService.selectByMedicalCode(medical);
            try{
                String sql = "UPDATE wlyy_patient_medical_records_rehabilitation` SET `patient_read_status`='1' WHERE (`code`='"+medical+"') ";
                jdbcTemplate.update(sql);
            }catch (Exception e){
                e.printStackTrace();
            }
            return write(200, "获取成功!", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    
    @RequestMapping(value = "selectByPatient", method = RequestMethod.GET)
    @ApiOperation("获取居民医院病历列表")
    public String selectByPatient(@ApiParam(name = "patient", value = "居民code", required = true)
                                      @RequestParam(value = "patient", required = true)String patient){
        
        try {
            List<PatientMedicalRecordsDO> result = wlyyRehabilitationManageService.findByPatient(patient);
            return write(200, "获取成功!", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    
    @RequestMapping(value = "getPlantCodeByMedicalRecordsCode", method = RequestMethod.GET)
    @ApiOperation("根据住院病历获取计划CODE")
    public String getPlantCodeByMedicalRecordsCode(@ApiParam(name = "code", value = "住院病历CODE", required = true)
                                                   @RequestParam(value = "code", required = true)String code){
        try {
            return write(200, "获取成功!", "data",wlyyRehabilitationManageService.getPlantCodeByMedicalRecordsCode(code));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "calendarPlanDetail", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按日历展示")
    public ObjEnvelop calendarPlanDetail(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                     @RequestParam(value = "executeStartTime", required = true)String executeStartTime,
                                     @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                     @RequestParam(value = "executeEndTime", required = true)String executeEndTime,
                                     @ApiParam(name = "planId", value = "计划id", required = true)
                                     @RequestParam(value = "planId", required = true)String planId,
                                     @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、复诊,4、随访)", required = false)
                                     @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                     @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                     @RequestParam(value = "status", required = false)Integer status){
        try {
            return rehabilitationManageService.calendarPlanDetail(executeStartTime,executeEndTime,planId,searchTask,status,null,null);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "serviceDoctorList", method = RequestMethod.GET)
    @ApiOperation("康复管理-微信端居民服务医生列表")
    public ObjEnvelop serviceDoctorList(){
        try {
            return rehabilitationManageService.serviceDoctorList(getUID());
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "calendarPlanDetailList", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按列表展示")
    public ObjEnvelop calendarPlanDetailList(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                         @RequestParam(value = "executeStartTime", required = true)String executeStartTime,
                                         @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                         @RequestParam(value = "executeEndTime", required = true)String executeEndTime,
                                         @ApiParam(name = "planId", value = "计划id", required = true)
                                         @RequestParam(value = "planId", required = true)String planId,
                                         @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、复诊,4、随访)", required = false)
                                         @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                         @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                         @RequestParam(value = "status", required = false)Integer status){
        try {
            return rehabilitationManageService.calendarPlanDetailList(planId,searchTask,status,null,executeStartTime,executeEndTime,null);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "calendarPlanDetailItems", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目按列表展示")
    public String calendarPlanDetailItems(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                          @RequestParam(value = "executeStartTime", required = true)String executeStartTime,
                                          @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                          @RequestParam(value = "executeEndTime", required = true)String executeEndTime,
                                          @ApiParam(name = "planId", value = "计划id", required = true)
                                          @RequestParam(value = "planId", required = true)String planId,
                                          @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、健康指导,4、随访,5、复诊)", required = false)
                                          @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                          @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status){
        try {
            List<Map<String,Object>> result = wlyyRehabilitationManageService.calendarPlanDetailItems(executeStartTime,executeEndTime,planId,searchTask,status,null);
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectByGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据计划查询指导留言")
    public String selectByGuidance(@ApiParam(name = "planId", value = "计划id", required = false)
                                   @RequestParam(value = "planId", required = true)String planId,
                                   @ApiParam(name = "itemCode", value = "服务项目code", required = true)
                                   @RequestParam(value = "itemCode", required = true)String itemCode){
        try {
            List<Map<String,Object>> mapList = wlyyRehabilitationManageService.selectByGuidance(planId,itemCode);
            return write(200, "获取成功", "data", mapList);
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectByPlanDetaiId", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取操作记录")
    public String selectByPlanDetaiId(
                                      @ApiParam(name = "planId", value = "计划id", required = true)
                                      @RequestParam(value = "planId", required = true)String planId,
                                      @ApiParam(name = "code", value = "服务项目code", required = true)
                                      @RequestParam(value = "code", required = true)String code,
                                      @ApiParam(name = "page", value = "", required = false)
                                      @RequestParam(value = "page", required = false)Integer page,
                                      @ApiParam(name = "pagesize", value = "", required = false)
                                      @RequestParam(value = "pagesize", required = false)Integer pagesize){
        try {
            return write(200, "获取成功", "data", wlyyRehabilitationManageService.selectByPlanDetaiId(null,planId,code,page,pagesize));//patient,
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectPlanByPatient", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据居民code查找康复计划")
    public String calendarPlanDetailItems(@ApiParam(name = "patient", value = "居民code", required = false)
                                          @RequestParam(value = "patient", required = false)String patient,
                                          @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status){
        try {
            List<Map<String,Object>> result = wlyyRehabilitationManageService.selectPlanByPatient(patient,status,null,null);
            return write(200, "获取成功", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "sendMessageIm", method = RequestMethod.POST)
    @ApiOperation("康复管理-扫描二维码发送消息")
    public String sendMessageIm(@ApiParam(name = "sendId", value = "发送者id")@RequestParam(value = "sendId", required = true)String sendId,
                                @ApiParam(name = "receiverId", value = "接受者id", required = true)@RequestParam(value = "receiverId", required = true)String receiverId,
                                @ApiParam(name = "content", value = "内容", required = true)@RequestParam(value = "content", required = true)String content){
        try {
            imUtill.sendMessage(sendId,receiverId,"1",content);
            wlyyRehabilitationManageService.sendMessage(sendId, receiverId, content);//发送康复下转邀请
            return write(200,"发送成功!");
        } catch (Exception e) {
            error(e);
            return error(-1, "发送失败!");
        }
    }
    @RequestMapping(value = "checkAfterQrCode", method = RequestMethod.POST)
    @ApiOperation("康复管理-居民扫码后验证是否是关联的居民扫码")
    public String checkAfterQrCode(@ApiParam(name = "planDetailId", value = "康复计划项目明细ID")@RequestParam(value = "planDetailId", required = true)String planDetailId,
                                   @ApiParam(name = "patientCode", value = "居民端登录的居民code")@RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            String message="";
            Boolean flag = true;
            Map<String,Object> map = rehabilitationPlanService.checkAfterQrCode(planDetailId,patientCode);
            int result = Integer.valueOf(String.valueOf(map.get("code")));
            if (result==200){
                message = "验证成功!";
            }
            if (result==-1){
                message = "请相关居民扫描二维码";
                flag=false;
            }
            if (result==-10000){
                message = "相关康复管理数据错误,请联系工作人员!";
                flag=false;
            }
            map.put("flag",flag);
            map.remove("code");
            return write(200, message, "data", map);
        } catch (Exception e) {
            error(e);
            return error(-1, "验证失败");
        }
    }
    @RequestMapping(value = "saveRehabilitationOperateRecord", method = RequestMethod.POST)
    @ApiOperation("康复管理-新增operateRecord")
    public String saveRehabilitationOperateRecord(@ApiParam(name = "dataJson", value = "实体json",defaultValue = "{\"rehabilitationDetailId\":\"402803f6657f195301657f4fbd3c0001\",\"patientCode\":\"00\",\"patientName\":\"11\",\"doctorCode\":\"22\",\"doctorName\":\"33\",\"node\":\"jjjjjj\",\"relationRecordType\":\"4\",\"relation_record_code\":\"55\",\"relationRecordImg\":\"666666\",\"status\":\"0\"}")@RequestParam(value = "dataJson", required = true)String dataJson){
        try {
            RehabilitationOperateRecordsDO result = rehabilitationPlanService.saveRehabilitationOperateRecord(dataJson);
            return write(200, "新增康复计划日志成功!", "data", result);
        } catch (Exception e) {
            error(e);
            return error(-1, "新增康复计划日志失败!");
        }
    }
    @RequestMapping(value = "recentPlanDetailRecord", method = RequestMethod.GET)
    @ApiOperation("康复管理-近期康复相关记录")
    public ObjEnvelop recentPlanDetailRecord(@ApiParam(name = "patientCode", value = "居民code", required = false)
                                         @RequestParam(value = "patientCode", required = false)String patientCode,
                                         @ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                         @RequestParam(value = "startTime", required = false)String startTime,
                                         @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                         @RequestParam(value = "endTime", required = false)String endTime,
                                         @ApiParam(name = "page", value = "第几页,从1开始", required = true)
                                         @RequestParam(value = "page", required = false,defaultValue = "1")Integer page,
                                         @ApiParam(name = "pageSize", value = "每页分页大小", required = true)
                                         @RequestParam(value = "pageSize", required = false,defaultValue = "10")Integer pageSize){
        try {
            if(!StringUtils.isNotEmpty(patientCode)){
                patientCode = getUID();
            }
            return rehabilitationManageService.recentPlanDetailRecord(patientCode,startTime,endTime,page,pageSize);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "serviceItemList", method = RequestMethod.GET)
    @ApiOperation("康复管理-多个康复计划服务项目内容列表")
    public ObjEnvelop serviceItemList(@ApiParam(name = "planDetailIds", value = "康复计划多个服务项目id(多个‘,’分隔)", required = true)
                                  @RequestParam(value = "planDetailIds", required = true)String planDetailIds){
        try {
            return rehabilitationManageService.serviceItemList(planDetailIds,null);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "serviceItem", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目确认详情页")
    public ObjEnvelop serviceItem(@ApiParam(name = "planDetailId", value = "康复计划服务项目id", required = true)
                              @RequestParam(value = "planDetailId", required = true)String planDetailId,
                              @ApiParam(name = "recordId", value = "记录id", required = false)
                              @RequestParam(value = "recordId", required = false)String recordId){
        try {
            return rehabilitationManageService.serviceItem(planDetailId,null,recordId);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "planSchedule", method = RequestMethod.GET)
    @ApiOperation("康复管理-计划总进度")
    public ObjEnvelop planSchedule(@ApiParam(name = "planId", value = "计划id", required = true)
                               @RequestParam(value = "planId", required = true)String planId,
                                   @ApiParam(name = "patientCode", value = "居民code", required = false)
                               @RequestParam(value = "patientCode", required = false)String patientCode){
        try {
            if(!StringUtils.isNotEmpty(patientCode)){
                patientCode = getRepUID();
            }
            return rehabilitationManageService.planSchedule(planId,patientCode,2);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "updatePatientImgById", method = RequestMethod.POST)
    @ApiOperation("更新康复计划居民签名照/证件照")
    public String updatePatientImgById(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                       @RequestParam(value = "planId")String planId,
                                       @ApiParam(name = "patientImg", value = "居民签名/证件照地址")
                                       @RequestParam(value = "patientImg")String patientImg){
        try {
            rehabilitationPlanService.updatePatientImgById(planId, patientImg);
            return write(200, "更新成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return error(-1, "更新失败");
        }
    }
    @RequestMapping(value = "getServiceItemsAfterStop", method = RequestMethod.GET)
    @ApiOperation("康复管理-已执行项目清单")
    public ObjEnvelop getServiceItemsAfterStop(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                           @RequestParam(value = "planId", required = true)String planId){
        try {
            return rehabilitationManageService.getServiceItemsAfterStop(planId);
        } catch (ServiceException se) {
            return ObjEnvelop.getError(se.getMessage(),-1);
        } catch (Exception e) {
            return ObjEnvelop.getError("获取失败",-1);
        }
    }
    @RequestMapping(value = "selectByRelationCodeAndGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据业务code查找康复指导")
    public String selectByRelationCodeAndGuidance(@ApiParam(name = "relationCode", value = "业务关联code", required = false)
                                       @RequestParam(value = "relationCode", required = false) String relationCode,
                                       @ApiParam(name = "patient", value = "居民code", required = false)
                                       @RequestParam(value = "patient", required = false) String patient,
                                       @ApiParam(name = "doctor", value = "医生code", required = false)
                                       @RequestParam(value = "doctor", required = false) String doctor) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.selectByRelationCode(patient,doctor,relationCode));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public String selectType(@ApiParam(name = "type", value = "康复指导类型", required = false)
                             @RequestParam(value = "type", required = false) Integer type,
                             @ApiParam(name = "id", value = "康复指导模板id", required = false)
                             @RequestParam(value = "id", required = false) String id,
                             @ApiParam(name = "title", value = "康复指导名称", required = false)
                             @RequestParam(value = "title", required = false) String title,
                             @ApiParam(name = "planId", value = "计划id", required = false)
                             @RequestParam(value = "planId", required = false) String planId,
                             @ApiParam(name = "page", value = "页码", required = false)
                             @RequestParam(value = "page", required = false) Integer page,
                             @ApiParam(name = "pagesize", value = "每页大小", required = false)
                             @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.select(title,type,id,planId,page,pagesize));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectPlanDetailByPlanId", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看其它服务计划")
    public String selectPlanDetailByPlanId(@ApiParam(name = "planId", value = "计划id", required = true)
                                           @RequestParam(value = "planId", required = true) String planId,
                                           @ApiParam(name = "planDetailId", value = "计划详情id", required = true)
                                           @RequestParam(value = "planDetailId", required = true) String planDetailId,
                                           @ApiParam(name = "itemId", value = "服务项目code", required = true)
                                           @RequestParam(value = "itemId", required = true) String itemId) {
        try {
            return write(200, "请求成功!","data",wlyyRehabilitationManageService.selectPlanDetailByPlan(planId,planDetailId,itemId));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "selectByRelationCode", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据业务code查找康复指导")
    public String selectByRelationCode(@ApiParam(name = "relationCode", value = "业务关联code", required = false)
                                       @RequestParam(value = "relationCode", required = false) String relationCode,
                                       @ApiParam(name = "patient", value = "居民code", required = false)
                                       @RequestParam(value = "patient", required = false) String patient,
                                       @ApiParam(name = "doctor", value = "医生code", required = false)
                                       @RequestParam(value = "doctor", required = false) String doctor) {
        try {
            return write(200, "请求成功!", "data", rehabilitationGuidanceService.selectByRelationCode(patient,doctor,relationCode));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    
    @RequestMapping(value = "getDiseaseTopicInfo", method = RequestMethod.GET)
    @ApiOperation("获取居民疾病专题首页相关数据")
    public String getDiseaseTopicInfo(@ApiParam(name = "patientCode", value = "住院病历CODE", required = true)
                                                   @RequestParam(value = "patientCode", required = true)String patientCode,
                                                   @ApiParam(name = "diseaseType", value = "疾病类型", required = true)
                                                   @RequestParam(value = "diseaseType", required = true)String diseaseType){
        try {
            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
            object.put("patientId",getUID());
            return write(200, "获取成功!", "data",wlyyRehabilitationManageService.getDiseaseTopicInfo(object,patientCode,diseaseType));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
    @RequestMapping(value = "getDiseaseHospital", method = RequestMethod.GET)
    @ApiOperation("获取入住疾病的医院列表")
    public String getDiseaseHospital(@ApiParam(name = "diseaseType", value = "疾病类型", required = true)
                                     @RequestParam(value = "diseaseType", required = true)String diseaseType,
                                     @ApiParam(name = "name", value = "医院名称", required = false)
                                     @RequestParam(value = "name", required = false)String name,
                                     @ApiParam(name = "page", value = "页码", required = false)
                                         @RequestParam(value = "page", required = false) Integer page,
                                     @ApiParam(name = "pagesize", value = "每页大小", required = false)
                                         @RequestParam(value = "pagesize", required = false) Integer pagesize){
        try {
            if(page==null){
                page = 1;
            }
            if(pagesize==null){
                pagesize = 15;
            }
            return write(200, "获取成功!", "data",wlyyRehabilitationManageService.getDiseaseHospital(diseaseType,name,page,pagesize));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }
}

+ 0 - 189
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/DeviceDetailService.java

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

+ 0 - 51
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/DeviceService.java

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

+ 0 - 93
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/DeviceWxMessageService.java

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

+ 0 - 129
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/PatientDeviceLogService.java

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

+ 0 - 653
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/PatientDeviceService.java

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

+ 0 - 1934
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/device/PatientHealthIndexService.java

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

+ 0 - 3411
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/FollowUpService.java

@ -1,3411 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.followup;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.afterDiagnosis.dao.followup.FollowUpDao;
import com.yihu.jw.afterDiagnosis.dao.followup.FollowupContentDao;
import com.yihu.jw.afterDiagnosis.dao.followup.FollowupDrugsDao;
import com.yihu.jw.afterDiagnosis.dao.followup.FollowupSignDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.elasticsearch.ElasticSearch7Helper;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.entity.followup.FollowupContent;
import com.yihu.jw.entity.followup.FollowupDrugs;
import com.yihu.jw.entity.followup.FollowupSign;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.followup.FollowupContentESDO;
import com.yihu.jw.followup.OlderPeopleHealthCheckRecordES;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.dict.service.WlyyHospitalSysDictService;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import com.yihu.jw.util.file.FileUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 随访服务
 *
 * @author hzp add 2016-12-07
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class FollowUpService {
    private static Logger logger = LoggerFactory.getLogger(FollowUpService.class);
    //统计随访类型
    public static String[] FOLLOWUP_TYPE = {"1","2","3","10","22"};
    //随访类别,多类别“,”分割【1.高血压 2.糖尿病 3.肿瘤 4.精神分裂症 5.产后 6.新生儿 7.严重精神病 8.80岁以上老人 9.肺结核】
    public static String[] FOLLOWUP_CLASS = {"1","2","1,2","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"};
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private FollowUpDao followupDao;
    @Autowired
    private FollowupContentDao followupContentDao;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private WlyyHospitalSysDictService hospitalSysDictService;
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FollowupDrugsDao followupDrugsDao;
    @Value("${es.index.FollowUp}")
    private String esIndex;
    @Autowired
    private ElasticSearch7Helper elasticSearch7Helper;
    @Resource(name="restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private FollowupSignDao followupSignDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private VisitDetailService visitDetailService;
    @Value("${fastDFS.fastdfs_file_url}")
    private String imgUrlDomain;
//    @Autowired
//    private RehabilitationManageService rehabilitationManageService;
    /**
     * 转译随访信息
     */
    private Map<String, String> getFollowupDetail(Followup followup) throws Exception {
        Map<String, String> re = new HashMap<>();
        //患者信息
        String patientCode = followup.getPatientCode();
        BasePatientDO patient = patientDao.findById(patientCode).orElse(null);
        if (patient != null) {
            re.put("patientCode", patientCode);
            re.put("patientName", patient.getName());
            re.put("idcard", patient.getIdcard());
            String mobile = patient.getMobile();
            if (StringUtils.isEmpty(mobile)) {
                mobile = patient.getMobileRemarks();
            }
            re.put("mobile", mobile);
            re.put("sex", String.valueOf(patient.getSex()));
            re.put("birthday", DateUtil.dateToStrLong(patient.getBirthday()));
            re.put("photo", patient.getPhoto());
        } else {
            throw new ServiceException("查找不到用户信息!");
        }
        re.put("id", String.valueOf(followup.getId()));
        re.put("followupNo", followup.getFollowupNo());
        re.put("followupDate", DateUtil.dateToStrLong(followup.getFollowupDate()));
        re.put("followupNextDate", DateUtil.dateToStrLong(followup.getFollowupNextDate()));
        //随访方式转译
        re.put("followupType", followup.getFollowupType());
        String followupTypeName = hospitalSysDictService.getDictValue("FOLLOWUP_WAY_DICT", followup.getFollowupType());
        re.put("followupTypeName", followupTypeName);
        //随访类别转译
        String followupClass = followup.getFollowupClass();
        re.put("followupClass", followupClass);
        String followupClassName = hospitalSysDictService.getDictValue("FOLLOWUP_CLASS_DICT", followup.getFollowupClass());
        if (StringUtils.isNoneBlank(followupClass) && followupClass.contains(",")) {
            String[] followupClassArray = followupClass.split(",");
            followupClassName = "";
            for (int i = 0; i < followupClassArray.length; i++) {
                followupClassName += hospitalSysDictService.getDictValue("FOLLOWUP_CLASS_DICT", followupClassArray[i]);
                if (i != followupClassArray.length - 1) {
                    followupClassName += ",";
                }
            }
        }
        re.put("followupClassName", followupClassName);
        //随访管理状态转译
        re.put("followupManagerStatus", followup.getFollowupManagerStatus());
        String followupManagerStatusName = hospitalSysDictService.getDictValue("FOLLOWUP_MANAGER_STATUS", followup.getFollowupManagerStatus());
        re.put("followupManagerStatusName", followupManagerStatusName);
        re.put("doctorCode", followup.getDoctorCode());
        re.put("doctorName", followup.getDoctorName());
        re.put("orgCode", followup.getOrgCode());
        re.put("orgName", followup.getOrgName());
        re.put("dataFrom", followup.getDataFrom());
        re.put("status", followup.getStatus());
        re.put("followupContentPhone", followup.getFollowupContentPhone());
        re.put("createTime", DateUtil.dateToStrLong(followup.getCreateTime()));
        re.put("creater", followup.getCreater());
        re.put("prescriptionCode",followup.getPrescriptionCode());
        return re;
    }
    /**
     * 获取医生随访列表
     */
    public List<Map<String, Object>> getListByDoctor(String doctorCode, String startTime, String endTime) throws Exception {
        List<Map<String, Object>> re = new ArrayList<>();
        Map<String, Map<String, Object>> temp = new HashMap<>();
        List<Followup> list = followupDao.findByDoctor(doctorCode, DateUtil.strToDate(startTime), DateUtil.strToDate(endTime));
        if (list != null && list.size() > 0) {
            for (Followup followup : list) {
                String date = DateUtil.dateToStrShort(followup.getFollowupDate());
                Map<String, String> map = getFollowupDetail(followup);
                if (temp.containsKey(date)) {
                    Map<String, Object> vo = temp.get(date);
                    vo.put("num", Integer.parseInt(vo.get("num").toString()) + 1);
                    ((List<Map<String, String>>) vo.get("list")).add(map);
                    temp.put(date, vo);
                } else {
                    Map<String, Object> vo = new HashMap<>();
                    List<Map<String, String>> list1 = new ArrayList<>();
                    vo.put("date", date);
                    vo.put("num", 1);
                    list1.add(map);
                    vo.put("list", list1);
                    temp.put(date, vo);
                }
            }
            for (Map<String, Object> map : temp.values()) {
                re.add(map);
            }
        }
        return re;
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param teamCode
     * @param page
     * @param pageSize
     * @param type     类型:0全部,1计划,2记录
     * @return
     */
    public JSONArray getListByPatientAndTeam(String patient,String doctor, Long teamCode, int page, int pageSize, String type) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = PageRequest.of(page, pageSize, sort);
        Page<Object> result = null;
        if (StringUtils.isBlank(type)) {
            result = followupDao.findByPatientAndTeam(patient, teamCode, doctor, pageRequest);
        } else if ("1".equals(type)) {
            //已经开始的就是记录
            result = followupDao.findPlanByPatientAndTeam(patient,teamCode, doctor, pageRequest);
        } else if ("2".equals(type)) {
            //未开始的就是计划
            result = followupDao.findRecordByPatientAndTeam(patient, teamCode,doctor, pageRequest);
        } else {
        }
        JSONArray array = new JSONArray();
        if (result != null && result.getContent().size() > 0) {
            Map<String, String> dictMap = new HashMap<>();
            Map<String, String> statusMap = new HashMap<>();
            Map<String, String> mngStatusMap = new HashMap<>();
            List<WlyyHospitalSysDictDO> dicts = wlyyHospitalSysDictDao.findByDictName("FOLLOWUP_WAY_DICT");
            List<WlyyHospitalSysDictDO> mngDicts = wlyyHospitalSysDictDao.findByDictName("FOLLOWUP_MANAGER_STATUS");
            if (dicts != null) {
                for (WlyyHospitalSysDictDO dict : dicts) {
                    dictMap.put(dict.getDictCode(), dict.getDictValue());
                }
            }
            if (mngDicts != null) {
                for (WlyyHospitalSysDictDO dict : mngDicts) {
                    mngStatusMap.put(dict.getDictCode(), dict.getDictValue());
                }
            }
            statusMap.put("0", "取消");
            statusMap.put("1", "已完成");
            statusMap.put("2", "未开始");
            statusMap.put("3", "进行中");
            for (Object obj : result) {
                JSONObject followup = new JSONObject();
                Object[] objArr = (Object[]) obj;
//              返回值增加居民信息
                BasePatientDO patientDetail = patientDao.findByIdAndDel(patient,"1");
                followup.put("patientName", patientDetail.getName() != null ? patientDetail.getName() : "");
                followup.put("photo", patientDetail.getPhoto() != null ? patientDetail.getPhoto() : "");
                followup.put("sex", patientDetail.getSex() != null ? patientDetail.getSex() : "");
                followup.put("birthday", patientDetail.getBirthday() != null ? patientDetail.getBirthday() : "");
                followup.put("id", objArr[15]);
                followup.put("followupNo", objArr[16]);
                followup.put("doctorCode", objArr[0]);
                followup.put("doctorName", objArr[1]);
                followup.put("doctorPhoto", objArr[2]);
                followup.put("followupType", objArr[3] == null ? "" : objArr[3]);
                followup.put("followupTypeName", objArr[3] == null ? "" : (dictMap.get(objArr[3].toString()) != null ? dictMap.get(objArr[3].toString()) : ""));
                followup.put("followupClass", objArr[4] == null ? "" : objArr[4]);
                if (objArr[4] == null) {
                    followup.put("followupClassName", "");
                } else {
                    if (objArr[4].toString().equals("1")) {
                        followup.put("followupClassName", "高血压");
                    } else if (objArr[4].toString().equals("2")) {
                        followup.put("followupClassName", "糖尿病");
                    } else if (objArr[4].toString().equals("1,2")) {
                        followup.put("followupClassName", "高血压,糖尿病");
                    } else {
                    }
                }
                followup.put("status", objArr[5] == null ? "" : objArr[5]);
                followup.put("statusName", objArr[5] == null ? "" : (statusMap.get(objArr[5].toString()) != null ? statusMap.get(objArr[5].toString()) : ""));
                followup.put("createTime", objArr[6] != null ? DateUtil.dateToStrLong((Date) objArr[6]) : "");
                followup.put("updateTime", objArr[7] != null ? DateUtil.dateToStrLong((Date) objArr[7]) : "");
                followup.put("followupManagerStatus", objArr[8] == null ? "" : objArr[8]);
                followup.put("followupManagerStatusName", objArr[8] == null ? "" : (mngStatusMap.get(objArr[8].toString()) != null ? mngStatusMap.get(objArr[8].toString()) : ""));
                followup.put("creatorCode", objArr[9]);
                followup.put("creatorName", objArr[10]);
                followup.put("creatorPhoto", objArr[11]);
                followup.put("followupDate", objArr[12] != null ? DateUtil.dateToStrLong((Date) objArr[12]) : "");
                followup.put("followupPlanDate", objArr[13] != null ? DateUtil.dateToStrLong((Date) objArr[13]) : "");
                followup.put("followupNextDate", objArr[14] != null ? DateUtil.dateToStrLong((Date) objArr[14]) : "");
                followup.put("prescriptionCode", objArr[17]);
                followup.put("type", objArr[18]);
                followup.put("total", result.getTotalElements());
                array.put(followup);
            }
        }
        return array;
    }
    /**
     * 查询居民随访列表
     *
     * @param patient
     * @param page
     * @param pageSize
     * @param type     类型:0全部,1计划,2记录
     * @return
     */
    public JSONArray getListByPatient(String patient,  int page, int pageSize, String type) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = PageRequest.of(page, pageSize, sort);
        Page<Object> result = null;
        if (StringUtils.isBlank(type)) {
            result = followupDao.findByPatient(patient, pageRequest);
        } else if ("1".equals(type)) {
            //已经开始的就是记录
            result = followupDao.findPlanByPatient(patient, pageRequest);
        } else if ("2".equals(type)) {
            //未开始的就是计划
            result = followupDao.findRecordByPatient(patient, pageRequest);
        } else {
        }
        JSONArray array = new JSONArray();
        if (result != null && result.getContent().size() > 0) {
            Map<String, String> dictMap = new HashMap<>();
            Map<String, String> statusMap = new HashMap<>();
            Map<String, String> mngStatusMap = new HashMap<>();
            List<WlyyHospitalSysDictDO> dicts = wlyyHospitalSysDictDao.findByDictCode("FOLLOWUP_WAY_DICT");
            List<WlyyHospitalSysDictDO> mngDicts = wlyyHospitalSysDictDao.findByDictCode("FOLLOWUP_MANAGER_STATUS");
            if (dicts != null) {
                for (WlyyHospitalSysDictDO dict : dicts) {
                    dictMap.put(dict.getDictCode(), dict.getDictValue());
                }
            }
            if (mngDicts != null) {
                for (WlyyHospitalSysDictDO dict : mngDicts) {
                    mngStatusMap.put(dict.getDictCode(), dict.getDictValue());
                }
            }
            statusMap.put("0", "取消");
            statusMap.put("1", "已完成");
            statusMap.put("2", "未开始");
            statusMap.put("3", "进行中");
            for (Object obj : result) {
                JSONObject followup = new JSONObject();
                Object[] objArr = (Object[]) obj;
//              返回值增加居民信息
                BasePatientDO patientDetail = patientDao.findByIdAndDel(patient,"1");
                followup.put("patientName", patientDetail.getName() != null ? patientDetail.getName() : "");
                followup.put("photo", patientDetail.getPhoto() != null ? patientDetail.getPhoto() : "");
                followup.put("sex", patientDetail.getSex() != null ? patientDetail.getSex() : "");
                followup.put("birthday", patientDetail.getBirthday() != null ? patientDetail.getBirthday() : "");
                followup.put("id", objArr[15]);
                followup.put("followupNo", objArr[16]);
                followup.put("doctorCode", objArr[0]);
                followup.put("doctorName", objArr[1]);
                followup.put("doctorPhoto", objArr[2]);
                followup.put("followupType", objArr[3] == null ? "" : objArr[3]);
                followup.put("followupTypeName", objArr[3] == null ? "" : (dictMap.get(objArr[3].toString()) != null ? dictMap.get(objArr[3].toString()) : ""));
                followup.put("followupClass", objArr[4] == null ? "" : objArr[4]);
                if (objArr[4] == null) {
                    followup.put("followupClassName", "");
                } else {
                    if (objArr[4].toString().equals("1")) {
                        followup.put("followupClassName", "高血压");
                    } else if (objArr[4].toString().equals("2")) {
                        followup.put("followupClassName", "糖尿病");
                    } else if (objArr[4].toString().equals("1,2")) {
                        followup.put("followupClassName", "高血压,糖尿病");
                    } else {
                    }
                }
                followup.put("status", objArr[5] == null ? "" : objArr[5]);
                followup.put("statusName", objArr[5] == null ? "" : (statusMap.get(objArr[5].toString()) != null ? statusMap.get(objArr[5].toString()) : ""));
                followup.put("createTime", objArr[6] != null ? DateUtil.dateToStrLong((Date) objArr[6]) : "");
                followup.put("updateTime", objArr[7] != null ? DateUtil.dateToStrLong((Date) objArr[7]) : "");
                followup.put("followupManagerStatus", objArr[8] == null ? "" : objArr[8]);
                followup.put("followupManagerStatusName", objArr[8] == null ? "" : (mngStatusMap.get(objArr[8].toString()) != null ? mngStatusMap.get(objArr[8].toString()) : ""));
                followup.put("creatorCode", objArr[9]);
                followup.put("creatorName", objArr[10]);
                followup.put("creatorPhoto", objArr[11]);
                followup.put("followupDate", objArr[12] != null ? DateUtil.dateToStrLong((Date) objArr[12]) : "");
                followup.put("followupPlanDate", objArr[13] != null ? DateUtil.dateToStrLong((Date) objArr[13]) : "");
                followup.put("followupNextDate", objArr[14] != null ? DateUtil.dateToStrLong((Date) objArr[14]) : "");
                followup.put("prescriptionCode", objArr[17]);
                followup.put("total", result.getTotalElements());
                array.put(followup);
            }
        }
        return array;
    }
    /**
     * 获取医生随访列表(创建者)
     */
    public List<Map<String, String>> getListByCreater(String doctorCode, String startTime, String endTime, String page, String pageSize) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        // 排序
        Sort sort = Sort.by(Sort.Direction.ASC, "followupDate");
        // 分页信息
        int pageInt = Integer.valueOf(page) - 1;
        int pageSizeInt = Integer.valueOf(pageSize);
        Pageable pageRequest = PageRequest.of(pageInt, pageSizeInt, sort);
        List<Followup> list = followupDao.findByCreater(doctorCode, DateUtil.strToDate(startTime), DateUtil.strToDate(endTime), pageRequest);
        if (list != null && list.size() > 0) {
            for (Followup followup : list) {
                Map<String, String> map = getFollowupDetail(followup);
                re.add(map);
            }
        }
        return re;
    }
    /**
     * 新增随访计划(批量)
     */
    @Transactional
    public Iterable<Followup> addFollowupPlan(String doctorCode, String patientCode, String data) throws Exception {
        //批量随访计划
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Map.class);
        List<Map<String, String>> list = objectMapper.readValue(data, javaType);
        if (list != null && list.size() > 0) {
            //获取患者信息
            BasePatientDO patient = patientDao.findByIdAndDel(patientCode,"1");
            if (patient == null) {
                throw new ServiceException("获取不到用户信息!");
            }
            List<Followup> followupPlan = new ArrayList<>();
            for (Map<String, String> map : list) {
                //获取医生信息
                BaseDoctorDO doctor = doctorDao.findByIdAndDel(map.get("doctor"));
                if (doctor == null) {
                    throw new ServiceException("获取不到医生信息!");
                }
                Followup followup = new Followup();
                followup.setFollowupType(map.get("type"));
                Date date = DateUtil.strToDate(map.get("date"));
                followup.setFollowupDate(date);
                followup.setFollowupPlanDate(date);
                followup.setDoctorCode(doctor.getId());
                followup.setDoctorName(doctor.getName());
//                followup.setOrgCode(doctor.getHospital());
//                followup.setOrgName(doctor.getHospitalName());
                followup.setPatientCode(patientCode);
                followup.setPatientName(patient.getName());
                followup.setIdcard(patient.getIdcard());
                followup.setDataFrom("2");//数据来源 1基卫 2APP
                followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
                followup.setCreateTime(new Date());
                followup.setCreater(doctorCode);
                followup.setFollowupClass(map.get("followupClass"));
                followup.setType(Integer.parseInt(map.get("type1")));
                followup.setSignType(2);
                followupPlan.add(followup);
            }
            return followupDao.saveAll(followupPlan);
        }
        return null;
    }
    /**
     * 新增随访计划(单个)
     */
    public Followup addFollowupPlanNew(String doctorCode, String patientCode, JSONObject data,String dataJson) throws Exception {
        //获取患者信息
        BasePatientDO patient = patientDao.findById(patientCode).orElse(null);
        if (patient == null) {
            throw new ServiceException("获取不到用户信息!");
        }
        //获取医生信息
        BaseDoctorDO doctor = doctorDao.findByIdAndDel(data.getString("doctor"));
        if (doctor == null) {
            throw new ServiceException("获取不到医生信息!");
        }
        Followup followup = new Followup();
        followup.setFollowupType(data.getString("type"));
        Date date = DateUtil.strToDate(data.getString("date"));
        followup.setFollowupDate(date);
        followup.setFollowupPlanDate(date);
        followup.setDoctorCode(doctor.getId());
        followup.setDoctorName(doctor.getName());
//        followup.setOrgCode(doctor.getHospital());
//        followup.setOrgName(doctor.getHospitalName());
        followup.setPatientCode(patientCode);
        followup.setPatientName(patient.getName());
        followup.setIdcard(patient.getIdcard());
        followup.setDataFrom("2");//数据来源 1基卫 2APP
        followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
        followup.setCreateTime(new Date());
        followup.setCreater(doctorCode);
        followup.setFollowupClass(data.getString("followupClass"));
        followup.setType(Integer.parseInt(data.get("type1").toString()));
        followup.setSignType(2);
        followup = followupDao.save(followup);
//        rehabilitationManageService.updateRelationCodeByDetailId(data.getString("id"),followup.getId()+"");
//        rehabilitationManageService.saveRehabilitationOperateRecord(dataJson);
        return followup;
    }
    /**
     * 编辑随访计划
     */
    public void editFollowupPlan(String doctorCode, String id, String date, String followupType) throws Exception {
        Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            Date followupDate = DateUtil.strToDate(date);
            followup.setFollowupDate(followupDate);
            followup.setFollowupPlanDate(followupDate);
            followup.setFollowupType(followupType);
            followup.setCreater(doctorCode);
            followupDao.save(followup);
        } else {
            throw new ServiceException("查找不到该随访!");
        }
    }
    /**
     * 开始随访记录
     */
    public Followup startFollowup(String id, String followupNo, String date, String followupType, String followupClass, String followupManagerStatus, String plandate, String prescriptioncode) throws Exception {
        Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            if(followup.getStatus().compareTo("2") == 0) {
                followup.setFollowupNo(followupNo);
                followup.setFollowupDate(DateUtil.strToDate(date));
                //计划下次随访时间--huangwenjie.2017.10.19
                if (StringUtils.isNoneBlank(plandate)) {
                    followup.setFollowupNextDate(DateUtil.strToDate(plandate));
                    Followup nextFollowup = new Followup();
                    nextFollowup.setDataFrom(followup.getDataFrom());
                    nextFollowup.setStatus("2");
                    nextFollowup.setFollowupType(followupType);
                    nextFollowup.setFollowupNo(followup.getFollowupNo());
                    nextFollowup.setFollowupDate(DateUtil.strToDate(plandate));
                    nextFollowup.setFollowupPlanDate(DateUtil.strToDate(plandate));
                    nextFollowup.setJwdoctorCode(followup.getJwdoctorCode());
                    nextFollowup.setJworgCode(followup.getJworgCode());
                    nextFollowup.setOrgCode(followup.getOrgCode());
                    nextFollowup.setOrgName(followup.getOrgName());
                    nextFollowup.setCreater(followup.getCreater());
                    nextFollowup.setSignCode(followup.getSignCode());
                    nextFollowup.setAdminTeamCode(followup.getAdminTeamCode());
                    nextFollowup.setFollowupClass(followupClass);
                    nextFollowup.setFollowupManagerStatus(followupManagerStatus);
                    nextFollowup.setPatientName(followup.getPatientName());
                    nextFollowup.setPatientCode(followup.getPatientCode());
                    nextFollowup.setCreateTime(new Date());
                    nextFollowup.setUpdateTime(new Date());
                    nextFollowup.setDoctorCode(followup.getDoctorCode());
                    nextFollowup.setDoctorName(followup.getDoctorName());
                    nextFollowup.setIdcard(followup.getIdcard());
                    nextFollowup.setSignType(followup.getSignType());
                    nextFollowup.setType(1);
                    followupDao.save(nextFollowup);
                }
                followup.setFollowupType(followupType);
                followup.setFollowupClass(followupClass);
                followup.setFollowupManagerStatus(followupManagerStatus);
                followup.setStatus("3");  //状态 0取消 1已完成 2未开始 3进行中
                followup.setPrescriptionCode(prescriptioncode);
                Followup f = followupDao.save(followup);
                System.out.println("随访状态status" + f.getStatus());
                return f;
            }
            return followup;
        } else {
            throw new ServiceException("查找不到该随访!");
        }
    }
    /**
     * 如果今日没有计划中的随访计划,则将随访消息设成已操作
     * @param doctor
     */
    public void getNotStartFollowup(String doctor, Date followupPlanDate) {
        //如果计划随访日已经没有未开始状态的随访计划,就将该天的随访消息设成已操作状态
        String now = DateUtil.dateToStrShort(followupPlanDate);
        String start = now + " 00:00:00";
        String end = now + " 23:59:59";
        String sql = "select count(1) count from wlyy_followup where status = 2 and (followup_class is null or followup_class in (1,2)) " +
                "and followup_plan_date>='" + start + "' and followup_plan_date<='" + end + "'and  doctor_code = '" +doctor +"'";
        //获取所有未执行随访计划
        Long followupToday = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println("计划中随访:" + followupToday);
        if(followupToday == 0){
            messageDao.setMessageOverByType(doctor, 4, DateUtil.strToDateLong(start), DateUtil.strToDateLong(end));
        }
    }
    /**
     * 新增临时随访记录(返回ID)
     */
    public String addFollowup(String doctorCode, String patientCode, String date, String followupType, String followupClass, String followupManagerStatus, String plandate, String prescriptioncode,Integer type) throws Exception {
        String re = "";
        //获取医生信息
        BaseDoctorDO doctor = doctorDao.findByIdAndDel(doctorCode);
        if (doctor == null) {
            throw new ServiceException("查找不到医生信息!");
        }
        //获取患者信息
        BasePatientDO patient = patientDao.findById(patientCode).orElse(null);
        if (patient == null) {
            throw new ServiceException("查找不到居民信息!");
        }
        Followup followup = new Followup();
        Date followDate = DateUtil.strToDate(date);
        followup.setFollowupDate(followDate);
        followup.setFollowupPlanDate(followDate);
        followup.setDoctorCode(doctorCode);
        followup.setDoctorName(doctor.getName());
//        followup.setOrgCode(doctor.getHospital());
//        followup.setOrgName(doctor.getHospitalName());
        followup.setPatientCode(patientCode);
        followup.setPatientName(patient.getName());
        followup.setIdcard(patient.getIdcard());
        followup.setFollowupType(followupType);
        followup.setFollowupClass(followupClass);
        followup.setFollowupManagerStatus(followupManagerStatus);
        followup.setDataFrom("2");//数据来源 1基卫 2APP
        followup.setStatus("2");     //状态 0取消 1已完成 2未开始 3进行中
        followup.setCreateTime(new Date());
        followup.setCreater(doctorCode);
        followup.setSignType(2);
        if (type!=null&&type!=0){
            followup.setType(type);
        }
        //如果有填入续方CODE,则添加续方关联--huangwenjie.2017.11.02
        if (StringUtils.isNotBlank(prescriptioncode)) {
            followup.setPrescriptionCode(prescriptioncode);
        }
        //计划下次随访时间--ysj.2017.10.26
        if (StringUtils.isNoneBlank(plandate)) {
            followup.setFollowupNextDate(DateUtil.strToDate(plandate));
            Followup nextFollowup = new Followup();
            nextFollowup.setDataFrom(followup.getDataFrom());
            nextFollowup.setStatus("2");
            nextFollowup.setFollowupType(followupType);
            nextFollowup.setFollowupNo(followup.getFollowupNo());
            nextFollowup.setFollowupDate(DateUtil.strToDate(plandate));
            nextFollowup.setFollowupPlanDate(DateUtil.strToDate(plandate));
            nextFollowup.setJwdoctorCode(followup.getJwdoctorCode());
            nextFollowup.setJworgCode(followup.getJworgCode());
            nextFollowup.setOrgCode(followup.getOrgCode());
            nextFollowup.setOrgName(followup.getOrgName());
            nextFollowup.setCreater(followup.getCreater());
            nextFollowup.setSignCode(followup.getSignCode());
            nextFollowup.setAdminTeamCode(followup.getAdminTeamCode());
            nextFollowup.setFollowupClass(followupClass);
            nextFollowup.setFollowupManagerStatus(followupManagerStatus);
            nextFollowup.setPatientName(followup.getPatientName());
            nextFollowup.setPatientCode(followup.getPatientCode());
            nextFollowup.setCreateTime(new Date());
            nextFollowup.setUpdateTime(new Date());
            nextFollowup.setDoctorCode(followup.getDoctorCode());
            nextFollowup.setDoctorName(followup.getDoctorName());
            nextFollowup.setIdcard(followup.getIdcard());
            nextFollowup.setSignType(followup.getSignType());
            nextFollowup.setType(type);
            followupDao.save(nextFollowup);
        }
        followupDao.save(followup);
        re = String.valueOf(followup.getId());
        return re;
    }
    /**
     * 取消随访计划
     */
    public void cancelFollowupPlan(String id) throws Exception {
        Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            followup.setStatus("0");  //状态 0取消 1已完成 2未开始 3进行中
            followupDao.save(followup);
        } else {
            throw new ServiceException("查找不到该随访计划!");
        }
    }
    /**
     * 完成随访记录,并上传随访记录
     */
    public void finishFollowup(String id) throws Exception {
         Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            followup.setStatus("1");  //状态 0取消 1已完成 2未开始 3进行中
            followup = followupDao.save(followup);
            
            //随访完成,增加随访状态完成的标记
//            Prescription prescription = prescriptionDao.findByCode(followup.getPrescriptionCode());
//            if(prescription  != null){
//                prescription.setViewSuifang(1);
//                prescriptionDao.save(prescription);
//            }
        } else {
            throw new ServiceException("查找不到该随访计划!");
        }
    }
    /*********************************** 随访详情 *******************************************************************/
    /**
     * 获取面访项目列表
     */
    public Map<String, String> getFollowup(String id) throws Exception {
        Map<String, String> re = new HashMap<>();
         Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            re = getFollowupDetail(followup);
        } else {
            throw new ServiceException("查找不到该随访信息");
        }
        return re;
    }
    /**
     * 获取面访项目列表
     */
    public List<Map<String, String>> getFollowupProject(String id) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        //获取已填写的面访项目
//        List<String> project = followupContentDao.findProjectByFollowupId(Long.valueOf(id));
        //修改为通过ES查询---2017.11.01--huangwenjie
        List<String> project = esfindProjectByFollowupId(id);
        //获取所有面访项目
        List<WlyyHospitalSysDictDO> dictList = hospitalSysDictService.findByDictName("FOLLOWUP_PROJECT");
        if (dictList != null && dictList.size() > 0) {
            for (WlyyHospitalSysDictDO dict : dictList) {
                Map<String, String> map = new HashMap<>();
                String code = dict.getDictCode();
                map.put("projectCode", code);
                map.put("projectName", dict.getDictValue());
                if (project != null && project.contains(code)) {
                    map.put("status", "1"); //已填写
                } else {
                    map.put("status", "0");//未填写
                }
                re.add(map);
            }
        }
        return re;
    }
    /**
     * 获取面访项目数据
     */
    public Map<String, String> getFollowupProjectData(String id, String followupProject) throws Exception {
        Map<String, String> re = new HashMap<>();
        List<FollowupContent> dataList = followupContentDao.findByFollowupIdAndFollowupProject(Long.valueOf(id), followupProject);
        for (FollowupContent item : dataList) {
            re.put(item.getFollowupKey(), item.getFollowupValue());
        }
        return re;
    }
    /**
     * 保存面访项目数据
     */
    @Transactional
    public void saveFollowupProjectData(String id, String followupProject, String followupProjectData) throws Exception {
        List<FollowupContent> dataList = followupContentDao.findByFollowupIdAndFollowupProject(Long.valueOf(id), followupProject);
        //删除原有记录
        followupContentDao.deleteAll(dataList);
        Map<String, String> data = objectMapper.readValue(followupProjectData, Map.class);
        if (data != null && data.keySet().size() > 0) {
            List<FollowupContent> newList = new ArrayList<>();
            for (String key : data.keySet()) {
                FollowupContent item = new FollowupContent();
                item.setFollowupId(Long.valueOf(id));
                item.setFollowupProject(followupProject);
                item.setFollowupKey(key);
                item.setFollowupValue(data.get(key));
                item.setCreateTime(new Date());
                newList.add(item);
            }
            followupContentDao.saveAll(newList);
        }
    }
    /*********************************** 电话随访 *****************************************************************/
    /**
     * 获取电话随访内容
     */
    public String getFollowupPhone(String id) throws Exception {
        String re = "";
         Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            re = followup.getFollowupContentPhone();
        } else {
            throw new ServiceException("查找不到该随访计划!");
        }
        return re;
    }
    /**
     * 记录电话随访内容
     */
    public void saveFollowupPhone(String id, String content) throws Exception {
         Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
        if (followup != null) {
            followup.setFollowupContentPhone(content);
            followupDao.save(followup);
        } else {
            throw new ServiceException("查找不到该随访计划!");
        }
    }
    /*************************************** 上次随访 ********************************************/
    /**
     * 获取上次随访
     */
    public Map<String, String> getLastFollowup(String doctor, String patient, String followClass) throws Exception {
        Map<String, String> re = new HashMap<>();
        //获取医生团队成员
        String[] doctors = new String[]{doctor};
        //获取最新的随访记录
        Followup followup = followupDao.findLastFollowup(doctors, patient, followClass);
        if (followup != null) {
            re.put("id", String.valueOf(followup.getId()));
            re.put("followupDate", DateUtil.dateToStrShort(followup.getFollowupDate()));
        } else {
            re = null;
        }
        return re;
    }
    /**
     * 获取上次随访
     */
    public void copyFollowup(Long id, Long fromId) throws Exception {
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", fromId))
        );
        List<FollowupContentESDO> list = elasticSearch7Helper.search(esIndex,searchSourceBuilder,FollowupContentESDO.class);
        if (list != null && list.size() > 0) {
            List<FollowupContentESDO> copyList = new ArrayList<>();
            for (FollowupContentESDO item : list) {
                FollowupContentESDO copyItem = new FollowupContentESDO();
                BeanUtils.copyProperties(item, copyItem);
                copyItem.setId(null);
                copyItem.setFollowup_id(id + "");
                copyItem.setCreate_time(new Date());
                copyList.add(copyItem);
            }
            elasticSearch7Helper.save(esIndex, copyList);
        }
    }
    /**************************************** 随访计划消息 ******************************************/
    /**
     * 每日发送随访计划提醒消息
     */
    @Transactional
    public void sendMessage(String date) {
        try {
            String start = date + " 00:00:00";
            String end = date + " 23:59:59";
            String sql = "select doctor_code,count(1) count from wlyy_followup where status not in ('0','1') and followup_plan_date>='" + start + "' and followup_plan_date<='" + end + "' group by doctor_code";
            //获取所有未执行随访计划
            List<Map<String, Object>> followupToday = jdbcTemplate.queryForList(sql);
            if (followupToday != null) {
                List<SystemMessageDO> list = new ArrayList<>();
                for (Map<String, Object> map : followupToday) {
                    String doctor = String.valueOf(map.get("doctor_code"));
                    String count = String.valueOf(map.get("count"));
                    // 添加签约消息
                    String title = "随访计划提醒";
                    String content = "您今日有" + count + "个随访计划待处理";
                    SystemMessageDO message = new SystemMessageDO();
                    message.setCode(CommonUtil.getCode());
                    message.setCreateTime(new Date());
                    message.setContent(content);
                    message.setIsRead("0");//设置未读
                    message.setReceiver(doctor);//设置接受医生的code
                    message.setSender("system");//设置发送的用户
                    message.setTitle(title);
                    message.setType("4");//随访计划提醒
                    message.setReadonly(1);//是否只读消息
                    list.add(message);
                }
                messageDao.saveAll(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * ES 保存随访记录详情
     *
     * @author huangwenjie
     * @date 2017/11/1 14:57
     */
    @Transactional
    public void esSaveFollowupProjectData(String id, String followupProject, String followupProjectData) throws Exception {
        try {
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", id))
                            .must(QueryBuilders.matchQuery("followup_project", followupProject))
            );
            FollowupContentESDO followupContentESDO = elasticSearch7Helper.searchOne(esIndex,searchSourceBuilder,FollowupContentESDO.class);
            List<FollowupContentESDO> dataList = new ArrayList<>();
            if(followupContentESDO != null){
                dataList.add(followupContentESDO);
                //删除原有记录
                this.esDeleteFollowUpContent(dataList);
            }
            //保存新的随访详情信息
            List<FollowupContentESDO> newdatalist = new ArrayList<>();
            followupContentESDO = new FollowupContentESDO();
            followupContentESDO = JSON.parseObject(followupProjectData, FollowupContentESDO.class);
            followupContentESDO.setFollowup_id(id);
            followupContentESDO.setFollowup_project(followupProject);
            followupContentESDO.setCreate_time(new Date());
            newdatalist.add(followupContentESDO);
            elasticSearch7Helper.save(esIndex, newdatalist);
            //如果该随访是已完成的,则添加随访信息上传映射,上传到基卫
             Followup followup = followupDao.findById(Long.valueOf(id)).orElse(null);
            if ("1".equals(followup.getStatus())) {
                //随访完成,增加随访状态完成的标记
//                Prescription prescription = prescriptionDao.findByCode(followup.getPrescriptionCode());
//                if(prescription  != null){
//                    prescription.setViewSuifang(1);
//                    prescriptionDao.save(prescription);
//                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * ES获取面访项目数据
     */
    public FollowupContentESDO esGetFollowupProjectData(String id, String followupProject) throws Exception {
        FollowupContentESDO followupContentESDO = null;
        try {
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", id))
                            .must(QueryBuilders.matchQuery("followup_project", followupProject))
            );
            followupContentESDO = elasticSearch7Helper.searchOne(esIndex,searchSourceBuilder,FollowupContentESDO.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return followupContentESDO;
    }
    /**
     * ES 删除随访详情信息
     *
     * @author huangwenjie
     * @date 2017/11/1 15:17
     */
    public void esDeleteFollowUpContent(List<FollowupContentESDO> datalist) throws Exception {
        try {
            BulkRequest bulkRequest = new BulkRequest();
            bulkRequest.timeout(TimeValue.timeValueSeconds(10));
            for (FollowupContentESDO obj : datalist) {
                bulkRequest.add(new DeleteRequest(esIndex)
                        .id(obj.getId()));
            }
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            logger.info("delete data count:" + datalist.size());
            logger.info(bulkResponse.buildFailureMessage());
            logger.info("delete flag:" + !bulkResponse.hasFailures());
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * ES获取面访项目数据列表
     *
     * @author huangwenjie
     * @date 2017/11/1 19:41
     */
    public List<String> esfindProjectByFollowupId(String id) throws Exception {
        List<String> resultList = new ArrayList<>();
        try {
            //根据随访ID、分类ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", id))
            );
            List<FollowupContentESDO> followupContentESDOList = elasticSearch7Helper.search(esIndex,searchSourceBuilder,FollowupContentESDO.class);
            if (!followupContentESDOList.isEmpty()) {
                for (FollowupContentESDO followupContentESDO : followupContentESDOList) {
                   
                    if("2".equals(followupContentESDO.getFollowup_project())){
                        if(StringUtils.isNotBlank(followupContentESDO.getBP_D()) && StringUtils.isNotBlank(followupContentESDO.getBP_U())){
                            resultList.add(followupContentESDO.getFollowup_project());
                        }
                        if(StringUtils.isNotBlank(followupContentESDO.getBLOOD_SUGAR()) && StringUtils.isNotBlank(followupContentESDO.getBLOOD_SUGAR_TYPE())){
                            resultList.add(followupContentESDO.getFollowup_project());
                        }
                    }else if("3".equals(followupContentESDO.getFollowup_project())){
                        //判断血糖必填
                        if(StringUtils.isNotBlank(followupContentESDO.getBS_FPG()) ||
                                StringUtils.isNotBlank(followupContentESDO.getNO_BS_FPG())||
                                    StringUtils.isNotBlank(followupContentESDO.getRANDOM_BLOOD_SUGAR())){
                            resultList.add(followupContentESDO.getFollowup_project());
                        }
                    }else{
                        resultList.add(followupContentESDO.getFollowup_project());
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return resultList;
    }
    /**
     * ES获取面访项目数据详情
     *
     * @author huangwenjie
     * @date 2017/11/1 19:41
     */
    public List<FollowupContentESDO> esfindFollowUpContestsByFollowupId(String id) throws Exception {
        List<FollowupContentESDO> followupContentESDOList = new ArrayList<>();
        try {
            //根据随访ID、分类ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", id))
            );
            followupContentESDOList = elasticSearch7Helper.search(esIndex,searchSourceBuilder,FollowupContentESDO.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return followupContentESDOList;
    }
    /**
     * 根据续方CODE获取随访记录信息
     *
     * @param prescriptionCode
     * @return
     */
    public String getFollowupByPrescriptionCode(String prescriptionCode) {
        Followup followup = followupDao.getFollowupByPrescriptionCode(prescriptionCode);
        String jsonString = JSON.toJSONString(followup);
        return jsonString;
    }
    /**
     * 获取随访详情记录分类记录数
     *
     * @param followupid
     * @param type
     * @return
     */
    public int getfollowupcontent(String followupid, String type) throws Exception {
        int count = 0;
        String[] typelist = null;
        if (type.contains(",")) {
            typelist = type.split(",");
        } else {
            typelist = new String[]{type};
        }
        for (String typekey : typelist) {
            if (!"drug".equals(type)) {
                FollowupContentESDO followupContentESDO = this.esGetFollowupProjectData(followupid, typekey);
                if (followupContentESDO != null) {
                    count++;
                }
            } else {
                //获取用药记录
                List<FollowupDrugs> drugsList = followupDrugsDao.findByFollowupId(Long.valueOf(followupid));
                if (!drugsList.isEmpty()) {
                    count = count + drugsList.size();
                }
            }
        }
        return count;
    }
    
    /**
     * 检查随访记录是否可完成
     * @param followupid
     * @return
     */
    public boolean checkfollowupcompleted(String followupid)  throws Exception {
        boolean result = true;
    
        List<FollowupContentESDO> eslist = this.esfindFollowUpContestsByFollowupId(followupid);
    
        if (!eslist.isEmpty()) {
            for (FollowupContentESDO followupContentESDO : eslist) {
            
                if("2".equals(followupContentESDO.getFollowup_project())){
                    //判断血压必填
                    if(StringUtils.isBlank(followupContentESDO.getBP_D()) || StringUtils.isBlank(followupContentESDO.getBP_U())){
                        return false;
                    }
                }else if("3".equals(followupContentESDO.getFollowup_project())){
                    //判断血糖必填
                    if(StringUtils.isBlank(followupContentESDO.getBS_FPG()) &&
                            StringUtils.isBlank(followupContentESDO.getNO_BS_FPG()) &&
                            StringUtils.isBlank(followupContentESDO.getRANDOM_BLOOD_SUGAR())){
                        return false;
                    }
                }else if("5".equals(followupContentESDO.getFollowup_project())){
                    //判断评价
                    if(StringUtils.isBlank(followupContentESDO.getDIA_FOLLOWUP_TYPE_CODE()) &&
                            StringUtils.isBlank(followupContentESDO.getHYP_FOLLOWUP_TYPE_CODE())){
                        return false;
                    }
                }else{}
            
            }
        }
        
        return result;
    }
    
    /**
     * 保存随访详情
     * @param followupContentESDO
     * @throws Exception
     */
    public void esSaveFollowupContentESDAO(FollowupContentESDO followupContentESDO)throws Exception{
        try {
            List<FollowupContentESDO> dataList = new ArrayList<>();
            if(followupContentESDO != null){
                dataList.add(followupContentESDO);
                //删除原有记录
                this.esDeleteFollowUpContent(dataList);
            }
            elasticSearch7Helper.save(esIndex, dataList);
        
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public void updateFollowup(Long id){
        Followup followup = followupDao.findById(id).orElse(null);
        followup.setStatus("1");
        followupDao.save(followup);
    }
    //============================上门访视相关接口================================================
    public Map<String,Object> findFollowupByMonth(String doctor,String patient,String followupClass,String patientName,String startTime,String endTime,String flag,Integer type1,String status)throws Exception{
        String sqlList = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate," +
                " wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName," +
                "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard," +
                "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode," +
                "wf.prescription_code as prescriptionCode,wf.type";
        String sql = " from wlyy_followup wf ";
        sql+= " where 1=1 and wf.status !=0";
        if(!org.apache.commons.lang.StringUtils.isEmpty(doctor)){
            sql+=" and wf.doctor_code = '"+doctor+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(patient)){
            sql+=" and wf.patient_code = '"+patient+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(followupClass)){
            sql+=" and wf.followup_class = '"+followupClass+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(patientName)){
            sql+=" and wf.patient_name like '%"+patientName+"%'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(startTime)){
            sql+=" and wf.followup_plan_date >='"+startTime+"'";
        }
        if (StringUtils.isNotBlank(status)){
            sql+=" and wf.status ='"+status+"' ";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(endTime)){
            Date currentTime = DateUtil.strToDate(endTime + " 23:59:59");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            sql+=" and wf.followup_plan_date <='"+dateString+"'";
        }
        if (type1!=null&&type1!=0){
            sql+=" and wf.type ="+type1;
        }
        if(flag==null){
            flag="0";
        }
        if(flag.equals("1")&&flag!=null){
            sql+=" and wf.followup_class in(5,6,7,8,9)";
        }
        if(flag.equals("2")&&flag!=null){
            sql+=" and (wf.followup_class in(1,2,3,4,11,12,13,14,15,16,17,18) or wf.followup_class IS NULL)";
        }
        sql+=" order by wf.followup_plan_date desc";
        List<Followup> followups = jdbcTemplate.query(sqlList+sql,new BeanPropertyRowMapper(Followup.class));
        //按时间分组
        Map<String,Object> date = sortFollowupByDate(followups);
        //统计每一天完成数与计划数目
        if(date!=null&&date.size()>0){
            for(String key : date.keySet()){
                //获取一天的数据
                Map<String,Object> d = (Map<String,Object>)date.get(key);
                // 获取一天随访数据
                List<Followup> dateFollowups = (List<Followup>)d.get("followups");
                //统计一天各项纬度指标
                List<Map<String,Object>> statistics = new ArrayList<>();
                for(String type : FOLLOWUP_TYPE){
                    for(String cls:FOLLOWUP_CLASS ){
                        //统计单条
                        Map<String,Object> fs = sortFollowupList(type,cls,dateFollowups);
                        Integer count = (Integer)fs.get("count");
                        if(count!=0){
                            statistics.add(fs);
                        }
                    }
                }
                d.put("statistics",statistics);
            }
        }
        return date;
    }
    public Map<String,Object> sortFollowupByDate(List<Followup> followups){
        //按时间分组
        Map<String,Object> date = new HashedMap();
        if(followups!=null&&followups.size()>0){
            Iterator it = followups.iterator();
            while (it.hasNext()){
                Followup followup = (Followup)it.next();
                //1.获取日期分组
                Map<String,Object> dateFollows = (Map<String,Object>)date.get(DateUtil.dateToStr(followup.getFollowupPlanDate(),"yyyy-MM-dd"));
                //判断随访时间是否已经创建分组
                if(dateFollows!=null&&dateFollows.size()>0){
                    //同一天时间已经有分组则加入list
                    List<Followup> list = (List<Followup>)dateFollows.get("followups");
                    list.add(followup);
                }else{
                    //同一天的时间没有该分组则创建这天的随访计划List
                    Map<String,Object> newdateFollow = new HashedMap();
                    List<Followup> dateFollowups = new ArrayList<>();
                    dateFollowups.add(followup);
                    newdateFollow.put("followups",dateFollowups);
                    date.put(DateUtil.dateToStr(followup.getFollowupPlanDate(),"yyyy-MM-dd"),newdateFollow);
                }
            }
        }
        return date;
    }
    public Map<String,Object> sortFollowupList(String followupType,String followupClass,List<Followup> followups){
        //统计完成数
        Integer compeleCount = 0;
        //总数
        Integer count = 0;
        //迭代数组
        List<Followup> rs = new ArrayList<>();
        if(followups!=null&&followups.size()>0){
            Iterator it = followups.iterator();
            while (it.hasNext()){
                Followup followup = (Followup)it.next();
                //判断随访类型与类别
                if(followupClass.equals(followup.getFollowupClass())&& followupType.equals(followup.getFollowupType())){
                    rs.add(followup);
                    if("1".equals(followup.getStatus())){
                        compeleCount++;
                    }
                    //删除迭代器中元素
                    //it.remove();
                }
            }
            //设置总数
            count = rs.size();
        }
        Map<String,Object> mapFollow =new HashedMap();
        mapFollow.put("followupType",followupType);
        mapFollow.put("followupClass",followupClass);
        mapFollow.put("compeleCount",compeleCount);
        mapFollow.put("count",count);
        return mapFollow;
    }
    /**
     * 获取随访计划
     * @param doctor
     * @param startTime
     * @param endTime
     * @return
     * @throws Exception
     */
    public List<Followup> findFollowupList(String followIds,String doctor,String patient,String followupClass,String patientName,String startTime,String endTime,String flag,Integer type,String status)throws Exception {
        //1.查找时间段中所有计划中的随访
        String sqlList = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate," +
                " wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName," +
                "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard," +
                "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode," +
                "wf.prescription_code as prescriptionCode,wf.age,wf.sex,wf.mobile,wf.idcard_encrypt AS idcardEncrypt,wf.type" +
                "";
        String sql = " from wlyy_followup wf ";
        sql+= " where 1=1 and wf.status !=0";
        if (StringUtils.isNotBlank(followIds)){
            List<String> followId = Arrays.asList(followIds.split(","));
            String wfIds = followId.stream().map(String::valueOf).collect(Collectors.joining("','"));
            sql+=" and wf.id in ('"+wfIds+"') ";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(doctor)){
            sql+=" and wf.doctor_code = '"+doctor+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(patient)){
            sql+=" and wf.patient_code = '"+patient+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(followupClass)){
            sql+=" and wf.followup_class = '"+followupClass+"'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(patientName)){
            sql+=" and wf.patient_name like '%"+patientName+"%'";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(startTime)){
            sql+=" and wf.followup_plan_date >='"+startTime+"'";
        }
        if (StringUtils.isNotBlank(status)){
            sql+=" and wf.status ='"+status+"' ";
        }
        if(!org.apache.commons.lang.StringUtils.isEmpty(endTime)){
            Date currentTime = DateUtil.strToDate(endTime + " 23:59:59");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            sql+=" and wf.followup_plan_date <='"+dateString+"'";
        }
        if(flag==null){
            flag="0";
        }
        if (type!=null&&type!=0){
            sql+=" AND  wf.type ="+type;
        }
        if(flag.equals("1")&&flag!=null){
            sql+=" and wf.followup_class in(5,6,7,8,9)";
        }
        if(flag.equals("2")&&flag!=null){
            sql+=" and (wf.followup_class in(1,2,3,4,11,12,13,14,15,16,17,18) or wf.followup_class IS NULL)";
        }
        sql+=" order by wf.followup_plan_date desc";
        List<Followup> followupAll = jdbcTemplate.query(sqlList+sql,new BeanPropertyRowMapper(Followup.class));
        List<Followup> followups = new ArrayList<>();
        for(Followup followup:followupAll){
            BasePatientDO patient1 = patientDao.findById(followup.getPatientCode()).orElse(null);
            int age = IdCardUtil.getAgeForIdcard(followup.getIdcard());
            patient1.setAge(age);
            List<Map<String,Object>> map = findPatientLabel(followup.getPatientCode());
            followup.setPatient(patient1);
            followup.setFollowupLabelPatient(map);
            followups.add(followup);
        }
        return followups;
    }
    /**
     * 获取随访标签列表带居民数
     * @return
     */
    public List<Map<String,Object>> findLabelListWithCount(){
        List<Map<String,Object>> rs = findFollowupLabel();
        if(rs!=null&& rs.size()>0){
            for(Map<String,Object> map:rs){
                String labelCode = (String)map.get("LableCode");
                map.put("count",findPatientFollowLabelCount(labelCode));
            }
        }
        return rs;
    }
    /**
     * 获取随访标签列表
     * @return
     */
    public List<Map<String,Object>> findFollowupLabel(){
        String sql=" SELECT " +
                " l.label_code AS LableCode, " +
                " l.label_name AS labelName " +
                " FROM " +
                " wlyy_followup_label l " +
                " ORDER BY " +
                " l.sort " +
                " ASC ";
        List<Map<String, Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
    /**
     * 计算随访标签人数
     * @param labelCode
     * @return
     */
    public Long findPatientFollowLabelCount(String labelCode){
        String sql =" SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wlyy_followup_label l " +
                " JOIN wlyy_followup_label_patient p ON l.label_code = p.label_code " +
                " WHERE " +
                " l.label_code ='"+labelCode+"'";
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        return count;
    }
    /**
     * 获取随访居民
     * @param namekey
     * @param labelCode
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    public Map<String,Object> findFollowUpPatient(String namekey,String doctor,String labelCode,Integer page,Integer size)throws Exception{
        String totalSql = " SELECT " +
                " DISTINCT p.id " +
                " FROM " +
                " wlyy_followup_label l " +
                " JOIN wlyy_followup_label_patient lp ON l.label_code = lp.label_code " +
                " JOIN base_patient p ON lp.patient = p.id " +
                " WHERE " +
                " 1=1 ";
        if(StringUtils.isNotBlank(namekey)){
            totalSql +=" AND p.name LIKE '%"+namekey+"%'";
        }
        if(StringUtils.isNotBlank(labelCode)){
            totalSql +=" AND lp.label_code ='"+labelCode+"' ";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Integer count = 0;
        if (rstotal != null && rstotal.size() > 0) {
            count = rstotal.size();
        }
        String sql = " SELECT DISTINCT" +
                " p.id, " +
                " p.`name`, " +
                " p.sex, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.photo" +
                " FROM " +
                " wlyy_followup_label l " +
                " JOIN wlyy_followup_label_patient lp ON l.label_code = lp.label_code " +
                " JOIN base_patient p ON lp.patient = p.id " +
                " WHERE " +
                " 1=1 ";
        if(StringUtils.isNotBlank(namekey)){
            sql +=" AND p.name LIKE '%"+namekey+"%'";
        }
        if(StringUtils.isNotBlank(labelCode)){
            sql +=" AND lp.label_code ='"+labelCode+"' ";
        }
        sql +=" limit " + (page-1)*size +"," + size;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        //设置标签
        if(list!=null&&list.size()>0){
            for(Map<String,Object> map:list){
                String patient = (String)map.get("code");
                map.put("labels",findPatientLabel(patient));
            }
        }
        Map<String,Object> rs = new HashedMap();
        rs.put("total",count);
        //统计随访数目
        rs.put("list",findPatientFollowCount(list,doctor));
        return rs;
    }
    /**
     * 统计当前医生的居民计划数与完成数
     * @param list
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> findPatientFollowCount(List<Map<String,Object>> list,String doctor)throws Exception{
        if(list!=null&&list.size()>0){
            for(Map<String,Object> map:list){
                String patient = (String)map.get("code");
                List<Followup> followups = followupDao.findAllPatientPlan(patient,doctor);
                //统计数目
                Integer count = 0;
                Integer compeleCount =0;
                if(followups!=null&&followups.size()>0){
                    count = followups.size();
                    for(Followup followup:followups){
                        if("1".equals(followup.getStatus())){
                            compeleCount++;
                        }
                    }
                    map.put("count",count);
                    map.put("compeleCount",compeleCount);
                    map.put("followups",followups);
                }else{
                    map.put("count",count);
                    map.put("compeleCount",compeleCount);
                    map.put("followups",followups);
                }
            }
        }
        return list;
    }
    /**
     * 获取居民详情
     * @param patient
     * @return
     */
    public Map<String,Object> findPatientInfo(String patient){
        String sql = " SELECT " +
                " p.`name`, " +
                " p.id, " +
                " p.sex, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.photo, " +
                " l.label_code AS labelCode, " +
                " l.label_name AS labelName, " +
                " p.address," +
                " p.idcard," +
                " p.mobile" +
                " FROM " +
                " wlyy_followup_label l " +
                " JOIN wlyy_followup_label_patient lp ON l.label_code = lp.label_code " +
                " JOIN base_patient p ON lp.patient = p.id " +
                " WHERE " +
                " p.id = '"+patient+ "'";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        if(rs!=null&&rs.size()>0){
            return rs.get(0);
        }
        return null;
    }
    /**
     * 获取居民随访列表
     * @param patient
     * @param doctor
     * @return
     * @throws Exception
     */
    public List<Followup> findPatientFollowList(String patient,String doctor)throws Exception{
        List<Followup> followups = followupDao.findAllPatientPlan(patient,doctor);
        return followups;
    }
    /**
     * 获取居民随访列表
     * @param patient
     * @param doctor
     * @return
     * @throws Exception
     */
    public List<Followup> findPatientFollowListByCondition(String patient,String doctor,String followupType,String followupClass,String type,
                                                           String status,String startDate,String endDate)throws Exception{
        StringBuilder sql = new StringBuilder("select * from wlyy_followup a where 1=1 ");
        if (StringUtils.isNotBlank(patient)){
            sql.append(" and a.patient_code ='"+patient+"' ");
        }
        if (StringUtils.isNotBlank(doctor)){
            sql.append(" and a.doctor_code ='"+doctor+"' ");
        }
        if (StringUtils.isNotBlank(followupType)){
            sql.append(" and a.followup_type ='"+followupType+"' ");
        }
        if (StringUtils.isNotBlank(followupClass)){
            sql.append(" and a.followup_class in("+followupClass+") ");
        }
        if (StringUtils.isNotBlank(type)){
            sql.append(" and a.type ='"+type+"' ");
        }
        if (StringUtils.isNotBlank(status)){
            sql.append(" and a.status ='"+status+"' ");
        }
        if (StringUtils.isNotBlank(startDate)){
            sql.append(" and a.followup_date >='"+startDate+"' ");
        }
        if (StringUtils.isNotBlank(endDate)){
            sql.append(" and a.followup_date <='"+endDate+"' ");
        }
        sql.append("order by a.followup_date desc");
        List<Followup> followups = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper<>(Followup.class));
        for (Followup tmp:followups){
            //随访方式
            sql = new StringBuilder("select dict_value from wlyy_hospital_sys_dict where dict_name='FOLLOWUP_WAY_DICT'  and dict_code ='"+tmp.getFollowupType()+"'");
            tmp.setFollowupTypeName(jdbcTemplate.queryForObject(sql.toString(),String.class));
            //随访类别
            String followupClassTmp = tmp.getFollowupClass();
            sql =new StringBuilder("select GROUP_CONCAT(\n" +
                    "  dict_value SEPARATOR ','\n" +
                    " ) AS followupClassName from wlyy_hospital_sys_dict where dict_name='FOLLOWUP_CLASS_DICT' ");
            sql.append(" and dict_code in ('").append(followupClassTmp.replace(",","','")).append("')");
            tmp.setFollowupClassName(jdbcTemplate.queryForObject(sql.toString(),String.class));
        }
        return followups;
    }
    /**
     * 创建随访
     * @param jsonFollowup
     * @return
     * @throws Exception
     */
    public Followup saveFollowup(String jsonFollowup)throws Exception{
        Followup followup =  objectMapper.readValue(jsonFollowup,Followup.class);
        //访视添加居民信息
        if(StringUtils.isBlank(followup.getPatientName()) && StringUtils.isBlank(followup.getIdcard())) {
            BasePatientDO p = patientDao.findById(followup.getPatientCode()).orElse(null);
            followup.setPatientName(p.getName());
            followup.setIdcard(p.getIdcard());
        }
        List<Date> dateList = followupDao.findFollowupDateList(followup.getDoctorCode(),followup.getPatientCode());
        Date prior = null;
        for (Date date : dateList) {
            try {
                if (prior == null) {
                    prior = date;
                } else {
                    if(prior.after(date)) {
                        prior = date;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Set statusList = followupDao.findStatusList(followup.getDoctorCode(), followup.getPatientCode());
        if (statusList.size() == 1 && statusList.iterator().next().equals("2")) {
            return followupDao.save(followup);
        }
        if (prior != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sdf1 = sdf.format(followup.getFollowupDate());
            String sdf2 = sdf.format(prior);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date followupDate = df.parse(sdf1);
            Date priorDate = df.parse(sdf2);
            Boolean b = null;
            if (followup.getId() != null) {
                b = this.isFirstTimeFollowup(followup.getDoctorCode(), followup.getPatientCode(), "9", followup.getId().intValue());
                List<Followup> followupList = followupDao.findFollowupList(followup.getDoctorCode(), followup.getPatientCode());
                if (b == true && followupList.size() >= 2) {
                    String two = sdf.format(followupList.get(1).getFollowupDate());
                    Date twoDate = df.parse(two);
                    if (followupDate.getTime() >= twoDate.getTime()) {
                        throw new ServiceException("第一次访视时间不能晚于第二次访视时间!");
                    }
                } else if (priorDate.getTime() >= followupDate.getTime()) {
                    throw new ServiceException("随访时间不能早于第一次随访时间!");
                } else {
                    return followupDao.save(followup);
                }
            } else if (priorDate.getTime() >= followupDate.getTime()) {
                throw new ServiceException("随访时间不能早于第一次随访时间!");
            } else {
                return followupDao.save(followup);
            }
        }
        return followupDao.save(followup);
    }
    public Followup delFollowup(Long followupId)throws Exception{
        Followup followup = followupDao.findById(followupId).orElse(null);
        List<Followup> followupList = followupDao.findFollowupList(followup.getDoctorCode(),followup.getPatientCode());
        if(followupList.size()>=2){
            if(followupList.get(1)!=null&&followupList.get(1).getStatus().equals("1")){
                throw new ServiceException("当前状态不可删除!");
            }
        }
        followupDao.deleteById(followupId);
        return followup;
    }
    /**
     * 获取随访详情
     * @param followupId
     * @return
     */
    public Followup findFollowupInfo(Long followupId){
        Followup followup = followupDao.findById(followupId).orElse(null);
        BasePatientDO patient = patientDao.findById(followup.getPatientCode()).orElse(null);
        followup.setPhoto(patient.getPhoto());
        followup.setPatient(patient);
        return followup;
    }
    /**
     * 随访签到
     * @param jsonSign
     * @return
     * @throws Exception
     */
    public Boolean saveFollowupSign(String jsonSign)throws Exception{
        FollowupSign followupSign = objectMapper.readValue(jsonSign,FollowupSign.class);
        List<FollowupSign> sign = followupSignDao.findByFollowupIdAndDel(followupSign.getFollowupId(),0);
        if(sign!=null&&sign.size()>0){
            //做更新操作
            for(FollowupSign s:sign){
                s.setDel(1);
            }
            followupSignDao.saveAll(sign);
        }else{
            //修改随访状态为进行中
            Followup followup = followupDao.findById(followupSign.getFollowupId()).orElse(null);
            followup.setStatus("3");
        }
        //新增更新随访状态
        followupSign.setCode(CommonUtil.getCode());
        followupSign.setCreateTime(new Date());
        followupSign.setDel(0);
        followupSignDao.save(followupSign);
        return true;
    }
    /**
     * 修改签到记录
     * @param jsonSign
     * @return
     * @throws Exception
     */
    public Boolean updateFollowupSign(String jsonSign)throws Exception{
        //重新签到
        FollowupSign followupSign = objectMapper.readValue(jsonSign,FollowupSign.class);
        FollowupSign sign = followupSignDao.findById(followupSign.getId()).orElse(null);
        sign.setDel(1);
        followupSignDao.save(sign);
        FollowupSign newSign = new FollowupSign();
        newSign.setCode(CommonUtil.getCode());
        newSign.setFollowupId(sign.getFollowupId());
        newSign.setAddress(sign.getAddress());
        newSign.setType(sign.getType());
        newSign.setCreateTime(new Date());
        newSign.setDoctor(sign.getDoctor());
        newSign.setDoctorName(sign.getDoctorName());
        newSign.setImg(sign.getImg());
        newSign.setLatitude(sign.getLatitude());
        newSign.setLongitude(sign.getLongitude());
        newSign.setDel(0);
        followupSignDao.save(newSign);
        return true;
    }
    /**
     * 门牌地址解析
     * @param url
     * @return
     * @throws Exception
     */
    public String urlAnalysis(String url)throws Exception{
        url.replace("http://www.fjadd.com/addr?","http://www.fjadd.com/shhyy/addr_list.jsp?showtp=1&system");
        Document doc = Jsoup.connect(url).get();
        String html = doc.toString();
        int start = html.indexOf("href=\"");
        int end = html.indexOf("\"}");
        int ed = url.indexOf("com");
        String ym = url.substring(0,ed+3);
        String path = html.substring(start+6,end);
        Document d = Jsoup.connect(ym+path).get();
        String address = d.select("div.dzksfd1_lz2").eq(0).text()+d.select("div.dzksfd1_lz2").eq(1).text();
        logger.info("url:"+url+" path:"+ym+path+" adress:"+address);
        return address;
    }
    /**
     * 随访完成
     * @param followupId
     * @return
     */
    public Boolean updateFollowStatus(Long followupId,Integer isFlag)throws Exception{
        Followup followup = followupDao.findById(followupId).orElse(null);
        followup.setStatus("1");
        followupDao.save(followup);
        return true;
    }
    /**
     * 签到详细
     * @param followupId
     * @return
     */
    public FollowupSign findByFollowupId(Long followupId){
        List<FollowupSign> sign = followupSignDao.findByFollowupIdAndDel(followupId,0);
        if(sign!=null&&sign.size()>0){
            return sign.get(0);
        }
        return null;
    }
    public List<Map<String,Object>> findPatientLabel(String patient){
        String sql ="SELECT " +
                " pl.label_code AS labelCode, " +
                " pl.label_name AS labelName " +
                " FROM " +
                " wlyy_followup_label_patient pl " +
                " WHERE " +
                " pl.patient = '"+patient+"'";
        List<Map<String,Object>> label = jdbcTemplate.queryForList(sql);
        return label;
    }
    public Boolean isFirstTimeFollowup(String doctor,String patient,String followupClass,Integer followupId){
        //按时间升序取第一条
        String sql =" SELECT " +
                " f.id, " +
                " f.create_time " +
                " FROM " +
                " wlyy_followup f " +
                " WHERE " +
//                " f.doctor_code = '"+doctor+"' AND " +
                "  f.patient_code = '"+patient+"' " +
                " AND f.followup_class = '"+followupClass+"' and f.status != 0 " +
                " ORDER BY " +
                " f.followup_date " +
                " ASC " +
                " LIMIT 0,1";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
            int id = (Integer)list.get(0).get("id");
            //如果与第一条的id不等,则非第一次
            if(!(id==followupId)){
                return false;
            }
        }
        return true;
    }
    //============================上门访视相关接口end================================================
    //============================高血压糖尿病表单整合start================================================
    /**
     * ES获取表单项目数据
     */
    public FollowupContentESDO esGetFollowupProjectDataList(String id, String followupProject) throws Exception {
        FollowupContentESDO followupContentESDO = null;
        try {
            //根据随访ID、分类ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            if(StringUtils.isNotBlank(followupProject)) {
                searchSourceBuilder.query(
                        new BoolQueryBuilder()
                                .must(QueryBuilders.matchQuery("followup_id", id))
                                .must(QueryBuilders.matchQuery("followup_project", followupProject))
                );
            }else {
                searchSourceBuilder.query(
                        new BoolQueryBuilder()
                                .must(QueryBuilders.matchQuery("followup_id", id))
                                .mustNot(QueryBuilders.existsQuery("followup_project"))
                );
            }
            followupContentESDO = elasticSearch7Helper.searchOne(esIndex,searchSourceBuilder,FollowupContentESDO.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return followupContentESDO;
    }
    /**
     * ES 保存随访记录详情
     *
     * @author huangwenjie
     * @date 2017/11/1 14:57
     */
    @Transactional
    public void saveAllFollowupProjectData(String id, String followupProjectData) throws Exception {
        try {
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", id))
            );
            List<FollowupContentESDO> followupContentESDOS = elasticSearch7Helper.search(esIndex,searchSourceBuilder,FollowupContentESDO.class);
            List<FollowupContentESDO> dataList = new ArrayList<>();
            if(followupContentESDOS != null){
                dataList.addAll(followupContentESDOS);
                //删除原有记录
                this.esDeleteFollowUpContent(dataList);
            }
            //保存新的随访详情信息
            List<FollowupContentESDO> newdatalist = new ArrayList<>();
            FollowupContentESDO followupContentESDO = new FollowupContentESDO();
            followupContentESDO = JSON.parseObject(followupProjectData, FollowupContentESDO.class);
            followupContentESDO.setFollowup_id(id);
            followupContentESDO.setCreate_time(new Date());
            newdatalist.add(followupContentESDO);
            elasticSearch7Helper.save(esIndex, newdatalist);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    public File writeWordFile(List<Long> orderId, HttpServletResponse response) throws Exception {
        String zipFileName = "入户访视详情";
        long time = System.currentTimeMillis();
        String exportConclusionList = time+"exportList";
        String path = this.getClass().getResource("/").getPath() + exportConclusionList;
        File file = new File(path);
        // 删除文件夹、文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        System.out.println("创建文件夹时间:"+sdf.format(new Date()));
        if (file.exists()) {
            if (file != null){
                CommonUtil.deleteFolder(file);
                file.mkdir();
            }else {
                file.delete();
                file.mkdir();
            }
        }else {
            file.mkdir();
        }
        int j =1;
        long doorStart = System.currentTimeMillis();
        long feeDetailStart = System.currentTimeMillis();
        long feeDetailEnd = System.currentTimeMillis();
        System.out.println("feeDetail用时:"+(feeDetailEnd-feeDetailStart)/1000);
        System.out.println("开始生成Word:"+sdf.format(new Date()));
        for (int i = 0; i < orderId.size(); i++) {
            try {
                Long followId = orderId.get(i);
                Followup followup = followupDao.findById(followId).orElse(null);
                if (null==followup){
                    continue;
                }
                if (!"8".equals(followup.getFollowupClass())){
                    continue;
                }
                String fileName = "入户访视详情_"+followup.getPatientName()+"_"+followId+".doc";;
                j = j + 1;
//            fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = java.net.URLEncoder.encode(fileName,"UTF-8");
                fileName = java.net.URLDecoder.decode(fileName,"UTF-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes(), "iso-8859-1"));
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                String pathName = this.getClass().getResource("/").getPath() + "health_examination.mht";
                Document doc = Jsoup.parse(new File(pathName), "UTF-8");
                String html = this.handleHealthExamData(doc, orderId.get(i),followup);
                if (StringUtils.isNotBlank(html)){
                    BufferedWriter bw = new BufferedWriter(new FileWriter(path+"/"+fileName));//创建的文件
                    bw.write(html);
                    bw.close();
                    File zipFile = new File(path.replace(exportConclusionList, "") + zipFileName + ".zip");
                    if (zipFile.exists()) {
                        zipFile.delete();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                continue;
            }
        }
        System.out.println("Word生成结束:"+sdf.format(new Date()));
        // 打包文件夹
        if (FileUtil.fileToZip(path, path.replace(exportConclusionList, ""), zipFileName)) {
            return new File(path.replace(exportConclusionList, "") + zipFileName + ".zip");
        } else {
            return null;
        }
    }
    public String handleHealthExamData(Document doc, Long orderId,Followup followup) throws Exception {
        String html = doc.toString();
        //根据随访ID获取随访记录详情
        OlderPeopleHealthCheckRecordES olderPeopleHealthCheckRecord = visitDetailService.getOlderPeopleHealthCheckRecord(orderId+"",null);
        if (null==olderPeopleHealthCheckRecord){
            return null;
        }
        html = html.replace("${patientName}", null==olderPeopleHealthCheckRecord.getName()?"":olderPeopleHealthCheckRecord.getName());
        html = html.replace("${idcard}", null==olderPeopleHealthCheckRecord.getIdcard()?"":olderPeopleHealthCheckRecord.getIdcard());
        html = html.replace("${number}", null==olderPeopleHealthCheckRecord.getNumber()?"":olderPeopleHealthCheckRecord.getNumber());
        html = html.replace("${duty}", null==olderPeopleHealthCheckRecord.getDuty()?" ":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getDuty()));
        html = html.replace("${responsibility_doctor_name}",olderPeopleHealthCheckRecord.getResponsibility_doctor_name());
        if (null==olderPeopleHealthCheckRecord.getSymptom()){
            html = html.replace("${symptom}"," ");
        }else {
            StringBuilder symptomName = new StringBuilder();
            String symptom =  olderPeopleHealthCheckRecord.getSymptom();
            String[] symptoms = symptom.split(",");
            for (String tmp:symptoms){
                symptomName.append(getSymptomName(tmp));
            }
            html = html.replace("${symptom}",symptomName.toString());
        }
        html = html.replace("${symptom_other}",olderPeopleHealthCheckRecord.getSymptom_other());
        /**一般状况**/
        html = html.replace("${temperature}",null==olderPeopleHealthCheckRecord.getTemperature()?" ":olderPeopleHealthCheckRecord.getTemperature()+"");
        html = html.replace("${pulse_frequency}",olderPeopleHealthCheckRecord.getPulse_frequency());
        html = html.replace("${breath_frequency}",olderPeopleHealthCheckRecord.getBreath_frequency());
        html = html.replace("${blood_pressure_left_low}",null==olderPeopleHealthCheckRecord.getBlood_pressure_left_low()?" ":olderPeopleHealthCheckRecord.getBlood_pressure_left_low()+"");
        html = html.replace("${blood_pressure_left_high}",null==olderPeopleHealthCheckRecord.getBlood_pressure_left_high()?" ":olderPeopleHealthCheckRecord.getBlood_pressure_left_high()+"");
        html = html.replace("${blood_pressure_right_low}",null==olderPeopleHealthCheckRecord.getBlood_pressure_right_low()?" ":olderPeopleHealthCheckRecord.getBlood_pressure_right_low()+"");
        html = html.replace("${blood_pressure_right_high}",null==olderPeopleHealthCheckRecord.getBlood_pressure_right_high()?" ":olderPeopleHealthCheckRecord.getBlood_pressure_right_high()+"");
        html = html.replace("${height}",null==olderPeopleHealthCheckRecord.getHeight()?" ":olderPeopleHealthCheckRecord.getHeight()+"");
        html = html.replace("${weight}",null==olderPeopleHealthCheckRecord.getWeight()?" ":olderPeopleHealthCheckRecord.getWeight()+"");
        html = html.replace("${waistline}",null==olderPeopleHealthCheckRecord.getWaistline()?" ":olderPeopleHealthCheckRecord.getWaistline()+"");
        html = html.replace("${BMI}",null==olderPeopleHealthCheckRecord.getBMI()?" ":olderPeopleHealthCheckRecord.getBMI()+"");
        if (null==olderPeopleHealthCheckRecord.getHealth_status()){
            html = html.replace("${health_status}"," ");
        }else {
            Integer health_status = olderPeopleHealthCheckRecord.getHealth_status();
            switch (health_status){
                case 1:html = html.replace("${health_status}","满意");break;
                case 2:html = html.replace("${health_status}","基本满意");break;
                case 3:html = html.replace("${health_status}","说不清");break;
                case 4:html = html.replace("${health_status}","不太满意");break;
                case 5:html = html.replace("${health_status}","不满意");break;
                default:html = html.replace("${health_status}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getSelfcare_ability()){
            html = html.replace("${selfcare_ability}"," ");
        }else {
            Integer selfcare_ability = olderPeopleHealthCheckRecord.getSelfcare_ability();
            switch (selfcare_ability){
                case 1:html = html.replace("${selfcare_ability}","可自理(0~3)分");break;
                case 2:html = html.replace("${selfcare_ability}","轻度依赖(4~8)分");break;
                case 3:html = html.replace("${selfcare_ability}","中度依赖(9~18)分");break;
                case 4:html = html.replace("${selfcare_ability}","不能自理(≥19)分");break;
                default:html = html.replace("${selfcare_ability}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getCognitive_function()){
            html = html.replace("${cognitive_function}"," ");
        }else {
            Integer cognitiveFunction = olderPeopleHealthCheckRecord.getCognitive_function();
            switch (cognitiveFunction){
                case 1:html = html.replace("${cognitive_function}","粗筛阴性");break;
                case 2:html = html.replace("${cognitive_function}","粗筛阳性");break;
                default:html = html.replace("${cognitive_function}"," ");break;
            }
        }
        html = html.replace("${cognitive_function_score}",null==olderPeopleHealthCheckRecord.getCognitive_function_score()?" ":olderPeopleHealthCheckRecord.getCognitive_function_score()+"");
        if (null==olderPeopleHealthCheckRecord.getEmotional_state()){
            html = html.replace("${emotional_state}"," ");
        }else {
            Integer emotionalState = olderPeopleHealthCheckRecord.getEmotional_state();
            switch (emotionalState){
                case 1:html = html.replace("${emotional_state}","粗筛阴性");break;
                case 2:html = html.replace("${emotional_state}","粗筛阳性");break;
                default:html = html.replace("${emotional_state}"," ");break;
            }
        }
        html = html.replace("${emotional_state_score}",null==olderPeopleHealthCheckRecord.getEmotional_state_score()?" ":olderPeopleHealthCheckRecord.getEmotional_state_score()+"");
        /**体育锻炼**/
        if (null==olderPeopleHealthCheckRecord.getExercise_frequency()){
            html = html.replace("${exercise_frequency}"," ");
        }else {
            Integer exerciseFrequency = olderPeopleHealthCheckRecord.getExercise_frequency();
            switch (exerciseFrequency){
                case 1:html = html.replace("${exercise_frequency}","每天");break;
                case 2:html = html.replace("${exercise_frequency}","每周一次以上");break;
                case 3:html = html.replace("${exercise_frequency}","偶尔");break;
                case 4:html = html.replace("${exercise_frequency}","不锻炼");break;
                default:html = html.replace("${exercise_frequency}"," ");break;
            }
        }
        html = html.replace("${exercise_time}",null==olderPeopleHealthCheckRecord.getExercise_time()?" ":olderPeopleHealthCheckRecord.getExercise_time()+"");
        html = html.replace("${sustain_exercise_time}",null==olderPeopleHealthCheckRecord.getSustain_exercise_time()?" ":olderPeopleHealthCheckRecord.getSustain_exercise_time()+"");
        html = html.replace("${exercise_type}",null==olderPeopleHealthCheckRecord.getExercise_type()?" ":olderPeopleHealthCheckRecord.getExercise_type()+"");
        /**饮食习惯**/
        if (null==olderPeopleHealthCheckRecord.getDietary_habit()){
            html = html.replace("${dietary_habit}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getDietary_habit();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="荤素均衡 ";break;
                    case "2":valueStrTmp+="荤食为主 ";break;
                    case "3":valueStrTmp+="素食为主 ";break;
                    case "4":valueStrTmp+="嗜盐 ";break;
                    case "5":valueStrTmp+="嗜油 ";break;
                    case "6":valueStrTmp+="嗜糖 ";break;
                }
            }
            html = html.replace("${dietary_habit}",valueStrTmp);
        }
        /**吸烟情况**/
        if (null==olderPeopleHealthCheckRecord.getSmoking_state()){
            html = html.replace("${smoking_state}"," ");
        }else {
            Integer smokingState = olderPeopleHealthCheckRecord.getSmoking_state();
            switch (smokingState){
                case 1:html = html.replace("${smoking_state}","从不吸烟");break;
                case 2:html = html.replace("${smoking_state}","已戒烟");break;
                case 3:html = html.replace("${smoking_state}","吸烟");break;
                default:html = html.replace("${smoking_state}"," ");break;
            }
        }
        html = html.replace("${smoking_daily}",null==olderPeopleHealthCheckRecord.getSmoking_daily()?" ":olderPeopleHealthCheckRecord.getSmoking_daily()+"");
        html = html.replace("${start_smoking_age}",null==olderPeopleHealthCheckRecord.getStart_smoking_age()?" ":olderPeopleHealthCheckRecord.getStart_smoking_age()+"");
        html = html.replace("${stop_smoking_age}",null==olderPeopleHealthCheckRecord.getStop_smoking_age()?" ":olderPeopleHealthCheckRecord.getStop_smoking_age()+"");
        /**饮酒情况**/
        if (null==olderPeopleHealthCheckRecord.getDrinking_frequency()){
            html = html.replace("${drinking_frequency}"," ");
        }else {
            Integer drinkingFrequency = olderPeopleHealthCheckRecord.getDrinking_frequency();
            switch (drinkingFrequency){
                case 1:html = html.replace("${drinking_frequency}","从不");break;
                case 2:html = html.replace("${drinking_frequency}","偶尔");break;
                case 3:html = html.replace("${drinking_frequency}","经常");break;
                case 4:html = html.replace("${drinking_frequency}","每天");break;
                default:html = html.replace("${drinking_frequency}"," ");break;
            }
        }
        html = html.replace("${drinking_daily}",null==olderPeopleHealthCheckRecord.getDrinking_daily()?" ":olderPeopleHealthCheckRecord.getDrinking_daily()+"");
        if (null==olderPeopleHealthCheckRecord.getIs_stop_drinking()){
            html = html.replace("${is_stop_drinking}"," ");
        }else {
            Integer isStopDrinking = olderPeopleHealthCheckRecord.getIs_stop_drinking();
            switch (isStopDrinking){
                case 1:html = html.replace("${is_stop_drinking}","否");break;
                case 2:html = html.replace("${is_stop_drinking}","是");break;
                default:html = html.replace("${is_stop_drinking}"," ");break;
            }
        }
        html = html.replace("${stop_drinking_age}",null==olderPeopleHealthCheckRecord.getStop_drinking_age()?" ":olderPeopleHealthCheckRecord.getStop_drinking_age()+"");
        html = html.replace("${start_drinking_age}",null==olderPeopleHealthCheckRecord.getStart_drinking_age()?" ":olderPeopleHealthCheckRecord.getStart_drinking_age()+"");
        if (null==olderPeopleHealthCheckRecord.getDrunkenness()){
            html = html.replace("${drunkenness}"," ");
        }else {
            Integer drunkenness = olderPeopleHealthCheckRecord.getDrunkenness();
            switch (drunkenness){
                case 1:html = html.replace("${drunkenness}","是");break;
                case 2:html = html.replace("${drunkenness}","否");break;
                default:html = html.replace("${drunkenness}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getDrinking_type()){
            html = html.replace("${drinking_type}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getDrinking_type();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="白酒 ";break;
                    case "2":valueStrTmp+="啤酒 ";break;
                    case "3":valueStrTmp+="红酒 ";break;
                    case "4":valueStrTmp+="黄酒 ";break;
                    case "5":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${drinking_type}",valueStrTmp);
        }
        html = html.replace("${other_drinking_type}",null==olderPeopleHealthCheckRecord.getOther_drinking_type()?" ":olderPeopleHealthCheckRecord.getOther_drinking_type());
        /**职业病危害因素接触史**/
        html = html.replace("${dust}",null==olderPeopleHealthCheckRecord.getDust()?" ":olderPeopleHealthCheckRecord.getDust());
        if (null==olderPeopleHealthCheckRecord.getDust_protective_measures()){
            html = html.replace("${dust_protective_measures}"," ");
        }else {
            Integer dustProtectiveMeasures = olderPeopleHealthCheckRecord.getDust_protective_measures();
            switch (dustProtectiveMeasures){
                case 1:html = html.replace("${dust_protective_measures}","无");break;
                case 2:html = html.replace("${dust_protective_measures}","有");break;
                default:html = html.replace("${dust_protective_measures}"," ");break;
            }
        }
        html = html.replace("${dust_protective_measures_has}",null==olderPeopleHealthCheckRecord.getDust_protective_measures_has()?" ":olderPeopleHealthCheckRecord.getDust_protective_measures_has());
        html = html.replace("${radiogen}",null==olderPeopleHealthCheckRecord.getRadiogen()?" ":olderPeopleHealthCheckRecord.getRadiogen());
        if (null==olderPeopleHealthCheckRecord.getRadiogen_protective_measures()){
            html = html.replace("${radiogen_protective_measures}"," ");
        }else {
            Integer radiogenProtectiveMeasures = olderPeopleHealthCheckRecord.getRadiogen_protective_measures();
            switch (radiogenProtectiveMeasures){
                case 1:html = html.replace("${radiogen_protective_measures}","无");break;
                case 2:html = html.replace("${radiogen_protective_measures}","有");break;
                default:html = html.replace("${radiogen_protective_measures}"," ");break;
            }
        }
        html = html.replace("${radiogen_protective_measures_has}",null==olderPeopleHealthCheckRecord.getRadiogen_protective_measures_has()?" ":olderPeopleHealthCheckRecord.getRadiogen_protective_measures_has());
        html = html.replace("${physical_factor}",null==olderPeopleHealthCheckRecord.getPhysical_factor()?" ":olderPeopleHealthCheckRecord.getPhysical_factor());
        if (null==olderPeopleHealthCheckRecord.getPhysical_protective_measures()){
            html = html.replace("${physical_protective_measures}"," ");
        }else {
            Integer physicalProtectiveMeasures   = olderPeopleHealthCheckRecord.getPhysical_protective_measures();
            switch (physicalProtectiveMeasures){
                case 1:html = html.replace("${physical_protective_measures}","无");break;
                case 2:html = html.replace("${physical_protective_measures}","有");break;
                default:html = html.replace("${physical_protective_measures}"," ");break;
            }
        }
        html = html.replace("${physical_protective_measures_has}",null==olderPeopleHealthCheckRecord.getPhysical_protective_measures_has()?" ":olderPeopleHealthCheckRecord.getPhysical_protective_measures_has());
        html = html.replace("${chemical_factor}",null==olderPeopleHealthCheckRecord.getChemical_factor()?" ":olderPeopleHealthCheckRecord.getChemical_factor());
        if (null==olderPeopleHealthCheckRecord.getChemical_protective_measures()){
            html = html.replace("${chemical_protective_measures}"," ");
        }else {
            Integer chemicalProtectiveMeasures   = olderPeopleHealthCheckRecord.getChemical_protective_measures();
            switch (chemicalProtectiveMeasures){
                case 1:html = html.replace("${chemical_protective_measures}","无");break;
                case 2:html = html.replace("${chemical_protective_measures}","有");break;
                default:html = html.replace("${chemical_protective_measures}"," ");break;
            }
        }
        html = html.replace("${chemical_protective_measures_has}",null==olderPeopleHealthCheckRecord.getChemical_protective_measures_has()?" ":olderPeopleHealthCheckRecord.getChemical_protective_measures_has());
        html = html.replace("${physical_protective_measures_has}",null==olderPeopleHealthCheckRecord.getPhysical_protective_measures_has()?" ":olderPeopleHealthCheckRecord.getPhysical_protective_measures_has());
        html = html.replace("${other_hazard_factors}",null==olderPeopleHealthCheckRecord.getOther_hazard_factors()?" ":olderPeopleHealthCheckRecord.getOther_hazard_factors());
        if (null==olderPeopleHealthCheckRecord.getOther_hazard_protective_measures()){
            html = html.replace("${other_hazard_protective_measures}"," ");
        }else {
            Integer other_hazard_protective_measures   = olderPeopleHealthCheckRecord.getOther_hazard_protective_measures();
            switch (other_hazard_protective_measures){
                case 1:html = html.replace("${other_hazard_protective_measures}","无");break;
                case 2:html = html.replace("${other_hazard_protective_measures}","有");break;
                default:html = html.replace("${other_hazard_protective_measures}"," ");break;
            }
        }
        html = html.replace("${other_hazard_protective_measures_has}",null==olderPeopleHealthCheckRecord.getOther_hazard_protective_measures_has()?" ":olderPeopleHealthCheckRecord.getOther_hazard_protective_measures_has());
        if (null==olderPeopleHealthCheckRecord.getLip()){
            html = html.replace("${lip}"," ");
        }else {
            Integer lip = olderPeopleHealthCheckRecord.getLip();
            switch (lip){
                case 1:html = html.replace("${lip}","红润");break;
                case 2:html = html.replace("${lip}","苍白");break;
                case 3:html = html.replace("${lip}","发钳");break;
                case 4:html = html.replace("${lip}","皲裂");break;
                case 5:html = html.replace("${lip}","疱疹");break;
                default:html = html.replace("${lip}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getDentition()){
            html = html.replace("${dentition}"," ");
        }else {
            Integer dentition = olderPeopleHealthCheckRecord.getDentition();
            switch (dentition){
                case 1:html = html.replace("${dentition}","正常");break;
                case 2:html = html.replace("${dentition}","缺齿");break;
                case 3:html = html.replace("${dentition}","龋齿");break;
                case 4:html = html.replace("${dentition}","义齿,假牙");break;
                default:html = html.replace("${dentition}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getOropharynx()){
            html = html.replace("${oropharynx}"," ");
        }else {
            Integer oropharynx = olderPeopleHealthCheckRecord.getOropharynx();
            switch (oropharynx){
                case 1:html = html.replace("${oropharynx}","无充血");break;
                case 2:html = html.replace("${oropharynx}","充血");break;
                case 3:html = html.replace("${oropharynx}","淋巴滤泡增生");break;
                default:html = html.replace("${oropharynx}"," ");break;
            }
        }
        html = html.replace("${left_eyesight}",null==olderPeopleHealthCheckRecord.getLeft_eyesight()?"":olderPeopleHealthCheckRecord.getLeft_eyesight()+"");
        html = html.replace("${right_eyesight}",null==olderPeopleHealthCheckRecord.getRight_eyesight()?"":olderPeopleHealthCheckRecord.getRight_eyesight()+"");
        html = html.replace("${left_correctional_eyesight}",null==olderPeopleHealthCheckRecord.getLeft_correctional_eyesight()?"":olderPeopleHealthCheckRecord.getLeft_correctional_eyesight()+"");
        html = html.replace("${right_correctional_eyesight}",null==olderPeopleHealthCheckRecord.getRight_correctional_eyesight()?"":olderPeopleHealthCheckRecord.getRight_correctional_eyesight()+"");
        if (null==olderPeopleHealthCheckRecord.getHearing()){
            html = html.replace("${hearing}"," ");
        }else {
            Integer hearing = olderPeopleHealthCheckRecord.getHearing();
            switch (hearing){
                case 1:html = html.replace("${hearing}","听见");break;
                case 2:html = html.replace("${hearing}","听不清或无法听见");break;
                default:html = html.replace("${hearing}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getMotor_function()){
            html = html.replace("${motor_function}"," ");
        }else {
            Integer motor_function = olderPeopleHealthCheckRecord.getMotor_function();
            switch (motor_function){
                case 1:html = html.replace("${motor_function}","可顺利完成");break;
                case 2:html = html.replace("${motor_function}","无法独立完成任何一个动作");break;
                default:html = html.replace("${motor_function}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getFundus()){
            html = html.replace("${fundus}"," ");
        }else {
            Integer function = olderPeopleHealthCheckRecord.getFundus();
            switch (function){
                case 1:html = html.replace("${fundus}","正常");break;
                case 2:html = html.replace("${fundus}","异常");break;
                default:html = html.replace("${fundus}"," ");break;
            }
        }
        html = html.replace("${fundus_abnormal}",null==olderPeopleHealthCheckRecord.getFundus_abnormal()?"":olderPeopleHealthCheckRecord.getFundus_abnormal());
        if (null==olderPeopleHealthCheckRecord.getSkin()){
            html = html.replace("${skin}"," ");
        }else {
            Integer skin = olderPeopleHealthCheckRecord.getSkin();
            switch (skin){
                case 1:html = html.replace("${skin}","正常");break;
                case 2:html = html.replace("${skin}","潮红");break;
                case 3:html = html.replace("${skin}","苍白");break;
                case 4:html = html.replace("${skin}","发钳");break;
                case 5:html = html.replace("${skin}","黄染");break;
                case 6:html = html.replace("${skin}","色素沉着");break;
                case 7:html = html.replace("${skin}","其他");break;
                default:html = html.replace("${skin}"," ");break;
            }
        }
        html = html.replace("${skin_other}",null==olderPeopleHealthCheckRecord.getSkin_other()?"":olderPeopleHealthCheckRecord.getSkin_other());
        if (null==olderPeopleHealthCheckRecord.getSclera()){
            html = html.replace("${sclera}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getSclera();
            switch (sclera){
                case 1:html = html.replace("${sclera}","正常");break;
                case 2:html = html.replace("${sclera}","黄染");break;
                case 3:html = html.replace("${sclera}","充血");break;
                case 4:html = html.replace("${sclera}","其他");break;
                default:html = html.replace("${sclera}"," ");break;
            }
        }
        html = html.replace("${sclera_other}",null==olderPeopleHealthCheckRecord.getSclera_other()?"":olderPeopleHealthCheckRecord.getSclera_other());
        if (null==olderPeopleHealthCheckRecord.getLymphaden()){
            html = html.replace("${lymphaden}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getLymphaden();
            switch (sclera){
                case 1:html = html.replace("${lymphaden}","未触及");break;
                case 2:html = html.replace("${lymphaden}","锁骨上");break;
                case 3:html = html.replace("${lymphaden}","腋窝");break;
                case 4:html = html.replace("${lymphaden}","其他");break;
                default:html = html.replace("${lymphaden}"," ");break;
            }
        }
        html = html.replace("${lymphaden_other}",null==olderPeopleHealthCheckRecord.getLymphaden_other()?"":olderPeopleHealthCheckRecord.getLymphaden_other());
        if (null==olderPeopleHealthCheckRecord.getBarrel_chest()){
            html = html.replace("${barrel_chest}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getBarrel_chest();
            switch (sclera){
                case 1:html = html.replace("${barrel_chest}","否");break;
                case 2:html = html.replace("${barrel_chest}","是");break;
                default:html = html.replace("${barrel_chest}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getBreath_sounds()){
            html = html.replace("${breath_sounds}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getBreath_sounds();
            switch (sclera){
                case 1:html = html.replace("${breath_sounds}","正常");break;
                case 2:html = html.replace("${breath_sounds}","异常");break;
                default:html = html.replace("${breath_sounds}"," ");break;
            }
        }
        html = html.replace("${breath_sounds_abnormal}",null==olderPeopleHealthCheckRecord.getBreath_sounds_abnormal()?"":olderPeopleHealthCheckRecord.getBreath_sounds_abnormal());
        if (null==olderPeopleHealthCheckRecord.getRale()){
            html = html.replace("${rale}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getRale();
            switch (sclera){
                case 1:html = html.replace("${rale}","无");break;
                case 2:html = html.replace("${rale}","干罗音");break;
                case 3:html = html.replace("${rale}","湿罗音");break;
                case 4:html = html.replace("${rale}","其他");break;
                default:html = html.replace("${rale}"," ");break;
            }
        }
        html = html.replace("${rale_abnormal}",null==olderPeopleHealthCheckRecord.getRale_abnormal()?"":olderPeopleHealthCheckRecord.getRale_abnormal());
        html = html.replace("${heart_rate}",null==olderPeopleHealthCheckRecord.getHeart_rate()?"":olderPeopleHealthCheckRecord.getHeart_rate()+"");
        if (null==olderPeopleHealthCheckRecord.getHeart_rhythm()){
            html = html.replace("${heart_rhythm}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getHeart_rhythm();
            switch (sclera){
                case 1:html = html.replace("${heart_rhythm}","齐");break;
                case 2:html = html.replace("${heart_rhythm}","不齐");break;
                case 3:html = html.replace("${heart_rhythm}","绝对不齐");break;
                default:html = html.replace("${heart_rhythm}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getHeart_noise()){
            html = html.replace("${heart_noise}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getHeart_noise();
            switch (sclera){
                case 1:html = html.replace("${heart_noise}","无");break;
                case 2:html = html.replace("${heart_noise}","有");break;
                default:html = html.replace("${heart_noise}"," ");break;
            }
        }
        html = html.replace("${heart_noise_has}",null==olderPeopleHealthCheckRecord.getHeart_noise_has()?"":olderPeopleHealthCheckRecord.getHeart_noise_has());
        if (null==olderPeopleHealthCheckRecord.getAbdominal_tenderness()){
            html = html.replace("${abdominal_tenderness}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAbdominal_tenderness();
            switch (sclera){
                case 1:html = html.replace("${abdominal_tenderness}","无");break;
                case 2:html = html.replace("${abdominal_tenderness}","有");break;
                default:html = html.replace("${abdominal_tenderness}"," ");break;
            }
        }
        html = html.replace("${tenderness_has}",null==olderPeopleHealthCheckRecord.getTenderness_has()?"":olderPeopleHealthCheckRecord.getTenderness_has());
        if (null==olderPeopleHealthCheckRecord.getAbdominal_mass()){
            html = html.replace("${abdominal_mass}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAbdominal_mass();
            switch (sclera){
                case 1:html = html.replace("${abdominal_mass}","无");break;
                case 2:html = html.replace("${abdominal_mass}","有");break;
                default:html = html.replace("${abdominal_mass}"," ");break;
            }
        }
        html = html.replace("${mass_has}",null==olderPeopleHealthCheckRecord.getMass_has()?"":olderPeopleHealthCheckRecord.getMass_has());
        if (null==olderPeopleHealthCheckRecord.getAbdominal_hepatomegaly()){
            html = html.replace("${abdominal_hepatomegaly}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAbdominal_hepatomegaly();
            switch (sclera){
                case 1:html = html.replace("${abdominal_hepatomegaly}","无");break;
                case 2:html = html.replace("${abdominal_hepatomegaly}","有");break;
                default:html = html.replace("${abdominal_hepatomegaly}"," ");break;
            }
        }
        html = html.replace("${hepatomegaly_has}",null==olderPeopleHealthCheckRecord.getHepatomegaly_has()?"":olderPeopleHealthCheckRecord.getHepatomegaly_has());
        if (null==olderPeopleHealthCheckRecord.getAbdominal_spleen_big()){
            html = html.replace("${abdominal_spleen_big}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAbdominal_spleen_big();
            switch (sclera){
                case 1:html = html.replace("${abdominal_spleen_big}","无");break;
                case 2:html = html.replace("${abdominal_spleen_big}","有");break;
                default:html = html.replace("${abdominal_spleen_big}"," ");break;
            }
        }
        html = html.replace("${spleen_big_has}",null==olderPeopleHealthCheckRecord.getSpleen_big_has()?"":olderPeopleHealthCheckRecord.getSpleen_big_has());
        if (null==olderPeopleHealthCheckRecord.getAbdominal_shifting_dullness()){
            html = html.replace("${abdominal_shifting_dullness}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAbdominal_shifting_dullness();
            switch (sclera){
                case 1:html = html.replace("${abdominal_shifting_dullness}","无");break;
                case 2:html = html.replace("${abdominal_shifting_dullness}","有");break;
                default:html = html.replace("${abdominal_shifting_dullness}"," ");break;
            }
        }
        html = html.replace("${shifting_dullness_has}",null==olderPeopleHealthCheckRecord.getShifting_dullness_has()?"":olderPeopleHealthCheckRecord.getShifting_dullness_has());
        if (null==olderPeopleHealthCheckRecord.getCrura_edema()){
            html = html.replace("${crura_edema}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getCrura_edema();
            switch (sclera){
                case 1:html = html.replace("${crura_edema}","无");break;
                case 2:html = html.replace("${crura_edema}","单侧");break;
                case 3:html = html.replace("${crura_edema}","双侧不对称");break;
                case 4:html = html.replace("${crura_edema}","双侧对称");break;
                default:html = html.replace("${crura_edema}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getDorsal_foot_pulse()){
            html = html.replace("${dorsal_foot_pulse}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getDorsal_foot_pulse();
            switch (sclera){
                case 1:html = html.replace("${dorsal_foot_pulse}","未接触");break;
                case 2:html = html.replace("${dorsal_foot_pulse}","触及双侧对称");break;
                case 3:html = html.replace("${dorsal_foot_pulse}","触及左侧弱或消失");break;
                case 4:html = html.replace("${dorsal_foot_pulse}","触及右侧弱或消失");break;
                default:html = html.replace("${dorsal_foot_pulse}"," ");break;
            }
        }
        if (null==olderPeopleHealthCheckRecord.getAnus_dre()){
            html = html.replace("${anus_dre}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAnus_dre();
            switch (sclera){
                case 1:html = html.replace("${anus_dre}","未见异常");break;
                case 2:html = html.replace("${anus_dre}","触痛");break;
                case 3:html = html.replace("${anus_dre}","包块");break;
                case 4:html = html.replace("${anus_dre}","前列腺异常");break;
                case 5:html = html.replace("${anus_dre}","其他");break;
                default:html = html.replace("${anus_dre}"," ");break;
            }
        }
        html = html.replace("${anus_dre_other}",null==olderPeopleHealthCheckRecord.getAnus_dre_other()?"":olderPeopleHealthCheckRecord.getAnus_dre_other());
        if (null==olderPeopleHealthCheckRecord.getBreast()){
            html = html.replace("${breast}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getBreast();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="未见异常 ";break;
                    case "2":valueStrTmp+="乳房切除 ";break;
                    case "3":valueStrTmp+="异常泌乳 ";break;
                    case "4":valueStrTmp+="乳腺包块 ";break;
                    case "5":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${breast}",valueStrTmp);
        }
        html = html.replace("${breast_other}",null==olderPeopleHealthCheckRecord.getBreast_other()?"":olderPeopleHealthCheckRecord.getBreast_other());
        if (null==olderPeopleHealthCheckRecord.getVulva()){
            html = html.replace("${vulva}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getVulva();
            switch (sclera){
                case 1:html = html.replace("${vulva}","未见异常");break;
                case 2:html = html.replace("${vulva}","异常");break;
                default:html = html.replace("${vulva}"," ");break;
            }
        }
        html = html.replace("${vulva_abnormal}",null==olderPeopleHealthCheckRecord.getVulva_abnormal()?"":olderPeopleHealthCheckRecord.getVulva_abnormal());
        if (null==olderPeopleHealthCheckRecord.getVagina()){
            html = html.replace("${vagina}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getVagina();
            switch (sclera){
                case 1:html = html.replace("${vagina}","未见异常");break;
                case 2:html = html.replace("${vagina}","异常");break;
                default:html = html.replace("${vagina}"," ");break;
            }
        }
        html = html.replace("${vagina_abnormal}",null==olderPeopleHealthCheckRecord.getVagina_abnormal()?"":olderPeopleHealthCheckRecord.getVagina_abnormal());
        if (null==olderPeopleHealthCheckRecord.getCervical()){
            html = html.replace("${cervical}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getCervical();
            switch (sclera){
                case 1:html = html.replace("${cervical}","未见异常");break;
                case 2:html = html.replace("${cervical}","异常");break;
                default:html = html.replace("${cervical}"," ");break;
            }
        }
        html = html.replace("${cervical_abnormal}",null==olderPeopleHealthCheckRecord.getCervical_abnormal()?"":olderPeopleHealthCheckRecord.getCervical_abnormal());
        if (null==olderPeopleHealthCheckRecord.getCorpus()){
            html = html.replace("${corpus}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getCorpus();
            switch (sclera){
                case 1:html = html.replace("${corpus}","未见异常");break;
                case 2:html = html.replace("${corpus}","异常");break;
                default:html = html.replace("${corpus}"," ");break;
            }
        }
        html = html.replace("${corpus_abnormal}",null==olderPeopleHealthCheckRecord.getCorpus_abnormal()?"":olderPeopleHealthCheckRecord.getCorpus_abnormal());
        if (null==olderPeopleHealthCheckRecord.getGynecologic_appendix()){
            html = html.replace("${gynecologic_appendix}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getGynecologic_appendix();
            switch (sclera){
                case 1:html = html.replace("${gynecologic_appendix}","未见异常");break;
                case 2:html = html.replace("${gynecologic_appendix}","异常");break;
                default:html = html.replace("${gynecologic_appendix}"," ");break;
            }
        }
        html = html.replace("${appendix_abnormal}",null==olderPeopleHealthCheckRecord.getAppendix_abnormal()?"":olderPeopleHealthCheckRecord.getAppendix_abnormal());
        html = html.replace("${physical_examination_other}",null==olderPeopleHealthCheckRecord.getPhysical_examination_other()?"":olderPeopleHealthCheckRecord.getPhysical_examination_other());
        html = html.replace("${hemoglobin}",null==olderPeopleHealthCheckRecord.getHemoglobin()?"":olderPeopleHealthCheckRecord.getHemoglobin()+"");
        html = html.replace("${leukocyte}",null==olderPeopleHealthCheckRecord.getLeukocyte()?"":olderPeopleHealthCheckRecord.getLeukocyte()+"");
        html = html.replace("${thrombocyte}",null==olderPeopleHealthCheckRecord.getThrombocyte()?"":olderPeopleHealthCheckRecord.getThrombocyte()+"");
        html = html.replace("${blood_routine_other}",null==olderPeopleHealthCheckRecord.getBlood_routine_other()?"":olderPeopleHealthCheckRecord.getBlood_routine_other()+"");
        html = html.replace("${urine_protein}",null==olderPeopleHealthCheckRecord.getUrine_protein()?"":olderPeopleHealthCheckRecord.getUrine_protein()+"");
        html = html.replace("${urine_sugar}",null==olderPeopleHealthCheckRecord.getUrine_sugar()?"":olderPeopleHealthCheckRecord.getUrine_sugar()+"");
        html = html.replace("${urine_acetone_bodies}",null==olderPeopleHealthCheckRecord.getUrine_acetone_bodies()?"":olderPeopleHealthCheckRecord.getUrine_acetone_bodies()+"");
        html = html.replace("${urine_occult_blood}",null==olderPeopleHealthCheckRecord.getUrine_occult_blood()?"":olderPeopleHealthCheckRecord.getUrine_occult_blood()+"");
        html = html.replace("${urine_routine_other}",null==olderPeopleHealthCheckRecord.getUrine_routine_other()?"":olderPeopleHealthCheckRecord.getUrine_routine_other()+"");
        html = html.replace("${fasting_blood_glucose_L}",null==olderPeopleHealthCheckRecord.getFasting_blood_glucose_L()?"":olderPeopleHealthCheckRecord.getFasting_blood_glucose_L()+"");
        html = html.replace("${fasting_blood_glucose_dL}",null==olderPeopleHealthCheckRecord.getFasting_blood_glucose_dL()?"":olderPeopleHealthCheckRecord.getFasting_blood_glucose_dL()+"");
        if (null==olderPeopleHealthCheckRecord.getElectrocardiogram()){
            html = html.replace("${electrocardiogram}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getElectrocardiogram();
            switch (sclera){
                case 1:html = html.replace("${electrocardiogram}","正常");break;
                case 2:html = html.replace("${electrocardiogram}","异常");break;
                default:html = html.replace("${electrocardiogram}"," ");break;
            }
        }
        html = html.replace("${electrocardiogram_abnormal}",null==olderPeopleHealthCheckRecord.getElectrocardiogram_abnormal()?"":olderPeopleHealthCheckRecord.getElectrocardiogram_abnormal()+"");
        html = html.replace("${microalbuminuria}",null==olderPeopleHealthCheckRecord.getMicroalbuminuria()?"":olderPeopleHealthCheckRecord.getMicroalbuminuria()+"");
        if(null==olderPeopleHealthCheckRecord.getOccult_blood_in_stool()){
            html = html.replace("${occult_blood_in_stool}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getOccult_blood_in_stool();
            switch (sclera){
                case 1:html = html.replace("${occult_blood_in_stool}","阴性");break;
                case 2:html = html.replace("${occult_blood_in_stool}","阳性");break;
                default:html = html.replace("${occult_blood_in_stool}"," ");break;
            }
        }
        html = html.replace("${glycated_hemoglobin}",null==olderPeopleHealthCheckRecord.getGlycated_hemoglobin()?"":olderPeopleHealthCheckRecord.getGlycated_hemoglobin()+"");
        if(null==olderPeopleHealthCheckRecord.getHBsAg()){
            html = html.replace("${HBsAg}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getHBsAg();
            switch (sclera){
                case 1:html = html.replace("${HBsAg}","阴性");break;
                case 2:html = html.replace("${HBsAg}","阳性");break;
                default:html = html.replace("${HBsAg}"," ");break;
            }
        }
        html = html.replace("${ALT}",null==olderPeopleHealthCheckRecord.getALT()?"":olderPeopleHealthCheckRecord.getALT()+"");
        html = html.replace("${SGOT}",null==olderPeopleHealthCheckRecord.getSGOT()?"":olderPeopleHealthCheckRecord.getSGOT()+"");
        html = html.replace("${albumin}",null==olderPeopleHealthCheckRecord.getAlbumin()?"":olderPeopleHealthCheckRecord.getAlbumin()+"");
        html = html.replace("${total_bilirubin}",null==olderPeopleHealthCheckRecord.getTotal_bilirubin()?"":olderPeopleHealthCheckRecord.getTotal_bilirubin()+"");
        html = html.replace("${conjugated_bilirubin}",null==olderPeopleHealthCheckRecord.getConjugated_bilirubin()?"":olderPeopleHealthCheckRecord.getConjugated_bilirubin()+"");
        html = html.replace("${serum_creatinine}",null==olderPeopleHealthCheckRecord.getConjugated_bilirubin()?"":olderPeopleHealthCheckRecord.getConjugated_bilirubin()+"");
        html = html.replace("${blood_urea_nitrogen}",null==olderPeopleHealthCheckRecord.getBlood_urea_nitrogen()?"":olderPeopleHealthCheckRecord.getBlood_urea_nitrogen()+"");
        html = html.replace("${blood_potassium_concentration}",null==olderPeopleHealthCheckRecord.getBlood_potassium_concentration()?"":olderPeopleHealthCheckRecord.getBlood_potassium_concentration()+"");
        html = html.replace("${blood_Na_concentration}",null==olderPeopleHealthCheckRecord.getBlood_Na_concentration()?"":olderPeopleHealthCheckRecord.getBlood_Na_concentration()+"");
        html = html.replace("${uric_acid}",null==olderPeopleHealthCheckRecord.getUric_acid()?"":olderPeopleHealthCheckRecord.getUric_acid()+"");
        html = html.replace("${total_cholesterol}",null==olderPeopleHealthCheckRecord.getTotal_cholesterol()?"":olderPeopleHealthCheckRecord.getTotal_cholesterol()+"");
        html = html.replace("${triglyceride}",null==olderPeopleHealthCheckRecord.getTriglyceride()?"":olderPeopleHealthCheckRecord.getTriglyceride()+"");
        html = html.replace("${LDL_cholesterol}",null==olderPeopleHealthCheckRecord.getLDL_cholesterol()?"":olderPeopleHealthCheckRecord.getLDL_cholesterol()+"");
        html = html.replace("${HDL_cholesterol}",null==olderPeopleHealthCheckRecord.getHDL_cholesterol()?"":olderPeopleHealthCheckRecord.getHDL_cholesterol()+"");
        html = html.replace("${alpha_fetal_protein}",null==olderPeopleHealthCheckRecord.getAlpha_fetal_protein()?"":olderPeopleHealthCheckRecord.getAlpha_fetal_protein()+"");
        if(null==olderPeopleHealthCheckRecord.getChest_Xray()){
            html = html.replace("${chest_Xray}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getChest_Xray();
            switch (sclera){
                case 1:html = html.replace("${chest_Xray}","正常");break;
                case 2:html = html.replace("${chest_Xray}","异常");break;
                default:html = html.replace("${chest_Xray}"," ");break;
            }
        }
        html = html.replace("${chest_Xray_abnormal}",null==olderPeopleHealthCheckRecord.getChest_Xray_abnormal()?"":olderPeopleHealthCheckRecord.getChest_Xray_abnormal());
        if(null==olderPeopleHealthCheckRecord.getAbdomen_B_ultrasonic()){
            html = html.replace("${abdomen_B_ultrasonic}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getAbdomen_B_ultrasonic();
            switch (sclera){
                case 1:html = html.replace("${abdomen_B_ultrasonic}","正常");break;
                case 2:html = html.replace("${abdomen_B_ultrasonic}","异常");break;
                default:html = html.replace("${abdomen_B_ultrasonic}"," ");break;
            }
        }
        html = html.replace("${abdomen_B_ultrasonic_abnormal}",null==olderPeopleHealthCheckRecord.getAbdomen_B_ultrasonic_abnormal()?"":olderPeopleHealthCheckRecord.getAbdomen_B_ultrasonic_abnormal());
        if(null==olderPeopleHealthCheckRecord.getB_ultrasonic_other()){
            html = html.replace("${B_ultrasonic_other}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getB_ultrasonic_other();
            switch (sclera){
                case 1:html = html.replace("${B_ultrasonic_other}","正常");break;
                case 2:html = html.replace("${B_ultrasonic_other}","异常");break;
                default:html = html.replace("${B_ultrasonic_other}"," ");break;
            }
        }
        html = html.replace("${B_ultrasonic_other_abnormal}",null==olderPeopleHealthCheckRecord.getB_ultrasonic_other_abnormal()?"":olderPeopleHealthCheckRecord.getB_ultrasonic_other_abnormal());
        if(null==olderPeopleHealthCheckRecord.getCervical_smear()){
            html = html.replace("${cervical_smear}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getCervical_smear();
            switch (sclera){
                case 1:html = html.replace("${cervical_smear}","正常");break;
                case 2:html = html.replace("${cervical_smear}","异常");break;
                default:html = html.replace("${cervical_smear}"," ");break;
            }
        }
        html = html.replace("${cervical_smear_abnormal}",null==olderPeopleHealthCheckRecord.getCervical_smear_abnormal()?"":olderPeopleHealthCheckRecord.getCervical_smear_abnormal());
        html = html.replace("${auxiliary_examination_other}",null==olderPeopleHealthCheckRecord.getAuxiliary_examination_other()?"":olderPeopleHealthCheckRecord.getAuxiliary_examination_other());
        if(null==olderPeopleHealthCheckRecord.getMild_physical()){
            html = html.replace("${mild_physical}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMild_physical();
            switch (sclera){
                case 1:html = html.replace("${mild_physical}","是");break;
                case 2:html = html.replace("${mild_physical}","倾向是");break;
                default:html = html.replace("${mild_physical}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getQi_deficiency()){
            html = html.replace("${qi_deficiency}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getQi_deficiency();
            switch (sclera){
                case 1:html = html.replace("${qi_deficiency}","是");break;
                case 2:html = html.replace("${qi_deficiency}","基本是");break;
                default:html = html.replace("${qi_deficiency}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getYang_deficiency()){
            html = html.replace("${yang_deficiency}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getYang_deficiency();
            switch (sclera){
                case 1:html = html.replace("${yang_deficiency}","是");break;
                case 2:html = html.replace("${yang_deficiency}","基本是");break;
                default:html = html.replace("${yang_deficiency}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getYin_deficiency()){
            html = html.replace("${yin_deficiency}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getYin_deficiency();
            switch (sclera){
                case 1:html = html.replace("${yin_deficiency}","是");break;
                case 2:html = html.replace("${yin_deficiency}","基本是");break;
                default:html = html.replace("${yin_deficiency}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getPhlegm_dampness()){
            html = html.replace("${phlegm_dampness}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getPhlegm_dampness();
            switch (sclera){
                case 1:html = html.replace("${phlegm_dampness}","是");break;
                case 2:html = html.replace("${phlegm_dampness}","基本是");break;
                default:html = html.replace("${phlegm_dampness}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getDampness_heat()){
            html = html.replace("${dampness_heat}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getDampness_heat();
            switch (sclera){
                case 1:html = html.replace("${dampness_heat}","是");break;
                case 2:html = html.replace("${dampness_heat}","基本是");break;
                default:html = html.replace("${dampness_heat}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getBlood_stasis()){
            html = html.replace("${blood_stasis}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getBlood_stasis();
            switch (sclera){
                case 1:html = html.replace("${blood_stasis}","是");break;
                case 2:html = html.replace("${blood_stasis}","基本是");break;
                default:html = html.replace("${blood_stasis}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getLogistic_regression()){
            html = html.replace("${logistic_regression}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getLogistic_regression();
            switch (sclera){
                case 1:html = html.replace("${logistic_regression}","是");break;
                case 2:html = html.replace("${logistic_regression}","基本是");break;
                default:html = html.replace("${logistic_regression}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getGrasp_quality()){
            html = html.replace("${grasp_quality}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getGrasp_quality();
            switch (sclera){
                case 1:html = html.replace("${grasp_quality}","是");break;
                case 2:html = html.replace("${grasp_quality}","基本是");break;
                default:html = html.replace("${grasp_quality}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getCerebrovascular_disease()){
            html = html.replace("${cerebrovascular_disease}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getCerebrovascular_disease();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="未发现 ";break;
                    case "2":valueStrTmp+="缺血性卒中 ";break;
                    case "3":valueStrTmp+="脑出血 ";break;
                    case "4":valueStrTmp+="蛛网膜下腔出血 ";break;
                    case "5":valueStrTmp+="短暂性脑缺血发作 ";break;
                    case "6":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${cerebrovascular_disease}",valueStrTmp);
        }
        html = html.replace("${cerebrovascular_disease_other}",null==olderPeopleHealthCheckRecord.getCerebrovascular_disease_other()?"":olderPeopleHealthCheckRecord.getCerebrovascular_disease_other());
        if(null==olderPeopleHealthCheckRecord.getNephropathy()){
            html = html.replace("${nephropathy}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getNephropathy();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="未发现 ";break;
                    case "2":valueStrTmp+="糖尿病肾病 ";break;
                    case "3":valueStrTmp+="肾功能衰竭 ";break;
                    case "4":valueStrTmp+="急性肾炎 ";break;
                    case "5":valueStrTmp+="慢性肾炎 ";break;
                    case "6":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${nephropathy}",valueStrTmp);
        }
        html = html.replace("${nephropathy_other}",null==olderPeopleHealthCheckRecord.getNephropathy_other()?"":olderPeopleHealthCheckRecord.getNephropathy_other());
        if(null==olderPeopleHealthCheckRecord.getHeart_disease()){
                    html = html.replace("${heart_disease}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getHeart_disease();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="未发现 ";break;
                    case "2":valueStrTmp+="心肌梗死 ";break;
                    case "3":valueStrTmp+="心绞痛 ";break;
                    case "4":valueStrTmp+="冠状动脉血运重建 ";break;
                    case "5":valueStrTmp+="充血性心力衰竭 ";break;
                    case "6":valueStrTmp+="心前区疼痛 ";break;
                    case "7":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${heart_disease}",valueStrTmp);
        }
        html = html.replace("${heart_disease_other}",null==olderPeopleHealthCheckRecord.getHeart_disease_other()?"":olderPeopleHealthCheckRecord.getHeart_disease_other());
        if(null==olderPeopleHealthCheckRecord.getVascular_disease()){
                    html = html.replace("${vascular_disease}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getVascular_disease();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="未发现 ";break;
                    case "2":valueStrTmp+="夹层动脉瘤 ";break;
                    case "3":valueStrTmp+="动脉闭塞性疾病 ";break;
                    case "4":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${vascular_disease}",valueStrTmp);
        }
        html = html.replace("${vascular_disease_other}",null==olderPeopleHealthCheckRecord.getVascular_disease_other()?"":olderPeopleHealthCheckRecord.getVascular_disease_other());
        if(null==olderPeopleHealthCheckRecord.getEye_disease()){
            html = html.replace("${eye_disease}"," ");
        }else {
            String smokingState = olderPeopleHealthCheckRecord.getEye_disease();
            String[] smokingStates = smokingState.split(",");
            String valueStrTmp = " ";
            for (String tmp:smokingStates){
                switch (tmp){
                    case "1":valueStrTmp+="未发现 ";break;
                    case "2":valueStrTmp+="视网膜出血或渗出 ";break;
                    case "3":valueStrTmp+="视乳头水肿 ";break;
                    case "4":valueStrTmp+="白内障 ";break;
                    case "5":valueStrTmp+="其他 ";break;
                }
            }
            html = html.replace("${eye_disease}",valueStrTmp);
        }
        html = html.replace("${eye_disease_other}",null==olderPeopleHealthCheckRecord.getEye_disease_other()?"":olderPeopleHealthCheckRecord.getEye_disease_other());
        if(null==olderPeopleHealthCheckRecord.getNervous_system_disease()){
            html = html.replace("${nervous_system_disease}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getNervous_system_disease();
            switch (sclera){
                case 1:html = html.replace("${nervous_system_disease}","未发现");break;
                case 2:html = html.replace("${nervous_system_disease}","有");break;
                default:html = html.replace("${nervous_system_disease}"," ");break;
            }
        }
        html = html.replace("${nervous_system_disease_has}",null==olderPeopleHealthCheckRecord.getNervous_system_disease_has()?"":olderPeopleHealthCheckRecord.getNervous_system_disease_has());
        if(null==olderPeopleHealthCheckRecord.getOther_system_disease()){
            html = html.replace("${other_system_disease}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getOther_system_disease();
            switch (sclera){
                case 1:html = html.replace("${other_system_disease}","未发现");break;
                case 2:html = html.replace("${other_system_disease}","有");break;
                default:html = html.replace("${other_system_disease}"," ");break;
            }
        }
        html = html.replace("${other_system_disease_has}",null==olderPeopleHealthCheckRecord.getOther_system_disease_has()?"":olderPeopleHealthCheckRecord.getOther_system_disease_has());
        html = html.replace("${admission_date1}",null==olderPeopleHealthCheckRecord.getAdmission_date1()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getAdmission_date1()));
        html = html.replace("${admission_date2}",null==olderPeopleHealthCheckRecord.getAdmission_date2()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getAdmission_date2()));
        html = html.replace("${discharge_date1}",null==olderPeopleHealthCheckRecord.getDischarge_date1()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getDischarge_date1()));
        html = html.replace("${discharge_date2}",null==olderPeopleHealthCheckRecord.getDischarge_date2()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getDischarge_date2()));
        html = html.replace("${admission_reason1}",null==olderPeopleHealthCheckRecord.getAdmission_reason1()?"":olderPeopleHealthCheckRecord.getAdmission_reason1());
        html = html.replace("${admission_reason2}",null==olderPeopleHealthCheckRecord.getAdmission_reason2()?"":olderPeopleHealthCheckRecord.getAdmission_reason2());
        html = html.replace("${admission_hospital_name1}",null==olderPeopleHealthCheckRecord.getAdmission_hospital_name1()?"":olderPeopleHealthCheckRecord.getAdmission_hospital_name1());
        html = html.replace("${admission_hospital_name2}",null==olderPeopleHealthCheckRecord.getAdmission_hospital_name2()?"":olderPeopleHealthCheckRecord.getAdmission_hospital_name2());
        html = html.replace("${admission_number1}",null==olderPeopleHealthCheckRecord.getAdmission_number1()?"":olderPeopleHealthCheckRecord.getAdmission_number1());
        html = html.replace("${admission_number2}",null==olderPeopleHealthCheckRecord.getAdmission_number2()?"":olderPeopleHealthCheckRecord.getAdmission_number2());
        html = html.replace("${building_bed_date1}",null==olderPeopleHealthCheckRecord.getBuilding_bed_date1()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getBuilding_bed_date1()));
        html = html.replace("${building_bed_date2}",null==olderPeopleHealthCheckRecord.getBuilding_bed_date2()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getBuilding_bed_date2()));
        html = html.replace("${cancel_bed_date1}",null==olderPeopleHealthCheckRecord.getCancel_bed_date1()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getCancel_bed_date1()));
        html = html.replace("${cancel_bed_date2}",null==olderPeopleHealthCheckRecord.getCancel_bed_date2()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getCancel_bed_date2()));
        html = html.replace("${building_bed_reason1}",null==olderPeopleHealthCheckRecord.getBuilding_bed_reason1()?"":olderPeopleHealthCheckRecord.getBuilding_bed_reason1());
        html = html.replace("${building_bed_reason2}",null==olderPeopleHealthCheckRecord.getBuilding_bed_reason2()?"":olderPeopleHealthCheckRecord.getBuilding_bed_reason2());
        html = html.replace("${building_bed_hospiatl_name1}",null==olderPeopleHealthCheckRecord.getBuilding_bed_hospiatl_name1()?"":olderPeopleHealthCheckRecord.getBuilding_bed_hospiatl_name1());
        html = html.replace("${building_bed_hospiatl_name2}",null==olderPeopleHealthCheckRecord.getBuilding_bed_hospiatl_name2()?"":olderPeopleHealthCheckRecord.getBuilding_bed_hospiatl_name2());
        html = html.replace("${building_bed_number1}",null==olderPeopleHealthCheckRecord.getBuilding_bed_number1()?"":olderPeopleHealthCheckRecord.getBuilding_bed_number1());
        html = html.replace("${building_bed_number2}",null==olderPeopleHealthCheckRecord.getBuilding_bed_number2()?"":olderPeopleHealthCheckRecord.getBuilding_bed_number2());
        html = html.replace("${medicine1}",null==olderPeopleHealthCheckRecord.getMedicine1()?"":olderPeopleHealthCheckRecord.getMedicine1());
        html = html.replace("${medicine2}",null==olderPeopleHealthCheckRecord.getMedicine2()?"":olderPeopleHealthCheckRecord.getMedicine2());
        html = html.replace("${medicine3}",null==olderPeopleHealthCheckRecord.getMedicine3()?"":olderPeopleHealthCheckRecord.getMedicine3());
        html = html.replace("${medicine4}",null==olderPeopleHealthCheckRecord.getMedicine4()?"":olderPeopleHealthCheckRecord.getMedicine4());
        html = html.replace("${medicine5}",null==olderPeopleHealthCheckRecord.getMedicine5()?"":olderPeopleHealthCheckRecord.getMedicine5());
        html = html.replace("${medicine6}",null==olderPeopleHealthCheckRecord.getMedicine6()?"":olderPeopleHealthCheckRecord.getMedicine6());
        html = html.replace("${medicine1_use}",null==olderPeopleHealthCheckRecord.getMedicine1_use()?"":olderPeopleHealthCheckRecord.getMedicine1_use());
        html = html.replace("${medicine2_use}",null==olderPeopleHealthCheckRecord.getMedicine2_use()?"":olderPeopleHealthCheckRecord.getMedicine2_use());
        html = html.replace("${medicine3_use}",null==olderPeopleHealthCheckRecord.getMedicine3_use()?"":olderPeopleHealthCheckRecord.getMedicine3_use());
        html = html.replace("${medicine4_use}",null==olderPeopleHealthCheckRecord.getMedicine4_use()?"":olderPeopleHealthCheckRecord.getMedicine4_use());
        html = html.replace("${medicine5_use}",null==olderPeopleHealthCheckRecord.getMedicine5_use()?"":olderPeopleHealthCheckRecord.getMedicine5_use());
        html = html.replace("${medicine6_use}",null==olderPeopleHealthCheckRecord.getMedicine6_use()?"":olderPeopleHealthCheckRecord.getMedicine6_use());
        html = html.replace("${medicine1_dosage}",null==olderPeopleHealthCheckRecord.getMedicine1_dosage()?"":olderPeopleHealthCheckRecord.getMedicine1_dosage());
        html = html.replace("${medicine2_dosage}",null==olderPeopleHealthCheckRecord.getMedicine2_dosage()?"":olderPeopleHealthCheckRecord.getMedicine2_dosage());
        html = html.replace("${medicine3_dosage}",null==olderPeopleHealthCheckRecord.getMedicine3_dosage()?"":olderPeopleHealthCheckRecord.getMedicine3_dosage());
        html = html.replace("${medicine4_dosage}",null==olderPeopleHealthCheckRecord.getMedicine4_dosage()?"":olderPeopleHealthCheckRecord.getMedicine4_dosage());
        html = html.replace("${medicine5_dosage}",null==olderPeopleHealthCheckRecord.getMedicine5_dosage()?"":olderPeopleHealthCheckRecord.getMedicine5_dosage());
        html = html.replace("${medicine6_dosage}",null==olderPeopleHealthCheckRecord.getMedicine6_dosage()?"":olderPeopleHealthCheckRecord.getMedicine6_dosage());
        html = html.replace("${medication1_time}",null==olderPeopleHealthCheckRecord.getMedication1_time()?"":olderPeopleHealthCheckRecord.getMedication1_time());
        html = html.replace("${medication2_time}",null==olderPeopleHealthCheckRecord.getMedication2_time()?"":olderPeopleHealthCheckRecord.getMedication2_time());
        html = html.replace("${medication3_time}",null==olderPeopleHealthCheckRecord.getMedication3_time()?"":olderPeopleHealthCheckRecord.getMedication3_time());
        html = html.replace("${medication4_time}",null==olderPeopleHealthCheckRecord.getMedication4_time()?"":olderPeopleHealthCheckRecord.getMedication4_time());
        html = html.replace("${medication5_time}",null==olderPeopleHealthCheckRecord.getMedication5_time()?"":olderPeopleHealthCheckRecord.getMedication5_time());
        html = html.replace("${medication6_time}",null==olderPeopleHealthCheckRecord.getMedication6_time()?"":olderPeopleHealthCheckRecord.getMedication6_time());
        if(null==olderPeopleHealthCheckRecord.getMedication1_compliance()){
            html = html.replace("${medication1_compliance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMedication1_compliance();
            switch (sclera){
                case 1:html = html.replace("${medication1_compliance}","规律");break;
                case 2:html = html.replace("${medication1_compliance}","间断");break;
                case 3:html = html.replace("${medication1_compliance}","不服药");break;
                default:html = html.replace("${medication1_compliance}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getMedication2_compliance()){
            html = html.replace("${medication2_compliance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMedication2_compliance();
            switch (sclera){
                case 1:html = html.replace("${medication2_compliance}","规律");break;
                case 2:html = html.replace("${medication2_compliance}","间断");break;
                case 3:html = html.replace("${medication2_compliance}","不服药");break;
                default:html = html.replace("${medication2_compliance}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getMedication3_compliance()){
            html = html.replace("${medication3_compliance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMedication3_compliance();
            switch (sclera){
                case 1:html = html.replace("${medication3_compliance}","规律");break;
                case 2:html = html.replace("${medication3_compliance}","间断");break;
                case 3:html = html.replace("${medication3_compliance}","不服药");break;
                default:html = html.replace("${medication3_compliance}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getMedication4_compliance()){
            html = html.replace("${medication4_compliance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMedication4_compliance();
            switch (sclera){
                case 1:html = html.replace("${medication4_compliance}","规律");break;
                case 2:html = html.replace("${medication4_compliance}","间断");break;
                case 3:html = html.replace("${medication4_compliance}","不服药");break;
                default:html = html.replace("${medication4_compliance}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getMedication5_compliance()){
            html = html.replace("${medication5_compliance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMedication5_compliance();
            switch (sclera){
                case 1:html = html.replace("${medication5_compliance}","规律");break;
                case 2:html = html.replace("${medication5_compliance}","间断");break;
                case 3:html = html.replace("${medication5_compliance}","不服药");break;
                default:html = html.replace("${medication5_compliance}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getMedication6_compliance()){
            html = html.replace("${medication6_compliance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getMedication6_compliance();
            switch (sclera){
                case 1:html = html.replace("${medication6_compliance}","规律");break;
                case 2:html = html.replace("${medication6_compliance}","间断");break;
                case 3:html = html.replace("${medication6_compliance}","不服药");break;
                default:html = html.replace("${medication6_compliance}"," ");break;
            }
        }
        html = html.replace("${vaccination_name1}",null==olderPeopleHealthCheckRecord.getVaccination_name1()?"":olderPeopleHealthCheckRecord.getVaccination_name1());
        html = html.replace("${vaccination_name2}",null==olderPeopleHealthCheckRecord.getVaccination_name2()?"":olderPeopleHealthCheckRecord.getVaccination_name2());
        html = html.replace("${vaccination_name3}",null==olderPeopleHealthCheckRecord.getVaccination_name3()?"":olderPeopleHealthCheckRecord.getVaccination_name3());
        html = html.replace("${vaccination_date1}",null==olderPeopleHealthCheckRecord.getVaccination_date1()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getVaccination_date1()));
        html = html.replace("${vaccination_date2}",null==olderPeopleHealthCheckRecord.getVaccination_date2()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getVaccination_date2()));
        html = html.replace("${vaccination_date3}",null==olderPeopleHealthCheckRecord.getVaccination_date3()?"":DateUtil.dateToStrShort(olderPeopleHealthCheckRecord.getVaccination_date3()));
        html = html.replace("${vaccination_hospital_name1}",null==olderPeopleHealthCheckRecord.getVaccination_hospital_name1()?"":olderPeopleHealthCheckRecord.getVaccination_hospital_name1());
        html = html.replace("${vaccination_hospital_name2}",null==olderPeopleHealthCheckRecord.getVaccination_hospital_name2()?"":olderPeopleHealthCheckRecord.getVaccination_hospital_name2());
        html = html.replace("${vaccination_hospital_name3}",null==olderPeopleHealthCheckRecord.getVaccination_hospital_name3()?"":olderPeopleHealthCheckRecord.getVaccination_hospital_name3());
        if(null==olderPeopleHealthCheckRecord.getHealth_examination()){
            html = html.replace("${health_examination}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getHealth_examination();
            switch (sclera){
                case 1:html = html.replace("${health_examination}","无");break;
                case 2:html = html.replace("${health_examination}","有异常");break;
                default:html = html.replace("${health_examination}"," ");break;
            }
        }
        html = html.replace("${health_examination_abnormal1}",null==olderPeopleHealthCheckRecord.getHealth_examination_abnormal1()?"":olderPeopleHealthCheckRecord.getHealth_examination_abnormal1());
        html = html.replace("${health_examination_abnormal2}",null==olderPeopleHealthCheckRecord.getHealth_examination_abnormal2()?"":olderPeopleHealthCheckRecord.getHealth_examination_abnormal2());
        html = html.replace("${health_examination_abnormal3}",null==olderPeopleHealthCheckRecord.getHealth_examination_abnormal3()?"":olderPeopleHealthCheckRecord.getHealth_examination_abnormal3());
        html = html.replace("${health_examination_abnormal4}",null==olderPeopleHealthCheckRecord.getHealth_examination_abnormal4()?"":olderPeopleHealthCheckRecord.getHealth_examination_abnormal4());
        if(null==olderPeopleHealthCheckRecord.getRegular_followup()){
            html = html.replace("${regular_followup}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getRegular_followup();
            switch (sclera){
                case 2:html = html.replace("${regular_followup}","定期随访:是");break;
                default:html = html.replace("${regular_followup}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getChronic_health_management()){
            html = html.replace("${chronic_health_management}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getChronic_health_management();
            switch (sclera){
                case 2:html = html.replace("${chronic_health_management}","纳入慢性病患者健康管理:是");break;
                default:html = html.replace("${chronic_health_management}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getSuggest_recheck()){
            html = html.replace("${suggest_recheck}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getSuggest_recheck();
            switch (sclera){
                case 2:html = html.replace("${suggest_recheck}","建议复查:是");break;
                default:html = html.replace("${suggest_recheck}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getSuggest_referral()){
            html = html.replace("${suggest_referral}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getSuggest_referral();
            switch (sclera){
                case 2:html = html.replace("${suggest_referral}","建议转诊:是");break;
                default:html = html.replace("${suggest_referral}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getOther_health_guidance()){
            html = html.replace("${other_health_guidance}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getOther_health_guidance();
            switch (sclera){
                case 2:html = html.replace("${other_health_guidance}","其他");break;
                default:html = html.replace("${other_health_guidance}"," ");break;
            }
        }
        html = html.replace("${other_health_guidance_description}",null==olderPeopleHealthCheckRecord.getOther_health_guidance_description()?"":olderPeopleHealthCheckRecord.getOther_health_guidance_description());
        if(null==olderPeopleHealthCheckRecord.getStop_smoking()){
            html = html.replace("${stop_smoking}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getStop_smoking();
            switch (sclera){
                case 2:html = html.replace("${stop_smoking}","戒烟:是");break;
                default:html = html.replace("${stop_smoking}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getHealthy_drinking()){
            html = html.replace("${healthy_drinking}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getHealthy_drinking();
            switch (sclera){
                case 2:html = html.replace("${healthy_drinking}","健康饮酒:是");break;
                default:html = html.replace("${healthy_drinking}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getDiet()){
            html = html.replace("${diet}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getDiet();
            switch (sclera){
                case 2:html = html.replace("${diet}","饮食:是");break;
                default:html = html.replace("${diet}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getExercise()){
            html = html.replace("${exercise}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getExercise();
            switch (sclera){
                case 2:html = html.replace("${exercise}","锻炼:是");break;
                default:html = html.replace("${exercise}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getLose_weight()){
            html = html.replace("${lose_weight}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getLose_weight();
            switch (sclera){
                case 2:html = html.replace("${lose_weight}","减肥:是");break;
                default:html = html.replace("${lose_weight}"," ");break;
            }
        }
        html = html.replace("${goal_weight}",null==olderPeopleHealthCheckRecord.getGoal_weight()?"":"目标:"+olderPeopleHealthCheckRecord.getGoal_weight()+"Kg");
        if(null==olderPeopleHealthCheckRecord.getRecommended_vaccination()){
            html = html.replace("${recommended_vaccination}"," ");
        }else {
            String sclera = olderPeopleHealthCheckRecord.getRecommended_vaccination();
            switch (sclera){
                case "2":html = html.replace("${recommended_vaccination}","建议接种疫苗:是");break;
                default:html = html.replace("${recommended_vaccination}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getOther_advice()){
            html = html.replace("${other_advice}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getOther_advice();
            switch (sclera){
                case 2:html = html.replace("${other_advice}","其他建议:是");break;
                default:html = html.replace("${other_advice}"," ");break;
            }
        }
        html = html.replace("${other_advice_description}",null==olderPeopleHealthCheckRecord.getOther_advice_description()?"":olderPeopleHealthCheckRecord.getOther_advice_description());
        if(null==olderPeopleHealthCheckRecord.getEat()){
            html = html.replace("${eat}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getEat();
            switch (sclera){
                case 1:html = html.replace("${eat}","    独立完成0-3分");break;
                case 2:html = html.replace("${eat}","    轻度依赖4-8分");break;
                case 3:html = html.replace("${eat}","    中度依赖9-18分");break;
                case 4:html = html.replace("${eat}","    不能自理≥19分");break;
                default:html = html.replace("${eat}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getWash()){
            html = html.replace("${wash}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getWash();
            switch (sclera){
                case 1:html = html.replace("${wash}","    独立完成0-3分");break;
                case 2:html = html.replace("${wash}","    轻度依赖4-8分");break;
                case 3:html = html.replace("${wash}","    中度依赖9-18分");break;
                case 4:html = html.replace("${wash}","    不能自理≥19分");break;
                default:html = html.replace("${wash}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getDress()){
            html = html.replace("${dress}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getDress();
            switch (sclera){
                case 1:html = html.replace("${dress}","    独立完成0-3分");break;
                case 2:html = html.replace("${dress}","    轻度依赖4-8分");break;
                case 3:html = html.replace("${dress}","    中度依赖9-18分");break;
                case 4:html = html.replace("${dress}","    不能自理≥19分");break;
                default:html = html.replace("${dress}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getToilet()){
            html = html.replace("${toilet}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getToilet();
            switch (sclera){
                case 1:html = html.replace("${toilet}","    独立完成0-3分");break;
                case 2:html = html.replace("${toilet}","    轻度依赖4-8分");break;
                case 3:html = html.replace("${toilet}","    中度依赖9-18分");break;
                case 4:html = html.replace("${toilet}","    不能自理≥19分");break;
                default:html = html.replace("${toilet}"," ");break;
            }
        }
        if(null==olderPeopleHealthCheckRecord.getActivity()){
            html = html.replace("${activity}"," ");
        }else {
            Integer sclera = olderPeopleHealthCheckRecord.getActivity();
            switch (sclera){
                case 1:html = html.replace("${activity}","    独立完成0-3分");break;
                case 2:html = html.replace("${activity}","    轻度依赖4-8分");break;
                case 3:html = html.replace("${activity}","    中度依赖9-18分");break;
                case 4:html = html.replace("${activity}","    能自理≥19分");break;
                default:html = html.replace("${activity}"," ");break;
            }
        }
        html = html.replace("${score}",null==olderPeopleHealthCheckRecord.getScore()?"":olderPeopleHealthCheckRecord.getScore()+"");
        String sign_wayStr="";
        String sign_time="";
        String sign_address="";
        String sign_imgs="";
        List<FollowupSign> followupSignDOs = followupSignDao.findByFollowupIdAndDel(Long.valueOf(olderPeopleHealthCheckRecord.getFollowup_id()),0);
        if (followupSignDOs.size()>0){
            FollowupSign followupSignDO = followupSignDOs.get(0);
            if (null!=followupSignDO){
                try {
                    switch (followupSignDO.getType()){
                        case "1":sign_wayStr="定位"; break;
                        case "2":sign_wayStr="拍照";break;
                        case "3":sign_wayStr="门牌";break;
                        default:sign_wayStr=" ";break;
                    }
                    sign_address = null==followupSignDO.getAddress()?" ":followupSignDO.getAddress();
                    if(StringUtils.isNotBlank(followupSignDO.getImg())) {
                        String imgs = followupSignDO.getImg();
                        String[] imgsArray;
                        if (imgs.contains(",")) {
                            imgsArray = imgs.split(",");
                        } else {
                            imgsArray = new String[]{imgs};
                        }
                        for (String img : imgsArray) {
                            sign_imgs += "<img width='80' height='100' src='" + imgUrlDomain + img + "' />&nbsp;";
                        }
                    }
                    sign_time = DateUtil.dateToStrLong(followupSignDO.getCreateTime());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        html = html.replace("${sign_way}",sign_wayStr);
        html = html.replace("${sign_time}",sign_time);
        html = html.replace("${sign_address}",sign_address);
        html = html.replace("${sigm_imgs}",sign_imgs);
        return html;
    }
    public String getSymptomName(String symptom){
        String symptomName="";
        switch (symptom){
            case "1": symptomName =  " 无症状 ";break;
            case "2": symptomName =  " 头痛 ";break;
            case "3": symptomName =  " 头晕 ";break;
            case "4": symptomName =  " 心悸 ";break;
            case "5": symptomName =  " 胸闷 ";break;
            case "6": symptomName =  " 胸痛 ";break;
            case "7": symptomName =  " 慢性咳嗽 ";break;
            case "8": symptomName =  " 咳痰 ";break;
            case "9": symptomName =  " 呼吸困难 ";break;
            case "10": symptomName =  "多饮 ";break;
            case "11": symptomName =  "多尿 ";break;
            case "12": symptomName =  "体重下降 ";break;
            case "13": symptomName =  "乏力 ";break;
            case "14": symptomName =  "关节肿痛 ";break;
            case "15": symptomName =  "视力模糊 ";break;
            case "16": symptomName =  "手脚麻木 ";break;
            case "17": symptomName =  "尿急 ";break;
            case "18": symptomName =  "尿痛 ";break;
            case "19": symptomName =  "便秘 ";break;
            case "20": symptomName =  "腹泻 ";break;
            case "21": symptomName =  "恶心呕吐 ";break;
            case "22": symptomName =  "眼花 ";break;
            case "23": symptomName =  "耳鸣 ";break;
            case "24": symptomName =  "乳房胀痛 ";break;
            case "25": symptomName =  "其他 ";break;
            default:symptomName=" ";break;
        }
        return symptomName;
    }
}

+ 0 - 105
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/FollowupDrugsService.java

@ -1,105 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.followup;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.afterDiagnosis.dao.dict.DmDrugsGroupItemDao;
import com.yihu.jw.afterDiagnosis.dao.followup.FollowupDrugsDao;
import com.yihu.jw.entity.base.dict.DmDrugsGroupItem;
import com.yihu.jw.entity.followup.FollowupDrugs;
import com.yihu.jw.followup.FollowupContentESDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.*;
/**
 * 随访用药服务
 * @author hzp add 2016-12-08
 *
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class FollowupDrugsService {
	@Autowired
	private FollowupDrugsDao followupDrugsDao;
	@Autowired
	private DmDrugsGroupItemDao dmDrugsGroupItemDao;
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private FollowUpService followUpService;
	private String drugsProject = "6";
	/**
	 * 获取面访用药数据
	 */
	public Map<String,Object> getFollowupDrugs(String id) throws Exception
	{
		Map<String,Object> re = new HashMap<>();
		
		//2017-11-16 修改为从ES获取--huangwenjie
		FollowupContentESDO followupContentESDO = followUpService.esGetFollowupProjectData(id, "6");
		if(followupContentESDO != null){
			re.put("DRUG_COMPLIANCE_CODE",followupContentESDO.getDRUG_COMPLIANCE_CODE());
		}
		//获取用药记录
		List<FollowupDrugs> drugsList = followupDrugsDao.findByFollowupId(Long.valueOf(id));
		re.put("DRUG_LIST",drugsList);
		return re;
	}
	/**
	 *保存面访用药数据
	 */
	@Transactional
	public void saveFollowupDrugs(String id,String drugsData) throws Exception {
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, Map.class);
		List<Map<String,String>> list = objectMapper.readValue(drugsData,javaType);
		Long followupId = Long.valueOf(id);
		//删除原有用药记录
		followupDrugsDao.deleteByFollowupId(Long.valueOf(followupId));
		if(list!=null && list.size()>0)
		{
			List<FollowupDrugs> newList = new ArrayList<>();
			for(Map<String,String> item:list)
			{
				FollowupDrugs drug = new FollowupDrugs();
				drug.setFollowupId(followupId);
				drug.setDrugsGroup(item.get("drugsGroup"));
				drug.setDrugsCode(item.get("drugsCode"));
				drug.setDrugsName(item.get("drugsName"));
				drug.setDose(item.get("dose"));
				drug.setUnit(item.get("unit"));
				drug.setFrequency(item.get("frequency"));
				drug.setCreateTime(new Date());
				newList.add(drug);
			}
			followupDrugsDao.saveAll(newList);
		}
	}
	/*********************************** 疾病用药 *****************************************************************/
	/**
	 *获取疾病用药
	 */
	public List<DmDrugsGroupItem> getFollowupClassDrugs(String followupClass) throws Exception {
		return dmDrugsGroupItemDao.findByFollowupClass(followupClass);
	}
}

+ 0 - 217
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/PhthisisFollowupService.java

@ -1,217 +0,0 @@
//package com.yihu.jw.afterDiagnosis.service.followup;
//
//import com.alibaba.fastjson.JSONObject;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.jw.afterDiagnosis.dao.followup.FollowUpDao;
//import com.yihu.jw.entity.followup.Followup;
//import com.yihu.jw.followup.PhthisisFirstFollowupES;
//import com.yihu.jw.followup.PhthisisFollowupManagementES;
//import com.yihu.jw.followup.PhthisisFollowupPatientInfoES;
//import com.yihu.jw.followup.PhthisisNTimesFollowupES;
//import com.yihu.jw.util.entity.EntityUtils;
//import org.apache.commons.collections.CollectionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//
//import javax.transaction.Transactional;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
///**
// * 肺结核随访服务
// */
//@Component
//@Transactional(rollbackOn = Exception.class)
//public class PhthisisFollowupService {
//
//    private Logger logger = LoggerFactory.getLogger(PhthisisFollowupService.class);
//
//    @Value("${es.index.phthisis_first_followup_index}")
//    private String firstIndex;
//
//    @Value("${es.type.phthisis_first_followup_type}")
//    private String firstType;
//
//    @Value("${es.index.phthisis_n_times_followup_index}")
//    private String nTimesIndex;
//
//    @Value("${es.type.phthisis_n_times_followup_type}")
//    private String nTimesType;
//
//    @Autowired
//    private ElasticSearchHelper elasticSearchHelper;
//
//    @Autowired
//    private FollowUpService followUpService;
//    @Autowired
//    private FollowUpDao followUpDao;
//
//    @Autowired
//    ObjectMapper objectMapper;
//
//    /**
//     * 保存第一次肺结核随访
//     *
//     * @param jsonData
//     */
//    public boolean saveFirstFollowup(String jsonData,StringBuilder errMsg) throws IOException {
//
//        try {
//            JSONObject.parseObject(jsonData);
//        } catch (Exception e) {
//            errMsg.append("参数转换成JSON对象异常:").append(e.getMessage());
//            logger.error(errMsg.toString());
//            return false;
//        }
//        PhthisisFirstFollowupES firstFollowupES = null;
//        try {
//            firstFollowupES = EntityUtils.jsonToEntity(jsonData, PhthisisFirstFollowupES.class);
//        } catch (Exception e) {
//            errMsg.append("第一次肺结核随访json转换成ES实体类异常:").append(e.getMessage());
//            logger.error(errMsg.toString());
//            return false;
//        }
//        if (StringUtils.isEmpty(firstFollowupES.getFollowup_id())) {
//            errMsg.append("随访id为空!");
//            logger.error(errMsg.toString());
//            return false;
//        }
//        Followup followupMysqlEntity = followUpService.findFollowupInfo(Long.parseLong(firstFollowupES.getFollowup_id()));
//        if(null == followupMysqlEntity || null == followupMysqlEntity.getId()){
//            errMsg.append("该随访不存在,随访id-->").append(firstFollowupES.getFollowup_id());
//            logger.error(errMsg.toString());
//            return false;
//        }
//        //设置当前随访状态
//        if(followupMysqlEntity.getStatus().equals("2")){
//            followupMysqlEntity.setStatus("3");
//            followUpDao.save(followupMysqlEntity);
//        }
//        // 设置居民基本信息
//        if(null == firstFollowupES.getPatient()){
//            firstFollowupES.setPatient(new PhthisisFollowupPatientInfoES());
//        }
//        firstFollowupES.getPatient().setName(followupMysqlEntity.getPatientName());
//        firstFollowupES.getPatient().setCode(followupMysqlEntity.getPatientCode());
//
//        //设置医生基本信息
//        firstFollowupES.setSignature_doctor(followupMysqlEntity.getDoctorCode());
//        firstFollowupES.setSignature_doctor_name(followupMysqlEntity.getDoctorName());
//
//        // 当前日期为随访日期
//        firstFollowupES.setCreate_time(new Date());
//
//        if (!elasticSearchHelper.saveWithCustomId(firstIndex, firstType, objectMapper.writeValueAsString(firstFollowupES), "followup_id", errMsg)) {
//            return false;
//        }
//        return true;
//    }
//
//
//    /**
//     * 保存第n次肺结核随访
//     *
//     * @param jsonData
//     */
//    public boolean saveNTimesFollowup(String jsonData,StringBuilder errMsg) throws IOException {
//
//        try {
//            JSONObject.parseObject(jsonData);
//        } catch (Exception e) {
//            errMsg.append("参数转换成JSON对象异常:").append(e.getMessage());
//            logger.error(errMsg.toString());
//            return false;
//        }
//        PhthisisNTimesFollowupES nTimesFollowupES = null;
//        try {
//            nTimesFollowupES = EntityUtils.jsonToEntity(jsonData, PhthisisNTimesFollowupES.class);
//        } catch (Exception e) {
//            errMsg.append("第n次肺结核随访json转换成ES实体类异常:").append(e.getMessage());
//            logger.error(errMsg.toString());
//            return false;
//        }
//        if (StringUtils.isEmpty(nTimesFollowupES.getFollowup_id())) {
//            errMsg.append("随访id为空!");
//            logger.error(errMsg.toString());
//            return false;
//        }
//        Followup followupMysqlEntity = followUpService.findFollowupInfo(Long.parseLong(nTimesFollowupES.getFollowup_id()));
//
//        if(null == followupMysqlEntity || null == followupMysqlEntity.getId()){
//            errMsg.append("该随访不存在,随访id-->").append(nTimesFollowupES.getFollowup_id());
//            logger.error(errMsg.toString());
//            return false;
//        }
//
//        //设置当前随访状态
//        if(followupMysqlEntity.getStatus().equals("2")){
//            followupMysqlEntity.setStatus("3");
//            followUpDao.save(followupMysqlEntity);
//        }
//        // 设置居民基本信息
//        if(null == nTimesFollowupES.getPatient()){
//            nTimesFollowupES.setPatient(new PhthisisFollowupPatientInfoES());
//        }
//        nTimesFollowupES.getPatient().setName(followupMysqlEntity.getPatientName());
//        nTimesFollowupES.getPatient().setCode(followupMysqlEntity.getPatientCode());
//
//        //设置管理情况的医生
//        if(null == nTimesFollowupES.getManagement()){
//            nTimesFollowupES.setManagement(new PhthisisFollowupManagementES());
//        }
//        nTimesFollowupES.getManagement().setSignature_doctor(followupMysqlEntity.getDoctorCode());
//        nTimesFollowupES.getManagement().setSignature_doctor_name(followupMysqlEntity.getDoctorName());
//
//        nTimesFollowupES.getData().forEach(one -> {
//            one.setFollowup_doctor(followupMysqlEntity.getDoctorCode());
//            one.setFollowup_doctor_name(followupMysqlEntity.getDoctorName());
//            one.setCreate_time(new Date());
//        });
//        if (!elasticSearchHelper.saveWithCustomId(nTimesIndex, nTimesType, objectMapper.writeValueAsString(nTimesFollowupES), "followup_id",errMsg)) {
//            return false;
//        }
//        return true;
//    }
//
//    /**
//     * 根据随访id查询第一次随访记录详情
//     *
//     * @param followupId
//     */
//    public JSONObject queryFirstByFollowupId(String followupId) {
//        List<JSONObject> result = new ArrayList<>();
//        String sql = "select * from " + firstIndex + " where followup_id = '" + followupId + "'";
//        try {
//            result = elasticSearchHelper.execCurl(sql);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        if (!CollectionUtils.isEmpty(result)) {
//            return result.get(0);
//        }
//        return new JSONObject();
//    }
//
//    /**
//     * 根据随访id查询第n次随访记录详情
//     *
//     * @param followupId
//     */
//    public List<JSONObject>  queryNTimesByFollowupId(String followupId) {
//        List<JSONObject> result = new ArrayList<>();
//        String sql = "select * from " + nTimesIndex + " where followup_id = '" + followupId + "'";
//        try {
//            result = elasticSearchHelper.execCurl(sql);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return result;
//    }
//
//}

+ 0 - 1051
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/followup/VisitDetailService.java

@ -1,1051 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.followup;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.afterDiagnosis.dao.followup.FollowUpDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.elasticsearch.ElasticSearch7Helper;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.followup.Followup;
import com.yihu.jw.followup.*;
import com.yihu.jw.followup.followupDisease.*;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.searchbox.client.JestClient;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
@Transactional(rollbackOn = Exception.class)
public class VisitDetailService {
    @Value("${es.index.PostpartumVisitRecord}")
    private String esIndexPostpartum;
    @Value("${es.index.FollowupSevereMentalDisorder}")
    private String esIndexSevereMentalDisorder;
    @Value("${es.index.OlderPeopleHealthCheckRecord}")
    private String esIndexOlderPeopleHealthCheck;
    @Value("${es.index.NewbornFamilyVisitRecord}")
    private String esIndexNewbornFamilyVisit;
    @Value("${es.index.phthisis_n_times_followup_index}")
    private String esIndexPhthisisNTimes;
    @Value("${es.index.GynecologicalInflammationDaily}")
    private String esIndexGynecologicalInflammationDaily;
    @Value("${es.index.GynecologicalInflammationFollowupArchives}")
    private String esIndexGynecologicalInflammationFollowupArchives;
    @Value("${es.index.COPDFirstTimeQuestionnaire}")
    private String esIndexCOPDFirstTimeQuestionnaire;
    @Value("${es.index.COPDDailyFollowup}")
    private String esIndexCOPDDailyFollowup;
    //慢性乳腺疾病日常随访
    @Value("${es.index.BreastFollowup}")
    private String esIndexBreastFollowup;//慢性乳腺疾病日常随访
    @Value("${es.index.CerebralApoplexyFollowup}")
    private String esIndexCerebralApoplexyFollowup;
    @Value("${es.index.CoronaryFollowup}")
    private String esIndexCoronaryFollowup;
    @Value("${es.index.FattyLiverFollowUp}")
    private String esIndexFattyLiverFollowUp;
    @Value("${es.index.NephropathyFollowup}")
    private String esIndexNephropathyFollowup;
    @Value("${es.index.ProstateFollowup}")
    private String esIndexProstateFollowup;
    @Autowired
    private ElasticSearch7Helper elasticSearch7Helper;
    @Autowired
    private FollowUpDao followupDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    /**
     * @Title: getNullPropertyNames
     * @Description: 获取值为空的属性名称
     * @createdBy:byrc
     */
    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
    /**
     * 保存孕产妇访视详情记录
     * @param followupId
     * @param followupProject
     * @param postpartumVisitDetails
     * @param doctorCode
     * @throws Exception
     */
    public void savePostpartumVisitDetails(String followupId, String followupProject, String postpartumVisitDetails, String doctorCode) throws Exception {
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        PostpartumVisitRecordES postpartumVisitRecordES = elasticSearch7Helper.searchOne(esIndexPostpartum,searchSourceBuilder,PostpartumVisitRecordES.class);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        //保存新的随访详情信息,如果是编辑的id不变
        String id = null;
        if(postpartumVisitRecordES != null && StringUtils.isNotBlank(postpartumVisitRecordES.getId())) {
            id = postpartumVisitRecordES.getId();
        }
        postpartumVisitRecordES = JSON.parseObject(postpartumVisitDetails,PostpartumVisitRecordES.class);
        postpartumVisitRecordES.setId(id);
        postpartumVisitRecordES.setFollowup_id(followupId);
        postpartumVisitRecordES.setFollowup_project(followupProject);
        postpartumVisitRecordES.setCreate_time(new Date());
        postpartumVisitRecordES.setCreate_user(doctorCode);
        postpartumVisitRecordES.setCreate_user_name(d.getName());
        postpartumVisitRecordES.setVisiting_doctor_code(doctorCode);
        elasticSearch7Helper.saveOne(esIndexPostpartum, postpartumVisitRecordES);
    }
    /**
     * 根据随访id获取孕产妇访视详情
     * @param followupId
     * @param followupProject
     * @return
     * @throws Exception
     */
    public PostpartumVisitRecordES getPostpartumVisitRecord(String followupId, String followupProject) throws Exception{
        PostpartumVisitRecordES postpartumVisitRecordES = null;
        try {
            //根据随访ID、分类ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
//                            .must(QueryBuilders.matchQuery("followup_project", followupProject))
            );
            postpartumVisitRecordES = elasticSearch7Helper.searchOne(esIndexPostpartum,searchSourceBuilder,PostpartumVisitRecordES.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return postpartumVisitRecordES;
    }
    /**
     * 保存严重精神障碍患者随访记录
     * @param followupId
     * @param followupProject
     * @param severeMentalDisorderData
     * @param doctorCode
     * @throws Exception
     */
    public void saveFollowupSevereMentalDisorder(String followupId, String followupProject, String severeMentalDisorderData, String doctorCode) throws Exception{
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        FollowupSevereMentalDisorderES severeMentalDisorderES = elasticSearch7Helper.searchOne(esIndexSevereMentalDisorder,searchSourceBuilder,FollowupSevereMentalDisorderES.class);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        //保存新的随访详情信息
        String id = null;
        if(severeMentalDisorderES != null && StringUtils.isNotBlank(severeMentalDisorderES.getId())) {
            id = severeMentalDisorderES.getId();
        }
        severeMentalDisorderES = JSON.parseObject(severeMentalDisorderData,FollowupSevereMentalDisorderES.class);
        severeMentalDisorderES.setId(id);
        severeMentalDisorderES.setFollowup_id(followupId);
        severeMentalDisorderES.setFollowup_project(followupProject);
        severeMentalDisorderES.setCreate_time(new Date());
        severeMentalDisorderES.setCreate_user(doctorCode);
        severeMentalDisorderES.setCreate_user_name(d.getName());
        elasticSearch7Helper.saveOne(esIndexSevereMentalDisorder, severeMentalDisorderES);
    }
    /**
     * 获取严重精神障碍患者随访记录
     * @param followupId
     * @param followupProject
     * @return
     * @throws IOException
     */
    public FollowupSevereMentalDisorderES getFollowupSevereMentalDisorder(String followupId, String followupProject) throws IOException {
        FollowupSevereMentalDisorderES severeMentalDisorderES = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
//                            .must(QueryBuilders.matchQuery("followup_project", followupProject))
            );
            severeMentalDisorderES = elasticSearch7Helper.searchOne(esIndexSevereMentalDisorder,searchSourceBuilder,FollowupSevereMentalDisorderES.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return severeMentalDisorderES;
    }
    /**
     * 保存老人健康体检随访记录
     * @param followupId
     * @param followupProject
     * @param olderPeopleHealthCheckData
     * @param doctorCode
     * @throws Exception
     */
    public void saveOlderPeopleHealthCheckRecord(String followupId, String followupProject, String olderPeopleHealthCheckData, String doctorCode,Integer bdStatus,Integer pgStatus) throws Exception{
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        OlderPeopleHealthCheckRecordES olderPeopleHealthCheckRecord = elasticSearch7Helper.searchOne(esIndexOlderPeopleHealthCheck,searchSourceBuilder,OlderPeopleHealthCheckRecordES.class);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        if (followup.getFollowupClass().equals("8")){
            if (bdStatus != null && bdStatus == 1){
                followup.setBdStatus(1);
            }else {
                followup.setPgStatus(1);
            }
        }
        followupDao.save(followup);
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        //保存新的随访详情信息
        String id = null;
        if(olderPeopleHealthCheckRecord != null && StringUtils.isNotBlank(olderPeopleHealthCheckRecord.getId())) {
            id = olderPeopleHealthCheckRecord.getId();
        }
        olderPeopleHealthCheckRecord = JSON.parseObject(olderPeopleHealthCheckData,OlderPeopleHealthCheckRecordES.class);
        olderPeopleHealthCheckRecord.setId(id);
        olderPeopleHealthCheckRecord.setFollowup_id(followupId);
        olderPeopleHealthCheckRecord.setFollowup_project(followupProject);
        olderPeopleHealthCheckRecord.setCreate_time(new Date());
        olderPeopleHealthCheckRecord.setCreate_user(doctorCode);
        olderPeopleHealthCheckRecord.setCreate_user_name(d.getName());
        elasticSearch7Helper.saveOne(esIndexOlderPeopleHealthCheck, olderPeopleHealthCheckRecord);
    }
    /**
     * 获取老人健康体检随访记录
     * @param followupId
     * @param followupProject
     * @return
     * @throws Exception
     */
    public OlderPeopleHealthCheckRecordES getOlderPeopleHealthCheckRecord(String followupId, String followupProject) throws Exception{
        OlderPeopleHealthCheckRecordES olderPeopleHealthCheckRecord = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
//                            .must(QueryBuilders.matchQuery("followup_project", followupProject))
            );
            olderPeopleHealthCheckRecord = elasticSearch7Helper.searchOne(esIndexOlderPeopleHealthCheck,searchSourceBuilder,OlderPeopleHealthCheckRecordES.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return olderPeopleHealthCheckRecord;
    }
    /**
     * 保存新生儿家庭访视记录
     * @param followupId
     * @param followupProject
     * @param newbornFamilyVisitRecordData
     * @param doctorCode
     * @throws Exception
     */
    public void saveNewbornFamilyVisitRecord(String followupId, String followupProject, String newbornFamilyVisitRecordData, String doctorCode) throws Exception{
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        NewbornFamilyVisitRecordES newbornFamilyVisitRecordES = elasticSearch7Helper.searchOne(esIndexNewbornFamilyVisit,searchSourceBuilder,NewbornFamilyVisitRecordES.class);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        //保存新的随访详情信息
        String id = null;
        if(newbornFamilyVisitRecordES != null && StringUtils.isNotBlank(newbornFamilyVisitRecordES.getId())) {
            id = newbornFamilyVisitRecordES.getId();
        }
        newbornFamilyVisitRecordES = JSON.parseObject(newbornFamilyVisitRecordData,NewbornFamilyVisitRecordES.class);
        newbornFamilyVisitRecordES.setId(id);
        newbornFamilyVisitRecordES.setFollowup_id(followupId);
        newbornFamilyVisitRecordES.setFollowup_project(followupProject);
        newbornFamilyVisitRecordES.setCreate_time(new Date());
        newbornFamilyVisitRecordES.setCreate_user(doctorCode);
        newbornFamilyVisitRecordES.setCreate_user_name(d.getName());
        elasticSearch7Helper.saveOne(esIndexNewbornFamilyVisit, newbornFamilyVisitRecordES);
    }
    /**
     * 获取新生儿家庭访视记录
     * @param followupId
     * @param followupProject
     * @return
     * @throws Exception
     */
    public NewbornFamilyVisitRecordES getNewbornFamilyVisitRecord(String followupId, String followupProject) throws Exception{
        JestClient jestClient = null;
        NewbornFamilyVisitRecordES newbornFamilyVisitRecordES = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
//                            .must(QueryBuilders.matchQuery("followup_project", followupProject))
            );
            newbornFamilyVisitRecordES = elasticSearch7Helper.searchOne(esIndexNewbornFamilyVisit,searchSourceBuilder,NewbornFamilyVisitRecordES.class);
        } catch (Exception e){
            e.printStackTrace();
        }
        return newbornFamilyVisitRecordES;
    }
    /**
     * 根据居民code和访视类别获取上次随访记录
     * @param patientCode
     * @param followupClass 5.产后 6.新生儿 7.严重精神病 8.80岁以上老人 9.肺结核
     * @return
     */
    public JSONObject getLastVisitRecord(String patientCode, String followupClass) throws Exception {
        JSONObject res = new JSONObject();
        List<Followup> followupList = followupDao.findAllByPatientCodeAndClass(patientCode, followupClass);
        if (followupList.size() > 0) {
            String sql = "";
            res.put("followup", followupList.get(0));
            //产后记录
            if(followupClass.equals("5")) {
                PostpartumVisitRecordES es = this.getPostpartumVisitRecord(followupList.get(0).getId() + "", null);
                res.put("detail", es);
            }else  if(followupClass.equals("6")) {
                NewbornFamilyVisitRecordES es = this.getNewbornFamilyVisitRecord(followupList.get(0).getId() + "", null);
                res.put("detail", es);
            }else  if(followupClass.equals("7")) {
                FollowupSevereMentalDisorderES es = this.getFollowupSevereMentalDisorder(followupList.get(0).getId() + "", null);
                res.put("detail", es);
            }else  if(followupClass.equals("8")) {
                OlderPeopleHealthCheckRecordES es = this.getOlderPeopleHealthCheckRecord(followupList.get(0).getId() + "", null);
                res.put("detail", es);
            }else  if(followupClass.equals("9") && followupList.size() >= 2) {  //非第一次肺结核访视
//                List<JSONObject> returnList = phthisisFollowupService.queryNTimesByFollowupId(followupList.get(0).getId() + "");
//                res.put("detail", returnList);
            }
        }
        return res;
    }
    /**
     * 保存慢性妇科炎症日常随访
     * @param followupId
     * @param jsonData
     * @param doctorCode
     * @return
     * @throws Exception
     */
    public GynecologicalInflammationDailyFollowupES saveGynecologicalInflammationDaily(String followupId, String jsonData, String doctorCode) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        Followup followupTemp = JSON.parseObject(jsonObject.getString("followup"), Followup.class);
        BeanUtils.copyProperties(followupTemp, followup, getNullPropertyNames(followupTemp));
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        GynecologicalInflammationDailyFollowupES dailyFollowupES = elasticSearch7Helper.searchOne(esIndexGynecologicalInflammationDaily,searchSourceBuilder,GynecologicalInflammationDailyFollowupES.class);
        GynecologicalInflammationDailyFollowupES dailyFollowupNew = JSON.parseObject(jsonObject.getString("content"), GynecologicalInflammationDailyFollowupES.class);
        if(dailyFollowupES != null) {
            BeanUtils.copyProperties(dailyFollowupNew, dailyFollowupES, getNullPropertyNames(dailyFollowupNew));
        }else {
            dailyFollowupES = dailyFollowupNew;
        }
        //保存新的随访详情信息
        if(StringUtils.isBlank(dailyFollowupES.getId())) {
            dailyFollowupES.setFollowup_id(followupId);
            dailyFollowupES.setCreateTime(new Date());
            dailyFollowupES.setCreateOperator(doctorCode);
            dailyFollowupES.setCreateOperatorName(d.getName());
            dailyFollowupES.setValidFlag("1");
        }
        dailyFollowupES.setModifyTime(new Date());
        dailyFollowupES.setModifyOperator(doctorCode);
        dailyFollowupES.setModifyOperatorName(d.getName());
        elasticSearch7Helper.saveOne(esIndexGynecologicalInflammationDaily, dailyFollowupES);
        return dailyFollowupES;
    }
    /**
     * 获取慢性妇科炎症日常随访
     * @param followupId
     * @return
     * @throws Exception
     */
    public JSONObject getGynecologicalInflammationDaily(String followupId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        jsonObject.put("followup", followup);
        GynecologicalInflammationDailyFollowupES dailyFollowupES = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
            );
            dailyFollowupES = elasticSearch7Helper.searchOne(esIndexGynecologicalInflammationDaily,searchSourceBuilder,GynecologicalInflammationDailyFollowupES.class);
            jsonObject.put("content", dailyFollowupES);
        } catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
    /**
     * 保存妇科炎症随访档案
     * @param followupId
     * @param jsonData
     * @param doctorCode
     * @return
     * @throws Exception
     */
    public GynecologicalInflammationFollowupArchivesES saveGynecologicalInflammationFollowupArchives(String followupId, String jsonData, String doctorCode) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        Followup followupTemp = JSON.parseObject(jsonObject.getString("followup"), Followup.class);
        BeanUtils.copyProperties(followupTemp, followup, getNullPropertyNames(followupTemp));
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        GynecologicalInflammationFollowupArchivesES followupArchives = elasticSearch7Helper.searchOne(esIndexGynecologicalInflammationFollowupArchives,searchSourceBuilder,GynecologicalInflammationFollowupArchivesES.class);
        GynecologicalInflammationFollowupArchivesES followupArchivesNew = JSON.parseObject(jsonObject.getString("content"), GynecologicalInflammationFollowupArchivesES.class);
        if(followupArchives != null) {
            BeanUtils.copyProperties(followupArchivesNew, followupArchives, getNullPropertyNames(followupArchivesNew));
        }else {
            followupArchives = followupArchivesNew;
        }
        //保存新的随访详情信息
        if(StringUtils.isBlank(followupArchives.getId())) {
            followupArchives.setFollowup_id(followupId);
            followupArchives.setCreateTime(new Date());
            followupArchives.setCreateOperator(doctorCode);
            followupArchives.setCreateOperatorName(d.getName());
            followupArchives.setValidFlag("1");
        }
        followupArchives.setModifyTime(new Date());
        followupArchives.setModifyOperator(doctorCode);
        followupArchives.setModifyOperatorName(d.getName());
        elasticSearch7Helper.saveOne(esIndexGynecologicalInflammationFollowupArchives, followupArchives);
        return followupArchives;
    }
    /**
     * 获取各类病种单日常随访
     * type:
     * BreastFollowup //4.慢性乳腺疾病日常随访
     * CerebralApoplexyFollowup //7.脑卒中日常随访
     * CoronaryFollowup//1.冠心病日常随访
     * FattyLiverFollowUp//8.脂肪肝日常随访
     * NephropathyFollowup//5.慢性肾病日常随访
     * ProstateFollowup//3.慢性前列腺疾病日常随访
     * @param followupId
     * @return
     * @throws Exception
     */
    public JSONObject selectFollowupDiseaseById(String followupId,String type) throws Exception {
        JSONObject jsonObject = new JSONObject();
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        jsonObject.put("followup", followup);
        BreastFollowupES breastFollowupES = null;
        CerebralApoplexyFollowupES cerebralApoplexyFollowupES = null;
        CoronaryFollowupES coronaryFollowupES = null;
        FattyLiverFollowUpES fattyLiverFollowUpES = null;
        NephropathyFollowupES nephropathyFollowupES = null;
        ProstateFollowupES prostateFollowupES = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
            );
            if (type.equalsIgnoreCase("BreastFollowup")) {
                breastFollowupES = elasticSearch7Helper.searchOne(esIndexBreastFollowup,searchSourceBuilder,BreastFollowupES.class);
                jsonObject.put("content", breastFollowupES);
            } else if (type.equalsIgnoreCase("CerebralApoplexyFollowup")) {
                cerebralApoplexyFollowupES = elasticSearch7Helper.searchOne(esIndexCerebralApoplexyFollowup,searchSourceBuilder,CerebralApoplexyFollowupES.class);
                jsonObject.put("content", cerebralApoplexyFollowupES);
            } else if (type.equalsIgnoreCase("CoronaryFollowup")) {
                coronaryFollowupES = elasticSearch7Helper.searchOne(esIndexCoronaryFollowup,searchSourceBuilder,CoronaryFollowupES.class);
                jsonObject.put("content", coronaryFollowupES);
            } else if (type.equalsIgnoreCase("FattyLiverFollowUp")) {
                fattyLiverFollowUpES = elasticSearch7Helper.searchOne(esIndexFattyLiverFollowUp,searchSourceBuilder,FattyLiverFollowUpES.class);
                jsonObject.put("content", fattyLiverFollowUpES);
            } else if (type.equalsIgnoreCase("NephropathyFollowup")) {
                nephropathyFollowupES = elasticSearch7Helper.searchOne(esIndexNephropathyFollowup,searchSourceBuilder,NephropathyFollowupES.class);
                jsonObject.put("content", nephropathyFollowupES);
            } else if (type.equalsIgnoreCase("ProstateFollowup")) {
                prostateFollowupES = elasticSearch7Helper.searchOne(esIndexProstateFollowup,searchSourceBuilder,ProstateFollowupES.class);
                jsonObject.put("content", prostateFollowupES);
            }
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("content", null);
        }
        return jsonObject;
    }
    /**
     *
     * @param followupId
     * @param jsonData
     * @param doctorCode
     * @param type
     * @return
     * @throws Exception
     * BreastFollowup: breast_followup
    CerebralApoplexyFollowup: cerebral_apoplexy_followup
    CoronaryFollowup: coronary_followup
    FattyLiverFollowUp: fatty_liverFollowUp
    NephropathyFollowup: nephropathy_followup
    ProstateFollowup: prostate_followup
     */
    public void saveFollowupDiseaseArchives(String followupId, String jsonData, String doctorCode,String type) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        Followup followupTemp = JSON.parseObject(jsonObject.getString("followup"), Followup.class);
        BeanUtils.copyProperties(followupTemp, followup, getNullPropertyNames(followupTemp));
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
//                        .must(QueryBuilders.matchQuery("followup_project", followupProject))
        );
        BasePatientDO patient1 = patientDao.findById(followup.getPatientCode()).orElse(null);
        String idcard = "";
        if (patient1!=null){
            idcard = patient1.getIdcard();
        }
        String followDoctor = followup.getJwdoctorCode();//随访医生
        String followTime= DateUtil.dateToStrLong(followup.getFollowupDate());//随访时间
        //判断随访方式【1.门诊 2.电话 3.入户】,待确定
        String followupType = followup.getFollowupType();
        String followType = "";
        if(followupType.equals("1") || followupType.equals("22")) {
            followType="1";
        }else if(followupType.equals("3")) {
            followType="2";
        }
        BaseDoctorDO doctor = doctorDao.findByIdAndDel(followup.getDoctorCode());
        String followDoctorType=doctor.getLevel()+"";
        String nextFollowTime=DateUtil.dateToStrLong(followup.getFollowupNextDate());//下次随访时间
        String assessSource="4";//评估来源【1.前台三合一 2. 前台独立 3.后台自动 4.i健康】
        //判断是新增还是编辑,如果是编辑传回随访ID,新增则不传
        if (type.equalsIgnoreCase("BreastFollowup")){
            //4.慢性乳腺疾病日常随访
            BreastFollowupES breastFollowup = elasticSearch7Helper.searchOne(esIndexBreastFollowup,searchSourceBuilder,BreastFollowupES.class);
            BreastFollowupES breastFollowupNew = JSON.parseObject(jsonObject.getString("content"), BreastFollowupES.class);
            if(breastFollowup != null) {
                BeanUtils.copyProperties(breastFollowupNew, breastFollowup, getNullPropertyNames(breastFollowupNew));
            }else {
                breastFollowup = breastFollowupNew;
            }
            //保存新的随访详情信息
            if(StringUtils.isBlank(breastFollowup.getId())) {
                breastFollowup.setFollowup_id(followupId);
                breastFollowup.setCreateTime(DateUtil.getStringDate());
                breastFollowup.setCreateOperator(doctorCode);
                breastFollowup.setCreateOperatorName(d.getName());
                breastFollowup.setValidFlag("1");
                breastFollowup.setIdentityCardNo(idcard);
//                breastFollowup.setOrgId(orgId);
//                breastFollowup.setFollowOrgId(followOrgId);
                breastFollowup.setFollowDoctor(followDoctor);
                breastFollowup.setFollowTime(followTime);
                breastFollowup.setFollowType(followType);
                breastFollowup.setFollowDoctorType(followDoctorType);
                breastFollowup.setAssessSource(assessSource);
                breastFollowup.setNextFollowTime(nextFollowTime);
            }
            breastFollowup.setModifyTime(DateUtil.getStringDate());
            breastFollowup.setModifyOperator(doctorCode);
            breastFollowup.setModifyOperatorName(d.getName());
            elasticSearch7Helper.saveOne(esIndexBreastFollowup, breastFollowup);
        }else if (type.equalsIgnoreCase("CoronaryFollowup")){
            //1.冠心病日常随访
            CoronaryFollowupES coronaryFollowup = elasticSearch7Helper.searchOne(esIndexCoronaryFollowup,searchSourceBuilder,CoronaryFollowupES.class);
            CoronaryFollowupES coronaryFollowupNew = JSON.parseObject(jsonObject.getString("content"), CoronaryFollowupES.class);
            if(coronaryFollowup != null) {
                BeanUtils.copyProperties(coronaryFollowupNew, coronaryFollowup, getNullPropertyNames(coronaryFollowupNew));
            }else {
                coronaryFollowup = coronaryFollowupNew;
            }
            //保存新的随访详情信息
            if(StringUtils.isBlank(coronaryFollowup.getId())) {
                coronaryFollowup.setFollowup_id(followupId);
                coronaryFollowup.setCreateTime(DateUtil.getStringDate());
                coronaryFollowup.setCreateOperator(doctorCode);
                coronaryFollowup.setCreateOperatorName(d.getName());
                coronaryFollowup.setValidFlag("1");
                coronaryFollowup.setIdentityCardNo(idcard);
//                coronaryFollowup.setOrgId(orgId);
//                coronaryFollowup.setFollowOrgId(followOrgId);
                coronaryFollowup.setFollowDoctor(followDoctor);
                coronaryFollowup.setFollowTime(followTime);
                coronaryFollowup.setFollowType(followType);
                coronaryFollowup.setFollowDoctorType(followDoctorType);
                coronaryFollowup.setAssessSource(assessSource);
                coronaryFollowup.setNextFollowTime(nextFollowTime);
            }
            coronaryFollowup.setModifyTime(DateUtil.getStringDate());
            coronaryFollowup.setModifyOperator(doctorCode);
            coronaryFollowup.setModifyOperatorName(d.getName());
            elasticSearch7Helper.saveOne(esIndexCoronaryFollowup, coronaryFollowup);
        }else if (type.equalsIgnoreCase("CerebralApoplexyFollowup")){
            //7.脑卒中日常随访
            CerebralApoplexyFollowupES cerebralApoplexyFollowup = elasticSearch7Helper.searchOne(esIndexCerebralApoplexyFollowup,searchSourceBuilder,CerebralApoplexyFollowupES.class);
            CerebralApoplexyFollowupES cerebralApoplexyFollowupNew = JSON.parseObject(jsonObject.getString("content"), CerebralApoplexyFollowupES.class);
            if(cerebralApoplexyFollowup != null) {
                BeanUtils.copyProperties(cerebralApoplexyFollowupNew, cerebralApoplexyFollowup, getNullPropertyNames(cerebralApoplexyFollowupNew));
            }else {
                cerebralApoplexyFollowup = cerebralApoplexyFollowupNew;
            }
            //保存新的随访详情信息
            if(StringUtils.isBlank(cerebralApoplexyFollowup.getId())) {
                cerebralApoplexyFollowup.setFollowup_id(followupId);
                cerebralApoplexyFollowup.setCreateTime(DateUtil.getStringDate());
                cerebralApoplexyFollowup.setCreateOperator(doctorCode);
                cerebralApoplexyFollowup.setCreateOperatorName(d.getName());
                cerebralApoplexyFollowup.setValidFlag("1");
                cerebralApoplexyFollowup.setIdentityCardNo(idcard);
//                cerebralApoplexyFollowup.setOrgId(orgId);
//                cerebralApoplexyFollowup.setFollowOrgId(followOrgId);
                cerebralApoplexyFollowup.setFollowDoctor(followDoctor);
                cerebralApoplexyFollowup.setFollowTime(followTime);
                cerebralApoplexyFollowup.setFollowType(followType);
                cerebralApoplexyFollowup.setFollowDoctorType(followDoctorType);
                cerebralApoplexyFollowup.setAssessSource(assessSource);
                cerebralApoplexyFollowup.setNextFollowTime(nextFollowTime);
            }
            cerebralApoplexyFollowup.setModifyTime(DateUtil.getStringDate());
            cerebralApoplexyFollowup.setModifyOperator(doctorCode);
            cerebralApoplexyFollowup.setModifyOperatorName(d.getName());
            elasticSearch7Helper.saveOne(esIndexCerebralApoplexyFollowup , cerebralApoplexyFollowup);
        }else if (type.equalsIgnoreCase("FattyLiverFollowUp")){
            //8.脂肪肝日常随访
            FattyLiverFollowUpES fattyLiverFollowUp = elasticSearch7Helper.searchOne(esIndexFattyLiverFollowUp,searchSourceBuilder,FattyLiverFollowUpES.class);
            FattyLiverFollowUpES fattyLiverFollowUpNew = JSON.parseObject(jsonObject.getString("content"), FattyLiverFollowUpES.class);
            if(fattyLiverFollowUp != null) {
                BeanUtils.copyProperties(fattyLiverFollowUpNew, fattyLiverFollowUp, getNullPropertyNames(fattyLiverFollowUpNew));
            }else {
                fattyLiverFollowUp = fattyLiverFollowUpNew;
            }
            //保存新的随访详情信息
            if(StringUtils.isBlank(fattyLiverFollowUp.getId())) {
                fattyLiverFollowUp.setFollowup_id(followupId);
                fattyLiverFollowUp.setCreateTime(DateUtil.getStringDate());
                fattyLiverFollowUp.setCreateOperator(doctorCode);
                fattyLiverFollowUp.setCreateOperatorName(d.getName());
                fattyLiverFollowUp.setValidFlag("1");
                fattyLiverFollowUp.setIdentityCardNo(idcard);
//                fattyLiverFollowUp.setOrgId(orgId);
//                fattyLiverFollowUp.setFollowOrgId(followOrgId);
                fattyLiverFollowUp.setFollowDoctor(followDoctor);
                fattyLiverFollowUp.setFollowTime(followTime);
                fattyLiverFollowUp.setFollowType(followType);
                fattyLiverFollowUp.setFollowDoctorType(followDoctorType);
                fattyLiverFollowUp.setAssessSource(assessSource);
                fattyLiverFollowUp.setNextFollowTime(nextFollowTime);
            }
            fattyLiverFollowUp.setModifyTime(DateUtil.getStringDate());
            fattyLiverFollowUp.setModifyOperator(doctorCode);
            fattyLiverFollowUp.setModifyOperatorName(d.getName());
            elasticSearch7Helper.saveOne(esIndexFattyLiverFollowUp , fattyLiverFollowUp);
        }else if (type.equalsIgnoreCase("NephropathyFollowup")){
            //8.脂肪肝日常随访
            NephropathyFollowupES nephropathyFollowup = elasticSearch7Helper.searchOne(esIndexNephropathyFollowup,searchSourceBuilder,NephropathyFollowupES.class);
            NephropathyFollowupES nephropathyFollowupNew = JSON.parseObject(jsonObject.getString("content"), NephropathyFollowupES.class);
            if(nephropathyFollowup != null) {
                BeanUtils.copyProperties(nephropathyFollowupNew, nephropathyFollowup, getNullPropertyNames(nephropathyFollowupNew));
            }else {
                nephropathyFollowup = nephropathyFollowupNew;
            }
            //保存新的随访详情信息
            if(StringUtils.isBlank(nephropathyFollowup.getId())) {
                nephropathyFollowup.setFollowup_id(followupId);
                nephropathyFollowup.setCreateTime(DateUtil.getStringDate());
                nephropathyFollowup.setCreateOperator(doctorCode);
                nephropathyFollowup.setCreateOperatorName(d.getName());
                nephropathyFollowup.setValidFlag("1");
                nephropathyFollowup.setIdentityCardNo(idcard);
//                nephropathyFollowup.setOrgId(orgId);
//                nephropathyFollowup.setFollowOrgId(followOrgId);
                nephropathyFollowup.setFollowDoctor(followDoctor);
                nephropathyFollowup.setFollowTime(followTime);
                nephropathyFollowup.setFollowType(followType);
                nephropathyFollowup.setFollowDoctorType(followDoctorType);
                nephropathyFollowup.setAssessSource(assessSource);
                nephropathyFollowup.setNextFollowTime(nextFollowTime);
            }
            nephropathyFollowup.setModifyTime(DateUtil.getStringDate());
            nephropathyFollowup.setModifyOperator(doctorCode);
            nephropathyFollowup.setModifyOperatorName(d.getName());
            elasticSearch7Helper.saveOne(esIndexNephropathyFollowup , nephropathyFollowup);
        }else if (type.equalsIgnoreCase("ProstateFollowup")){
            //8.脂肪肝日常随访
            ProstateFollowupES prostateFollowup = elasticSearch7Helper.searchOne(esIndexProstateFollowup,searchSourceBuilder,ProstateFollowupES.class);
            ProstateFollowupES prostateFollowupNew = JSON.parseObject(jsonObject.getString("content"), ProstateFollowupES.class);
            if(prostateFollowup != null) {
                BeanUtils.copyProperties(prostateFollowupNew, prostateFollowup, getNullPropertyNames(prostateFollowupNew));
            }else {
                prostateFollowup = prostateFollowupNew;
            }
            //保存新的随访详情信息
            if(StringUtils.isBlank(prostateFollowup.getId())) {
                prostateFollowup.setFollowup_id(followupId);
                prostateFollowup.setCreateTime(DateUtil.getStringDate());
                prostateFollowup.setCreateOperator(doctorCode);
                prostateFollowup.setCreateOperatorName(d.getName());
                prostateFollowup.setValidFlag("1");
                prostateFollowup.setIdentityCardNo(idcard);
//                prostateFollowup.setOrgId(orgId);
//                prostateFollowup.setFollowOrgId(followOrgId);
                prostateFollowup.setFollowDoctor(followDoctor);
                prostateFollowup.setFollowTime(followTime);
                prostateFollowup.setFollowType(followType);
                prostateFollowup.setFollowDoctorType(followDoctorType);
                prostateFollowup.setAssessSource(assessSource);
                prostateFollowup.setNextFollowTime(nextFollowTime);
            }
            prostateFollowup.setModifyTime(DateUtil.getStringDate());
            prostateFollowup.setModifyOperator(doctorCode);
            prostateFollowup.setModifyOperatorName(d.getName());
            elasticSearch7Helper.saveOne(esIndexProstateFollowup , prostateFollowup);
        }
    }
    /**
     * 获取妇科炎症随访档案
     * @param followupId
     * @return
     * @throws Exception
     */
    public JSONObject getGynecologicalInflammationFollowupArchives(String followupId) throws Exception {
        JSONObject jsonObject = new JSONObject();
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        jsonObject.put("followup", followup);
        GynecologicalInflammationFollowupArchivesES followupArchivesES = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
            );
            followupArchivesES = elasticSearch7Helper.searchOne(esIndexGynecologicalInflammationFollowupArchives,searchSourceBuilder,GynecologicalInflammationFollowupArchivesES.class);
            jsonObject.put("content", followupArchivesES);
        } catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
    /**
     * 保存慢性阻塞性肺病--首次问卷
     * @param followupId
     * @param jsonData
     * @param doctorCode
     * @return
     * @throws Exception
     */
    public COPDFirstTimeQuestionnaireES saveCOPDFirstTimeQuestionnaire(String followupId, String jsonData, String doctorCode) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        Followup followupTemp = JSON.parseObject(jsonObject.getString("followup"), Followup.class);
        BeanUtils.copyProperties(followupTemp, followup, getNullPropertyNames(followupTemp));
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
        );
        COPDFirstTimeQuestionnaireES COPD = elasticSearch7Helper.searchOne(esIndexCOPDFirstTimeQuestionnaire,searchSourceBuilder,COPDFirstTimeQuestionnaireES.class);
        COPDFirstTimeQuestionnaireES COPDNew = JSON.parseObject(jsonObject.getString("content"), COPDFirstTimeQuestionnaireES.class);
        if(COPD != null) {
            BeanUtils.copyProperties(COPDNew, COPD, getNullPropertyNames(COPDNew));
        }else {
            COPD = COPDNew;
        }
        //保存新的随访详情信息
        if(StringUtils.isBlank(COPD.getId())) {
            COPD.setFollowup_id(followupId);
            COPD.setValidFlag("1");
            COPD.setCreateTime(new Date());
            COPD.setCreateOperator(doctorCode);
            COPD.setCreateOperatorName(d.getName());
        }
        COPD.setModifyTime(new Date());
        COPD.setModifyOperator(doctorCode);
        COPD.setModifyOperatorName(d.getName());
        elasticSearch7Helper.saveOne(esIndexCOPDFirstTimeQuestionnaire, COPD);
        return COPD;
    }
    /**
     * 获取慢性阻塞性肺病--首次问卷
     * @param followupId
     * @return
     * @throws IOException
     */
    public JSONObject getCOPDFirstTimeQuestionnaire(String followupId) throws IOException {
        JSONObject jsonObject = new JSONObject();
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        jsonObject.put("followup", followup);
        JestClient jestClient = null;
        COPDFirstTimeQuestionnaireES COPD = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
            );
            COPD = elasticSearch7Helper.searchOne(esIndexCOPDFirstTimeQuestionnaire,searchSourceBuilder,COPDFirstTimeQuestionnaireES.class);
            jsonObject.put("content", COPD);
        } catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
    /**
     * 保存慢性阻塞性肺病--日常随访
     * @param followupId
     * @param jsonData
     * @param doctorCode
     * @return
     * @throws Exception
     */
    public COPDDailyFollowupES saveCOPDDailyFollowup(String followupId, String jsonData, String doctorCode) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(jsonData);
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        Followup followupTemp = JSON.parseObject(jsonObject.getString("followup"), Followup.class);
        BeanUtils.copyProperties(followupTemp, followup, getNullPropertyNames(followupTemp));
        //设置当前随访状态
        if(followup.getStatus().equals("2")){
            followup.setStatus("3");
            followupDao.save(followup);
        }
        BaseDoctorDO d = null;
        if(StringUtils.isNotBlank(doctorCode)){
            d = doctorDao.findByIdAndDel(doctorCode);
        }else {
            throw new ServiceException("该医生不存在!");
        }
        //先根据条件查找出来
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(
                new BoolQueryBuilder()
                        .must(QueryBuilders.matchQuery("followup_id", followupId))
        );
        COPDDailyFollowupES COPD = elasticSearch7Helper.searchOne(esIndexCOPDDailyFollowup,searchSourceBuilder,COPDDailyFollowupES.class);
        COPDDailyFollowupES COPDNew = JSON.parseObject(jsonObject.getString("content"), COPDDailyFollowupES.class);
        if(COPD != null) {
            BeanUtils.copyProperties(COPDNew, COPD, getNullPropertyNames(COPDNew));
        }else {
            COPD = COPDNew;
        }
        //保存新的随访详情信息
        if(StringUtils.isBlank(COPD.getId())) {
            COPD.setFollowup_id(followupId);
            COPD.setValidFlag("1");
            COPD.setCreateTime(new Date());
            COPD.setCreateOperator(doctorCode);
            COPD.setCreateOperatorName(d.getName());
        }
        COPD.setModifyTime(new Date());
        COPD.setModifyOperator(doctorCode);
        COPD.setModifyOperatorName(d.getName());
        elasticSearch7Helper.saveOne(esIndexCOPDDailyFollowup, COPD);
        return COPD;
    }
    /**
     * 获取慢性阻塞性肺病--日常随访
     * @param followupId
     * @return
     * @throws IOException
     */
    public JSONObject getCOPDDailyFollowup(String followupId) throws IOException {
        JSONObject jsonObject = new JSONObject();
        Followup followup = followupDao.findById(Long.parseLong(followupId)).orElse(null);
        jsonObject.put("followup", followup);
        COPDDailyFollowupES COPD = null;
        try {
            //根据随访ID获取随访记录详情
            //先根据条件查找出来
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(
                    new BoolQueryBuilder()
                            .must(QueryBuilders.matchQuery("followup_id", followupId))
            );
            COPD = elasticSearch7Helper.searchOne(esIndexCOPDDailyFollowup,searchSourceBuilder,COPDDailyFollowupES.class);
            jsonObject.put("content", COPD);
        } catch (Exception e){
            e.printStackTrace();
        }
        return jsonObject;
    }
}

+ 0 - 276
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PatientPrescriptionPayService.java

@ -1,276 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.prescription;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.afterDiagnosis.dao.prescription.PrescriptionPayDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.order.PayLog;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDiagnosisDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.order.dao.PayLogDao;
import com.yihu.jw.order.pay.utils.PayLogService;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Reece on 2017/7/28/028.
 * 患者支付
 */
@Service
public class PatientPrescriptionPayService {
    private Logger logger = LoggerFactory.getLogger(PatientPrescriptionPayService.class);
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PayLogService logService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private PrescriptionPayDao payDao;
    @Autowired
    private WlyyPrescriptionService prescriptionService;
    @Autowired
    private PrescriptionInfoDao infoDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionExpressageDao expressageDao;
    @Autowired
    private PrescriptionInfoService infoService;
    @Autowired
    private PayLogDao payLogDao;
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    @Autowired
    private BaseOrgDao hospitalDao;
    /**
     * 长处方配送信息查询接口
     *
     * @param
     * @return
     */
    public JSONObject dispatch(String prescriptionCode, String orgCode) throws Exception {
        JSONObject result = new JSONObject();
        List manage = new ArrayList();
        List types = new ArrayList();
        BaseOrgDO hospital = hospitalDao.findByCode(orgCode);
        String hostpitalName = hospital.getName();
        String address = hospital.getAddress();
        String streeCode = hospital.getStreetCode();
        String townCode = hospital.getTownCode();
        String townName = hospital.getTownName();
        String cityCode = hospital.getCityCode();
        String cityName = hospital.getCityName();
        String provinceCode = hospital.getProvinceCode();
        String provinceName = hospital.getProvinceName();
        String h = orgCode.substring(0, 8);
        String sql = "SELECT h.`code`,h.`name`,h.`province` provinceCode,h.`province_name` provinceName,h.`city` cityCode ,h.`city_name` cityName," +
                " h.`town` townCode,h.`town_name` townName,h.`road_code` streeCode,h.`address` " +
                " FROM dm_hospital h  " +
                " WHERE h.`code` LIKE '%" + h + "%' AND RIGHT(h.code,2)<>'00' ";
        List<Map<String, Object>> hs = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> hspital : hs) {
            Map temp = new HashMap();
            String code = (String) hspital.get("code");
            String name = (String) hspital.get("name");
            String manageProvinceCode = (String) hspital.get("provinceCode");
            String manageProvinceName = (String) hspital.get("provinceName");
            String manageCityCode = (String) hspital.get("cityCode");
            String manageCityName = (String) hspital.get("cityName");
            String manageTownCode = (String) hspital.get("townCode");
            String manageTownName = (String) hspital.get("townName");
            String manageStreeCode = (String) hspital.get("streeCode");
            String manageAddress = (String) hspital.get("address");
            temp.put("code", code);
            temp.put("name", name);
            temp.put("provinceCode", manageProvinceCode);
            temp.put("provinceName", manageProvinceName);
            temp.put("cityCode", manageCityCode);
            temp.put("cityName", manageCityName);
            temp.put("townCode", manageTownCode);
            temp.put("townName", manageTownName);
            temp.put("streeCode", manageStreeCode);
            temp.put("address", manageAddress);
            manage.add(temp);
        }
        //                社区下没有服务站只能自取或快递
        if (hs == null) {
            Map self = new HashMap();
            self.put("code", orgCode);
            self.put("name", hostpitalName);
            self.put("provinceCode", provinceCode);
            self.put("provinceName", provinceName);
            self.put("cityCode", cityCode);
            self.put("cityName", cityName);
            self.put("townCode", townCode);
            self.put("townName", townName);
            self.put("streeCode", streeCode);
            self.put("address", address);
            types.add(1);
            Map express = new HashMap();
            types.add(2);
            result.put("self", self);
            result.put("express", express);
            result.put("types", types);
            return result;
        }
        Map self = new HashMap();
        self.put("code", orgCode);
        self.put("name", hostpitalName);
        self.put("provinceCode", provinceCode);
        self.put("provinceName", provinceName);
        self.put("cityCode", cityCode);
        self.put("cityName", cityName);
        self.put("townCode", townCode);
        self.put("townName", townName);
        self.put("streeCode", streeCode);
        self.put("address", address);
        types.add(1);
        Map express = new HashMap();
        types.add(2);
        Map manager = new HashMap();
        manager.put("codes", manage);
        result.put("self", self);
        result.put("express", express);
        result.put("manager", manager);
        result.put("types", types);
        return result;
    }
    /**
     * 长处方支付成功前端页面回调接口
     *
     * @param
     * @return
     */
    public Map recipeReturnUrl(HttpServletRequest request, HttpServletResponse response, String accessToken) throws Exception {
        return new HashMap();
    }
    /**
     * 长处方对接方异步回调接口 市医保
     *
     * @return
     */
    public String receiveRecipeNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return null;
    }
    /**
     * 长处方对接方异步回调接口 自费
     *
     * @return
     */
    public String receiveRecipeNotify2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return null;
    }
    /**
     * 长处方支付,成功则返回支付路径
     */
    @Transactional
    public Map charge(int type, String addressJson, String orgCode, String prescriptionCode, int totalAmount, String people, String repUid, String accessToken, String returnUrl, String deliveryTime) throws Exception {
        Map resultMap = new HashMap();
        return resultMap;
    }
//******************************************  支付查询基本工具方法  *******************************************************************************
    /**
     * 家庭医生签约支付查询
     */
    public String chargeQuery(String code, String accessToken) throws Exception {
        return null;
    }
    public String getSignFamilyPayResult(String outChargeNo, String accessToken, String appId, String appSecret) throws Exception {
        return null;
    }
    /**
     * 查询缴费居民手机绑定情况
     *
     * @param user 需要缴费的患者code(共济支付为被代理人)
     * @return
     * @throws Exception
     */
    public String getPatientMobile(String user) throws Exception {
        String mobile = null;
        try {
            BasePatientDO patient = patientDao.findById(user).orElse(null);
            if (patient != null) {
                mobile = patient.getMobile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mobile;
    }
    
    /**
     * 根据长处方代码查询支付日志
     * @param prescriptionCode
     * @return
     * @throws Exception
     */
    public List<PayLog> getPayLogsByPrescriptionCode(String prescriptionCode)throws Exception{
        List<PayLog> result = payLogDao.getPayLogsByPrescriptionCode(prescriptionCode);
    
        for (int i = 0; i < result.size(); i++) {
            result.get(i).setResponse("");
            result.get(i).setParams("");
        }
        
        return result;
    }
    /**
     * 家庭医生签约支付查询
     */
    public String getChargeQuery(String code, String accessToken) throws Exception {
        return null;
    }
}

+ 0 - 217
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionAdjustService.java

@ -1,217 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.prescription;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.afterDiagnosis.dao.prescription.PrescriptionReviewedDao;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionLogDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionReviewedDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionLogService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
 * 线下调整处方
 * Created by yeshijie on 2017/8/17.
 */
@Service
public class PrescriptionAdjustService {
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private PrescriptionLogService prescriptionLogService;
    @Autowired
    private WlyyPrescriptionService prescriptionService;
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private PrescriptionReviewedDao prescriptionReviewedDao;
    @Autowired
    private PrescriptionInfoService prescriptionInfoService;
    @Autowired
    private ImUtil imUtill;
//    @Autowired
//    private OrgAddressDao orgAddressDao;
    /**
     * 保存续方科室和挂号类型
     * @param code 续方code
     * @param jwGisterTypeCode 基卫-挂号类型编码
     * @param jwDeptCode 基卫-挂号科室
     * @param jwRegisterFee 基卫-诊金
     */
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public void saveDept(String code,String jwDeptCode,String jwGisterTypeCode,String jwRegisterFee,String deptCode){
        WlyyPrescriptionDO prescription = prescriptionDao.findById(code).orElse(null);
//        prescription.setJwGisterTypeCode(jwGisterTypeCode);
//        prescription.setJwDeptCode(jwDeptCode);
//        prescription.setJwRegisterFee(jwRegisterFee);
//        prescription.setDeptCode(deptCode);
        prescriptionDao.save(prescription);
    }
    /**
     * 线下调整处方
     * @param code
     */
    @Transactional
    public JSONObject adjustPrescription(String code,String deptCode,String orgAddress){
        JSONObject re = new JSONObject();
        WlyyPrescriptionDO prescription= prescriptionDao.findById(code).orElse(null);
        if (StringUtils.isNotEmpty(deptCode)){
//            prescription.setDeptCode(deptCode);
//            OrgAddress address = orgAddressDao.findByDeptCode(deptCode);
//            prescription.setDeptCodeName(address.getDeptName());
        }
        if (StringUtils.isNotEmpty(orgAddress)){
//            prescription.setOrgAddress(orgAddress);
        }
        if(prescription.getStatus()== WlyyPrescriptionLogDO.PrescriptionLogStatus.revieweding.getValue()||
                prescription.getStatus()== WlyyPrescriptionLogDO.PrescriptionLogStatus.change_error.getValue()){
            //待审核状态才可以线下调整处方
            prescriptionDao.save(prescription);
//            String response = jwPrescriptionService.saveRecipe(code,prescription.getJwGisterTypeCode(),prescription.getJwDeptCode(), deptCode);
            String response = "";
            JSONObject json = JSONObject.parseObject(response);
            if(json.getInteger("status")==200){
                JSONObject data = json.getJSONObject("data");
                String zyCode = data.getString("CODE");
                if("1".equals(zyCode)){
                    JSONArray returnData = data.getJSONArray("returnData");
                    if(returnData.size()>0){
                        JSONObject pre = returnData.getJSONArray(0).getJSONObject(0);
                        String visitNo = pre.getString("VISIT_NO");
                        String recipeNo = pre.getString("RECIPE_NO");
                        prescription.setStatus(WlyyPrescriptionLogDO.PrescriptionLogStatus.changeing.getValue());
                        prescription.setSerialNo(visitNo);
                        prescription.setRealOrder(recipeNo);
                        prescriptionDao.save(prescription);
                        //添加日志
                        prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),1,2);
                        re.put("status",200);
                    }else {
                        //请求失败
                        prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                        JSONArray byRefParaData = data.getJSONArray("byRefParaData");
                        re.put("status",-1);
                        re.put("msg",byRefParaData.getJSONObject(0).getString("errorMsg"));
                    }
                }else {
                    //调整请求失败
                    prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                    re.put("status",-1);
                    re.put("msg",data.getString("MESSAGE"));
                }
            }else{
                //请求报错
                prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                re.put("status",-1);
                re.put("msg","请求调整失败");
            }
        }else {
            re.put("status",-1);
            re.put("msg","只有待审核和调整失败的续方可以转线下调整");
        }
        return  re;
    }
    /**
     * 上传ca认证信息
     * @param code
     */
    @Transactional
    public JSONObject uploadCaDigital(String code){
        JSONObject re = new JSONObject();
        WlyyPrescriptionDO prescription= prescriptionDao.findById(code).orElse(null);
        if(prescription.getStatus()==WlyyPrescriptionLogDO.PrescriptionLogStatus.change_success.getValue()){
//            String response = jwPrescriptionService.affirmCARecipe(code);
            String response = "";
            JSONObject json = JSONObject.parseObject(response);
            if(json.getInteger("status")==200){
                JSONObject data = json.getJSONObject("data");
                String zyCode = data.getString("CODE");
                if("1".equals(zyCode)){
                    JSONArray returnData = data.getJSONArray("returnData");
                    if(returnData.size()>0){
                        //{"status":200,"msg":"CA认证通过接口!","data":"{\"CODE\":\"1\",\"returnData\":[{\"result\":\"True\"}],\"byRefParaData\":[{ \"errorMsg\": \"\" }]}"}
                        JSONObject pre = returnData.getJSONObject(0);
                        if("True".equals(pre.getString("result"))){
                            //认证成功-审核完成
                            prescription.setStatus(WlyyPrescriptionLogDO.PrescriptionLogStatus.wait_pay.getValue());
                            //设置审核通过
                            WlyyPrescriptionReviewedDO reviewed = prescriptionReviewedDao.findByPrescriptionCode(code);
                            reviewed.setStatus(1);
                            reviewed.setReviewedTime(new Date());
                            prescriptionDao.save(prescription);
                            //审核通过模板消息
                            prescriptionInfoService.sendRMess(prescription.getId(), 1);
                            //修改系统的续方消息的审核状态
                            messageDao.updatePreScriptionMessage(prescription.getConsult(), "1", 6);
                            //修改系统的消息的待ca认证
//                            messageDao.updatePreScriptionMessage(prescription.getCode(), 9);
                            //获取智业待结算接口,更新药品金额
                            prescriptionService.getPerscriptionInfoCostFromPayInfo(prescription.getId());
                            //添加日志
                            prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),1,2);
                            //发送Im消息
                            JSONObject content = new JSONObject();
                            content.put("title", "我已经审核您" + DateUtil.dateToStr(prescription.getCreateTime(), "yyyy-MM-dd") + "发起的续方申请");
                            content.put("result", "审核通过");
                            content.put("reason", "");
                            content.put("url", "");
                            imUtill.sendTopicIM(prescription.getDoctor(), prescription.getDoctorName(), prescription.getConsult(), "15", content.toString(), null);
                            re.put("status",200);
                        }else {
                            //请求失败
                            prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                            JSONArray byRefParaData = data.getJSONArray("byRefParaData");
                            re.put("status",-1);
                            re.put("msg",byRefParaData.getJSONObject(0).getString("errorMsg"));
                        }
                    }else {
                        //请求失败
                        prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                        JSONArray byRefParaData = data.getJSONArray("byRefParaData");
                        re.put("status",-1);
                        re.put("msg",byRefParaData.getJSONObject(0).getString("errorMsg"));
                    }
                }else {
                    //调整请求失败
                    prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                    re.put("status",-1);
                    re.put("msg",data.getString("MESSAGE"));
                }
            }else{
                //请求报错
                prescriptionLogService.addLog(prescription,WlyyPrescriptionLogDO.PrescriptionLogType.zy.getValue(),0,2);
                re.put("status",-1);
                re.put("msg","请求调整失败");
            }
        }else {
            re.put("status",-1);
            re.put("msg","只有调整成功的续方才可上传ca认证信息");
        }
        return  re;
    }
}

+ 0 - 110
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionAdressService.java

@ -1,110 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.prescription;
import com.yihu.jw.entity.hospital.prescription.WlyyPatientExpressageAddrDO;
import com.yihu.jw.hospital.prescription.dao.WlyyPatientExpressageAddrDao;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * Created by Trick on 2017/10/20.
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class PrescriptionAdressService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyyPatientExpressageAddrDao prescriptionAdressDao;
    //获取列表
    public List<Map<String,Object>> getAdressList(String patient){
        String sql = "SELECT ad.* FROM wlyy_patient_expressage_addr ad WHERE ad.patient ='"+patient+"' ORDER BY ad.default_flag DESC";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
    public Map<String,Object> getDefAdress(String patient){
        String sql = "SELECT ad.* FROM wlyy_patient_expressage_addr ad WHERE ad.patient ='"+patient+"' AND ad.default_flag = 1";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        if(rs!=null&&rs.size()>0){
            return rs.get(0);
        }else{
            return null;
        }
    }
    //保存
    public String saveAdress(String adressJosn){
        JSONObject jsonObject = JSONObject.fromObject(adressJosn);
        WlyyPatientExpressageAddrDO p = (WlyyPatientExpressageAddrDO) JSONObject.toBean(jsonObject,WlyyPatientExpressageAddrDO.class);
        p.setCreateTime(new Date());
        if(p.getIsDefault()==1){
            List<WlyyPatientExpressageAddrDO> list =  prescriptionAdressDao.queryByPatient(p.getPatient());
            if(list!=null&&list.size()>0){
                String sql ="UPDATE wlyy_prescription_adress set default_flag = 0 WHERE patient ='"+p.getPatient()+"' ";
                jdbcTemplate.execute(sql);
            }
        }
        prescriptionAdressDao.save(p);
        return "1";
    }
    //更新
    public String updateAdress(String adressJson){
        JSONObject jsonObject = JSONObject.fromObject(adressJson);
        WlyyPatientExpressageAddrDO p = (WlyyPatientExpressageAddrDO) JSONObject.toBean(jsonObject,WlyyPatientExpressageAddrDO.class);
        p.setCreateTime(new Date());
        if(p.getIsDefault()==1){
            String sql ="UPDATE wlyy_patient_expressage_addr set defaultFlag = 0 WHERE patient ='"+p.getPatient()+"' ";
            jdbcTemplate.execute(sql);
        }
        prescriptionAdressDao.save(p);
        return "1";
    }
    //删除
    public String delAdress(String id){
        prescriptionAdressDao.deleteById(id);
        return "1";
    }
    public List<Map<String,Object>> getProvince(){
        String sql = "SELECT " +
                " p.`code`, " +
                " p.`name` " +
                " FROM " +
                " base_province p";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
    public List<Map<String,Object>> getCityByProvince(String province){
        String sql = "SELECT " +
                " p.`code`, " +
                " p.`name` " +
                " FROM " +
                " base_city p " +
                " WHERE p.province = '"+province+"'";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
    public List<Map<String,Object>> getTowmByCity(String city){
        String sql = "SELECT " +
                " p.`code`, " +
                " p.`name` " +
                " FROM " +
                " base_town p " +
                " WHERE p.city = '"+city+"'";
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
}

+ 0 - 163
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionDiagnosisService.java

@ -1,163 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.prescription;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDiagnosisDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDiagnosisDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * 长处方疾病类型
 * Created by yeshijie on 2017/7/28.
 */
@Service
public class PrescriptionDiagnosisService {
    @Autowired
    private PrescriptionDiagnosisDao prescriptionDiagnosisDao;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 获取续方的疾病类型
     * @param prescriptionCode
     * @return
     */
    public JSONArray getPrescriptionDiagnosis(String prescriptionCode){
        String re = "";
        JSONArray jsonArray = new JSONArray();
        try {
            if(!StringUtils.isEmpty(prescriptionCode))
            {
                //判断该续方的疾病类型redis是否存在
                String key = "prescription:"+prescriptionCode+":diseaseTypes";
                re = redisTemplate.opsForValue().get(key);
                if(StringUtils.isEmpty(re))
                {
                    List<WlyyPrescriptionDiagnosisDO> list = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionCode,1);
                    if(list!=null&&list.size()>0){
                        for (WlyyPrescriptionDiagnosisDO diagnosis:list){
                            JSONObject json = new JSONObject();
                            json.put("code",diagnosis.getCode());//疾病代码
                            json.put("name",diagnosis.getName());//疾病名称
                            jsonArray.add(json);
                        }
                        re = jsonArray.toString();
                        redisTemplate.opsForValue().set(key,re,180, TimeUnit.DAYS);
                    }
                }else {
                    jsonArray = JSONArray.fromObject(re);
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonArray;
    }
    /**
     * 获取续方的药品信息
     * @param prescriptionCode
     * @return
     */
    public JSONArray getPrescriptionInfo(String prescriptionCode){
        String re = "";
        JSONArray jsonArray = new JSONArray();
        try {
            if(!StringUtils.isEmpty(prescriptionCode))
            {
                //判断该续方的药品信息redis是否存在
                String key = "prescription:"+prescriptionCode+":drugInfo";
                re = redisTemplate.opsForValue().get(key);
                if(StringUtils.isEmpty(re))
                {
                    List<WlyyPrescriptionInfoDO> list = prescriptionInfoDao.findByPrescriptionId(prescriptionCode,1);
                    if(list!=null&&list.size()>0){
                        jsonArray = JSONArray.fromObject(list);
                        re = jsonArray.toString();
                        redisTemplate.opsForValue().set(key,re,180, TimeUnit.DAYS);
                    }
                }else {
                    jsonArray = JSONArray.fromObject(re);
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonArray;
    }
    /**
     * 设置处方redis疾病类型
     * @param prescriptionCode
     * @return
     */
    public boolean setPrescriptionDiagnosis(String prescriptionCode){
        try {
            if(!StringUtils.isEmpty(prescriptionCode))
            {
                //判断该续方的疾病类型redis是否存在
                String key = "prescription:"+prescriptionCode+":diseaseTypes";
                List<WlyyPrescriptionDiagnosisDO> list = prescriptionDiagnosisDao.findByPrescriptionId(prescriptionCode,1);
                if(list!=null&&list.size()>0){
                    JSONArray jsonArray = new JSONArray();
                    for (WlyyPrescriptionDiagnosisDO diagnosis:list){
                        JSONObject json = new JSONObject();
                        json.put("code",diagnosis.getCode());//疾病代码
                        json.put("name",diagnosis.getName());//疾病名称
                        jsonArray.add(json);
                    }
                    String re = jsonArray.toString();
                    redisTemplate.opsForValue().set(key,re,180, TimeUnit.DAYS);
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 设置处方redis药品信息
     * @param prescriptionCode
     * @return
     */
    public boolean setPrescriptionInfo(String prescriptionCode){
        try {
            if(!StringUtils.isEmpty(prescriptionCode))
            {
                //判断该续方的药品信息redis是否存在
                String key = "prescription:"+prescriptionCode+":drugInfo";
                List<WlyyPrescriptionInfoDO> list = prescriptionInfoDao.findByPrescriptionId(prescriptionCode,1);
                if(list!=null&&list.size()>0){
                    String re = JSONArray.fromObject(list).toString();
                    redisTemplate.opsForValue().set(key,re,180, TimeUnit.DAYS);
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }
}

+ 0 - 376
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionDispensaryCodeService.java

@ -1,376 +0,0 @@
package com.yihu.jw.afterDiagnosis.service.prescription;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.afterDiagnosis.dao.prescription.PrescriptionDispensaryCodeDao;
import com.yihu.jw.entity.hospital.prescription.PrescriptionDispensaryCode;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionLogDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageLogDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionLogDao;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.entity.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by Administrator on 2017/7/21.
 *长处方取码
 */
@Service
public class PrescriptionDispensaryCodeService {
    @Autowired
    private PrescriptionDispensaryCodeDao prescriptionDispensaryCodeDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PrescriptionInfoDao prescriptionInfoDao;
    @Autowired
    private PrescriptionDao prescriptionDao;
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private PrescriptionLogDao prescriptionLogDao;
    @Autowired
    private PrescriptionExpressageLogDao prescriptionExpressageLogDao;
    @Autowired
    private WlyyPrescriptionExpressageService prescriptionExpressageService;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    private static Object obj = new Object();
    private static Object obj2 = new Object();
    //获取居民端取药码列表
    public  JSONArray findByStatusAndTime(Integer timeType, String patientCode, Integer status, Integer page, Integer pagesize,Integer type) {
        // 分页信息
        long timeLimit = 0;
        if(timeType!=null){
            switch (timeType){
                case 1:timeLimit = 7*24*60*60;break;//近一周
                case 2:timeLimit = 7*24*60*60*31;break;//近一月
                case 3:timeLimit = 7*24*60*60*31*6;break;//近半年
                case 4:timeLimit = 7*24*60*60*31*12;break;//近一年
            }
        }
        List<Object> params = new ArrayList<>();//p2.*,p1.diagnosis as diagnosis ,p3.address as address
        String precriptionSql = "select p1.status , p1.diagnosis ,p3.address as address,p2.prescription_code as prescriptionCode,p2.code as dispensaryCode,p2.type,p1.create_time as createTime  from wlyy_prescription_dispensary_code p2 " +
                " left join  wlyy_prescription p1 on p2.prescription_code=p1.code LEFT JOIN wlyy_prescription_expressage p3 on p1.code=p3.prescription_code where p1.patient=? and p2.type=?  ";
        params.add(patientCode);
        params.add(type);
        if(status!=null){
            precriptionSql += " and p1.status = ? ";
            params.add(status);
        }else {
            precriptionSql += " and p1.status in (?,?,?,?,?,?)" ;
            params.add(WlyyPrescriptionLogDO.PrescriptionLogStatus.pay_success.getValue());
            params.add(WlyyPrescriptionLogDO.PrescriptionLogStatus.wait_expressage.getValue());
            params.add(WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageing_error.getValue());
            params.add(WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageJGS.getValue());
            params.add(WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageing.getValue());
            params.add(WlyyPrescriptionLogDO.PrescriptionLogStatus.expressage2hospital.getValue());
//            params.add(PrescriptionLog.PrescriptionLogStatus.finish.getValue());
        }
        if(timeType!=null){
            precriptionSql +=  "AND TIMESTAMPDIFF(SECOND, p2.create_Time, CURRENT_TIME) < ?  ";
            params.add(timeLimit);
        }
        precriptionSql += " ORDER BY p1.status asc ,p2.create_Time desc ";
        precriptionSql += " limit "+(page-1)*pagesize+","+pagesize;
        List<Map<String, Object>> result = jdbcTemplate.queryForList(precriptionSql,params.toArray());
        List<Map<String, Object>> result2 = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Map<String, Object> m:result) {
            List<WlyyPrescriptionInfoDO> list = prescriptionInfoDao.findByPrescriptionId(m.get("prescriptionCode").toString(),1);
            m.put("prescriptionInfo",list);
            m.put("createTime",m.get("createTime")!=null?simpleDateFormat.format(m.get("createTime")):"");
            result2.add(m);
        }
        JSONArray array = new JSONArray(result2);
        return array;
    }
    //判断居民是否有(21等待领药、20配送中、100已完成)取药码
    public int dispensaryCodeCount(String patientCode,Integer type){
        String sql = "select  count(1) from wlyy_prescription_dispensary_code p1 left join wlyy_prescription p2 on p1.prescription_code=p2.code where p1.is_use=0 and p1.type=? and p2.patient =? ";// where p2.status in(21,20,100)  and p2.patient =?1
        int count = jdbcTemplate.queryForObject(sql,Integer.class,type,patientCode);
        return  count;
    }
    //生成取药码时,判断是否已经有重复的取药码
    public boolean getResidentQRCodeCount(String code){
        int count = prescriptionDispensaryCodeDao.getResidentQRCodeCount(code);
        if(count>0){
            return true;
        }
        return false;
    }
    @Transactional
    public void saveQRCode(String prescriptionCode) throws Exception {
        WlyyPrescriptionDO prescription = prescriptionDao.findById(prescriptionCode).orElse(null);
        //取药类型:1 自取 2快递配送 3健管师配送 4网格员派送
        Integer type = prescription.getDispensaryType();
        PrescriptionDispensaryCode p1 = prescriptionDispensaryCodeDao.findByPrescriptionCodeAndIsUseAndType(prescriptionCode,0,1);
        if(p1==null){
            p1 = savePatientQRCode(prescriptionCode);
        }
        if(p1==null){
            throw new ServiceException("二维码生成失败!");
        }
        if(type==3){
            PrescriptionDispensaryCode p2 = prescriptionDispensaryCodeDao.findByPrescriptionCodeAndIsUseAndType(prescriptionCode,0,2);
            if(p2==null){
                p2 = saveQRCode(p1.getCode(),prescriptionCode,2);
            }
            if(p2==null){
                throw new ServiceException("二维码生成失败!");
            }
            PrescriptionDispensaryCode p3 = prescriptionDispensaryCodeDao.findByPrescriptionCodeAndIsUseAndType(prescriptionCode,0,3);
            if(p3==null){
                p3 = saveQRCode(p1.getCode(),prescriptionCode,3);
            }
            if(p3==null){
                throw new ServiceException("二维码生成失败!");
            }
        }
    }
    //生成居民端取药码
    @Transactional
    public PrescriptionDispensaryCode savePatientQRCode(String prescriptionCode) throws Exception {
        //获取年月日8位数
        // 二维码内容 改成用处方号当取药码
        WlyyPrescriptionDO prescription = prescriptionDao.findById(prescriptionCode).orElse(null);
        String code = prescription.getAdmNo();
        // 生成二维码
        InputStream ipt = QrcodeUtil.createQrcode(code,300,"png");
//        Prescription类  取药类型:1 自取 2快递配送 3健管师配送
    
        String fileUrl = "";
        // 圖片列表
        List<String> tempPaths = new ArrayList<String>();
        try {
            ObjectNode imgNode = fastDFSUtil.upload(ipt,"png","QRCode_"+System.currentTimeMillis());
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(imgNode.toString());
            tempPaths.add(json.getString("fid"));
            String urls = "";
            for (String image : tempPaths) {
                if (urls.length() == 0) {
                    urls = image;
                } else {
                    urls += "," + image;
                }
            }
            fileUrl = fastdfs_file_url + urls;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //新增居民处方取码记录
        PrescriptionDispensaryCode prescriptionDispensaryCode = new PrescriptionDispensaryCode();
        prescriptionDispensaryCode.setCode(code);
        prescriptionDispensaryCode.setCreateTime(new Date());
        prescriptionDispensaryCode.setImgUrl(fileUrl);
        prescriptionDispensaryCode.setPrescriptionCode(prescriptionCode);
        prescriptionDispensaryCode.setType(1);
        prescriptionDispensaryCode.setIsUse(0);
        return prescriptionDispensaryCodeDao.save(prescriptionDispensaryCode);
    }
    //生成配送员(健管师)(2、取药码  2、配送码)
    @Transactional
    public PrescriptionDispensaryCode saveQRCode(String code,String prescriptionCode,Integer type) throws Exception {
        String jgsCode= "";
        synchronized (obj2){
            boolean bl = true;
            while (bl){
                String randomNum = randomString("0123456789",2);
                jgsCode = code +randomNum;
                bl = getResidentQRCodeCount(jgsCode);
            }
        }
        // 生成二维码
        InputStream ipt = QrcodeUtil.createQrcode(jgsCode,300,"png");
//        Prescription类  取药类型:1 自取 2快递配送 3健管师配送
        String fileUrl = "";
        // 圖片列表
        List<String> tempPaths = new ArrayList<String>();
        try {
            ObjectNode imgNode = fastDFSUtil.upload(ipt,"png","QRCode_"+System.currentTimeMillis());
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(imgNode.toString());
            tempPaths.add(json.getString("fid"));
            String urls = "";
            for (String image : tempPaths) {
                if (urls.length() == 0) {
                    urls = image;
                } else {
                    urls += "," + image;
                }
            }
            fileUrl = fastdfs_file_url + urls;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //新增配送员处方取码记录
        PrescriptionDispensaryCode prescriptionDispensaryCode = new PrescriptionDispensaryCode();
        prescriptionDispensaryCode.setCode(jgsCode);
        prescriptionDispensaryCode.setCreateTime(new Date());
        prescriptionDispensaryCode.setImgUrl(fileUrl);
        prescriptionDispensaryCode.setPrescriptionCode(prescriptionCode);
        prescriptionDispensaryCode.setType(type);
        prescriptionDispensaryCode.setIsUse(0);
        return prescriptionDispensaryCodeDao.save(prescriptionDispensaryCode);
    }
    //随机生成匹配数字
    public  String randomString(String base, int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
    public Map<String, Object> getQrcode(String prescriptionCode ,String patientCode ,Integer type) throws Exception {
        String sql = "select  p2.is_use as isUse,p2.code as dispensaryCode,p2.img_url,p3.hospital_name as hospitalName  from wlyy_prescription_dispensary_code p2 " +
                " left join  wlyy_prescription p1 on p2.prescription_code=p1.code LEFT JOIN wlyy_prescription_expressage p3 on p1.code=p3.prescription_code " +
                " where p2.prescription_code=?  and p2.type=? ";
        if(type==2||type==3){
            sql +=" and p3.expressage_code=? ";
        }else{
            sql +=" and p1.patient=? ";
        }
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql,prescriptionCode,type,patientCode);
        if(result.size()>0){
            return result.get(0);
        }
        throw new ServiceException("二维码错误或者已过期!");
    }
    public Map<String, Object> getJumiQrcode(String prescriptionCode) throws Exception {
        String sql = "SELECT jpc.del isUse,pick_code dispensaryCode ,jpc.qr_code img_url ,p.hospital_name hospitalName FROM wlyy_jumi_pick_code jpc , wlyy_prescription p\n" +
                "WHERE jpc.prescription_code = '"+prescriptionCode+"' AND jpc.prescription_code = p.id AND jpc.del = 0 ORDER BY jpc.id DESC";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        if(result.size()>0){
            return result.get(0);
        }
        throw new ServiceException("二维码错误或者已过期!");
    }
    @Transactional
    public PrescriptionDispensaryCode scanQrcode(String code,String userCode) throws Exception{
        PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeDao.findByCodeAndIsUse(code,0);
        if(prescriptionDispensaryCode!=null){
            WlyyPrescriptionDO prescription = prescriptionDao.findById(prescriptionDispensaryCode.getPrescriptionCode()).orElse(null);
            if(prescription.getDispensaryType()==3){
                //健管师配送
                //修改系统的续方消息的审核状态
                messageDao.updatePreScriptionMessage(prescription.getId(), "1", 7);
            }
        }else{
            throw new ServiceException("取药码错误!");
        }
        Integer status =  prescriptionExpressageService.expressage(code, userCode);
        if (status == -1) {
            throw new ServiceException("取药码错误!");
        } else if (status == -2) {
            throw new ServiceException("编码已使用!");
        } else if (status == -3) {
            throw new ServiceException("编码类型错误!");
        } else if (status == -6) {
            throw new ServiceException("发药错误");
        } else if (status == -7) {
            throw new ServiceException("已无待取药品");
        }
        return prescriptionDispensaryCode;
    }
    @Transactional
    public PrescriptionDispensaryCode scanQrcodeHlw(String code,String equ_num) throws Exception{
        WlyyPrescriptionDO prescription = prescriptionDao.findByRealOrder(code);
        if (1==prescription.getDispensaryType()){
            if (StringUtils.isNotBlank(equ_num)){
                //判断线上续方开单科室是否与设备关联的可是相同
                    String sql = "  select dept_code from wlyy_org_address_doctor  where hospital_code='"+prescription.getHospital()+"' and equ_nums like '%"+equ_num+"%' " ;
                    List<String> equDeptCodes = jdbcTemplate.queryForList(sql,String.class);
                    if (equDeptCodes.size()==0){
                        throw new ServiceException("该自助机未找到发药人呀!可能未投入使用");
                    }
                    if (!equ_num.equals(equDeptCodes.get(0))){
                        throw new ServiceException("出药设备与续方订单开药设备不符,无法取药");
                    }
            }
        }
        PrescriptionDispensaryCode prescriptionDispensaryCode = prescriptionDispensaryCodeDao.findByPrescriptionCodeAndIsUseAndType(prescription.getId(),0,1);
        if(prescriptionDispensaryCode!=null){
            if(prescription.getDispensaryType()==3){
                //健管师配送
                //修改系统的续方消息的审核状态
                messageDao.updatePreScriptionMessage(prescription.getId(), "1", 7);
            }
            if (prescription.getStatus()<WlyyPrescriptionLogDO.PrescriptionLogStatus.pay_success.getValue()){
                throw new ServiceException("续方未支付!");
            }
            if (prescription.getStatus()==WlyyPrescriptionLogDO.PrescriptionLogStatus.expressageing_error.getValue()){
                prescriptionDispensaryCode.setIsUse(1);
                prescriptionDispensaryCodeDao.save(prescriptionDispensaryCode);
                throw new ServiceException("订单已线下退费,无法取药!");
            }
            Integer status =  prescriptionExpressageService.expressage(prescriptionDispensaryCode.getCode(), prescription.getPatientCode());
            if (status == -1) {
                throw new ServiceException("取药码错误!");
            } else if (status == -2) {
                throw new ServiceException("编码已使用!");
            } else if (status == -3) {
                throw new ServiceException("编码类型错误!");
            } else if (status == -6) {
                throw new ServiceException("发药错误");
            }else if (status == -7) {
                throw new ServiceException("已无待取药品");
            }
        }else{
            throw new ServiceException("取药码错误或已被使用!");
        }
        return prescriptionDispensaryCode;
    }
}

+ 0 - 0
svr/svr-after-diagnosis/src/mian/java/com/yihu/jw/afterDiagnosis/service/prescription/PrescriptionFollowupContentService.java


部分文件因为文件数量过多而无法显示