Browse Source

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

yeshijie 3 years ago
parent
commit
50e982bd2a
86 changed files with 13500 additions and 157 deletions
  1. 12 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  2. 19 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/DoctorPatientRelationDao.java
  3. 15 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/GuidanceMessageLogDao.java
  4. 10 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/PatientMedicalRecordsDao.java
  5. 13 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/RehabilitationDetailAppointmentDao.java
  6. 38 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/RehabilitationOperateRecordsDao.java
  7. 41 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/SpecialistPatientRelationDao.java
  8. 193 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/service/DoctorPatientRelationService.java
  9. 15 0
      business/base-service/src/main/java/com/yihu/jw/security/RSADao.java
  10. 258 0
      business/base-service/src/main/java/com/yihu/jw/sign/dao/MessagesDao.java
  11. 26 0
      business/base-service/src/main/java/com/yihu/jw/team/BaseDoctorTeamDao.java
  12. 42 0
      business/base-service/src/main/java/com/yihu/jw/team/BaseDoctorTeamMemberDao.java
  13. 3 0
      business/base-service/src/main/java/com/yihu/jw/wechat/dao/JsapiTicketDao.java
  14. 8 0
      business/base-service/src/main/java/com/yihu/jw/wechat/dao/WxAccessTokenDao.java
  15. 1 0
      business/base-service/src/mqConfig/mqdata/event1.json
  16. 1 0
      business/base-service/src/mqConfig/mqdata/event2.json
  17. 16 1
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  18. 6 0
      common/common-entity/pom.xml
  19. 124 124
      common/common-entity/src/main/java/com/yihu/jw/entity/base/doctor/BaseDoctorDO.java
  20. 0 3
      common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxAccessTokenDO.java
  21. 2 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceSosLogDO.java
  22. 2 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/DmHospitalDO.java
  23. 77 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamFunction.java
  24. 48 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMemberAuthority.java
  25. 49 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMemberRole.java
  26. 77 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamRole.java
  27. 119 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/Frequency.java
  28. 55 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  29. 1 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/team/WlyyAdminTeamDO.java
  30. 2 4
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/team/WlyyAdminTeamMemberDO.java
  31. 131 0
      common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientEvent.java
  32. 120 0
      common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/RehabilitationguidanceDO.java
  33. 141 0
      common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/RehabilitationguidancePatientDO.java
  34. 72 0
      common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/SpecialDiseaseMessagesDO.java
  35. 406 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/DoctorPatientRelationDO.java
  36. 20 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/SpecialistPatientRelationDO.java
  37. 233 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientMedicalRecordsDO.java
  38. 9 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientRehabilitationPlanDO.java
  39. 73 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationAdviceDO.java
  40. 31 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/RSA.java
  41. 208 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/SystemConf.java
  42. 72 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wlyyinfo/WechatTag.java
  43. 74 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/rehabilitation/RehabilitationRequestMapping.java
  44. 3 0
      gateway/ag-basic/src/main/resources/application.yml
  45. 92 5
      svr/svr-rehabilitation/pom.xml
  46. 8 1
      svr/svr-rehabilitation/src/main/java/com/yihu/SvrRehabilitationApplication.java
  47. 14 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ObserverRequired.java
  48. 89 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ObserverRequiredAOP.java
  49. 22 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ServicesAuth.java
  50. 5 1
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/config/jpa/HibernateProperties.java
  51. 5 1
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/config/jpa/RehabilitationJpa.java
  52. 318 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanController.java
  53. 3 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanningController.java
  54. 166 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitaionInfoController.java
  55. 984 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationManageController.java
  56. 426 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationPlanController.java
  57. 48 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/message/DoctorMessageController.java
  58. 265 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/patient/PatientRehabilitationManageController.java
  59. 21 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/FrequencyDao.java
  60. 18 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientEventDao.java
  61. 19 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientMedicalRecordsRehabilitationDao.java
  62. 58 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientRehabilitationPlanDao.java
  63. 20 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationAdviceDao.java
  64. 94 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationDetailDao.java
  65. 15 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationGuidanceDao.java
  66. 17 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationGuidancePatientDao.java
  67. 19 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationPlanTemplateDao.java
  68. 16 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationServiceItemDao.java
  69. 18 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationTemplateDetailDao.java
  70. 461 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/SignFamilyDao.java
  71. 25 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/SpecialDiseaseMessagesDao.java
  72. 315 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/PatientRecordService.java
  73. 221 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationGuidanceService.java
  74. 588 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationInfoService.java
  75. 3293 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationManageService.java
  76. 1409 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanService.java
  77. 6 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanningService.java
  78. 34 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ServiceException.java
  79. 280 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/SpecialistEvaluateSevice.java
  80. 157 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ZsRehabilitationInfoService.java
  81. 285 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/message/RehabilitationMessageService.java
  82. 38 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/HtmlUtil.java
  83. 440 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/RHHttpClientUtil.java
  84. 47 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/vo/TemplateDetailVo.java
  85. 258 9
      svr/svr-rehabilitation/src/main/resources/application.yml
  86. 17 8
      svr/svr-rehabilitation/src/main/resources/bootstrap.yml

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

@ -36,4 +36,16 @@ public interface SystemMessageDao extends PagingAndSortingRepository<SystemMessa
    int orderMessageDelByType(String doctor, String orderId,String type);
    SystemMessageDO findByRelationCodeAndReceiver(String relationCode,String receiver);
    @Query("update SystemMessageDO a set a.isRead=0,a.over = '0' where a.id = ?1")
    @Modifying
    Integer setSpecialistById(String id);
    @Query("update SystemMessageDO a set a.isRead = 0 where a.id = ?1" )
    @Modifying
    Integer setSpecialistReadById(String id);
}

+ 19 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/DoctorPatientRelationDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.rehabilitation;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.GuidanceMessageLogDO;
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 DoctorPatientRelationDao extends PagingAndSortingRepository<DoctorPatientRelationDO, String>, JpaSpecificationExecutor<DoctorPatientRelationDO> {
    @Query("from DoctorPatientRelationDO t where t.doctor =?1 and t.patient =?2")
    List<DoctorPatientRelationDO> findByDoctorAndPatient(String doctor,String patient);
    @Query("from DoctorPatientRelationDO t where t.doctor =?1 and t.patient =?2 and t.dischargeRecord = ?3")
    DoctorPatientRelationDO findByDoctorAndPatientAndCode(String doctor,String patient,String code);
}

+ 15 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/GuidanceMessageLogDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.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);
}

+ 10 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/PatientMedicalRecordsDao.java

@ -0,0 +1,10 @@
package com.yihu.jw.rehabilitation;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface PatientMedicalRecordsDao extends PagingAndSortingRepository<PatientMedicalRecordsDO, String>, JpaSpecificationExecutor<PatientMedicalRecordsDO> {
}

+ 13 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/RehabilitationDetailAppointmentDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.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> {
}

+ 38 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/RehabilitationOperateRecordsDao.java

@ -0,0 +1,38 @@
package com.yihu.jw.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);
}

+ 41 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/SpecialistPatientRelationDao.java

@ -0,0 +1,41 @@
package com.yihu.jw.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> {
    public 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")
    public 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")
    public 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")
    public 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);
}

+ 193 - 0
business/base-service/src/main/java/com/yihu/jw/rehabilitation/service/DoctorPatientRelationService.java

@ -0,0 +1,193 @@
package com.yihu.jw.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
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.patient.Patient;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.DoctorPatientRelationDao;
import com.yihu.jw.rehabilitation.PatientMedicalRecordsDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Service
public class DoctorPatientRelationService <T, R extends CrudRepository> extends BaseJpaService<DoctorPatientRelationDO, DoctorPatientRelationDao> {
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DoctorPatientRelationDao doctorPatientRelationDao;
    @Autowired
    private PatientMedicalRecordsDao patientMedicalRecordsDao;
    public MixEnvelop findDoctorPatients(String doctor, String patient, String patientName, String isdeal, String idcard,Integer page , Integer pageSize){
        MixEnvelop mixEnvelop = new MixEnvelop();
        String sql = "select t.id as \"id\"," +
                " t.discharge_record as \"dischargeRecord\"," +
                " t.doctor as \"doctor\"," +
                " t.doctor_name as \"doctorName\"," +
                " t.patient as \"patient\"," +
                " t.patient_name as \"patientName\"," +
                " t.create_time as \"createTime\"," +
                " t.isdeal as \"isdeal\"," +
                " b.idcard as \"idcard\"," +
                " t.status as \"status\"," +
                " t.relation_type as \"relationType\"" +
                " from wlyy_doctor_patient_relation t " +
                " left join base_patient b on t.patient = b.id where 1=1";
        if (StringUtils.isNoneBlank(doctor)){
            sql+=" and t.doctor='"+doctor+"'";
        }
        if (StringUtils.isNoneBlank(patient)){
            sql+=" and t.patient='"+patient+"'";
        }
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and t.patient_name like '%"+patientName+"%'";
        }
        if (StringUtils.isNoneBlank(isdeal)){
            sql+=" and t.isdeal = '"+isdeal+"'";
        }
        if (StringUtils.isNoneBlank(idcard)){
            sql+=" and b.idcard = '"+idcard+"'";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        for (Map<String,Object> map:list){
            String sex = map.get("idcard")==null?"未知": IdCardUtil.getSexForIdcard_new(map.get("idcard").toString());
            Integer age = map.get("idcard")==null?0: IdCardUtil.getAgeForIdcard(map.get("idcard").toString());
            map.put("sex",sex);
            map.put("age",age);
        }
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setTotalCount(list==null?0:list.size());
        return mixEnvelop;
    }
    public void saveSingleDoctorPatientRelation(String json,String relationType) throws  Exception{
        JSONObject jsonObject = JSON.parseObject(json);
        String doctor = jsonObject.getString("doctor");
        String idCard = jsonObject.getString("idCard");
        String patientName = jsonObject.getString("patientName");
        String patientRecord = jsonObject.getString("patientRecord");
        String reOutpatientId = jsonObject.getString("reOutatientId");
        String recordCode="";
        BasePatientDO basePatientDO = basePatientDao.findByIdcard(idCard);
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);
        if (null==basePatientDO){
            basePatientDO.setIdcard(idCard);
            basePatientDO.setName(patientName);
            String salt = UUID.randomUUID().toString().substring(0,5);
            String pw = idCard.substring(idCard.length()-6,idCard.length());
            basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
            basePatientDO.setDel("1");
            basePatientDO.setLocked(0);
            basePatientDO.setEnabled(1);
            basePatientDO.setSex(Integer.valueOf(IdCardUtil.getSexForIdcard_new(idCard)));
            basePatientDO.setSalt(salt);
            basePatientDO.setBirthday(IdCardUtil.getBirthdayForIdcard(idCard));
            basePatientDO.setCreateTime(new Date());
            basePatientDO=basePatientDao.save(basePatientDO);
        }
        //保存医生居民关系映射表
        if ("1".equalsIgnoreCase(relationType)){
            //创建创建对应的出院记录
            PatientMedicalRecordsDO patientMedicalRecordsDO=objectMapper.readValue(patientRecord, PatientMedicalRecordsDO.class);
            patientMedicalRecordsDO = patientMedicalRecordsDao.save(patientMedicalRecordsDO);
            recordCode=patientMedicalRecordsDO.getCode();
        }else if ("2".equalsIgnoreCase(relationType)){
            recordCode=reOutpatientId;
        }
        DoctorPatientRelationDO doctorPatientRelationDO = doctorPatientRelationDao.findByDoctorAndPatientAndCode(doctor,basePatientDO.getId(),recordCode);
        if (doctorPatientRelationDO==null){
            doctorPatientRelationDO = new DoctorPatientRelationDO();
        }
        doctorPatientRelationDO.setPatient(basePatientDO.getId());
        doctorPatientRelationDO.setPatientName(basePatientDO.getName());
        doctorPatientRelationDO.setDoctor(doctor);
        doctorPatientRelationDO.setDoctorName(baseDoctorDO==null?"":baseDoctorDO.getName());
        doctorPatientRelationDO.setIsdeal("0");
        doctorPatientRelationDO.setStatus("0");
        doctorPatientRelationDO.setRelationType(relationType);
        doctorPatientRelationDO.setDischargeRecord(recordCode);
        doctorPatientRelationDO.setCreateTime(new Date());
        doctorPatientRelationDao.save(doctorPatientRelationDO);
    }
    public void savePatientDisease(){
    }
    /**
     *
     * @param patientInfo
     * @param doctorCode
     * @return
     */
    public JSONObject getPatientByIdcardOrSsc(String patientInfo, String doctorCode) {
        JSONObject data = new JSONObject();
        BasePatientDO patientList = basePatientDao.findByIdcardAndDel(patientInfo,"1");
        BasePatientDO patient = null;
        String recordCode="123";
        if(patientList==null){
            //未找到居民,从健康档案添加居民
            patient = new BasePatientDO();//todo 调用医院查询居民接口
            patient.setName("测试");
            patient.setSex(1);
            patient.setIdcard("210555111199992525");
            patient.setPhone("18877777777");
            basePatientDao.save(patient);
        }else{
            patient = patientList;
        }
        if(patient==null){
            data.put("status", -1);
            data.put("msg", "未查询到患者");
            return data;
        }
        BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
        DoctorPatientRelationDO doctorPatientRelationDO = doctorPatientRelationDao.findByDoctorAndPatientAndCode(doctorCode,patient.getId(),recordCode);
        if (doctorPatientRelationDO==null){
            doctorPatientRelationDO = new DoctorPatientRelationDO();
        }
        doctorPatientRelationDO.setPatient(patient.getId());
        doctorPatientRelationDO.setPatientName(patient.getName());
        doctorPatientRelationDO.setDoctor(doctorCode);
        doctorPatientRelationDO.setDoctorName(doctor==null?"":doctor.getName());
        doctorPatientRelationDO.setIsdeal("0");
        doctorPatientRelationDO.setStatus("0");
        doctorPatientRelationDO.setRelationType("");
        doctorPatientRelationDO.setDischargeRecord("");
        doctorPatientRelationDO.setCreateTime(new Date());
        doctorPatientRelationDao.save(doctorPatientRelationDO);
        data.put("status",200);
        return data;
    }
}

+ 15 - 0
business/base-service/src/main/java/com/yihu/jw/security/RSADao.java

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

+ 258 - 0
business/base-service/src/main/java/com/yihu/jw/sign/dao/MessagesDao.java

@ -0,0 +1,258 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.sign.dao;
import com.yihu.jw.entity.patient.Message;
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 org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
public interface MessagesDao extends PagingAndSortingRepository<Message, Long>, JpaSpecificationExecutor<Message> {
    @Query("select count(1) from Message a where a.type in(1,101) and a.read= 1 and a.receiver=?1 ")
    Integer amountUnreadByReceiver(String doctor);
    @Query("select a from Message a where a.type in(1,101) and a.read= 1 and a.receiver=?1 order by a.czrq desc")
    Page<Message> amountUnreadLastByReceiver(String doctor, Pageable pageRequest);
    @Query("select count(1) from Message a where a.type =2 and a.read= 1 and a.receiver=?1 ")
    Integer amountUnreadHealthByReceiver(String doctor);
    @Query("select a from Message a where a.type =2 and a.read= 1 and a.receiver=?1 order by a.czrq desc")
    List<Message> amountUnreadHealthLastByReceiver(String doctor, Pageable pageRequest);
    @Modifying
    @Query("update Message a set a.read = 0,a.over='0' where a.id = ?1")
    int read(long msgid);
    @Modifying
    @Query("update Message a set a.read = 0 where a.id = ?1")
    int updateReadById(long msgid);
    @Modifying
    @Query("update Message a set a.read = 0,a.over='1' where a.code = ?1")
    int read(String msgCode);
    @Query("SELECT a FROM Message a WHERE a.sender=?1 AND a.receiver = ?2 and a.signStatus = ?3 and a.read=1 ORDER BY czrq DESC")
    List<Message> findUnreadSign(String sender, String receiver, String signStatus);
    @Query(" from Message a where a.read = 1 and over ='1' and a.sender = ?1 and a.receiver=?2 and a.signStatus='1'")
    List<Message> findByPatient(String patient, String doctor);
    @Query(" from Message a where a.read = 1 and over ='1' and a.sender = ?1 and a.receiver=?2 ")
    List<Message> findByPatientRenew(String patient, String doctor);
    @Query("select a from Message a where a.receiver = ?1 and a.sender=?2 and a.tzType=?3  and a.over=1 order by a.createTime desc")
    List<Message> getHealthIndexMessageByPatient(String doctor, String patient, String type, Pageable pageRequest);
    //查询医生下的签约居民未读体征异常消息
    @Query("SELECT a FROM Message a WHERE a.sender=?1 AND a.receiver = ?2 AND a.type = 2 and a.del = '1' and a.read=1 ORDER BY czrq DESC")
    List<Message> findUnreadHealthIndex(String sender, String receiver);
    @Modifying
    @Query("update Message a set a.read = 0 where a.receiver = ?1 and a.sender=?2 and a.tzType=?3")
    int updateHealthIndexMessageByPatient(String doctor, String patient, String type);
    @Query("select a from Message a where a.read= 1 and a.receiver = ?1 and a.type not in (1,2,6,7,12,101,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,32,33,301,401,402,403,407,408,409,430,431,432,434,435) and (a.over = 1 or a.over is null) order by a.czrq desc")
    List<Message> getSystemMessageUnread(String doctor);
    @Query("select a from Message a where a.receiver = ?1 and a.prescriptionStatus=?2 and a.type in (6,7,33) order by a.createTime desc")
    List<Message> getSysTemMessageByPrescription(String doctor, String prescriptionStatus);
    @Query("select a from Message a where a.receiver = ?1 and a.prescriptionStatus=?2 and a.type =31 order by a.createTime desc")
    List<Message> getSysTemMessageByExamination(String doctor, String prescriptionStatus);
    @Query("select a from Message a where a.receiver = ?1 and a.type not in (1,2,6,7,12,101,14,15,301,16,17,18,19,20,21,22,23,24,25,26,27,28,29,32,33,401,402,403,407,408,409,430,431,432,434,435) and (a.del = '1' or a.del is null) and (a.over = 1 or a.over is null) ")
    List<Message> getSystemMessage(String doctor, Pageable pageRequest);
    @Query("select a from Message a where a.receiver = ?1 and ((a.type=?2 and a.prescriptionStatus='0') or a.type = 33 )")
    List<Message> getPrescriptionMessage(String doctor, Integer type, Pageable pageRequest);
    @Query("select count(a) from Message a where a.read = 0 and a.over ='0'  and a.receiver=?1 and a.type=?2 ")
    int findMessageNum(String doctor, Integer type);
    @Modifying
    @Query("update Message a set a.prescriptionStatus=?2 where a.relationCode = ?1 and a.type=?3 ")
    int updatePreScriptionMessage(String relationCode, String prescriptionStatus, Integer type);
    @Query("update Message a set a.read = 0,a.over = '0' where a.relationCode = ?1 and a.type = ?2")
    @Modifying
    @Transactional
    int updateMessageByRelationCode(String relationCode, Integer type);
    @Query("update Message a set a.read = 0,a.over = '0' where a.receiver = ?1 and a.type = ?2")
    @Modifying
    int setMessageReaded(String doctor, Integer type);
    @Query("update Message a set a.read = 0,a.over = '0' where a.receiver = ?1 and a.id = ?2")
    @Modifying
    int setMessageReadedById(String doctor, Long id);
    @Query("update Message a set a.read = 0 where a.receiver = ?1 and a.id = ?2")
    @Modifying
    int setMessageById(String doctor, Long id);
    @Query("update Message a set a.read = 0,a.over = '0' where a.receiver = ?1 and a.type not in (1,2,6,7)")
    @Modifying
    int setSysMessageReaded(String doctor);
    @Query("from Message a where a.receiver = ?1 and relationCode = ?2 and a.type=?3 ")
    List<Message> findByReceiverAndRelationCode(String receiver, String relationCode, Integer type);
    //查询患者最近7天的体征异常记录
    @Query(value = "SELECT COUNT(1) FROM wlyy_message WHERE type = '2' and sender = ?1 and create_time>=date_add(now(),interval -7 day) ", nativeQuery = true)
    int findTzMessage(String patient);
    //根据续方关联code查询团队长分配健管师消息
    @Query("from Message a where a.type = 8 and a.state=0 and a.del='1' and a.over='0' and relationCode = ?1  ")
    Message findByRelationCode(String relationCode);
    @Query("from Message a where a.type IN(24,25,26,27,12) and a.del='1' and a.over='1' and receiver = ?1  order by a.createTime desc")
    List<Message> findByReceiverCallService(String doctor);
    @Query("select a from Message a where a.receiver = ?1 and a.type=?2 and a.over='1' and a.read=1 order by a.createTime desc")
    List<Message> getMessageByType(String doctor, Integer type, Pageable pageRequest);
    @Query("from Message a where a.type = 12 and a.del='1' and a.over='1' and relationCode = ?1  ")
    List<Message> findByCallServiceRelationCode(String relationCode);
    @Query(" select a from Message a where a.type IN (15,30) and a.del='1' and a.read=1 and a.receiver=?1 and a.over='1' order by a.createTime desc ")
    List<Message> findEduArticle1(String receiver);
    @Query(" select a from Message a where a.type=?2 and a.del='1' and a.read=1 and a.receiver=?1 and a.over='1' order by a.createTime desc ")
    List<Message> findEduArticle(String receiver, Integer type);
    @Query(" select a from Message a where a.type=?2 and a.del='1'  and a.receiver=?1 ")
    List<Message> findEduArticle(String receiver, Integer type, Pageable pageRequest);
    @Query(" select a from Message a where a.type IN (15,30)and a.del='1'  and a.receiver=?1 ")
    List<Message> findEduArticle1(String receiver, Pageable pageRequest);
    @Modifying
    @Query("delete from Message a   where a.receiver = ?1 and a.data = ?2 and a.type in (14,15,30) ")
    int setMessageDel(String doctor, String articleCode);
    @Modifying
    @Query("delete from Message a   where  a.data = ?1 and a.type in (14,15,30) ")
    int setMessageDel1(String articleCode);
    @Modifying
    @Query("delete from Message a   where a.receiver = ?1 and a.relationCode = ?2 and a.type in (14,15,30) ")
    int setMessageDel2(String doctor, String refinementCode);
    @Modifying
    @Query("delete from Message a   where a.receiver = ?1 and a.relationCode = ?2 and a.type ='407'")
    int orderMessageDel(String doctor, String orderId);
    @Query(" select a from Message a where a.type=?2 and a.del='1' and a.read=1 and a.receiver=?1 and a.over='1' order by a.createTime desc ")
    List<Message> findUnReadByReceiverAndType(String receiver, Integer type);
    @Query("select a from Message a where a.read = 1 and a.receiver = ?1 and a.state = 1 and a.over = ?2 and a.type in (16,20,22,23) order by a.czrq desc")
    List<Message> getSpecialistApply(String receiver, String over);
    @Query("select a from Message a where a.receiver = ?1 and a.state = 1 and a.type = 17 order by a.czrq desc")
    List<Message> getFamilyTransfer(String receiver);
    @Query("select a from Message a where a.read = 1 and a.receiver = ?1 and a.state = 1 and a.type = 18 order by a.czrq desc")
    List<Message> getFamilySign(String receiver);
    @Query("select a from Message a where a.receiver = ?1 and a.state = 1 and a.type in(18,19,20,21,22,23,29)")
    List<Message> selectFamilySign(String receiver, Pageable pageableRequest);
    @Query("select a from Message a where a.read= ?2 and a.receiver = ?1 and a.state = 1 and a.over = ?3 and a.type = 17 order by a.czrq desc")
    List<Message> getFamilyTransferReadAndOver(String receiver, Integer read, String over);
    @Query("select a from Message a where a.receiver = ?1 and a.type=31 and a.read= ?2 and a.over = ?3 and a.prescriptionStatus='0' ")
    List<Message> getExaminationMessage(String doctor, Integer read, String over);
    @Query("select a from Message a where a.receiver = ?1 and a.state = 1 and a.over = ?2 and a.type in (16,20,22,23) order by a.czrq desc")
    List<Message> getSpecialistUntreated(String receiver, String over, Pageable pageable);
    @Query("select a from Message a where  a.receiver = ?1 and a.state = 1 and a.over = ?2 and a.type in (19,21,29) order by a.czrq desc")
    List<Message> getSpecialistMessages(String receiver, String over, Pageable pageable);
    @Query("select a from Message a where a.read= ?2 and a.receiver = ?1 and a.state = 1 and a.over = ?3 and a.type in (17) order by a.czrq desc")
    List<Message> getTransferMessage(String receiver, Integer read, String over, Pageable pageable);
    @Query("select a from Message a where a.code = ?1")
    Message findByCode(String code);
    @Query("select a from Message a where a.relationCode = ?1 and a.receiver = ?2 and a.type = ?3")
    Message findOldMessage(String orderId, String receiver, int type);
    @Query("select a from Message a where a.read = 1 and a.receiver = ?1 and a.state = 1 and a.type in (19,21,29) order by a.czrq desc")
    List<Message> getSpecialistUnRead(String receiver);
    @Query("select a from Message a where a.read = 1 and a.receiver = ?1 and a.state = 1 and a.type in (18,19,20,21,22,23,29) order by a.czrq desc")
    List<Message> getSpecialistUnRead2(String receiver);
    @Query("update Message a set a.read=0,a.over = '0' where a.id = ?1")
    @Modifying
    int setSpecialistById(Long id);
    @Query("update Message a set a.read = 0 where a.id = ?1")
    @Modifying
    int setSpecialistReadById(Long id);
    @Query("select a from Message a where a.read = 1 and a.receiver = ?1 and a.state = 1 and a.type in (24,25,26,27,12,32) order by a.czrq desc")
    List<Message> getSynergyService(String receiver);
    @Query("select a from Message a where  a.receiver = ?1 and a.state = 1 and a.type in (12,32,24,25,26,27) order by a.czrq desc")
    List<Message> getSynergyMessages(String receiver, Pageable pageable);
    @Query("update Message a set a.read = 0 where a.receiver = ?1 and a.type in (12,32,24,25,26,27)")
    @Modifying
    int setSynergyMessagesByRead(String doctor);
    @Query("select a from Message a where  a.receiver = ?1 and a.type = 28  and a.state = 1 and a.del = '1' and a.createTime > ?2 order by a.czrq desc")
    List<Message> findBirthdayReminder(String doctor, Date now);
    @Query("select a from Message a where  a.receiver = ?1 and a.over = 1 and a.type in (17) order by a.czrq desc")
    List<Message> getTransferMessageByPCIM(String receiver, Pageable pageable);
    @Query("select a from Message a where  a.receiver = ?1 and a.over = 1 and a.type in(?2)  order by a.czrq desc")
    List<Message> getPCIMFamilyServer(String receiver, String types, Pageable pageable);
    @Query(" select a from Message a where a.type IN (401,402) and a.del='1' and a.read=1 and a.receiver=?1 and a.over='1' order by a.createTime desc ")
    List<Message> findDoorOrder(String receiver);
    @Query(" select a from Message a where a.type IN (408,407,403,409) and a.del='1' and a.receiver=?1 and a.over='1' order by a.createTime desc ")
    List<Message> findDoorByOrder(String receiver);
    @Query("select a from Message a where  a.receiver = ?1 and a.state = 1 and a.over = ?2 and a.type in (?3) order by a.czrq desc")
    List<Message> findWaitingMessages(String receiver, String over, List<Integer> typeList, Pageable pageable);
    //获取资质申请审核有效的未结束已发送的消息
    @Query("select a from Message a where a.type in (401,408) and a.del='1' and a.over='1' and a.state=1  and relationCode = ?1  ")
    List<Message> findMessageByRelationCode(String relationCode);
/*    //获取资质申请审核有效的未结束已发送的消息
    @Query("select a from Message a where a.type = 401 and a.del='1' and a.over='1' and a.state=1  and a.relationCode = ?1 ")
    List<Message> findMessageByRelationCodeAndReceiver(String relationCode);*/
    List<Message> queryByRelationCodeAndTypeIn(String relationCode, Integer[] type);
    @Query("select a from Message a where a.receiver = ?1 and a.type=?2 and  a.over='1' order by a.createTime desc")
    List<Message> getMessageByReceiverByType(String receiver, Integer type, Pageable pageRequest);
    @Query("update Message a set a.read = 0,a.over = '0' where a.receiver = ?1 and a.type = ?2 and (a.createTime > ?3 and a.createTime< ?4)")
    @Modifying
    void setMessageOverByType(String doctor, Integer type, Date start, Date end);
    @Query("update Message a set a.read = 0,a.over = '0' where a.receiver = ?1 and a.relationCode = ?2 and a.type=?3 ")
    @Modifying
    void updateByReceiverAndRelationCode(String receiver, String relationCode, Integer type);
}

+ 26 - 0
business/base-service/src/main/java/com/yihu/jw/team/BaseDoctorTeamDao.java

@ -0,0 +1,26 @@
package com.yihu.jw.team;
import com.yihu.jw.entity.base.team.BaseTeamDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Map;
/**
 * 
 * 团队信息 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong 	1.0  		2018年08月31日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface BaseDoctorTeamDao extends PagingAndSortingRepository<BaseTeamDO, String>, JpaSpecificationExecutor<BaseTeamDO>  {
    @Query("select orgCode as code,orgName as name from BaseTeamDO")
    List<Map<String,Object>> getTeamOrgList();
 }

+ 42 - 0
business/base-service/src/main/java/com/yihu/jw/team/BaseDoctorTeamMemberDao.java

@ -0,0 +1,42 @@
package com.yihu.jw.team;
import com.yihu.jw.entity.base.team.BaseTeamMemberDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * 
 * 团队成员 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong 	1.0  		2018年08月31日 	Created
 *
 * </pre>
 * @since 1.
 */
public interface BaseDoctorTeamMemberDao extends PagingAndSortingRepository<BaseTeamMemberDO, String>, JpaSpecificationExecutor<BaseTeamMemberDO>  {
    @Query("select doc.name as name,doc.idcard as idcard ,doc.id as doctorCode from BaseDoctorDO doc where doc.id in (select team.doctorCode from BaseTeamMemberDO team where team.teamCode = ?1)")
    List<Map<String,Object>> getTeamMemberList(String teamCode);
    @Query("select id from BaseTeamMemberDO where teamCode = ?1")
    Set<Object> findIdListByTeamCode(String teamCode);
    List<BaseTeamMemberDO> findByTeamCode(String teamCode);
    @Query("from BaseTeamMemberDO  t where t.doctorCode = ?1 and t.del ='1'")
    List<BaseTeamMemberDO> findUseDoctorCode(String doctorCode);
    @Query("from BaseTeamMemberDO  t where t.doctorCode = ?1 and t.del ='1'")
    List<BaseTeamMemberDO> findUseDoctorCodeAndDel(String doctorCode);
    @Query("from BaseTeamMemberDO  t where t.doctorCode = ?1 and t.teamCode=?2 and t.del ='1'")
    BaseTeamMemberDO findUseDoctorCodeAndTeamCode(String doctorCode, String teamCode);
}

+ 3 - 0
business/base-service/src/main/java/com/yihu/jw/wechat/dao/JsapiTicketDao.java

@ -9,4 +9,7 @@ public interface JsapiTicketDao extends PagingAndSortingRepository<JsApiTicket,
    @Query("select p from JsApiTicket p where p.acc_id = ?1 order by p.add_timestamp desc")
    Iterable<JsApiTicket> findJsapiTicket(String accId);
}

+ 8 - 0
business/base-service/src/main/java/com/yihu/jw/wechat/dao/WxAccessTokenDao.java

@ -19,4 +19,12 @@ public interface WxAccessTokenDao extends PagingAndSortingRepository<WxAccessTok
    @Modifying
    @Query("delete from WxAccessTokenDO p where p.wechatId=?1 ")
    void deleteByWechatId(String wechatId);
    @Query("select p from WxAccessTokenDO p where p.code = ?1 order by p.addTimestamp desc")
    Iterable<WxAccessTokenDO> findAccessToken(String accId);
    @Modifying
    @Query("delete from WxAccessTokenDO p where p.code=?1 ")
    void deleteByAccId(String accId);
}

File diff suppressed because it is too large
+ 1 - 0
business/base-service/src/mqConfig/mqdata/event1.json


File diff suppressed because it is too large
+ 1 - 0
business/base-service/src/mqConfig/mqdata/event2.json


+ 16 - 1
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -802,7 +802,7 @@ public class ImUtil {
//			return 0;
//		}
	}
	
	/**
	 *获取所有会话未读消息数。
	 * @param userid
@ -836,4 +836,19 @@ public class ImUtil {
//		}
	}
	/**
	 * 获取会话未读消息数量
	 * @param sessionId
	 * @param userId
	 * @return
	 */
	public JSONObject getSessionUnreadMessageCount(String sessionId, String userId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/unread_message_count?user_id=" + userId;
		try {
			String ret = httpClientUtil.get(url, "utf-8");
			return  JSONObject.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
		}
	}
}

+ 6 - 0
common/common-entity/pom.xml

@ -27,5 +27,11 @@
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>

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

@ -11,173 +11,173 @@ import java.util.Date;
/**
* 医生基本信息实体
*
* @author Administrator on  2018年09月05日
*
*/
 * 医生基本信息实体
 *
 * @author Administrator on  2018年09月05日
 *
 */
@Entity
@Table(name = "base_doctor")
public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
    /**
	 * 密码
	 */
	private String password;
     * 密码
     */
    private String password;
    /**
	 * 
	 */
	private String salt;
     *
     */
    private String salt;
    /**
	 * 姓名
	 */
	private String name;
     * 姓名
     */
    private String name;
    /**
	 * 性别(1男,2女) 用国家标准字典
	 */
	private Integer sex;
     * 性别(1男,2女) 用国家标准字典
     */
    private Integer sex;
    /**
	 * 医生专长
	 */
	private String expertise;
     * 医生专长
     */
    private String expertise;
    /**
	 * 医生介绍
	 */
	private String introduce;
     * 医生介绍
     */
    private String introduce;
    /**
	 *  身份证
	 */
	private String idcard;
     *  身份证
     */
    private String idcard;
    /**
	 * 生日
	 */
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date birthday;
     * 生日
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date birthday;
    /**
	 * 头像http地址
	 */
	private String photo;
     * 头像http地址
     */
    private String photo;
    /**
	 * 手机号
	 */
	private String mobile;
     * 手机号
     */
    private String mobile;
    /**
	 * 医生二维码
	 */
	private String qrcode;
     * 医生二维码
     */
    private String qrcode;
    /**
	 * 省代码
	 */
	private String provinceCode;
     * 省代码
     */
    private String provinceCode;
    /**
	 * 省名称
	 */
	private String provinceName;
     * 省名称
     */
    private String provinceName;
    /**
	 * 市代码
	 */
	private String cityCode;
     * 市代码
     */
    private String cityCode;
    /**
	 * 市名称
	 */
	private String cityName;
     * 市名称
     */
    private String cityName;
    /**
	 * 区县代码
	 */
	private String townCode;
     * 区县代码
     */
    private String townCode;
    /**
	 * 区县名称
	 */
	private String townName;
     * 区县名称
     */
    private String townName;
    /**
	 * 街道代码
	 */
	private String streetCode;
     * 街道代码
     */
    private String streetCode;
    /**
	 * 街道名称
	 */
	private String streetName;
     * 街道名称
     */
    private String streetName;
    /**
	 * 资格是否认证通过,1是,0否
	 */
	private String iscertified;
     * 资格是否认证通过,1是,0否
     */
    private String iscertified;
    /**
	 * 是否是名医,1是,0否
	 */
	private Integer isFamous;
     * 是否是名医,1是,0否
     */
    private Integer isFamous;
    /**
	 * 是否提示设置密码  1 提示过 0未提示
	 */
	private String isPasswordPrompt;
     * 是否提示设置密码  1 提示过 0未提示
     */
    private String isPasswordPrompt;
    /**
	 * 名称拼音首字母
	 */
	private String spell;
     * 名称拼音首字母
     */
    private String spell;
    /**
	 * CA证书过期时间
	 */
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date certifiedOvertime;
     * CA证书过期时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date certifiedOvertime;
    /**
	 * CA证书编号
	 */
	private String certificateNum;
     * CA证书编号
     */
    private String certificateNum;
    /**
	 * 用户微信openid
	 */
	private String openid;
     * 用户微信openid
     */
    private String openid;
	/**
	 * 职称代码
	 */
	private String jobTitleCode;
    /**
     * 职称代码
     */
    private String jobTitleCode;
	/**
	 * 职称名称
	 */
	private String jobTitleName;
    /**
     * 职称名称
     */
    private String jobTitleName;
    /**
     * 号别字典
     */
    private String chargeType;
    /**
	 * 作废标识,1正常,0作废
	 */
	private String del;
     * 作废标识,1正常,0作废
     */
    private String del;
    /**
     * 是否锁定:0可用;1锁定
     */
	private Integer locked;
    private Integer locked;
    /**
     * 账号是否可用,1为可用;0为不可用
     */
	private Integer enabled;
    private Integer enabled;
    /**
@ -373,7 +373,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.password = password;
    }
	@Column(name = "salt")
    @Column(name = "salt")
    public String getSalt() {
        return salt;
    }
@ -381,7 +381,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.salt = salt;
    }
	@Column(name = "name")
    @Column(name = "name")
    public String getName() {
        return name;
    }
@ -389,7 +389,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.name = name;
    }
	@Column(name = "sex")
    @Column(name = "sex")
    public Integer getSex() {
        return sex;
    }
@ -397,7 +397,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.sex = sex;
    }
	@Column(name = "expertise")
    @Column(name = "expertise")
    public String getExpertise() {
        return expertise;
    }
@ -405,7 +405,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.expertise = expertise;
    }
	@Column(name = "introduce")
    @Column(name = "introduce")
    public String getIntroduce() {
        return introduce;
    }
@ -413,7 +413,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.introduce = introduce;
    }
	@Column(name = "idcard")
    @Column(name = "idcard")
    public String getIdcard() {
        return idcard;
    }
@ -421,7 +421,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.idcard = idcard;
    }
	@Column(name = "birthday")
    @Column(name = "birthday")
    public Date getBirthday() {
        return birthday;
    }
@ -429,7 +429,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.birthday = birthday;
    }
	@Column(name = "photo")
    @Column(name = "photo")
    public String getPhoto() {
        return photo;
    }
@ -437,7 +437,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.photo = photo;
    }
	@Column(name = "mobile")
    @Column(name = "mobile")
    public String getMobile() {
        return mobile;
    }
@ -445,7 +445,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.mobile = mobile;
    }
	@Column(name = "qrcode")
    @Column(name = "qrcode")
    public String getQrcode() {
        return qrcode;
    }
@ -453,7 +453,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.qrcode = qrcode;
    }
	@Column(name = "province_code")
    @Column(name = "province_code")
    public String getProvinceCode() {
        return provinceCode;
    }
@ -461,7 +461,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.provinceCode = provinceCode;
    }
	@Column(name = "province_name")
    @Column(name = "province_name")
    public String getProvinceName() {
        return provinceName;
    }
@ -469,7 +469,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.provinceName = provinceName;
    }
	@Column(name = "city_code")
    @Column(name = "city_code")
    public String getCityCode() {
        return cityCode;
    }
@ -477,7 +477,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.cityCode = cityCode;
    }
	@Column(name = "city_name")
    @Column(name = "city_name")
    public String getCityName() {
        return cityName;
    }
@ -485,7 +485,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.cityName = cityName;
    }
	@Column(name = "town_code")
    @Column(name = "town_code")
    public String getTownCode() {
        return townCode;
    }
@ -493,7 +493,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.townCode = townCode;
    }
	@Column(name = "town_name")
    @Column(name = "town_name")
    public String getTownName() {
        return townName;
    }
@ -501,7 +501,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.townName = townName;
    }
	@Column(name = "street_code")
    @Column(name = "street_code")
    public String getStreetCode() {
        return streetCode;
    }
@ -509,7 +509,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.streetCode = streetCode;
    }
	@Column(name = "street_name")
    @Column(name = "street_name")
    public String getStreetName() {
        return streetName;
    }
@ -517,7 +517,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.streetName = streetName;
    }
	@Column(name = "iscertified")
    @Column(name = "iscertified")
    public String getIscertified() {
        return iscertified;
    }
@ -525,7 +525,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.iscertified = iscertified;
    }
	@Column(name = "is_famous")
    @Column(name = "is_famous")
    public Integer getIsFamous() {
        return isFamous;
    }
@ -533,7 +533,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.isFamous = isFamous;
    }
	@Column(name = "is_password_prompt")
    @Column(name = "is_password_prompt")
    public String getIsPasswordPrompt() {
        return isPasswordPrompt;
    }
@ -541,7 +541,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.isPasswordPrompt = isPasswordPrompt;
    }
	@Column(name = "spell")
    @Column(name = "spell")
    public String getSpell() {
        return spell;
    }
@ -549,7 +549,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.spell = spell;
    }
	@Column(name = "certified_overtime")
    @Column(name = "certified_overtime")
    public Date getCertifiedOvertime() {
        return certifiedOvertime;
    }
@ -557,7 +557,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.certifiedOvertime = certifiedOvertime;
    }
	@Column(name = "certificate_num")
    @Column(name = "certificate_num")
    public String getCertificateNum() {
        return certificateNum;
    }
@ -565,7 +565,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.certificateNum = certificateNum;
    }
	@Column(name = "openid")
    @Column(name = "openid")
    public String getOpenid() {
        return openid;
    }
@ -573,7 +573,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.openid = openid;
    }
	@Column(name = "del")
    @Column(name = "del")
    public String getDel() {
        return del;
    }

+ 0 - 3
common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxAccessTokenDO.java

@ -59,9 +59,6 @@ public class WxAccessTokenDO extends UuidIdentityEntity implements java.io.Seria
		return this.expiresIn;
	}
	public void setExpiresIn(Long expiresIn) {
		this.expiresIn = expiresIn;
	}
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "czrq", nullable = false, length = 0)

+ 2 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceSosLogDO.java

@ -3,6 +3,7 @@ package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.Date;
@ -11,6 +12,7 @@ import java.util.Date;
 */
@Entity
@Table(name="base_device_sos_log")
@SequenceGenerator(name="id_generated", sequenceName="seq_base_device_sos_log")
public class DeviceSosLogDO extends IdEntity {
    private String patient; //居民code
    private String patientName; //姓名

+ 2 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/DmHospitalDO.java

@ -4,6 +4,7 @@ import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
@ -13,6 +14,7 @@ import javax.persistence.Table;
 */
@Entity
@Table(name = "dm_hospital")
@SequenceGenerator(name="id_generated", sequenceName="seq_dm_hospital")
public class DmHospitalDO extends IntegerIdentityEntity {
	private static final long serialVersionUID = 8039389705624435301L;

+ 77 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamFunction.java

@ -0,0 +1,77 @@
package com.yihu.jw.entity.hospital.doctor;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * @author Sand
 */
@Entity
@Table(name = "dr_admin_team_function")
public class AdminTeamFunction extends IdEntity {
    private String name;
    private String code;
    private boolean avaliable;
    private Date createTime;
    private String creator;
    private String remarks;
    public String getName() {
        return name;
    }
    @Column(name = "name")
    public void setName(String name) {
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    @Column(name = "code")
    public void setCode(String code) {
        this.code = code;
    }
    public boolean isAvaliable() {
        return avaliable;
    }
    @Column(name = "avaliable")
    public void setAvaliable(boolean avaliable) {
        this.avaliable = avaliable;
    }
    public Date getCreateTime() {
        return createTime;
    }
    @Column(name = "create_time")
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getCreator() {
        return creator;
    }
    @Column(name = "creator")
    public void setCreator(String creator) {
        this.creator = creator;
    }
    public String getRemarks() {
        return remarks;
    }
    @Column(name = "remarks")
    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }
}

+ 48 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMemberAuthority.java

@ -0,0 +1,48 @@
package com.yihu.jw.entity.hospital.doctor;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 成员权限。
 *
 * @author Sand
 */
@Entity
@Table(name = "dr_admin_team_member_authority")
public class AdminTeamMemberAuthority extends IdEntity {
    private long teamdId;
    private long roleId;
    private long functionId;
    public long getTeamdId() {
        return teamdId;
    }
    @Column(name = "team_id")
    public void setTeamdId(long teamdId) {
        this.teamdId = teamdId;
    }
    public long getRoleId() {
        return roleId;
    }
    @Column(name = "role_id")
    public void setRoleId(long roleId) {
        this.roleId = roleId;
    }
    public long getFunctionId() {
        return functionId;
    }
    @Column(name = "function_id")
    public void setFunctionId(long functionId) {
        this.functionId = functionId;
    }
}

+ 49 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMemberRole.java

@ -0,0 +1,49 @@
package com.yihu.jw.entity.hospital.doctor;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 团队成员角色。
 *
 * @author Sand
 */
@Entity
@Table(name = "dr_admin_team_member_role")
public class AdminTeamMemberRole extends IdEntity {
    private long teamId;
    private long doctorId;
    private long roleId;
    public long getTeamId() {
        return teamId;
    }
    @Column(name = "team_id")
    public void setTeamId(long teamId) {
        this.teamId = teamId;
    }
    public long getDoctorId() {
        return doctorId;
    }
    @Column(name = "doctor_id")
    public void setDoctorId(long doctorId) {
        this.doctorId = doctorId;
    }
    public long getRoleId() {
        return roleId;
    }
    @Column(name = "role_id")
    public void setRoleId(long roleId) {
        this.roleId = roleId;
    }
}

+ 77 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamRole.java

@ -0,0 +1,77 @@
package com.yihu.jw.entity.hospital.doctor;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * @author Sand
 */
@Entity
@Table(name = "dr_admin_team_role")
public class AdminTeamRole extends IdEntity {
    private String name;
    private boolean avaliable;
    private Date createTime;
    private long creatorId;
    private int multiply;
    private String remarks;
    public String getName() {
        return name;
    }
    @Column(name = "name")
    public void setName(String name) {
        this.name = name;
    }
    public boolean isAvaliable() {
        return avaliable;
    }
    @Column(name = "avaliable")
    public void setAvaliable(boolean avaliable) {
        this.avaliable = avaliable;
    }
    public Date getCreateTime() {
        return createTime;
    }
    @Column(name = "create_time")
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public long getCreatorId() {
        return creatorId;
    }
    @Column(name = "creator_id")
    public void setCreatorId(long creatorId) {
        this.creatorId = creatorId;
    }
    public int getMultiply() {
        return multiply;
    }
    @Column(name = "multiply")
    public void setMultiply(int multiply) {
        this.multiply = multiply;
    }
    public String getRemarks() {
        return remarks;
    }
    @Column(name = "remarks")
    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }
}

+ 119 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/Frequency.java

@ -0,0 +1,119 @@
package com.yihu.jw.entity.hospital.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by wzn54 on 2019/1/17.
 */
@Entity
@Table(name = "wlyy_frequency")
public class Frequency extends IdEntity {
    private String code;//医属频次编码
    private String name;//医属频次名称
    private Integer count;//频次次数
    private Integer number;//频次数目
    private String unit;//频次单位
    private String time;//时间段
    private String description;//执行表达式
    private Integer del;//删除标志(0、删除,1、正常)
    private Date createTime;//创建时间
    private Date updateTime;//修改时间
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "count")
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }
    @Column(name = "number")
    public Integer getNumber() {
        return number;
    }
    public void setNumber(Integer number) {
        this.number = number;
    }
    @Column(name = "unit")
    public String getUnit() {
        return unit;
    }
    public void setUnit(String unit) {
        this.unit = unit;
    }
    @Column(name = "time")
    public String getTime() {
        return time;
    }
    public void setTime(String time) {
        this.time = time;
    }
    @Column(name = "description")
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    @Column(name = "create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @Column(name = "update_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

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

@ -73,6 +73,61 @@ public class SystemMessageDO extends UuidIdentityEntity {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date createTime;
    private String content;
    private Integer state;
    private Integer readonly;
    private String reason;
    private String code;
    private String senderPhoto;
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Column(name = "state")
    public Integer getState() {
        return state;
    }
    public void setState(Integer state) {
        this.state = state;
    }
    @Column(name = "readonly")
    public Integer getReadonly() {
        return readonly;
    }
    public void setReadonly(Integer readonly) {
        this.readonly = readonly;
    }
    @Column(name = "reason")
    public String getReason() {
        return reason;
    }
    public void setReason(String reason) {
        this.reason = reason;
    }
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "sender_photo")
    public String getSenderPhoto() {
        return senderPhoto;
    }
    public void setSenderPhoto(String senderPhoto) {
        this.senderPhoto = senderPhoto;
    }
    @Column(name = "type")
    public String getType() {
        return type;

+ 1 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/team/WlyyAdminTeamDO.java

@ -17,6 +17,7 @@ import java.util.List;
@Entity
@Table(name = "wlyy_admin_team")
@EntityListeners(AuditingEntityListener.class)
public class WlyyAdminTeamDO implements Serializable {
    private Integer id;

+ 2 - 4
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/team/WlyyAdminTeamMemberDO.java

@ -3,10 +3,7 @@ package com.yihu.jw.entity.hospital.team;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.*;
import java.util.Date;
/**
@ -14,6 +11,7 @@ import java.util.Date;
 */
@Entity
@Table(name = "wlyy_admin_team_member")
@SequenceGenerator(name="id_generated", sequenceName="seq_wlyy_admin_team_member")
public class WlyyAdminTeamMemberDO extends IntegerIdentityEntity {
    private static final long serialVersionUID = 1L;
    private Long teamId;

+ 131 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientEvent.java

@ -0,0 +1,131 @@
package com.yihu.jw.entity.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
 * 患者就诊事件
 */
@Entity
@Table(name = "wlyy_patient_event")
public class PatientEvent extends UuidIdentityEntity implements Serializable {
	// 患者代码
	private String patient;
	// 就诊时间
	private Date eventDate;
	// 就诊类型
	private String eventType;
	// 机构代码
	private String orgCode;
	// 机构名称
	private String orgName;
	// 科室代码
	private String deptCode;
	// 科室名称
	private String deptName;
	// 医生代码
	private String doctorCode;
	// 医生名称
	private String doctorName;
	// 诊断
	private String dianosis;
	// 创建时间
	private Date createTime;
	public String getPatient() {
		return patient;
	}
	public void setPatient(String patient) {
		this.patient = patient;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getEventDate() {
		return eventDate;
	}
	public void setEventDate(Date eventDate) {
		this.eventDate = eventDate;
	}
	public String getEventType() {
		return eventType;
	}
	public void setEventType(String eventType) {
		this.eventType = eventType;
	}
	public String getOrgCode() {
		return orgCode;
	}
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	public String getOrgName() {
		return orgName;
	}
	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}
	public String getDeptCode() {
		return deptCode;
	}
	public void setDeptCode(String deptCode) {
		this.deptCode = deptCode;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	public String getDoctorCode() {
		return doctorCode;
	}
	public void setDoctorCode(String doctorCode) {
		this.doctorCode = doctorCode;
	}
	public String getDoctorName() {
		return doctorName;
	}
	public void setDoctorName(String doctorName) {
		this.doctorName = doctorName;
	}
	public String getDianosis() {
		return dianosis;
	}
	public void setDianosis(String dianosis) {
		this.dianosis = dianosis;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
}

+ 120 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/RehabilitationguidanceDO.java

@ -0,0 +1,120 @@
package com.yihu.jw.entity.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by hmf on 2020/2/26.
 */
@Entity
@Table(name = "wlyy_rehabilitation_guidance")
public class RehabilitationguidanceDO extends IntegerIdentityEntity {
    private String code;
    private String title;//模板名称
    private String content;//模板内容
    private String createUser;//创建医生code,该字段为空即系统模板
    private String createUserName;//创建医生名称
    private Integer type;//指导类型0、冠心病,1、脑卒中,2、慢性前列腺,3肺癌
    private String typeName;//指导类型0、冠心病,1、脑卒中,2、慢性前列腺,3肺癌
    private Integer useCount;//使用次数
    private Date czrq;//操作时间
    private Integer del;//删除标志(1正常,0删除)
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "create_user")
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    @Column(name = "create_user_name")
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    @Column(name = "title")
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Column(name = "use_count")
    public Integer getUseCount() {
        return useCount;
    }
    public void setUseCount(Integer useCount) {
        this.useCount = useCount;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    @Column(name = "type_name")
    public String getTypeName() {
        return typeName;
    }
    public void setTypeName(String typeName) {
        this.typeName = typeName;
    }
}

+ 141 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/RehabilitationguidancePatientDO.java

@ -0,0 +1,141 @@
package com.yihu.jw.entity.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
 * Created by hmf on 2020/2/26.
 */
@Entity
@Table(name = "wlyy_rehabilitation_guidance_patient")
public class RehabilitationguidancePatientDO extends IntegerIdentityEntity {
    private String patient;
    private String name;
    private String article;//模板code
    private String doctor;//模板内容
    private String doctorName;//创建医生code,该字段为空即系统模板
    private Integer isRead;//是否已读
    private String attachedContent;//康复指导内容
    private String attachedTitle;//康复指导标题
    private Integer sendStatus;//发送状态(1成功0失败)
    private String relationCode;//业务关联
    private Date czrq;//操作时间
    @Transient
    private String photo;//图片
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "article")
    public String getArticle() {
        return article;
    }
    public void setArticle(String article) {
        this.article = article;
    }
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "is_read")
    public Integer getIsRead() {
        return isRead;
    }
    public void setIsRead(Integer isRead) {
        this.isRead = isRead;
    }
    @Column(name = "attached_content")
    public String getAttachedContent() {
        return attachedContent;
    }
    public void setAttachedContent(String attachedContent) {
        this.attachedContent = attachedContent;
    }
    @Column(name = "attached_title")
    public String getAttachedTitle() {
        return attachedTitle;
    }
    public void setAttachedTitle(String attachedTitle) {
        this.attachedTitle = attachedTitle;
    }
    @Column(name = "send_status")
    public Integer getSendStatus() {
        return sendStatus;
    }
    public void setSendStatus(Integer sendStatus) {
        this.sendStatus = sendStatus;
    }
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name = "relation_code")
    public String getRelationCode() {
        return relationCode;
    }
    public void setRelationCode(String relationCode) {
        this.relationCode = relationCode;
    }
    @Transient
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
}

+ 72 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/SpecialDiseaseMessagesDO.java

@ -0,0 +1,72 @@
package com.yihu.wlyy.entity.specialist;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
/***
 * @ClassName: SpecialDiseaseMessages
 * @Description:
 * @Auther: shi kejing
 * @Date: 2021/4/20 9:42
 */
@Entity
@Table(name = "wlyy_special_disease_messages")
public class SpecialDiseaseMessages extends IdEntity {
    private String name;
    private String address;
    private String result;
    private String createTime;
    private String code;
    private String codeType;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public String getCreateTime() {
        return createTime;
    }
    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getCodeType() {
        return codeType;
    }
    public void setCodeType(String codeType) {
        this.codeType = codeType;
    }
}

+ 406 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/DoctorPatientRelationDO.java

@ -0,0 +1,406 @@
package com.yihu.jw.entity.specialist;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
@Entity
@Table(name = "wlyy_doctor_patient_relation")
public class DoctorPatientRelationDO extends UuidIdentityEntity {
    @Column(name = "saas_id")
    private String saasId;
    @Column(name = "discharge_record")
    private String dischargeRecord;//最新出院记录
    @Column(name = "doctor")
    private String doctor;//专科医生
    @Column(name = "doctor_name")
    private String doctorName;//专科医生姓名
    @Column(name = "patient")
    private String patient;// 居民(患者)
    @Column(name = "patient_name")
    private String patientName;//居民(患者)姓名
    @Column(name = "health_assistant")
    private String healthAssistant;//计管师
    @Column(name = "health_assistant_name")
    private String healthAssistantName;//计管师
    @Column(name = "sign_status")
    private String signStatus;//居民与专科医生签约状态: -2 医生拒绝,-1 已经取消,0待审核,1同意',
    @Column(name = "status")
    private String status;//1.已经分配,0,待分配,-1失效
    @Column(name = "pk_code")
    private String pkCode; //服务包code
    @Column(name = "sign_code")
    private String signCode;//签约code
    @Column(name = "sign_doctor")
    private String signDoctor;//签约医生
    @Column(name = "sign_doctor_name")
//    @Convert(converter = StringFStringEncryptConverter.class)
    private String signDoctorName;//签约医生
    @Column(name = "health_doctor")
    private String healthDoctor;//健康管理师
    @Column(name = "health_doctor_name")
//    @Convert(converter = StringFStringEncryptConverter.class)
    private String healthDoctorName;//健康管理师姓名
    @Column(name = "sign_year")
    private String signYear;//签约年度
    @Column(name = "team_code")
    private String teamCode;//专科医生签约团队',
    @Column(name = "sign_date")
    private Date signDate;//签约日期
    @Column(name = "remark")
    private String remark;//记录专科医生审核原因等
    @Column(name = "sign_certificate")
    private String signCertificate;//签约证明
    @Column(name = "health_status_code")
    private String healthStatusCode;//健康状况编码
    @Column(name = "disease_code")
    private String diseaseCode;//签约疾病编码,多个使用逗号隔开
    @Column(name = "is_manage")
    private Integer isManage;//是否管理(1管理0未管理)
    @Column(name = "manage_user")
    private String manageUser;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "manage_time")
    private Date manageTime;
    private Date createTime;
    private String createUser;
    private String createUserName;
    private Date updateTime;
    private String updateUser;
    private String updateUserName;
    private String remindTime;
    @Column(name = "isdeal")
    private String isdeal;
    @Column(name = "relation_type")
    private String relationType;//relation_type
    private String dept;
    private String deptName;
    @Column(name = "dept")
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
    @Column(name = "dept_name")
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    public String getIsdeal() {
        return isdeal;
    }
    public void setIsdeal(String isdeal) {
        this.isdeal = isdeal;
    }
    public String getRelationType() {
        return relationType;
    }
    public void setRelationType(String relationType) {
        this.relationType = relationType;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getDischargeRecord() {
        return dischargeRecord;
    }
    public void setDischargeRecord(String dischargeRecord) {
        this.dischargeRecord = dischargeRecord;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    public String getSignCode() {
        return signCode;
    }
    public void setSignCode(String signCode) {
        this.signCode = signCode;
    }
    public String getSignDoctor() {
        return signDoctor;
    }
    public void setSignDoctor(String signDoctor) {
        this.signDoctor = signDoctor;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getSignDoctorName() {
        return signDoctorName;
    }
    public void setSignDoctorName(String signDoctorName) {
        this.signDoctorName = signDoctorName;
    }
    public String getHealthDoctor() {
        return healthDoctor;
    }
    public void setHealthDoctor(String healthDoctor) {
        this.healthDoctor = healthDoctor;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getHealthDoctorName() {
        return healthDoctorName;
    }
    public void setHealthDoctorName(String healthDoctorName) {
        this.healthDoctorName = healthDoctorName;
    }
    public String getSignYear() {
        return signYear;
    }
    public void setSignYear(String signYear) {
        this.signYear = signYear;
    }
    public Date getSignDate() {
        return signDate;
    }
    public void setSignDate(Date signDate) {
        this.signDate = signDate;
    }
    public String getTeamCode() {
        return teamCode;
    }
    public void setTeamCode(String teamCode) {
        this.teamCode = teamCode;
    }
    public String getHealthAssistant() {
        return healthAssistant;
    }
    public void setHealthAssistant(String healthAssistant) {
        this.healthAssistant = healthAssistant;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getHealthAssistantName() {
        return healthAssistantName;
    }
    public void setHealthAssistantName(String healthAssistantName) {
        this.healthAssistantName = healthAssistantName;
    }
    public String getPkCode() {
        return pkCode;
    }
    public void setPkCode(String pkCode) {
        this.pkCode = pkCode;
    }
    public String getSignStatus() {
        return signStatus;
    }
    public void setSignStatus(String signStatus) {
        this.signStatus = signStatus;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public String getSignCertificate() {
        return signCertificate;
    }
    public void setSignCertificate(String signCertificate) {
        this.signCertificate = signCertificate;
    }
    public String getHealthStatusCode() {
        return healthStatusCode;
    }
    public void setHealthStatusCode(String healthStatusCode) {
        this.healthStatusCode = healthStatusCode;
    }
    public String getDiseaseCode() {
        return diseaseCode;
    }
    public void setDiseaseCode(String diseaseCode) {
        this.diseaseCode = diseaseCode;
    }
    public Integer getIsManage() {
        return isManage;
    }
    public void setIsManage(Integer isManage) {
        this.isManage = isManage;
    }
    public String getManageUser() {
        return manageUser;
    }
    public void setManageUser(String manageUser) {
        this.manageUser = manageUser;
    }
    public Date getManageTime() {
        return manageTime;
    }
    public void setManageTime(Date manageTime) {
        this.manageTime = manageTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    //    @Convert(converter = StringFStringEncryptConverter.class)
    public String getUpdateUserName() {
        return updateUserName;
    }
    public void setUpdateUserName(String updateUserName) {
        this.updateUserName = updateUserName;
    }
    public String getRemindTime() {
        return remindTime;
    }
    public void setRemindTime(String remindTime) {
        this.remindTime = remindTime;
    }
}

+ 20 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/SpecialistPatientRelationDO.java

@ -99,6 +99,26 @@ public class SpecialistPatientRelationDO extends UuidIdentityEntity implements S
    private String updateUser;
    private String updateUserName;
    private String remindTime;
    @Column(name = "isdeal")
    private String isdeal;
    @Column(name = "relation_type")
    private String relationType;//relation_type
    public String getIsdeal() {
        return isdeal;
    }
    public void setIsdeal(String isdeal) {
        this.isdeal = isdeal;
    }
    public String getRelationType() {
        return relationType;
    }
    public void setRelationType(String relationType) {
        this.relationType = relationType;
    }
    public String getSaasId() {
        return saasId;

+ 233 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientMedicalRecordsDO.java

@ -0,0 +1,233 @@
package com.yihu.jw.entity.specialist.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IntegerIdentityEntity;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * create by hmf on 2020/02/27 居民住院病历
 */
@Entity
@Table(name = "wlyy_patient_medical_records_rehabilitation")
public class PatientMedicalRecordsDO extends UuidIdentityEntity {
    private String code;
    private String patient;//居民code
    private String patientName;//居民姓名
    private String hospital;//诊疗医院code
    private String hospitalName;//诊疗医院名称
    private String dischargeDiagnosis;//出院诊断code,多个用逗号隔开
    private String dischargeDiagnosisName;//出院诊断名称,多个用逗号隔开
    private String admittingDiagnosis;//入院诊断code,多个用逗号隔开
    private String admittingDiagnosisName;//入院诊断名称,多个用逗号隔开
    private String advice;//医嘱小结
    private Date admissionTime;//入院时间
    private Date dischargeTime;//出院时间
    private String images;//病历图片,多个用逗号隔开
    private Date createTime;//创建时间
    private String createUser;//创建者
    private String createUserName;//创建者
    private String event;//健康档案病历eventID
    private String dataFrom;//病历来源:1基位,2app,3中山医院,4智业六家医院
    private String jwpatient;//基位居民code 获取病历详情用
    private String diseaseCode;//专病code
    private String diseaseName;//专病名称
    private int  patientReadStatus;
    private int  doctorReadStatus;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getDischargeDiagnosis() {
        return dischargeDiagnosis;
    }
    public void setDischargeDiagnosis(String dischargeDiagnosis) {
        this.dischargeDiagnosis = dischargeDiagnosis;
    }
    public String getDischargeDiagnosisName() {
        return dischargeDiagnosisName;
    }
    public void setDischargeDiagnosisName(String dischargeDiagnosisName) {
        this.dischargeDiagnosisName = dischargeDiagnosisName;
    }
    public String getAdmittingDiagnosis() {
        return admittingDiagnosis;
    }
    public void setAdmittingDiagnosis(String admittingDiagnosis) {
        this.admittingDiagnosis = admittingDiagnosis;
    }
    public String getAdmittingDiagnosisName() {
        return admittingDiagnosisName;
    }
    public void setAdmittingDiagnosisName(String admittingDiagnosisName) {
        this.admittingDiagnosisName = admittingDiagnosisName;
    }
    public String getImages() {
        return images;
    }
    public void setImages(String images) {
        this.images = images;
    }
    public String getAdvice() {
        return advice;
    }
    public void setAdvice(String advice) {
        this.advice = advice;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getAdmissionTime() {
        return admissionTime;
    }
    public void setAdmissionTime(Date admissionTime) {
        this.admissionTime = admissionTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getDischargeTime() {
        return dischargeTime;
    }
    public void setDischargeTime(Date dischargeTime) {
        this.dischargeTime = dischargeTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
    public String getEvent() {
        return event;
    }
    public void setEvent(String event) {
        this.event = event;
    }
    public String getDataFrom() {
        return dataFrom;
    }
    public void setDataFrom(String dataFrom) {
        this.dataFrom = dataFrom;
    }
    public String getJwpatient() {
        return jwpatient;
    }
    public void setJwpatient(String jwpatient) {
        this.jwpatient = jwpatient;
    }
    @Column(name = "disease_code")
    public String getDiseaseCode() {
        return diseaseCode;
    }
    public void setDiseaseCode(String diseaseCode) {
        this.diseaseCode = diseaseCode;
    }
    @Column(name = "disease_name")
    public String getDiseaseName() {
        return diseaseName;
    }
    public void setDiseaseName(String diseaseName) {
        this.diseaseName = diseaseName;
    }
    @Column(name = "patient_read_status")
    public int getPatientReadStatus() {
        return patientReadStatus;
    }
    public void setPatientReadStatus(int patientReadStatus) {
        this.patientReadStatus = patientReadStatus;
    }
    @Column(name = "doctor_read_status")
    public int getDoctorReadStatus() {
        return doctorReadStatus;
    }
    public void setDoctorReadStatus(int doctorReadStatus) {
        this.doctorReadStatus = doctorReadStatus;
    }
}

+ 9 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientRehabilitationPlanDO.java

@ -61,6 +61,15 @@ public class PatientRehabilitationPlanDO extends UuidIdentityEntity implements S
    private String updateUserName;
    private String healthStatusCode;//健康情况
    private String isVerify;
    @Column(name = "is_verify")
    public String getIsVerify() {
        return isVerify;
    }
    public void setIsVerify(String isVerify) {
        this.isVerify = isVerify;
    }
    @Column(name = "saas_id")
    public String getSaasId() {

+ 73 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationAdviceDO.java

@ -0,0 +1,73 @@
package com.yihu.jw.entity.specialist.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by hmf on 2020/2/26.
 */
@Entity
@Table(name = "wlyy_rehabilitation_advice")
public class RehabilitationAdviceDO extends IdEntity {
    private String code;
    private String name;//模板时间
    private String content;//模板内容
    private String createUser;//创建医生code,该字段为空即系统模板
    private String createUserName;//创建医生名称
    private Date createTime;//操作时间
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getCreateUserName() {
        return createUserName;
    }
    public void setCreateUserName(String createUserName) {
        this.createUserName = createUserName;
    }
}

+ 31 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/util/RSA.java

@ -0,0 +1,31 @@
package com.yihu.jw.entity.util;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
/**
 * 非对象算法加密信息
 * @author George
 *
 */
@Entity
@Table(name = "dm_rsa")
public class RSA extends IdEntity {
	private static final long serialVersionUID = 7832717679571844202L;
	
	private byte[] data;
	@Lob
	public byte[] getData() {
	    return data;
	}
	
	public void setData(byte[] data){
		this.data = data;
	}
}

+ 208 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/util/SystemConf.java

@ -0,0 +1,208 @@
package com.yihu.jw.entity.util;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Component
public class SystemConf {
    // 别处登录
    public static final int LOGIN_OTHER = 999;
    // 登录超时
    public static final int LOGIN_TIMEOUT = 998;
    // 未登录
    public static final int NOT_LOGIN = 997;
    // 文件保存临时路径
    private static final String TEMP_PATH = "upload_temp_path";
    // 血糖餐前最小值
    public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;
    // 血糖餐前最大值
    public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;
    // 血糖餐后最小值
    public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;
    // 血糖餐后最大值
    public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;
    // 舒张压最小值
    public static final double HEALTH_STANDARD_SZY_MIN = 60;
    // 舒张压最大值
    public static final double HEALTH_STANDARD_SZY_MAX = 90;
    // 收缩压最小值
    public static final double HEALTH_STANDARD_SSY_MIN = 90;
    // 收缩压最大值
    public static final double HEALTH_STANDARD_SSY_MAX = 140;
    // 同一手机号大最短信数
    public static final int MAX_SMS_MOBILE = 5;
    // 发送短信验证码间隔(分钟)
    public static final int SMS_INTERVAL = 2;
    private static Object lock = new Object();
    // 全局系统配置信息
    private static SystemConf systemConf;
    // 系统配置文件
    private Properties systemProperties;
    //im列表
    private String imListGet;
    public static SystemConf getInstance() {
        if (systemConf == null) {
            synchronized (lock) {
                systemConf = new SystemConf();
            }
        }
        return systemConf;
    }
    /**
     * 加载系统配置文件
     *
     * @return
     */
    public Properties getSystemProperties() {
        if (systemProperties == null) {
            InputStream is = null;
            try {
                is = this.getClass().getResourceAsStream("/system.properties");
                systemProperties = new Properties();
                systemProperties.load(is);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return systemProperties;
    }
    /**
     * 短信接口地址
     */
    public String getSmsUrl() {
        return getSystemProperties().getProperty("yihu_sms_url");
    }
    /**
     * 短信企业编号
     */
    public String getSmsCode() {
        return getSystemProperties().getProperty("yihu_sms_code");
    }
    /**
     * 短信用户名
     */
    public String getSmsName() {
        return getSystemProperties().getProperty("yihu_sms_name");
    }
    /**
     * 短信登录密码
     */
    public String getSmsPassword() {
        return getSystemProperties().getProperty("yihu_sms_password");
    }
    ;
    /**
     * 挂号接口地址
     */
    public String getGuahaoUrl() {
        return getSystemProperties().getProperty("yihu_guahao_url");
    }
    /**
     * 挂号接口对接appid
     */
    public String getGuahaoAppid() {
        return getSystemProperties().getProperty("yihu_guahao_appid");
    }
    /**
     * 挂号接口对接app secret
     */
    public String getGuahaoSecret() {
        return getSystemProperties().getProperty("yihu_guahao_secret");
    }
    /**
     * 获取文件保存的临时路径
     *
     * @return
     */
    public String getTempPath() {
        return getSystemProperties().getProperty(TEMP_PATH);
    }
    /**
     * 获取图片存在地址
     *
     * @return
     */
    /**
     * 获取服务全路径
     *
     * @return
     */
    /******************************** 挂号配置 ********************************************/
    /**
     * 获取厦门预约服务地址
     */
    public String getXMGuahaoUrl() {
        return getSystemProperties().getProperty("guahao_url");
    }
    /**
     * 获取厦门预约服务命名空间
     */
    public String getXMGuahaoNamespace() {
        return getSystemProperties().getProperty("guahao_namespace");
    }
    /****************************************************************************************/
    /********************************* EHR配置 **********************************************/
    /**
     * 是否启用EHR演示
     */
    public Boolean getEhrUsed() {
        return Boolean.valueOf(getSystemProperties().getProperty("ehr_used"));
    }
    /**
     * EHR档案服务地址
     */
    public String getEhrServices() {
        return getSystemProperties().getProperty("ehr_services");
    }
    /**
     * EHR底层地址
     */
    public String getEhrServicesBase() {
        return getSystemProperties().getProperty("ehr_services_base");
    }
    /**************************************************************************************/
    /**************************************************************************************/
}

+ 72 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/wlyyinfo/WechatTag.java

@ -0,0 +1,72 @@
package com.yihu.jw.entity.wlyyinfo;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by chenweida on 2017/8/4.
 */
@Entity
@Table(name = "wx_tag")
public class WechatTag extends IdEntity {
    private Integer tagId;
    private String tagName;
    private Date createTime;
    private Integer del;
    private String townCode;//区code
    private String townName;//区名称
    public Integer getTagId() {
        return tagId;
    }
    public void setTagId(Integer tagId) {
        this.tagId = tagId;
    }
    public String getTagName() {
        return tagName;
    }
    public void setTagName(String tagName) {
        this.tagName = tagName;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    public String getTownCode() {
        return townCode;
    }
    public void setTownCode(String townCode) {
        this.townCode = townCode;
    }
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
}

+ 74 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/rehabilitation/RehabilitationRequestMapping.java

@ -32,6 +32,80 @@ public class RehabilitationRequestMapping {
        public static final String findInformationPage = "findInformationPage";
    }
    public static class DoctorRehabilitationInfo {
        public static final String Perfix = "/rehabilitationInfo";
        public static final String createAdvice = "/createAdvice";
        public static final String deleteAdvice = "/deleteAdvice";
        public static final String getAdviceListByDoctor = "/getAdviceListByDoctor";
        public static final String sendWxMsgRemindSign = "/sendWxMsgRemindSign";
        public static final String findInformationById = "findInformationById";
        public static final String findInformationByPatientId = "findInformationByPatientId";
        public static final String findInformationPage = "findInformationPage";
    }
    public static class DoctorRehabilitationPlan {
        public static final String Perfix = "/rehabilitationPlan";
        public static final String createRehabilitationPlan = "/createRehabilitationPlan";
        public static final String createServiceQrCode = "/createServiceQrCode";
        public static final String checkAfterQrCode = "/checkAfterQrCode";
        public static final String saveRehabilitationOperateRecord = "/saveRehabilitationOperateRecord";
        public static final String updatePlanStatusById = "/updatePlanStatusById";
        public static final String updatePatientImgById = "/updatePatientImgById";
        public static final String findServicePackageItem = "/findServicePackageItem";
        public static final String findServiceItemInBase = "/findServiceItemInBase";
        public static final String findDoctorByTeams = "/findDoctorByTeams";
        public static final String findDoctorTeams = "/findDoctorTeams";
        public static final String findDoctorPatients = "/findDoctorPatients";
    }
    public static class PatientRehabilitationManage {
        public static final String Perfix = "/patientRehabilitationManage";
        public static final String patientRehabilitationDetail = "/patientRehabilitationDetail";
        public static final String calendarPlanDetail = "/calendarPlanDetail";
        public static final String serviceDoctorList = "/serviceDoctorList";
        public static final String calendarPlanDetailList = "/calendarPlanDetailList";
        public static final String sendMessageIm = "/sendMessageIm";
        public static final String checkAfterQrCode = "/checkAfterQrCode";
        public static final String saveRehabilitationOperateRecord = "/saveRehabilitationOperateRecord";
        public static final String recentPlanDetailRecord = "/recentPlanDetailRecord";
        public static final String serviceItemList = "/serviceItemList";
        public static final String serviceItem = "/serviceItem";
        public static final String planSchedule = "/planSchedule";
        public static final String updatePatientImgById = "/updatePatientImgById";
        public static final String getServiceItemsAfterStop = "/getServiceItemsAfterStop";
    }
    public static class DoctorRehabilitationManage {
        public static final String perfix = "/rehabilitationManage";
        public static final String findRehabilitationPlanList = "/findRehabilitationPlanList";
        public static final String findRehabilitationPlanDetailList = "/findRehabilitationPlanDetailList";
        public static final String calendarPlanDetail = "/calendarPlanDetail";
        public static final String calendarPlanDetailList = "/calendarPlanDetailList";
        public static final String serviceItemList = "/serviceItemList";
        public static final String serviceItem = "/serviceItem";
        public static final String saveGuidanceMessage = "/saveGuidanceMessage";
        public static final String updateStatusRehabilitationOperate = "/updateStatusRehabilitationOperate";
        public static final String patientRehabilitationDetail = "/patientRehabilitationDetail";
        public static final String recentPlanDetailRecord = "/recentPlanDetailRecord";
        public static final String serviceDoctorList = "/serviceDoctorList";
        public static final String appCalendarPlanDetailList = "/appCalendarPlanDetailList";
        public static final String updatePlanDetailStatusById = "/updatePlanDetailStatusById";
        public static final String planSchedule = "/planSchedule";
        public static final String patientCount = "/patientCount";
        public static final String sendToFamilyDoctor = "/sendToFamilyDoctor";
        public static final String getServiceItemsAfterStop = "/getServiceItemsAfterStop";
        public static final String selectFrequencys = "/selectFrequencys";
        public static final String updateNoteAndImageRehabilitationOperate = "/updateNoteAndImageRehabilitationOperate";
        public static final String updatePlanDetailExecuteTimeById = "/updatePlanDetailExecuteTimeById";
    }
    public static class TreatmentProgram {
        public static final String treatmentProgram = api_rehabilitation_common + "/treatmentProgram";

+ 3 - 0
gateway/ag-basic/src/main/resources/application.yml

@ -83,6 +83,9 @@ zuul:
    svr-cloud-care:
      path: /cloudCare/**
      serviceId: svr-cloud-care
    svr-rehabilitation:
      path: /rehabilitation/**
      serviceId: svr-rehabilitation
#---
#spring:

+ 92 - 5
svr/svr-rehabilitation/pom.xml

@ -102,22 +102,109 @@
			<artifactId>mysql-starter</artifactId>
			<version>2.0.0</version>
		</dependency>
		<dependency>
			<groupId>com.yihu.jw</groupId>
			<artifactId>base-service</artifactId>
			<version>2.0.0</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>com.yihu.jw</groupId>
			<artifactId>im-service</artifactId>
			<version>2.0.0</version>
		</dependency>
		<dependency>
			<groupId>org.springside</groupId>
			<artifactId>springside-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springside</groupId>
			<artifactId>springside-core</artifactId>
			<version>4.2.3-GA</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>svr-rehabilitation</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin </artifactId>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<!-- 生成的jar中,不要包含pom.xml和pom.properties这两个文件 -->
						<addMavenDescriptor>false</addMavenDescriptor>
						<manifest>
							<!-- 是否要把第三方jar加入到类构建路径 -->
							<addClasspath>true</addClasspath>
							<!-- 外部依赖jar包的最终位置 -->
							<classpathPrefix>lib/</classpathPrefix>
							<mainClass>com.yihu.SvrRehabilitationApplication</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
			<!--拷贝依赖到jar外面的lib目录-->
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-lib</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<!-- 依赖包输出目录,将来不打进jar包里 -->
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<excludeTransitive>false</excludeTransitive>
							<stripVersion>false</stripVersion>
							<includeScope>runtime</includeScope>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<!--指定配置文件,将resources打成外部resource-->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<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>

+ 8 - 1
svr/svr-rehabilitation/src/main/java/com/yihu/SvrRehabilitationApplication.java

@ -2,13 +2,20 @@ package com.yihu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@EnableJpaAuditing
@SpringBootApplication
public class SvrRehabilitationApplication {
public class SvrRehabilitationApplication extends SpringBootServletInitializer {
	public static void main(String[] args) {
		SpringApplication.run(SvrRehabilitationApplication.class, args);
	}
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return builder.sources(SvrRehabilitationApplication.class);
	}
}

+ 14 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ObserverRequired.java

@ -0,0 +1,14 @@
package com.yihu.rehabilitation.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by Trick on 2017/6/24.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ObserverRequired {
}

+ 89 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ObserverRequiredAOP.java

@ -0,0 +1,89 @@
package com.yihu.rehabilitation.aop;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
 * Created by Trick on 2017/6/24..
 */
@Aspect
@Component
public class ObserverRequiredAOP {
    //Controller层切点路径
    @Pointcut("execution(* com.yihu.rehabilitation..*.*(..))")
    public void controllerAspect() {
    }
    public ObserverRequiredAOP() {
        //System.out.println("Observer---------------------------------------");
    }
    @Around("controllerAspect() && @annotation(com.yihu.rehabilitation.aop.ObserverRequired)")
    public Object checkToken(ProceedingJoinPoint point) throws Throwable {
        Object o = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String error = "";
        try {
            response.setCharacterEncoding("UTF-8");
            JSONObject json = getAgent(request);
            String observer = json.has("observer") ? json.getString("observer") : "";
            if(StringUtils.isNotBlank(observer)&&"1".equals(observer)){
                PrintWriter writer=response.getWriter();
                writer.write(error(403, "该操作没有权限"));
                writer.flush();
                return o;
            }
        }catch (Exception e){
            //return o;
        }
         o = point.proceed();
        return o;
    }
    public String write(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public String error(int code, String msg) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            return json.toString();
        } catch (Exception e) {
            return null;
        }
    }
    public JSONObject getAgent(HttpServletRequest request) {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            System.out.println("userAgent:" + userAgent);
            return new JSONObject(userAgent);
        } catch (Exception e) {
            return null;
        }
    }
}

+ 22 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ServicesAuth.java

@ -0,0 +1,22 @@
package com.yihu.rehabilitation.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 使用该注解必须带item。注解的方法参数必须有patientId
 * 服务项权限控制
 * Created by yeshijie on 2021/3/5.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ServicesAuth {
    /**
     * 服务项code
     * @return
     */
    String item();
}

+ 5 - 1
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/config/jpa/HibernateProperties.java

@ -1,3 +1,4 @@
/*
package com.yihu.rehabilitation.config.jpa;
import org.springframework.beans.factory.annotation.Value;
@ -6,9 +7,11 @@ import org.springframework.stereotype.Component;
import java.util.Properties;
*/
/**
 * Created by chenweida on 2017/4/6.
 */
 *//*
@Component
@RefreshScope
public class HibernateProperties {
@ -27,3 +30,4 @@ public class HibernateProperties {
        return properties;
    }
}
*/

+ 5 - 1
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/config/jpa/RehabilitationJpa.java

@ -1,3 +1,4 @@
/*
package com.yihu.rehabilitation.config.jpa;
@ -17,9 +18,11 @@ import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
*/
/**
 * Created by humingfen on 2018/4/27.
 */
 *//*
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
@ -56,3 +59,4 @@ public class RehabilitationJpa {
        return new JpaTransactionManager(builder);
    }
}
*/

File diff suppressed because it is too large
+ 318 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanController.java


+ 3 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanningController.java

@ -6,6 +6,7 @@ import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.rehabilitation.RehabilitationPlanningVO;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.rehabilitation.service.RehabilitationPlanningService;
import com.yihu.rehabilitation.service.RehabilitationTreatmentProgramService;
import io.swagger.annotations.Api;
@ -116,4 +117,6 @@ public class RehabilitationPlanningController extends EnvelopRestEndpoint {
            return MixEnvelop.getError(e.getMessage());
        }
    }
}

+ 166 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitaionInfoController.java

@ -0,0 +1,166 @@
package com.yihu.rehabilitation.controller.doctor;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.service.RehabilitationInfoService;
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.*;
import java.text.SimpleDateFormat;
import java.util.List;
@RestController
@RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.Perfix, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-康复下转管理")
public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private ObjectMapper objectMapper;
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.createAdvice, method = RequestMethod.POST)
    @ApiOperation("创建/编辑康复建议模板")
    @ObserverRequired
    public Envelop 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 success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.deleteAdvice, method = RequestMethod.POST)
    @ApiOperation("删除康复建议模板")
    @ObserverRequired
    public Envelop deleteAdvice(@ApiParam(name = "id", value = "模板id")
                               @RequestParam(value = "id", required = false) Long id) {
        try {
            rehabilitationInfoService.deleteAdvice(id);
            return success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @RequestMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationInfo.getAdviceListByDoctor, method = RequestMethod.GET)
    @ApiOperation("获取医生创建康复建议模板及系统模板")
    public Envelop 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 success("操作成功",list);
        } catch (Exception e) {
           e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.sendWxMsgRemindSign, method = RequestMethod.POST)
    @ApiOperation("发送微信模板提醒签约消息")
    public Envelop sendWxTemplate(@ApiParam(name = "patient", value = "居民code", required = false)
                                 @RequestParam(value = "patient", required = false)String patient,
                                 @ApiParam(name = "wxId", value = "微信id", required = false)
                                 @RequestParam(value = "wxId", required = false)String wxId,
                                  @ApiParam(name = "scene", value = "模板code", required = false)
                                      @RequestParam(value = "scene", required = false)String scene){
        try {
            rehabilitationInfoService.sendSFWxTemplate(patient,wxId,scene);
            return success("发送成功");
        } catch (Exception e) {
           e.printStackTrace();
            return failed("发送失败");
        }
    }
    @RequestMapping(value = "createMedicalRecords", method = RequestMethod.POST)
    @ApiOperation("添加编辑住院病历")
    @ObserverRequired
    public Envelop 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();
            }
            System.out.println("111doctorid"+doctorCode);
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO = objectMapper.readValue(jsonData, PatientMedicalRecordsDO.class);
            System.out.println("实体转换完成");
            return success( "添加成功", rehabilitationInfoService.createMedicalRecords(doctorCode, patient, patientName, patientMedicalRecordsDO, id));
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @RequestMapping(value = "getRehabilitationPatientList", method = RequestMethod.GET)
    @ApiOperation("获取康复下转居民列表")
    public Envelop 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 = "doctor", value = "",required = false)
                                                    @RequestParam(value = "doctor", required = false,defaultValue = "3") String doctor) {
        try {
            JSONObject result = rehabilitationInfoService.getRehabilitationPatientList(idcard, doctor,isTurnDown);
            return success( "请求成功", result);
        } catch (Exception e) {
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "/getIcd10Info", method = RequestMethod.GET)
    @ApiOperation(value = "获取诊断结果")
    public Envelop getIcd10Info(@RequestParam(required = false)
                                @ApiParam(value = "诊断结果关键字", name = "nameKey") String nameKey,
                                @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
                                @RequestParam(value = "page") Integer page,
                                @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "15",required = true)
                                @RequestParam(value = "pageSize") Integer pageSize) {
        try {
            return success("操作成功!", rehabilitationInfoService.getIcd10Info(nameKey, page, pageSize).toString());
        } catch (Exception e) {
            return failed( "查询失败!");
        }
    }
}

+ 984 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationManageController.java

@ -0,0 +1,984 @@
package com.yihu.rehabilitation.controller.doctor;
import com.netflix.discovery.converters.Auto;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
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.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.service.RehabilitationGuidanceService;
import com.yihu.rehabilitation.service.RehabilitationManageService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.service.message.RehabilitationMessageService;
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.*;
/**
 * Created by 刘文彬 on 2018/8/30.
 */
@RestController
@RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.perfix)
@Api(description = "医生端-康复管理")
public class DoctorRehabilitationManageController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RehabilitationMessageService rehabilitationMessageService;
    @Autowired
    private RehabilitationGuidanceService rehabilitationGuidanceService;
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.findRehabilitationPlanList, method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划列表")
    public MixEnvelop findRehabilitationPlanList(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                             @RequestParam(value = "doctorCode", required = false)String doctorCode,
//                                             @ApiParam(name = "doctorType", value = "医生类型(1、专科医生,2、家庭医生)", required = true)
//                                             @RequestParam(value = "doctorType", required = true)Integer doctorType,
                                                 @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 = getUID();
            }
            return  rehabilitationManageService.findRehabilitationPlan(doctorCode,diseaseCode,planType,todaybacklog,patientCondition,page,pageSize);
        } catch (Exception e) {
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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 = getUID();
            }
            return rehabilitationManageService.findRehabilitationPlanDetailList(doctorCode,patientCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("请求失败");
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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、复诊)", 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 = getUID();
            }
            return rehabilitationManageService.calendarPlanDetail(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode,"1");
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping("calendarPlanDetailBypatient")
    @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 = getUID();
            }
            return rehabilitationManageService.calendarPlanDetailByPatient(executeStartTime,executeEndTime,patient,searchTask,status,doctorCode,"1");
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @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 = getUID();
            }
            return rehabilitationManageService.calendarPlanDetailListByPatient(executeStartTime,executeEndTime,patient,searchTask,status,doctorCode,taskExecutor);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "请求失败");
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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、随访,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,
                                         @ApiParam(name = "taskExecutor", value = "", required = false)
                                             @RequestParam(value = "taskExecutor", required = false)String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getUID();
            }
            return rehabilitationManageService.calendarPlanDetailList( planId, searchTask, status, doctorCode, executeStartTime, executeEndTime,taskExecutor);
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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 = getUID();
            }
            return  rehabilitationManageService.serviceItemList(planDetailIds,doctorCode);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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 = getUID();
            }
            return rehabilitationManageService.serviceItem(planDetailId,doctorCode,recordId);
        } catch (Exception e) {
          e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.saveGuidanceMessage, method = RequestMethod.POST)
    @ApiOperation("康复管理-保存指导留言")
    public Envelop saveGuidanceMessage(@ApiParam(name = "messageId", value = "消息id", required = true)
                                      @RequestParam(value = "messageId", required = true)String messageId,
//                                      @ApiParam(name = "patientCode", value = "居民code", required = true)
//                                      @RequestParam(value = "patientCode", required = false)String patientCode,
                                      @ApiParam(name = "doctorCode", value = "医生code", required = false)
                                      @RequestParam(value = "doctorCode", required = false)String doctorCode,
//                                      @ApiParam(name = "doctorType", value = "医生类型(1、专科医生,2、家庭医生)", required = true)
//                                      @RequestParam(value = "doctorType", required = true)Integer doctorType,
                                      @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 = getUID();
            }
            return  rehabilitationManageService.saveGuidanceMessage(messageId,doctorCode,content,planDetailId,contentType);
        } catch (Exception e) {
          e.printStackTrace();
            return Envelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.updateStatusRehabilitationOperate, method = RequestMethod.POST)
    @ApiOperation("康复管理-更新康复计划操作完成日志状态")
    public Envelop 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){
        return rehabilitationManageService.updateStatusRehabilitationOperate(status,planDetailId);
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.patientRehabilitationDetail, method = RequestMethod.GET)
    @ApiOperation("康复管理-居民详情页")
    public ObjEnvelop patientRehabilitationDetail(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                              @RequestParam(value = "patientCode", required = true)String patientCode){
        return rehabilitationManageService.patientRehabilitationDetail(patientCode);
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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 (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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 (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.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 = 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.appCalendarPlanDetailList(planId,searchTask,status,executeStartTime,executeEndTime);
        } catch (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.updateNoteAndImageRehabilitationOperate)
    @ApiOperation(value = "康复计划完成时更新服务完成笔记和图片接口并且确认完成")
    public ObjEnvelop updateNoteAndImageRehabilitationOperate(@ApiParam(name = "planDetailId", value = "服务项目id", required = true)@RequestParam(value = "planDetailId", required = true)String planDetailId,
                                                              @ApiParam(name = "node", value = "服务完成笔记", required = true)@RequestParam(value = "node", required = false)String node,
                                                              @ApiParam(name = "image", value = "相关记录图片,json格式", required = true)@RequestParam(value = "image", required = false)String image,
                                                              @ApiParam(name = "relationCode", value = "业务code", required = true)@RequestParam(value = "relationCode", required = false)String relationCode,
                                                              @ApiParam(name = "status", value = "是否确认完成 0未确认 1确认", required = true)@RequestParam(value = "status", required = false)String status){
        try {
            Map<String,Object> map = rehabilitationManageService.updateNodeAndRelationRecordImg(node,image,status,planDetailId,relationCode);
            return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.updatePlanDetailStatusById)
    @ApiOperation(value = "康复管理-更新康复计划项目状态")
    public Envelop updatePlanDetailStatusById(@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 {
            return rehabilitationManageService.updatePlanDetailStatusById(status,planDetailId);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError(e.getMessage());
        }
    }
    @PostMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.updatePlanDetailExecuteTimeById)
    @ApiOperation(value = "康复管理-修改康复计划项目执行时间")
    public Envelop updatePlanDetailExecuteTimeById(@ApiParam(name = "planDetailId", value = "服务项目id", required = true)
                                                   @RequestParam(value = "planDetailId", required = true)String planDetailId,
                                                   @ApiParam(name = "executeTime", value = "状态", required = true)
                                                   @RequestParam(value = "executeTime", required = true)String executeTime){
        try {
            Date date = DateUtil.strToDateLong(executeTime);
            return rehabilitationManageService.updatePlanDetailExecuteTimeById(date,planDetailId);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.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);
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.patientCount)
    @ApiOperation(value = "医生已计划数,已完成计划数(居民数)")
    public ObjEnvelop patientCount(@ApiParam(name = "doctorCode", value = "医生code", required = true)
                                   @RequestParam(value = "doctorCode", required = true)String doctorCode){
        try {
            return rehabilitationManageService.patientCount(doctorCode);
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.sendToFamilyDoctor)
    @ApiOperation(value = "给家医发送居民的康复计划")
    public Envelop 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,"");
            return Envelop.getSuccess(SpecialistMapping.api_success);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError(e.getMessage());
        }
    }
    @GetMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.getServiceItemsAfterStop)
    @ApiOperation(value = "康复管理-中止康复计划结算项目清单")
    public ObjEnvelop getServiceItemsAfterStop(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                               @RequestParam(value = "planId", required = true)String planId){
        try {
            return rehabilitationManageService.getServiceItemsAfterStop(planId);
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 康复管理-频次列表
     *
     * @return
     */
    @RequestMapping(value =  RehabilitationRequestMapping.DoctorRehabilitationManage.selectFrequencys, method = RequestMethod.GET)
    @ApiOperation("康复管理-频次列表")
    public MixEnvelop selectFrequencys(){
        try {
            return MixEnvelop.getSuccess("操作成功",rehabilitationManageService.selectFrequences());
        } catch (Exception e) {
            return MixEnvelop.getError( e.getMessage());
        }
    }
    @RequestMapping(value = "selectAllPlaneByPatient",method = RequestMethod.GET)
    @ApiOperation("获取居民所有康复计划")
    public Envelop getPatientAllRehabilitationPlan(@ApiParam(name = "patient",value = "居民Code", required = true)
                                                  @RequestParam(value = "patient",required = true)String patient){
        try {
            return success("获取成功",  rehabilitationManageService.getPatientAllRehabilitationPlan(patient));
        }catch (Exception e){
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectByGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据计划查询指导留言")
    public Envelop 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 = rehabilitationManageService.selectByGuidance(planId,itemCode);
            return success("获取成功",  mapList);
        } catch (Exception e) {
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "manageAllPlanByPatient",method = RequestMethod.POST)
    @ApiOperation("一键确认管理居民所有的康复计划")
    public Envelop manageAllPlanByPatient(@ApiParam(name="patient",value = "患者code",required = true)
                                         @RequestParam(value = "patient",required = true)String patient){
        try {
            return  success("操作成功",rehabilitationManageService.manageAllPlanByPatient(patient,getUID()));
        }catch (Exception e){
            return failed( "请求失败");
        }
    }
    @PostMapping(value = "planDetailAfterCall")
    @ApiOperation(value = "康复管理-电话关怀拨打后生成记录对应怪坏记录")
    public MixEnvelop<RehabilitationOperateRecordsDO,RehabilitationOperateRecordsDO> planDetailAfterCall(
            @ApiParam(name = "planDetailId", value = "planDetailId", required = false)
            @RequestParam(value = "planDetailId", required = false)String planDetailId,
            @ApiParam(name = "doctorCode", value = "doctorCode", required = false)
            @RequestParam(value = "doctorCode", required = false)String doctorCode,
            @ApiParam(name = "doctorName", value = "doctorName", required = false)
            @RequestParam(value = "doctorName", required = false)String  doctorName){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("doctorCode",doctorCode);
        jsonObject.put("doctorName",doctorName);
        jsonObject.put("rehabilitationDetailId",planDetailId);
        try {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationManageService.planDetailAfterCall(jsonObject.toString()));
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "/dailyJobSendMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划每天8点,16点发送服务进展的job")
    @ObserverRequired
    public Envelop dailyJobSendMessage(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                      @RequestParam(value = "startTime", required = true)String startTime,
                                      @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                      @RequestParam(value = "endTime", required = true)String endTime,
                                      @ApiParam(name = "type", value = "8点:23,16点:22", required = true)
                                      @RequestParam(value = "type", required = true)Integer type){
        try {
            rehabilitationManageService.dailyJobSendMessage(startTime,endTime,type);
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "/tomorrowJobSendMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划每天15点发送明天服务定时提醒的job")
    @ObserverRequired
    public Envelop tomorrowJobSendMessage(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                         @RequestParam(value = "startTime", required = true)String startTime,
                                         @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                         @RequestParam(value = "endTime", required = true)String endTime,
                                         @ApiParam(name = "type", value = "15点:23", required = true)
                                         @RequestParam(value = "type", required = true)Integer type){
        try {
            rehabilitationManageService.tomorrowJobSendMessage(startTime,endTime,type);
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "/dailyByJobSendMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划每15分钟服务进展提醒")
    @ObserverRequired
    public Envelop dailyByJobSendMessage(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                        @RequestParam(value = "startTime", required = true)String startTime,
                                        @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                        @RequestParam(value = "endTime", required = true)String endTime,
                                        @ApiParam(name = "type", value = "15分钟,22", required = true)
                                        @RequestParam(value = "type", required = true)Integer type){
        try {
            rehabilitationManageService.dailyByJobSendMessage(startTime,endTime,type);
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "/dailyJobReserve", method = RequestMethod.POST)
    @ApiOperation("康复管理-10天、7天、5天、当天(0)康复服务预约复诊通知")
    @ObserverRequired
    public Envelop dailyJobReserve(@ApiParam(name = "num", value = "10天、7天、5天、当天康复服务预约复诊通知", required = false)
                                  @RequestParam(value = "num", required = false)Integer num){
        try {
            if(num!=null){
                rehabilitationManageService.dailyJobReserve(num,20);
            }else{
                Integer[] days = {10,7,5,0};
                for(Integer one : days){
                    rehabilitationManageService.dailyJobReserve(one,20);
                }
            }
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "selectByMedicalCode", method = RequestMethod.GET)
    @ApiOperation("获取医院病历")
    public Envelop selectByMedicalCode(@ApiParam(name = "medical", value = "住院code", required = true)
                                      @RequestParam(value = "medical", required = true)String medical){
        try {
            List<PatientMedicalRecordsDO> result = rehabilitationManageService.selectByMedicalCode(medical);
            try {
                String sql = "UPDATE `wlyy_patient_medical_records_rehabilitation` SET `doctor_read_status`='1' WHERE (`code`='"+medical+"') ";
                jdbcTemplate.update(sql);
            }catch (Exception e){
                e.printStackTrace();
            }
            return success("操作成功", result);
        } catch (Exception e) {
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "getPlanDetailForModifing",method = RequestMethod.GET)
    @ApiOperation(value = "根据planId、模板id获取计划列表")
    public Envelop 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 success("查询成功",rehabilitationManageService.getPlanDetailForModifing(planId, templateId));
        }catch (Exception e){
            return failed("查询失败");
        }
    }
    @RequestMapping(value = "selectPlanServerDoctor", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划的服务医生")
    public Envelop selectPlanServerDoctor(@ApiParam(name = "planId", value = "康复计划ID")@RequestParam(value = "planId", required = true)String planId){
        try {
            String doctorCode = getUID();
            return success("查询成功",rehabilitationManageService.selectPlanServerDoctor(planId,doctorCode));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "查询失败");
        }
    }
    @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 = getUID();
            }
            JSONObject result = rehabilitationManageService.selectBySpecialistDoctor1(level,area,doctorCode,diseaseCode,page,pageSize,doctorType,patientInfo,filterPlan,turnDownState);
            JSONArray showList = result.getJSONArray("showList");
            JSONObject turnDownStateObj = result.getJSONObject("turnDownState");
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "获取成功");
            json.put("data",showList);
            json.put("data2",turnDownStateObj);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败";
        }
    }
    @RequestMapping(value = "createSpecialDoctorQrCode", method = RequestMethod.POST)
    @ApiOperation("康复管理-生成康复下转专科医生二维码")
    @ObserverRequired
    public Envelop 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 success("获取二维码成功!", rehabilitationManageService.createSpecialDoctorQrCode(doctorCode,teamCode,teamName));
        } catch (Exception e) {
            return failed( "请求二维码失败");
        }
    }
    @RequestMapping(value = "selectAllCompleteServiceItemsByPatient",method = RequestMethod.GET)
    @ApiOperation("康复计划主页动态")
    public Envelop selectAllCompleteServiceItemsByPatient(@ApiParam(name = "patient",value = "居民Code", required = true)
                                                         @RequestParam(value = "patient",required = true)String patient){
        try {
            return success("获取成功", rehabilitationManageService.selectAllCompleteServiceItemsByPatient(patient));
        }catch (Exception e){
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "calendarPlanDetailItems", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目按列表展示")
    public Envelop 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 = getUID();
            }
            List<Map<String,Object>> result = rehabilitationManageService.calendarPlanDetailItems(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode);
            return success( "获取成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "confirmManage", method = RequestMethod.GET)
    @ApiOperation("康复管理-确认管理")
    public Envelop 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 {
            rehabilitationManageService.confirmManage(patient,signDoctor,specialist,relationId,planId);
            return success("请求成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectByPlanDetaiId", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取操作记录")
    public Envelop selectByPlanDetaiId(@ApiParam(name = "patient", value = "居民code", required = true)
                                      @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 success("获取成功",  rehabilitationManageService.selectByPlanDetaiId(patient,planId,code,page,pagesize).toString());
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    /*@GetMapping(value = "selectRelationCode")
    @ResponseBody
    @ApiOperation("业务关联code")
    public Envelop selectRelationCode(@ApiParam(name = "relationCode", value = "业务关联code",required = true)
                                     @RequestParam String relationCode) {
        try {
            return success("请求成功!",wlyyDoorServiceOrderService.selectRelationCode(relationCode));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }*/
    @RequestMapping(value = "getServiceItemList", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取服务项目列表")
    public Envelop getServiceItemList(@ApiParam(name = "name", value = "服务项目名称", required = false)
                                     @RequestParam(value = "name", required = false) String name) {
        try {
            return success( "请求成功!", rehabilitationManageService.getServiceItemList(name));
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @ApiOperation("获取居民最近的一次住院病历")//wlyy_patient_medical_records_rehabilitation
    @RequestMapping(value = "getNewRehabilitation", method = RequestMethod.GET)
    public Envelop getNewRehabilitation(
            @ApiParam(name = "patientCode", value = "居民code", required = true)
            @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            List<PatientMedicalRecordsDO> result = rehabilitationManageService.getNewRehabilitation(patientCode,getUID());
            return success("获取成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectPlanByPatient", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据居民code查找康复计划")
    public Envelop 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 = rehabilitationManageService.selectPlanByPatient(patient,status,planId,getUID());
            return success("获取成功",  result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    /**
     *
     * @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("康复管理-发送微信模板消息")
    @ObserverRequired
    public Envelop 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 {
            rehabilitationMessageService.sendSpecialistWeixinMessage(patient,doctor,type,relationCode,planId,reservationType);
            return success("请求成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "selectType", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表标题")
    public Envelop selectType(@ApiParam(name="planId",value = "根据计划id取该计划对应疾病的指导",required = false)
                             @RequestParam(value = "planId",required = false)String planId) {
        try {
            return success("请求成功!",  rehabilitationGuidanceService.selectType(planId));
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "sendGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-发送康复指导")
    public Envelop 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 success( "请求成功!",  rehabilitationGuidanceService.sendGuidanceToPatient(rehabilitationguidancePatientDOS,planId));
        } catch (Exception e) {
           e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public Envelop 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 success( "请求成功!", rehabilitationGuidanceService.select(title,type,id,planId,page,pagesize));
        } catch (Exception e) {
           e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "selectPatientGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public Envelop 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 success( "请求成功!", rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,code,page,pagesize));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
}

+ 426 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationPlanController.java

@ -0,0 +1,426 @@
package com.yihu.rehabilitation.controller.doctor;
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.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.entity.util.AesEncryptUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.service.DoctorPatientRelationService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.service.PatientRecordService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.service.ZsRehabilitationInfoService;
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.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * Created by humingfen on 2018/8/22.
 */
@RestController
@RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.Perfix,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-康复服务套餐管理")
public class DoctorRehabilitationPlanController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private PatientRecordService patientRecordService;
    @Autowired
    private ZsRehabilitationInfoService zsRehabilitationInfoService;
    @Autowired
    private DoctorPatientRelationService doctorPatientRelationService;
    @Value("${demo.flag}")
    private Boolean demoFlag;
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.createRehabilitationPlan, method = RequestMethod.POST)
    @ApiOperation(value = "创建居民康复计划")
    @ObserverRequired
    public ObjEnvelop 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 baseDoctorDO = baseDoctorDao.findById(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 ObjEnvelop.getError("计划创建失败!您设置了重复项目时间,请修改后生成!",-1);
            }
            return  ObjEnvelop.getSuccess("获取成功",rehabilitationPlanService.createRehabilitationPlan(json,baseDoctorDO),200);
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    /*@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){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            return write(200, "获取成功", "data", rehabilitationPlanService.findTemplateInfo(doctor, patient));
        } catch (Exception e) {
            error(e);
            return error(-1, "请求失败");
        }
    }*/
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.createServiceQrCode)
    @ApiOperation(value = "根据康复计划明细id和医生code生成服务码")
    public MixEnvelop<String,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 rehabilitationPlanService.createServiceQrCode(planDetailId,doctorCode);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value =RehabilitationRequestMapping.DoctorRehabilitationPlan.checkAfterQrCode)
    @ApiOperation(value = "居民扫码后验证是否是关联的居民扫码")
    public MixEnvelop<Map<String,Object>,Map<String,Object>> 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 MixEnvelop.getSuccess(message,map);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.saveRehabilitationOperateRecord, method = RequestMethod.POST)
    @ApiOperation("康复管理-新增operateRecord")
    public MixEnvelop 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 {
            JSONObject json = new JSONObject(dataJson);
            if(json.has("patientCode")){
                BasePatientDO patient = basePatientDao.findById(json.get("patientCode")+"");
                json.put("patientName",patient!=null?patient.getName():"");
            }
            if(json.has("doctorCode")){
                BaseDoctorDO doctor = baseDoctorDao.findById(json.get("doctorCode")+"");
                json.put("doctorName",doctor!=null?doctor.getName():"");
            }
            RehabilitationOperateRecordsDO rehabilitationOperateRecordsDO= toEntity(json.toString(), RehabilitationOperateRecordsDO.class);
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationPlanService.saveRehabilitationRecord(rehabilitationOperateRecordsDO));
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.updatePlanStatusById)
    @ApiOperation(value = "康复管理-更新康复计划状态")
    public MixEnvelop updatePlanStatusById(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                           @RequestParam(value = "planId", required = true)String planId,
                                           @ApiParam(name = "status", value = "状态", required = true)
                                           @RequestParam(value = "status", required = true)Integer status,
                                           @ApiParam(name = "abortReason", value = "中止原因", required = true)
                                           @RequestParam(value = "abortReason", required = false)String abortReason){
        try {
            if(status!=0){
                return rehabilitationPlanService.updatePlanStatusById(status,planId);
            }else {
                return rehabilitationPlanService.abortPlanById(planId,abortReason);
            }
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.updatePatientImgById)
    @ApiOperation(value = "更新康复计划居民签名照/证件照")
    public Envelop updatePatientImgById(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                        @RequestParam(value = "planId")String planId,
                                        @ApiParam(name = "patientImg", value = "居民签名/证件照地址",required = true)
                                        @RequestParam(value = "patientImg")String patientImg){
        try {
            return rehabilitationPlanService.updatePatientImgById(planId, patientImg);
        }catch (Exception e){
            e.printStackTrace();
            return Envelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findServicePackageItem)
    @ApiOperation(value = "查询康复计划项目")
    public ObjEnvelop findServicePackageItem(@ApiParam(name = "doctorId", value = "医生id", required = true)
                                        @RequestParam(value = "doctorId")String doctorId){
        try {
            return rehabilitationPlanService.findServiceItemByDoctor(doctorId);
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findDoctorTeams)
    @ApiOperation(value = "查询医生团队")
    public ObjEnvelop findDoctorTeams(@ApiParam(name = "doctor", value = "医生id", required = false)
                                             @RequestParam(value = "doctor", required = false)String doctor){
        try {
            return ObjEnvelop.getSuccess("操作成功",rehabilitationPlanService.findDoctorTeams(doctor));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findDoctorByTeams)
    @ApiOperation(value = "根据团队查询医生列表")
    public ObjEnvelop findDoctorByTeams(@ApiParam(name = "teamCode", value = "团队id", required = false)
                                            @RequestParam(value = "teamCode", required = false)String teamCode){
        try {
            return ObjEnvelop.getSuccess("操作成功",rehabilitationPlanService.findDoctorByTeams( teamCode));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findDoctorPatients)
    @ApiOperation(value = "根据团队查询医生列表")
    public MixEnvelop findDoctorPatients(@ApiParam(name = "doctor", value = "医生id", required = false)
                                        @RequestParam(value = "doctor", required = false)String doctor,
                                         @ApiParam(name = "patient", value = "患者id", required = false)
                                         @RequestParam(value = "patient", required = false)String patient,
                                         @ApiParam(name = "patientName", value = "患者姓名", required = false)
                                             @RequestParam(value = "patientName", required = false)String patientName,
                                         @ApiParam(name = "isDeal", value = "是否下转1是0否", required = false)
                                             @RequestParam(value = "isDeal", required = false)String isDeal,
                                         @ApiParam(name = "idcard", value = "是否下转1是0否", required = false)
                                             @RequestParam(value = "idcard", required = false)String idcard,
                                         @ApiParam(name = "page", value = "page", required = false)
                                             @RequestParam(value = "page", required = false)Integer page,
                                         @ApiParam(name = "pageSize", value = "pageSize", required = false)
                                             @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            return doctorPatientRelationService.findDoctorPatients(doctor,patient,patientName,isDeal,idcard,page,pageSize);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "getPatientByIdcardOrSsc", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("根据患者身份证或社保卡号进行搜索添加出院记录")
    public Envelop getPatientByIdcardOrSsc(@ApiParam(name = "patientInfo", value = "居民身份证或者社保卡", required = true)
                                          @RequestParam(value = "patientInfo")String patientInfo) {
        try {
            com.alibaba.fastjson.JSONObject object = doctorPatientRelationService.getPatientByIdcardOrSsc(patientInfo, getUID());
            if(object.getInteger("status") == 200) {
                return success("添加成功!", object.get("data"));
            }else {
                return failed( object.getString("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed("添加失败!");
        }
    }
    @RequestMapping(value = "/updateRehabilitationPlan", method = RequestMethod.POST)
    @ApiOperation(value = "编辑居民康复计划")
    public Envelop 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 = baseDoctorDao.findById(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 failed( "计划创建失败!您设置了重复项目时间,请修改后生成!");
            }
            return success("获取成功", rehabilitationPlanService.updateRehabilitationPlan(json,d,updateStatus));
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "getRehabilitationPlanLog",method = RequestMethod.GET)
    @ApiOperation(value = "获取康复计划修改记录")
    public Envelop getRehabilitationPlanLog(@ApiParam(name = "planId",value = "康复计划Id",required = true)
                                           @RequestParam(value = "planId",required = true) String planId){
        try {
            return success("获取成功",rehabilitationPlanService.getRehabilitationPlanLog(planId));
        }catch (Exception e){
            return failed("请求失败");
        }
    }
    /**
     * 查询居民信息
     *
     * @param patient 患者
     * @return
     */
    @GetMapping(value = "/patient")
    @ApiOperation("查询居民信息")
    public Envelop getPatient(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return failed( "居民不能为空");
            }
            JSONObject p = rehabilitationPlanService.getPatient(patient,getUID());
            return success( "查询成功",  p);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "居民不能为空");
        }
    }
    @RequestMapping(value = "/findTemplateDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取康复服务套餐模板明细")
    public Envelop findTemplateDetail(@ApiParam(name = "templateId", value = "模板id")
                                     @RequestParam(required = true)String templateId){
        try {
            return success( "获取成功", rehabilitationPlanService.findTemplateDetailInfo(templateId));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @ApiOperation("获取门诊记录/住院记录(基卫+APP)")
    @RequestMapping(value = "/event", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Envelop getAllEvent(@ApiParam(name = "patient", value = "患者代码", defaultValue = "")
                              @RequestParam(value = "patient", required = false) String patient,
                              @ApiParam(name = "type", value = "类型", defaultValue = "")
                              @RequestParam(value = "type", required = false) String type,
                              @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,
                              @ApiParam(name = "lastTime", value = "最后一条时间", defaultValue = "2010-10-10 00:00:00")
                              @RequestParam(value = "lastTime", required = false) String lastTime) {
        try {
            if(demoFlag){
                String res;
                switch (type){
                    case "1":
                    case "2":
                        res = patientRecordService.getJosnFileResullt("event"+type);
                        break;
                    default:
                        return success("获取成功");
                }
                return success(res);
            }else {
                List<Map<String, String>> result = patientRecordService.getAllEvent(patient, type, page, pageSize, lastTime);
                return success("获取就诊记录成功!", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().indexOf("卡号尚未在医疗机构注册过") > 0) {
                return failed("对不起,您的社保卡有变更,请改天再试");
            } else if (e.getMessage().startsWith("error")) {
                return failed( e.getMessage());
            } else {
                return failed("获取门/急诊数据失败!");
            }
        }
    }
}

+ 48 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/message/DoctorMessageController.java

@ -0,0 +1,48 @@
package com.yihu.rehabilitation.controller.message;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.rehabilitation.service.message.RehabilitationMessageService;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/doctor/message",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,method = {RequestMethod.GET,RequestMethod.POST})
@Api(description = "医生端-消息")
public class DoctorMessageController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationMessageService messageService;
    /**
     * 设置待办消息已处理
     *
     * @param id
     * @param type
     * @return
     */
    @RequestMapping(value = "setSpecialistOver",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("设置待办消息已处理" )
    public Envelop setSpecialistOver(@ApiParam(name = "id",value = "消息id")
                                    @RequestParam(value = "id")String  id,
                                     @ApiParam(name = "type",value = "消息类型")
                                    @RequestParam(value = "type")Integer type) {
        try {
            return success( "获取消息总数成功!",  messageService.setSpecialistOver(id,type));
        } catch (Exception e) {
          e.printStackTrace();
            return failed( e.getMessage());
        }
    }
}

+ 265 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/patient/PatientRehabilitationManageController.java

@ -0,0 +1,265 @@
package com.yihu.rehabilitation.controller.patient;
/**
 * Created by 刘文彬 on 2018/8/31.
 */
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.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.rehabilitation.service.RehabilitationManageService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
 * Created by 刘文彬 on 2018/8/30.
 */
@RestController
@RequestMapping(value =  RehabilitationRequestMapping.PatientRehabilitationManage.Perfix, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "居民端-康复管理")
public class PatientRehabilitationManageController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private ImUtil imUtill;
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.patientRehabilitationDetail, method = RequestMethod.GET)
    @ApiOperation("康复管理-微信端-居民详情页")
    public ObjEnvelop patientRehabilitationDetail(){
        try {
            return  rehabilitationManageService.patientRehabilitationDetail(getUID());
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.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 (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.serviceDoctorList, method = RequestMethod.GET)
    @ApiOperation("康复管理-微信端居民服务医生列表")
    public ObjEnvelop serviceDoctorList(){
        try {
            return rehabilitationManageService.serviceDoctorList(getUID());
        } catch (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.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 (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.sendMessageIm, method = RequestMethod.POST)
    @ApiOperation("康复管理-扫描二维码发送消息")
    public Envelop 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);
            return success("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failed("发送失败");
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.checkAfterQrCode, method = RequestMethod.POST)
    @ApiOperation("康复管理-居民扫码后验证是否是关联的居民扫码")
    public ObjEnvelop 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 {
            return ObjEnvelop.getSuccess( "操作成功",rehabilitationPlanService.checkAfterQrCode(planDetailId,patientCode));
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.saveRehabilitationOperateRecord, method = RequestMethod.POST)
    @ApiOperation("康复管理-新增operateRecord")
    public MixEnvelop 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 {
            JSONObject json = new JSONObject(dataJson);
            if(json.has("patientCode")){
                BasePatientDO patient = basePatientDao.findById(json.get("patientCode")+"");
                json.put("patientName",patient!=null?patient.getName():"");
            }
            if(json.has("doctorCode")){
                BaseDoctorDO doctor = baseDoctorDao.findById(json.get("doctorCode")+"");
                json.put("doctorName",doctor!=null?doctor.getName():"");
            }
            RehabilitationOperateRecordsDO rehabilitationOperateRecordsDO= toEntity(json.toString(), RehabilitationOperateRecordsDO.class);
            rehabilitationPlanService.saveRehabilitationRecord(rehabilitationOperateRecordsDO);
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationPlanService.saveRehabilitationRecord(rehabilitationOperateRecordsDO));
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.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 (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.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 (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.serviceItem, method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目确认详情页")
    public ObjEnvelop serviceItem(@ApiParam(name = "planDetailId", value = "康复计划服务项目id", required = true)
                              @RequestParam(value = "planDetailId", required = true)String planDetailId){
        try {
            return rehabilitationManageService.serviceItem(planDetailId,null,"");
        } catch (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.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 = getUID();
            }
            return rehabilitationManageService.planSchedule(planId,patientCode);
        } catch (Exception e) {
           e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value =RehabilitationRequestMapping.PatientRehabilitationManage.updatePatientImgById, method = RequestMethod.POST)
    @ApiOperation("更新康复计划居民签名照/证件照")
    public Envelop 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 success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @GetMapping(value = RehabilitationRequestMapping.PatientRehabilitationManage.getServiceItemsAfterStop)
    @ApiOperation(value = "康复管理-中止康复计划结算项目清单")
    public ObjEnvelop getServiceItemsAfterStop(@ApiParam(name = "planId", value = "康复计划id", required = true)
                                               @RequestParam(value = "planId", required = true)String planId){
        try {
            return rehabilitationManageService.getServiceItemsAfterStop(planId);
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
}

+ 21 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/FrequencyDao.java

@ -0,0 +1,21 @@
package com.yihu.rehabilitation.dao;
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);
}

+ 18 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientEventDao.java

@ -0,0 +1,18 @@
package com.yihu.rehabilitation.dao;
import com.yihu.jw.entity.patient.PatientEvent;
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 PatientEventDao extends PagingAndSortingRepository<PatientEvent, String>, JpaSpecificationExecutor<PatientEvent> {
      @Query("select a from PatientEvent a where a.patient = ?1 order by a.eventDate desc")
      List<PatientEvent> findByPatient(String patient) throws Exception;
      @Query("select a from PatientEvent a where a.patient = ?1 and a.eventType = ?2 order by a.eventDate desc")
      List<PatientEvent> findByPatientAndEventType(String patient, String type) throws Exception;
}

+ 19 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientMedicalRecordsRehabilitationDao.java

@ -0,0 +1,19 @@
package com.yihu.rehabilitation.dao;
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);
    
    
}

+ 58 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientRehabilitationPlanDao.java

@ -0,0 +1,58 @@
package com.yihu.rehabilitation.dao;
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, Long>,JpaSpecificationExecutor<PatientRehabilitationPlanDO> {
    PatientRehabilitationPlanDO findById(String id);
    @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);
}

+ 20 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationAdviceDao.java

@ -0,0 +1,20 @@
package com.yihu.rehabilitation.dao;
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);
}

+ 94 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationDetailDao.java

@ -0,0 +1,94 @@
package com.yihu.rehabilitation.dao;
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.planId=?1")
    List<RehabilitationDetailDO> findByPlanId(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);
}

+ 15 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationGuidanceDao.java

@ -0,0 +1,15 @@
package com.yihu.rehabilitation.dao;
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, Integer>, JpaSpecificationExecutor<RehabilitationguidanceDO> {
    @Query("select p from RehabilitationguidanceDO p where p.code = ?1 and p.del=1")
    RehabilitationguidanceDO findByCode(String code);
//    Page<RehabilitationguidanceDO> findByCondition(String sql,PageRequest page);
}

+ 17 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationGuidancePatientDao.java

@ -0,0 +1,17 @@
package com.yihu.rehabilitation.dao;
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, Integer>, 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);
}

+ 19 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationPlanTemplateDao.java

@ -0,0 +1,19 @@
package com.yihu.rehabilitation.dao;
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);
}

+ 16 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationServiceItemDao.java

@ -0,0 +1,16 @@
package com.yihu.rehabilitation.dao;
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();
}

+ 18 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationTemplateDetailDao.java

@ -0,0 +1,18 @@
package com.yihu.rehabilitation.dao;
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);
}

+ 461 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/SignFamilyDao.java

@ -0,0 +1,461 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.rehabilitation.dao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
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;
public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Long>, JpaSpecificationExecutor<SignFamily> {
    /*@Query("select count(a.id) from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
    int hasSingStatus(String idcard);
    @Modifying
    @Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1")
    int updatePatientMobile(String patient, String mobile);
    //更新有效签约患者手机号
    @Modifying
    @Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1 and a.status > 0 ")
    int updateSignMobile(String patient, String mobile);
    @Query("select a from SignFamily a where a.idcard = ?1 and status = ?2 and a.type = 2")
    SignFamily findByPatientStatus(String idcard, int status);
    @Query("select a from SignFamily a where a.patient = ?1 and status = ?2 and a.type = 2")
    SignFamily findByPatientCodeStatus(String patient, int status);
    @Query("select a from SignFamily a where a.patient = ?1 and status >= ?2 and a.type = 2")
    SignFamily findByPatientCodeStatus2(String patient, int status);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status >= 1")
    SignFamily findByPatientAndType(String patient, int type);
    SignFamily findByFamilyCode(String familyCode);
    SignFamily findByTeamCode(String TeamCode);
    @Query("select a from SignFamily a where a.teamCode = ?1 and a.type = 2 and a.code=?2")
    List<SignFamily> findByTeamCodeIsValid(String teamCode, String code);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.type = 2 and a.status >= 0")
    SignFamily findByDoctorPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and (a.type = 2 or a.type=1) and a.status >= 0")
    List<SignFamily> findSSandFamilyByDoctorPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.doctorHealth = ?1 and a.patient = ?2 and a.type = 2 and a.status >= 0 ")
    SignFamily findByDoctorHealthPatient(String doctor, String patient);
    @Query("select p from BasePatientDO p,SignFamily a where a.doctorHealth = ?1  and a.adminTeamId=?2 and a.patient =p.id and a.type = 2 and a.status >= 0")
    List<BasePatientDO> findByDoctorHealthPatient(String doctor, Long team);
    @Query("select p from BasePatientDO p,SignFamily a where (a.doctorHealth = ?1 or a.doctor=?2 ) and a.patient =p.id and a.type = 2 and a.status >= 0")
    List<BasePatientDO> findByDoctorOrDoctorHealthPatient(String doctorHealth, String doctor);
    @Query("select p from BasePatientDO p,SignFamily a where a.doctor = ?1 and a.adminTeamId=?2 and a.patient =p.id and a.type = 2 and a.status >= 0")
    List<BasePatientDO> findByDoctorPatient(String doctor, Long team);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.type = 1 and a.status > 0")
    SignFamily findSsSignByDoctorPatient(String doctor, String patient);
    *//*@Query("select a from SignFamily a,DoctorTeamMember w where a.teamCode = w.team and w.del = '1' and w.memberCode = ?1 and a.patient = ?2 and a.status > 0")
    List<SignFamily> findByDoctorAndPatient(String doctor, String patient);*//*
    @Query(value = "select a from SignFamily a where a.doctor =?1 and a.patient = ?2 and a.status =0 and a.signYear =?3")
    List<SignFamily> findByDoctorAndPatientOverDue(String doctor, String patient, String signYear);
    @Query(value = "select a from SignFamily a where a.doctorHealth =?1 and a.patient = ?2 and a.status =0 and a.signYear =?3")
    List<SignFamily> findByDoctorHealthAndPatient(String doctorHealth, String patient, String signYear);
    @Query(value = "select a from SignFamily a where a.doctor =?1 and a.patient = ?2 and a.signYear =?3 and a.status = 1 and a.expensesStatus ='1'")
    List<SignFamily> findByDoctorAndPatientIsValid(String doctor, String patient, String signYear);
    @Query(value = "select a from SignFamily a where a.doctorHealth =?1 and a.patient = ?2 and a.signYear =?3 and a.status = 1 and a.expensesStatus ='1'")
    List<SignFamily> findByDoctorHealthAndPatientIsValid(String doctorHealth, String patient, String signYear);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.status = 1 and a.type = 2")
    SignFamily findByFamilyDoctorAndPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.patient = ?2 and a.status = 1 and a.type = 1")
    SignFamily findBySanshiDoctorAndPatient(String doctor, String patient);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.openid = ?2 and a.type = 2 and a.status >= 0")
    SignFamily findByDoctorOpenid(String doctor, String openid);
    @Query("select a from SignFamily a where a.doctor = ?1 and a.idcard = ?2 and a.type = 2 and a.status >= 0")
    SignFamily findByDoctorIdcard(String doctor, String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByIdcard(String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status > 0 and a.expensesStatus ='1'")
    SignFamily getExpensesSignByIdcard(String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type =1 and a.status >= 0")
    SignFamily findSSByIdcard(String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 ")
    List<SignFamily> findAllByIdcard(String idcard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.status >= 0")
    List<SignFamily> findSSandJTByIdcard(String idcard);
    @Query("select a from SignFamily a where a.openid = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByOpenid(String openid);
    // 取消签约申请
    @Modifying
    @Query("update SignFamily a set a.status = -1 where a.patient = ?1 and a.doctor = ?2 and a.type = 2 and a.status = 0")
    void unsignByPatient(String patient, String doctor);
    // 取消签约申请
    @Modifying
    @Query("update SignFamily a set a.status = -1 where a.openid = ?1 and a.doctor = ?2 and a.type = 2 and a.status = 0")
    void unsignByOpenid(String openid, String doctor);
    // 查询医生的签约数量
    @Query("select count(a.id) from SignFamily a where a.doctor = ?1")
    int countByDoctor(String doctor);
    // 查询医生的签约数量
    @Query("select count(a.id) from SignFamily a")
    int countByDoctor();
    // 更新状态为待解约
    @Modifying
    @Query("update SignFamily a set a.status = 2 where a.patient = ?1 and a.doctor = ?2 and a.status = 1 and a.type = 2")
    int surrender(String patient, String doctor);
    // 更新待签约状态为拒绝或同意状态
    @Modifying
    @Query("update SignFamily a set a.status = ?1 where a.patient = ?2 and a.status = 0 and a.type = 2")
    int handleSign(int status, String patient);
    // 更新已签约状态为解约
    @Modifying
    @Query("update SignFamily a set a.status = -3, a.reason = ?1 where a.patient = ?2 and a.status = 2 and a.type = 2")
    int handleSurrender(String reason, String patient);
    // 拒绝解约
    @Modifying
    @Query("update SignFamily a set a.status = 1 where a.patient = ?1 and a.status = 2 and a.type = 2")
    int refuseSurrender(String patient);
    // 查询患者已生效的家庭签约
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status > 0")
    SignFamily findSignByPatient(String patient);
    @Modifying
    @Query("update SignFamily a set a.openid = ?1 where patient = ?2")
    int updateOpenidByPatient(String openid, String patient);
    // 查询已签约的总数
    @Query("select count(a.id) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and (a.status = 1 or a.status = 2) and a.type = 2")
    int countAmountSignedByDoctor(String doctor);
    // 查询待签约总数
    @Query("select count(a.id) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and a.status = 0 and a.type = 2")
    int countAmountUnsignByDoctor(String doctor);
    // 查询团队中的健康管理师 sf.doctorHealth,sf.doctorHealthName,
    //select sf.doctorHealth,sf.doctorHealthName,count(*) totalContract from SignFamily sf where sf.healthDoctor = ?1
    @Query("select sf.doctorHealth,sf.doctorHealthName,count(sf)  from SignFamily sf where sf.doctorHealth = ?1")
    List<Object> findTeamHealthDoctors(String healthDoctor);
    // 查询团队中的全科医生 sf.doctor,sf.doctorName,d.hosptialName,
    //select sf.doctor,sf.doctorName,d.hosptialName,count(*) totalContract from SignFamily sf left join Doctor d on sf.doctor = d.code where sf.doctor = ?1
    @Query("select sf.doctor,sf.doctorName,d.hospitalName,count(sf) from SignFamily sf, Doctor d  where ( sf.doctor is null or sf.doctor = d.code) and sf.doctor = ?1")
    List<Object> findTeamQkDoctors(String doctor);
    // 待签约 待解决 已签约
    @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,Patient b,DoctorTeam t,DoctorTeamMember td where a.patient=b.code and a.teamCode=t.code and t.code=td.team and td.memberCode=?1 and td.type=?2 and a.status=?3 order by a.begin desc")
    Page<Object> findToBeSignSignWebByDoctor(String doctor, int doctorType, int status, Pageable pageRequest);
    *//**
     * 查询全科医生签约患者
     *
     * @param doctor
     * @param status
     * @param pageRequest
     * @return
     *//*
    @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,Patient b where a.patient=b.code and a.doctor = ?1 and a.status=?2 order by a.begin desc")
    Page<Object> findSignedPatientByQkDoctor(String doctor, int status, Pageable pageRequest);
    *//**
     * 查询健康管理师签约患者
     *
     * @param doctor
     * @param status
     * @param pageRequest
     * @return
     *//*
    @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,Patient b where a.patient=b.code and a.doctorHealth = ?1 and a.status=?2 order by a.begin desc")
    Page<Object> findSignedPatientByJkDoctor(String doctor, int status, Pageable pageRequest);
    *//**
     * 查询全科医生已解约患者
     *
     * @param doctor
     * @param pageRequest
     * @return
     *//*
    @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,Patient b where a.patient=b.code and a.doctor = ?1 and (a.status=-3 or a.status=-4) order by a.begin desc")
    Page<Object> findUnSignedPatientByQkDoctor(String doctor, Pageable pageRequest);
    *//**
     * 查询健康管理师已解约患者
     *
     * @param doctor
     * @param pageRequest
     * @return
     *//*
    @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,Patient b where a.patient=b.code and a.doctorHealth = ?1 and (a.status=-3 or a.status=-4) order by a.begin desc")
    Page<Object> findUnSignedPatientByJkDoctor(String doctor, Pageable pageRequest);
    //已经解约
   *//* @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,Patient b,DoctorTeam t,DoctorTeamMember td where a.patient=b.code and a.teamCode=t.code and t.code=td.team and td.memberCode=?1 and td.type=?2 and(a.status=-3 or a.status=-4 ) order by a.begin desc")
    Page<Object> findToBeSignSignWebByDoctor_34(String doctor, int doctorType, Pageable pageRequest);*//*
    @Query("select a from SignFamily a where a.mobile = ?1 and a.type = 2 and a.status >= 0")
    SignFamily findByMobile(String mobile);
    @Query("select a.code,a.doctor,b.code,b.name,b.provinceName,b.cityName,b.townName,b.address,b.photo,a.status,a.id,a.applyDate,a.reason,b.streetName,b.sex from SignFamily a,BasePaitentDO b where a.patient=b.id and a.doctor=?1 and a.status=?2 order by a.begin desc")
    Page<Object> findToBeSignSignWebByDoctor_0(String doctor, int i, Pageable pageRequest);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status >= 1")
    SignFamily findBySanshiPatient(String code);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status >= 0")
    SignFamily findBySsPatient(String code);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 1")
    SignFamily findByjiatingPatient(String code);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status = 1")
    SignFamily findByjiatingPatientYes(String code);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =1 and a.status = 1")
    SignFamily findBySanshiPatientYes(String id);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status in (0,1,2,3)")
    SignFamily findByPatientSanshiSignInfo(String idCard);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status in (0,1,2,3)")
    SignFamily findByPatientFamilySignInfo(String idCard);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >=0")
    SignFamily findByjiatingPatientStatus0(String patient);
    //查找昨天的家庭签约数据
    @Query(" from SignFamily a where  a.type =2 and a.status = 1  and unix_timestamp(a.applyDate)>=unix_timestamp(?1) and unix_timestamp(a.applyDate)<unix_timestamp(?2) and a.expensesStatus=1 ")
    List<SignFamily> findByJiatingSignYesterdayExpensesStatus(String yesterday, String today);
    //查找昨天的家庭签约数据
    @Query(" from SignFamily a where  a.type =2 and a.status >= 1  and  unix_timestamp(a.applyDate)<=unix_timestamp(?1) and a.expensesStatus=1 ")
    List<SignFamily> findByJiatingSignYesterdayExpensesStatus(String yesterday);
    //查找昨天的家庭签约数据
    @Query(" from SignFamily a where  a.type =2 and a.status >= 1  and  unix_timestamp(a.applyDate)<=unix_timestamp(?1) ")
    List<SignFamily> findByJiatingSignYesterday(String yesterday);
    //查找昨天的家庭解约数据
    @Query(" from SignFamily a where  a.type =2 and a.status in (-3,-4) and unix_timestamp(a.applyUnsignDate)>=unix_timestamp(?1) and unix_timestamp(a.applyUnsignDate)<unix_timestamp(?2) and a.expensesStatus=1")
    List<SignFamily> findByJiatingUnSignYesterdayExpensesStatus(String yesterday, String today);
    //查找昨天的家庭待数据
    @Query(" from SignFamily a where  a.type =2 and a.status =0  and unix_timestamp(a.patientApplyDate)>=unix_timestamp(?1) and unix_timestamp(a.patientApplyDate)<unix_timestamp(?2)")
    List<SignFamily> findByJiatingWaitSignYesterdayExpensesStatus(String yesterday, String today);
    //查找昨天的家庭待改签
    @Query(" from SignFamily a where  a.type =2 and a.status =100  and unix_timestamp(a.patientApplyDate)>=unix_timestamp(?1) and unix_timestamp(a.patientApplyDate)<unix_timestamp(?2) and a.expensesStatus=1 ")
    List<SignFamily> findByJiatingChaangeSignYesterdayExpensesStatus(String yesterday, String now);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 1 and a.status in (0,1,2)")
    SignFamily findSanshiSignByPatient(String patientCode);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status in (0,1,2)")
    SignFamily findFamilySignByPatient(String patientCode);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status =-4 and a.signYear =?2")
    SignFamily findFamilySignByPatientOverDue(String patientCode, String signYear);
    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard from SignFamily a,BasePaitentDO p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = p.id and a.status in (1,2,3)")
    List<Object> findDoctorSignPatients(String doctor);
    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,BasePaitentDO p where (a.doctor = ?1 or a.doctorHealth = ?1) and p.name like ?2 and a.patient = p.id and a.status in (1,2,3)")
    List<Object> findDoctorSignPatientsLikeName(String doctor, String name);
    @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,BasePaitentDO p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and a.patient = p.id and a.status in (1,2,3)")
    List<Object> findDoctorSignPatientsBySignType(String doctor, int type);*/
   /* @Query("select p.code, p.name, p.photo, p.birthday, p.sex, p.diseaseCondition, p.disease, p.recordAmount,a.type,a.applyDate,p.idcard  from SignFamily a,BasePaitentDO p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and p.name like ?3 and a.patient = p.id and a.status in (1,2,3)")
    List<Object> findDoctorSignPatientsByTypeName(String doctor, int type, String name);*/
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 0")
    SignFamily findByPatient(String patient);
    /*@Query("select a from SignFamily a where a.teamCode = ?1 and a.type =2 and a.status >= 0")
    SignFamily findByTeam(String teamCode);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.status >= 0")
    List<SignFamily> findByPatients(String patient);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type =2 and a.signYear =?2 and a.status in (-4,1,2,3) order by a.id desc ")
    List<SignFamily> findByPatientsLastYear(String patient, String signYear);
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status >= 0")
    SignFamily findBySanshiIdcard(String idcard);
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = ?2 and a.status > 0")
    SignFamily findSignByPatient(String patient, int type);
    SignFamily findByCode(String code);
    @Query(" from SignFamily a where a.patient = ?1 and a.type = ?2 and (a.status=-3 or a.status=-4)  order by a.id desc")
    List<SignFamily> findLastJySignByPatient(String patient, int type);
    @Query(" from SignFamily a where  a.type =1 and unix_timestamp(a.czrq)=unix_timestamp( ?1 )  ")
    List<SignFamily> findByDate(String s);
    @Modifying
    @Query("update SignFamily set expenses_type = ?1 where patient = ?2 and status > 0 and type = 2")
    int updateExpensesType(String expensesType, String patient);
    @Query("select count(*) from SignFamily where patient = ?1 and status > 0 and type = 1")
    int countPatientSsSign(String patient);
    @Query("select count(*) from SignFamily where patient = ?1 and status > 0 and type = 2")
    int countPatientJtSign(String patient);
    // 查询患者已生效的家庭签约
    @Query("select a from SignFamily a where a.patient = ?1 and a.type = 2 and a.status = 0")
    SignFamily findSigningByPatient(String patient);
    //找出家庭签约中 团队是空的值
    @Query("select a from SignFamily a where a.type = 2 and a.status = 1 and a.adminTeamId is null")
    List<SignFamily> findBySignTypeAndTeamCode();
    //找出没有健康管理师的签约数据
    @Query("select a from SignFamily a where a.type = 2 and a.status >= 1 and a.doctorHealth is null and a.adminTeamId = ?1 order by a.czrq desc")
    List<SignFamily> findNoHealthSignFamilyNum(Long teamCode);
    //找出没有健康管理师的签约数据
    @Query("select a from SignFamily a where a.type = 2 and a.status >= 1 and a.doctorHealth is null and a.doctor=?1 order by a.czrq desc")
    Page<SignFamily> findNoHealthSignFamilyHealth(String doctor, Pageable pageRequest);
    @Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 order by a.id")
    Page<SignFamily> findByTypeAndSignSource(Integer type, String signSource, Pageable pageable);
    @Query("select a from SignFamily a where a.type = ?1 and a.signSource = ?2 and a.status > 0 and a.id >= ?3 and a.id <= ?4 order by a.id")
    Page<SignFamily> findByTypeAndSignSourceAndId(Integer type, String signSource, Long start, Long end, Pageable pageable);
    @Query("select a from SignFamily a where a.patient = ?1 and a.status >= 0")
    List<SignFamily> findAllSignByPatient(String patient);
    *//**
     * 获取所有有效的签约信息(不包含-1 -2)
     *
     * @param patient
     * @return
     *//*
    @Query("select a from SignFamily a where a.patient = ?1 and a.status <> -1 and a.status <> -2 order by a.czrq")
    List<SignFamily> findAllActiveSignByPatient(String patient);
    @Query("select a.patient from SignFamily a where a.doctor = ?1 and a.type = 2 and a.status > 0 and a.doctorHealth is null")
    List<String> findNohealthByDoctor(String doctor);
    *//**
     * 获取团队中有效的患者
     *
     * @param teamCode
     * @param status
     * @return
     *//*
    @Query("select count(f) from SignFamily f where f.adminTeamId = ?1 and f.status >= ?2 ")
    int findByAdminTeamIdAndStatus(long teamCode, int status);
    @Query("select f from SignFamily f where f.patient = ?1 and f.adminTeamId = ?2 and f.status > 0 and f.type = ?3")
    SignFamily findByPatientAndAdminTeamId(String patient, Long teamCode, Integer type);
    //根据医生和居民判断是否存在签约关系(全科及健管)
    @Query("select count(1) from SignFamily f where f.status > 0 and f.patient = ?1 and ( f.doctor = ?2 or doctorHealth = ?2  )")
    int findByPatientAndDoctor(String patient, String doctor);
    @Query(value = "select a from SignFamily a where a.patient = ?1 and a.signYear =?2 and a.status >= 0")
    List<SignFamily> findByDoctorAndPatientHossPost(String patient, String signYear);
    @Query(value = " select a.*  from wlyy_sign_family a where a.patient = ?1  and a.status = -4 order by a.apply_date desc limit 0,1", nativeQuery = true)
    SignFamily findOutTimeSigningByPatient(String patient);
    @Query(value = " select a.*  from wlyy_sign_family a where a.patient = ?1  and a.status = -4 and a.team_code = ?2 order by a.apply_date desc limit 0,1", nativeQuery = true)
    SignFamily findOutTimeSigningByPatientAndTeamCode(String patient, String teamCode);
    //      完成缴费后更新签约开始时间begin 缴费状态expensesStatus 医保流水号medical_insurance_num  扣费时间expenses_time
    @Modifying
    @Query("update SignFamily a set a.begin = ?2 ,a.medicalInsuranceNum=?3,a.expensesStatus = ?4,a.expensesTime = ?2,a.signPaySource = ?5 where a.code = ?1 ")
    int updatePatientBegin(String code, Date begin, String medicalInsuranceNum, String expensesStatus, int signPaySource);
    //查询居民的扣费状态
    @Query(" select a from SignFamily a where a.patient = ?1 ")
    SignFamily findPatientExpensesStatus(String patient);
    // 查询团队已签约的总数
    @Query("select count(1) from SignFamily a where  a.adminTeamId = ?1 and (a.status = 1 or a.status = 2) and a.type = 2")
    int countAmountSignedByAdminTeam(Long id);
    // 查询已签约未缴费居民
    @Query("select a from SignFamily a where  a.patient = ?1 and a.type = 2 and a.expensesStatus = '0' and a.status >0")
    SignFamily findUnpay(String patient);
    //根据身份证号码查询该人的签约情况
    @Query("select count(1) from SignFamily a where a.idcard=?1 and a.status>0 and a.type=2")
    int hasSignCount(String idcard);
    //根据patient查找有效签约的hospital
    @Query("select a.hospital from SignFamily a where a.patient = ?1 and a.status = 1 and a.expensesStatus = '1'")
    String getHospital(String patient);
    //查看团队内医生签约人数
    @Query("select count(1) from SignFamily a where a.status > 0 and a.adminTeamId = ?1 and (a.doctor = ?2 or a.doctorHealth = ?2)")
    int countByAdminTeamId(Long adminTeamId, String doctor);
    //根据居民和医生找出居民签约团队
    @Query("select f from SignFamily f where f.status > 0 and f.patient = ?1 and ( f.doctor = ?2 or doctorHealth = ?2  )")
    SignFamily findSignFamilyByPatientAndDoctor(String patient, String doctor);*/
    //根据居民获取有效的签约
    List<SignFamily> findByPatientAndExpensesStatusAndStatus(String patient, String expensesStatus, Integer status);
    /*//根据居民找出居民签约团队
    @Query("select a from SignFamily a where a.patient = ?1 and a.status = 1 and a.expensesStatus = '1'")
    SignFamily findSignFamilyByPatient(String patient);
    //根据居民查出有效签约
    @Query("select a from SignFamily a where a.patient = ?1 and a.status > 0 order by czrq desc")
    List<SignFamily> getSignFamilyByPatient(String patient);
    @Query("select count(distinct a.patient) from SignFamily a where  a.status = 1 and a.expensesStatus = '1'")
    int allCountSignNum();
    @Modifying
    @Query("update SignFamily p set p.ssc = ?1 where p.idcard = ?2 and p.status=1")
    int updateSscByIdCard(String ssc, String idCard);
    //根据年份,社区查出有效签约居民
    @Query("select a from SignFamily a where a.signYear = ?1 and a.status = 1 and a.hospital = ?2")
    List<SignFamily> getSignFamilyBySignYearAndStatusAndHospital(String signyear, String hospital);*/
}

+ 25 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/SpecialDiseaseMessagesDao.java

@ -0,0 +1,25 @@
package com.yihu.wlyy.repository.specialist;
import com.yihu.wlyy.entity.message.WlyyDynamicMessages;
import com.yihu.wlyy.entity.specialist.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);
}

+ 315 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/PatientRecordService.java

@ -0,0 +1,315 @@
package com.yihu.rehabilitation.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.patient.PatientEvent;
import com.yihu.jw.entity.util.SystemConf;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.security.MD5;
import com.yihu.rehabilitation.dao.PatientEventDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
 * Created by hzp on 2016/11/24.
 * 市民健康档案服务
 */
@Service
public class PatientRecordService {
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private BaseOrgDao hospitalDao;
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private ZsRehabilitationInfoService zsRehabilitationInfoService;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private PatientEventDao patientEventDao;
    @Value("${sign.check_upload}")
    private String jwUrl;
    /**
     * 获取本地示例返参
     *
     * @param fid 服务id
     * @return
     * @throws Exception
     */
    public String getJosnFileResullt(String fid) throws Exception {
        String contentStr = null;
        Resource resource = new ClassPathResource("mqConfig/mqdata/" + fid + ".json");
        if (resource.exists()) {
            InputStream is = resource.getInputStream();
            contentStr = new BufferedReader(new InputStreamReader(is, "utf-8"))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
//            contentStr =  replaceSpecialStr(contentStr);
        } else {
            throw new Exception("文件不存在");
        }
        return contentStr;
    }
    /******************************************************************************************************************/
    /**
     * 新的住院记录接口
     * @param patientCode
     * @param type
     * @param page
     * @param pageSize
     * @param lastTime
     * @param hospital
     * @return
     * @throws Exception
     */
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public List<Map<String, String>> getAllEvent_new(String patientCode, String type, String page, String pageSize, String lastTime,String hospital) throws Exception {
        //获取患者
        BasePatientDO patient = patientDao.findById(patientCode);
        BaseOrgDO hos = hospitalDao.findByCode(hospital);
        //如果是中山医院,优先查找中山医院的接口
        if("922b8fa9-5aff-11e6-8344-fa163e8aee56".equals(hospital)){
            List<Map<String, String>> map = zsRehabilitationInfoService.zsHospitalRecord(patient,hos,page,pageSize);
            if(map.size()>0){
                return map;
            }
        }
        //获取基卫数据--
        List hlsit = new ArrayList();
        hlsit.add("922b91b8-5aff-11e6-8344-fa163e8aee56");//厦门市中医院
        hlsit.add("0a0b4ec0-5b04-11e6-8344-fa163e8aee56");//厦门大学附属第一医院
        hlsit.add("97fbc7707643471b8458-6def1ff92496");//厦门大学附属心血管病医院
        hlsit.add("0a11148d-5b04-11e6-8344-fa163e8aee56");//厦门市海沧医院
        hlsit.add("8d94ce907e4d4356b68f6c5d4d0d6bc9");//厦门市妇幼保健院
        hlsit.add("922b8fa9-5aff-11e6-8344-fa163e8aee56");//厦门大学附属中山医院
        if(hlsit.contains(hospital)){
            List<Map<String, String>> map = rehabilitationInfoService.getEmrList(patient.getIdcard(),null,null,Integer.parseInt(page),Integer.parseInt(pageSize));
            if(map.size()>0){
                return map;
            }
        }
        return new ArrayList<>();
    }
    /**
     * 获取门/急诊记录 + 住院记录
     */
    public List<Map<String, String>> getAllEvent(String patientCode, String type, String page, String pageSize, String lastTime) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        //获取患者
        BasePatientDO patient = patientDao.findById(patientCode);
        //获取基卫数据
        String response = getResidentEventListJson(patient.getSsc(), type, page, pageSize);
        //获取app数据
        List<PatientEvent> eventList = new ArrayList<>();
        if (StringUtils.isEmpty(type)) {
            eventList = patientEventDao.findByPatient(patientCode);
        } else {
            eventList = patientEventDao.findByPatientAndEventType(patientCode, type);
        }
        if (!StringUtils.isEmpty(response)) {
            JSONArray array = new JSONArray(response);
            String max = "";
            String min = "";
            if (!"[{}]".equals(response)) {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject item = array.getJSONObject(i);
                    if (i == 0) //最大值
                    {
                        max = item.optString("END_TIME");
                    } else if (i == array.length() - 1) //最小值
                    {
                        min = item.optString("END_TIME");
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.optString("EVENT"));
                    map.put("patient", patientCode);
                    map.put("eventDate", item.optString("END_TIME"));
                    map.put("eventType", item.optString("TYPE"));
                    map.put("orgName", item.optString("ORG_NAME"));
                    map.put("orgCode", item.optString("ORG_ID"));
                    map.put("dianosis", item.optString("DIAGNOSIS"));
                    map.put("createTime", item.optString("END_TIME"));
                    map.put("dataFrom", "1");//基卫数据
                    re.add(map);
                }
            }
            //过滤
            for (PatientEvent item : eventList) {
                String eventDate = DateUtil.dateToStrLong(item.getEventDate());
                int maxCompare = eventDate.compareTo(max);
                int minCompare = eventDate.compareTo(min);
                Boolean contain = false;
                if (maxCompare < 0 && minCompare >= 0)       //时间范围内
                {
                    contain = true;
                }
                //第一页特殊处理
                if ("1".equals(page) && maxCompare >= 0) {
                    contain = true;
                }
                //最后一页特殊处理
                if (!"1".equals(page) && (array.length() == 0 || "[{}]".equals(response)) && !StringUtils.isEmpty(lastTime)) {
                    int lastTimeCompare = eventDate.compareTo(lastTime);
                    if (lastTimeCompare < 0) {
                        contain = true;
                    }
                }
                if (contain) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.getId().toString());
                    map.put("patient", item.getPatient());
                    map.put("eventDate", DateUtil.dateToStrLong(item.getEventDate()));
                    map.put("eventType", item.getEventType());
                    map.put("orgName", item.getOrgName());
                    map.put("orgCode", item.getOrgCode());
                    map.put("dianosis", item.getDianosis());
                    map.put("createTime", DateUtil.dateToStrLong(item.getCreateTime()));
                    map.put("dataFrom", "2");   //APP数据
                    re.add(map);
                }
            }
            //排序
            re = sortMapList(re, "eventDate", "DESC");
        } else {
            if ("1".equals(page)) {
                for (PatientEvent item : eventList) {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", item.getId().toString());
                    map.put("patient", item.getPatient());
                    map.put("eventDate", DateUtil.dateToStrLong(item.getEventDate()));
                    map.put("eventType", item.getEventType());
                    map.put("orgName", item.getOrgName());
                    map.put("orgCode", item.getOrgCode());
                    map.put("dianosis", item.getDianosis());
                    map.put("createTime", DateUtil.dateToStrLong(item.getCreateTime()));
                    map.put("dataFrom", "2");   //APP数据
                    re.add(map);
                }
            }
        }
        return re;
    }
    /**
     * 获取门/急诊记录 + 住院记录
     */
    public String getResidentEventListJson(String strSSID,String type,String page,String pageSize)  throws Exception
    {
        if(SystemConf.getInstance().getEhrUsed())     //演示环境
        {
            return "";
        }
        else {
            String re = "";
            String url = jwUrl + "/third/smjk/ResidentEventList";
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("strSSID", strSSID));
            if (!StringUtils.isEmpty(type)) {
                params.add(new BasicNameValuePair("type", type));
            }
            params.add(new BasicNameValuePair("page", page));
            params.add(new BasicNameValuePair("pageSize", pageSize));
            String response = httpClientUtil.post(url, params, "UTF-8");
            if (!StringUtils.isEmpty(response)) {
                JSONObject responseObject = new JSONObject(response);
                int status = responseObject.getInt("status");
                if (status == 200) {
                    String data = responseObject.getString("data");
                    if (!StringUtils.isEmpty(data) && data.startsWith("error")) {
                        throw new Exception(data);
                    } else {
                        JSONObject jsonData = new JSONObject(data);
                        JSONArray jsonArray = jsonData.getJSONArray("EventList");
                        re = jsonArray.toString();
                    }
                } else {
                    throw new Exception(responseObject.getString("msg"));
                }
            } else {
                throw new Exception("null response.");
            }
            if(re.contains("[{}]"))
            {
                re = re.replace("[{}]","[]");
            }
            return re;
        }
    }
    /**
     * 字符串List排序
     */
    public List<Map<String, String>> sortMapList(List<Map<String, String>> mapList, final String sort, final String order) {
        Collections.sort(mapList, new Comparator<Map<String, String>>() {
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                String map1value = o1.get(sort);
                String map2value = o2.get(sort);
                if ("DESC".equals(order.toUpperCase())) {
                    return map2value.compareTo(map1value);
                } else {
                    return map1value.compareTo(map2value);
                }
            }
        });
        return mapList;
    }
}

+ 221 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationGuidanceService.java

@ -0,0 +1,221 @@
package com.yihu.rehabilitation.service;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
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.door.SignFamily;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidanceDO;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidancePatientDO;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.rehabilitation.dao.RehabilitationGuidanceDao;
import com.yihu.rehabilitation.dao.RehabilitationGuidancePatientDao;
import com.yihu.rehabilitation.dao.SignFamilyDao;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
 * Created by wangzhinan on 2018/8/29.
 */
@Service
@Transactional
public class RehabilitationGuidanceService {
    private Logger logger = LoggerFactory.getLogger(RehabilitationGuidanceService.class);
    @Autowired
    private RehabilitationGuidanceDao rehabilitationGuidanceDao;
    @Autowired
    private RehabilitationGuidancePatientDao rehabilitationGuidancePatientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 康复指导类型标题
     * @return
     */
    public List<Map<String,Object>> selectType(String planId){
        String disease="";
        if (StringUtils.isNoneBlank(planId)){
            String sql ="select * from wlyy_patient_rehabilitation_plan where id='"+planId+"' ";
            Map<String,Object> map = jdbcTemplate.queryForMap(sql);
            if (map.get("disease")!=null&&StringUtils.isNoneBlank(map.get("disease").toString())){
                disease = map.get("disease").toString();
            }
        }
        StringBuffer sql = new StringBuffer("select g.type,g.type_name as typeName,COUNT(g.id) as number from wlyy_rehabilitation_guidance g where g.del=1 ");
        if (StringUtils.isNoneBlank(disease)){
            sql.append("and g.type in ( '").append(disease.replace(",","','")).append("') ");
        }
        sql.append("group by g.type");
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql.toString());
        return mapList;
    }
    /**
     * 查询康复指导列表
     *
     * @param type
     * @param code
     * @param page
     * @param pagesize
     * @return
     */
    public Page<RehabilitationguidanceDO> select(String title, Integer type, String code, String planId, Integer page, Integer pagesize){
        String disease="";
        if (StringUtils.isNoneBlank(planId)){
            String sql ="select * from wlyy_patient_rehabilitation_plan where id='"+planId+"' ";
            Map<String,Object> map = jdbcTemplate.queryForMap(sql);
            if (map.get("disease")!=null&&StringUtils.isNoneBlank(map.get("disease").toString())){
                disease = map.get("disease").toString();
            }
        }
        if(page >=1){
            page --;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        StringBuffer sql =  new StringBuffer("select * from wlyy_rehabilitation_guidance where 1=1 and del =1 ");
        StringBuffer sqlCounts =  new StringBuffer("select count(1) from wlyy_rehabilitation_guidance where 1=1 and del =1 ");
        if (StringUtils.isNoneBlank(code)){
            sql.append("and code='"+code+"' ");
            sqlCounts.append("and code='"+code+"' ");
        }
        if (type!=null){
            sql.append("and type='"+type+"' ");
            sqlCounts.append("and type='"+type+"' ");
        }
        if (StringUtils.isNoneBlank(title)){
            sql.append("and title like '%"+title+"%' ");
            sqlCounts.append("and title like '%"+title+"%' ");
        }
        if (StringUtils.isNoneBlank(disease)){
            sql.append("and type in ( '").append(disease.replace(",","','")).append("') ");
            sqlCounts.append("and type in ( '").append(disease.replace(",","','")).append("') ");
        }
        sql.append("order by czrq desc limit "+page*pagesize+","+(page+1)*pagesize);
        List<RehabilitationguidanceDO> list = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper<>(RehabilitationguidanceDO.class));
        Long totalCount = jdbcTemplate.queryForObject(sqlCounts.toString(),Long.class);
        for (RehabilitationguidanceDO temp:list){
            String contents = temp.getContent();
//            System.out.println(contents);
            temp.setContent(StringEscapeUtils.unescapeJava(contents));
//            System.out.println(StringEscapeUtils.unescapeJava(contents));
        }
        PageRequest pageRequest = new PageRequest(page, pagesize);
        if (list.size() <= 0) {
            return new PageImpl(new ArrayList<>(), pageRequest, 0);
        }
        return new PageImpl(list, pageRequest, totalCount);
    }
    /**
     * 发送康复指导
     *
     * @param rehabilitationguidancePatientDOS
     * @return
     */
    public List<RehabilitationguidancePatientDO> sendGuidanceToPatient(List<RehabilitationguidancePatientDO> rehabilitationguidancePatientDOS,String planId) throws Exception {
        for (RehabilitationguidancePatientDO rehabilitationguidancePatientDO:rehabilitationguidancePatientDOS){
            RehabilitationguidanceDO rehabilitationguidanceDO = rehabilitationGuidanceDao.findByCode(rehabilitationguidancePatientDO.getArticle());
            rehabilitationguidanceDO.setUseCount(rehabilitationguidanceDO.getUseCount()+1);
            rehabilitationGuidanceDao.save(rehabilitationguidanceDO);
            BasePatientDO patient = patientDao.findById(rehabilitationguidancePatientDO.getPatient());
            BaseDoctorDO doctor = doctorDao.findById(rehabilitationguidancePatientDO.getDoctor());
            rehabilitationguidancePatientDO.setAttachedTitle(rehabilitationguidanceDO.getTitle());
            if (patient!=null){
                rehabilitationguidancePatientDO.setName(patient.getName());
            }
            if (doctor!=null){
                rehabilitationguidancePatientDO.setDoctorName(doctor.getName());
            }
            rehabilitationguidancePatientDO.setAttachedContent(rehabilitationguidanceDO.getContent());
            rehabilitationguidancePatientDO.setCzrq(new Date());
            rehabilitationguidancePatientDO.setIsRead(0);
            rehabilitationguidancePatientDO.setSendStatus(0);
            rehabilitationguidancePatientDO = rehabilitationGuidancePatientDao.save(rehabilitationguidancePatientDO);
            //this.sendSpecialistWeixinMessage(rehabilitationguidancePatientDO.getPatient(),rehabilitationguidancePatientDO.getDoctor(),1,rehabilitationguidancePatientDO.getArticle(),planId,null);
        }
        return rehabilitationguidancePatientDOS;
    }
    /**
     * 查看发送的康复指导
     * @param patient
     * @param doctor
     * @param relationCode
     * @return
     */
    public List<RehabilitationguidancePatientDO> selectByRelationCode(String patient,String doctor,String relationCode){
        if (StringUtils.isNoneBlank(relationCode)){
            return rehabilitationGuidancePatientDao.findByRelationCode(relationCode);
        }else {
            return rehabilitationGuidancePatientDao.findByPatientAndDoctor(patient,doctor);
        }
    }
    public Page<RehabilitationguidancePatientDO> selectPatientGuidances(String patient,String doctor,String code,Integer page,Integer pagesize){
        if(page >=1){
            page --;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "czrq");
        // 分页信息
        PageRequest pageRequest = new PageRequest(page, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 指定患者
        if (StringUtils.isNoneBlank(code)) {
            filters.put("code", new SearchFilter("code", SearchFilter.Operator.EQ, code));
        }
        if (StringUtils.isNoneBlank(patient)) {
            filters.put("patient", new SearchFilter("patient", SearchFilter.Operator.EQ, patient));
        }
        if (StringUtils.isNoneBlank(doctor)) {
            filters.put("doctor", new SearchFilter("doctor", SearchFilter.Operator.EQ, doctor));
        }
        Specification<RehabilitationguidancePatientDO> spec = DynamicSpecifications.bySearchFilter(filters.values(), RehabilitationguidancePatientDO.class);
        Page<RehabilitationguidancePatientDO> rehabilitationguidancePatientDOS = rehabilitationGuidancePatientDao.findAll(spec,pageRequest);
        for (RehabilitationguidancePatientDO rehabilitationguidancePatientDO:rehabilitationguidancePatientDOS){
            BasePatientDO patient1 = patientDao.findById(rehabilitationguidancePatientDO.getPatient());
            rehabilitationguidancePatientDO.setPhoto(patient1.getPhoto());
        }
        return rehabilitationguidancePatientDOS;
    }
}

File diff suppressed because it is too large
+ 588 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationInfoService.java


+ 3293 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationManageService.java

@ -0,0 +1,3293 @@
package com.yihu.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.*;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.rehabilitation.dao.*;
import com.yihu.rehabilitation.util.HtmlUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by 刘文彬 on 2018/8/16.
 */
@Service
@Transactional
public class RehabilitationManageService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RehabilitationDetailDao rehabilitationDetailDao;
    @Autowired
    private PatientRehabilitationPlanDao patientRehabilitationPlanDao;
    @Autowired
    private GuidanceMessageLogDao guidanceMessageLogDao;
    @Autowired
    private SpecialistPatientRelationDao specialistPatientRelationDao;
    @Autowired
    private RehabilitationOperateRecordsDao rehabilitationOperateRecordsDao;
    @Autowired
    private RehabilitationDetailAppointmentDao rehabilitationDetailAppointmentDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;
    @Autowired
    private BasePatientDao  basePatientDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private SpecialistEvaluateSevice specialistEvaluateSevice;
    @Autowired
    private FrequencyDao frequencyDao;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao medicalRecordsRehabilitationDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private DoctorPatientRelationDao doctorPatientRelationDao;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao patientMedicalRecordsDao;
    @Value("${im.data_base_name}")
    private String imDBName;
    @Value("${neiwang.enable}")
    private Boolean isneiwang;  //如果不是内网项目要转到到内网wlyy在上传
    @Autowired
    private ZsRehabilitationInfoService zsRehabilitationInfoService;
    @Autowired
    private PatientRecordService patientRecordService;
    @Autowired
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${demo.flag}")
    private Boolean demoFlag;
    /**
     * 预约协诊
     * @param doctor
     * @param doctorName
     * @param sendTime
     * @param planDetailId
     */
    public ObjEnvelop appointmentConsultation(String patient,String doctor, String doctorName,
            String appointmentDoctor,String appointmentDoctorName,String sendTime, String planDetailId){
        RehabilitationDetailAppointmentDO appointment = new RehabilitationDetailAppointmentDO();
        appointment.setAppointmentTime(sendTime+":00");
        appointment.setCreateTime(new Date());
        appointment.setDoctor(doctor);
        appointment.setDoctorName(doctorName);
        appointment.setAppointmentDoctor(appointmentDoctor);
        appointment.setAppointmentDoctorName(appointmentDoctorName);
        appointment.setIsSend(0);
        appointment.setRehabilitationPlanDetailId(planDetailId);
        appointment.setPatient(patient);
        rehabilitationDetailAppointmentDao.save(appointment);
        return ObjEnvelop.getSuccess("获取成功",appointment);
    }
    /**
     * 康复管理(专科)-- 计划列表
     * @param doctorCode
     * @param diseaseCode
     * @param planType
     * @param todaybacklog
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    public MixEnvelop<Map<String,Object>, Map<String,Object>> findRehabilitationPlan(String doctorCode, String diseaseCode, Integer planType,Integer todaybacklog, String patientCondition,Integer page, Integer pageSize) throws Exception{
        Integer doctorType =null;
        BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
        List<BaseDoctorRoleDO> baseDoctorRoleDO = baseDoctorRoleDao.findByDoctorCode(doctor.getId());
        for(BaseDoctorRoleDO baseDoctorRoleDO1:baseDoctorRoleDO){
            if ("specialist".equalsIgnoreCase(baseDoctorRoleDO1.getRoleCode())){
                doctorType = 1;
                break;
            }else {
                doctorType = 2;
            }
        }
        String sql = " select DISTINCT p.* " +
                " from wlyy_rehabilitation_plan_detail a INNER JOIN wlyy_patient_rehabilitation_plan p " +
                " on a.plan_id = p.id  " ;
        if(doctorType==2){//家医是根据签约关系过滤
            sql+=" INNER JOIN wlyy_sign_family f ON f.patient = p.patient \n" +
                    "\tand f.expenses_status=1\n" +
                    "\tAND f.STATUS >= 1 \n" +
                    "\tAND ( f.doctor = '"+doctorCode+"' OR f.doctor_health = '"+doctorCode+"' )  ";
        }
        sql += " where 1=1 ";
        if(todaybacklog!=null&&todaybacklog==1){
            String todayStart = DateUtil.getStringDateShort()+" "+"00:00:00";
            String todayEnd = DateUtil.getStringDateShort()+" "+"23:59:59";
            sql += " and a.execute_time>='"+todayStart+"' and a.execute_time<='"+todayEnd+"'";
        }
        if(planType!=null){
            sql += " and p.plan_type="+planType;
        }
        if(StringUtils.isNotEmpty(diseaseCode)){
            sql+=" and p.disease='"+diseaseCode+"'";
        }
        if(StringUtils.isNotEmpty(patientCondition)){//姓名idcard模糊查询
            sql +=" AND EXISTS (select code from base_patient where  `id` = p.patient and ( `name` LIKE '%"+patientCondition+"%' or idcard like '%"+patientCondition+"%') )";
        }
        if (doctorType==1){
            sql +=" AND (p.create_user = '"+doctorCode+"' \n" +
                    "\tOR a.doctor = '"+doctorCode+"' ) ";
        }
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planAll2(sql);
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        int count = 0;
        if(rstotal!=null&&rstotal.size()>0&&rstotal.get(0).get("id")!=null){
            count = rstotal.size();
        }
        sql += " ORDER BY p.create_time DESC LIMIT "+(page-1)*pageSize+","+pageSize;
        System.out.println("sql==="+sql);
        List<Map<String,Object>> patientRehabilitationPlanDOList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> resultList = new ArrayList<>();
        BasePatientDO patient =null;
        if(patientRehabilitationPlanDOList.size()>0&&patientRehabilitationPlanDOList.get(0).get("id")!=null){
            for(Map<String,Object> one:patientRehabilitationPlanDOList){
                Map<String,Object> resultMap = new HashMap<>();
//                Integer age = IdCardUtil.getAgeForIdcard(one.get("idcard")+"");
//                String sex = IdCardUtil.getSexForIdcard_new(one.get("idcard")+"");
//                resultMap.put("age",age);
                resultMap.put("hospitalName",one.get("hospital_name"));
//                resultMap.put("sex","1".equals(sex)?"男":("2".equals(sex)?"女":"未知"));
                resultMap.put("patientName",one.get("patientName"));
                resultMap.put("patientCode",one.get("patient"));
                patient = basePatientDao.findById(one.get("patient").toString());
                if (patient!=null){
                    resultMap.put("photo",patient!=null?patient.getPhoto():"");
                    Integer age = IdCardUtil.getAgeForIdcard(patient.getIdcard());
                    String sex = IdCardUtil.getSexForIdcard_new(patient.getIdcard());
                    resultMap.put("age",age);
                    resultMap.put("sex","1".equals(sex)?"男":("2".equals(sex)?"女":"未知"));
                    SignFamily signFamily = signFamilyDao.findByPatient(one.get("patient").toString());
                    if (signFamily != null){
                        resultMap.put("hospitalName",signFamily.getHospitalName());
                    }else {
                        resultMap.put("hospitalName","");
                    }
                }
                resultMap.put("id",one.get("id"));
                resultMap.put("status",one.get("status"));//康复计划状态
                //健康情况
                String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+one.get("patient")+"' and label_type=8";
                List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
                String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
                String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
                resultMap.put("healthyCondition",healthyCondition);
                resultMap.put("healthyConditionType",healthyConditionType);
                //安排类型
                String planTypeName = null;
                Integer planTypeTemp = (Integer)one.get("plan_type");
                switch (planTypeTemp){
                    case 1:planTypeName="康复计划" ;break;
                    case 2:planTypeName="(转)社区医院" ;break;
                    case 3:planTypeName="(转)转家庭病床" ;break;
                }
                resultMap.put("planTypeName",planTypeName);
                resultMap.put("planCreateUser",one.get("create_user"));
                //今日待办(即今日全部的项目)
                Date beginTime = DateUtil.strToDateLong(DateUtil.getStringDateShort()+ " "+"00:00:00");
                Date endTime = DateUtil.strToDateLong(DateUtil.getStringDateShort()+ " "+"23:59:59");
                Integer todayBacklogCount = rehabilitationDetailDao.todayBacklogCount(one.get("id").toString(),beginTime,endTime);
                resultMap.put("todayBacklogCount",todayBacklogCount);//今日待办总数
                //已完成
                Integer finishedCount = rehabilitationDetailDao.completenessCount(1,one.get("id").toString(),beginTime,endTime);
                resultMap.put("finishedCount",finishedCount);//已完成
                //未完成
                Integer notstartedCount = rehabilitationDetailDao.completenessCount(0,one.get("id").toString(),beginTime,endTime);//未开始
                Integer underwayCount = rehabilitationDetailDao.completenessCount(2,one.get("id").toString(),beginTime,endTime);//已预约
                Integer unfinishedCount = notstartedCount+underwayCount;
                resultMap.put("unfinishedCount",unfinishedCount);//未完成
                //完成度(已完成/(已完成+未完成))
                Integer allFinishCount = rehabilitationDetailDao.findByStatusAndPlanId(1,one.get("id").toString());
                Integer allCount = rehabilitationDetailDao.findAllByPlanId(one.get("id").toString());
                resultMap.put("allCount",allCount);//总数
                resultMap.put("allFinishCount",allFinishCount);//全部已完成数
                resultMap.put("createTime",one.get("create_time"));
                resultList.add(resultMap);
            }
        }
        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success,resultList,page,pageSize,Long.valueOf(count));
    }
    /**
     * 康复管理更多计划
     * @param currentDoctorCode
     * @param patientCode
     * @return
     * @throws Exception
     */
    public ObjEnvelop findRehabilitationPlanDetailList(String currentDoctorCode,String patientCode) throws Exception{
        String sql = " select DISTINCT r.* from wlyy_doctor_patient_relation r join wlyy_patient_rehabilitation_plan p on r.patient=p.patient where r.status in('0','1') and r.patient='"+patientCode+"' ";
        //sql = TransforSqlUtl.specialistPatientRelationAll2(sql);
        List<Map<String,Object>> specialistPatientRelationList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> resultList = new ArrayList<>();
        for(Map<String,Object> temp: specialistPatientRelationList){
            String doctorCode = temp.get("doctor")+"";
            Map<String,Object> resultMap = new HashMap<>();
            Integer isOperator = 0;
            resultMap.put("patientCode",patientCode);//居民code
            String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+patientCode+"' and label_type=8";
            List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
            String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
            String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
            resultMap.put("healthyCondition",healthyCondition);
            resultMap.put("healthyConditionType",healthyConditionType);
            //专科医生
            String specialistRelationSql = "select r.*,t.name as teamName,h.name as specialistHospitalName from wlyy_doctor_patient_relation r left join base_team t on r.team_code=t.id left join base_org h on t.org_code=h.code where  r.status in('0','1') and r.patient='"+patientCode+"' and r.doctor='"+doctorCode+"'";
            specialistRelationSql = TransforSqlUtl.specialistPatientRelationAll2(specialistRelationSql);
            List<Map<String,Object>> specialistRelationList = jdbcTemplate.queryForList(specialistRelationSql);
            Map<String,Object> specialistMap = specialistRelationList.get(0);
            resultMap.put("specialistAdminTeamName",specialistMap.get("teamName"));
            resultMap.put("specialistHospitalName",specialistMap.get("specialistHospitalName"));//专科医生所在医院
            Integer specialistUnfinishCount1 = rehabilitationDetailDao.unfinishItemByDoctor(doctorCode,patientCode,1);
            Integer specialistFinishCount1 = rehabilitationDetailDao.findItemByDoctor(doctorCode,patientCode);
            Integer specialistServiceCount1 = rehabilitationDetailDao.completeServiceByDoctor(doctorCode,patientCode,1);
            /*Integer specialistUnfinishCount2 = rehabilitationDetailDao.unfinishItemByDoctor(specialistMap.get("health_assistant")+"",patientCode,1);
            Integer specialistFinishCount2 = rehabilitationDetailDao.findItemByDoctor(specialistMap.get("health_assistant")+"",patientCode);
            Integer specialistServiceCount2 = rehabilitationDetailDao.completeServiceByDoctor(specialistMap.get("health_assistant")+"",patientCode,1);*/
            resultMap.put("specialistFinishItemCount",specialistFinishCount1-specialistUnfinishCount1);//完成项目
            resultMap.put("specialistServiceRecordCount",specialistServiceCount1);//服务次数
            //家庭医生(包括全科医生、健管师)
            String signFamilySql = "SELECT f.*,t.name as teamName FROM wlyy_sign_family f LEFT JOIN wlyy_admin_team t on f.admin_team_code=t.id where f.status =1 and f.expenses_status='1' and f.patient='"+patientCode+"'";
            List<Map<String,Object>> signFamilyList = jdbcTemplate.queryForList(signFamilySql);
            if(signFamilyList != null && signFamilyList.size() >0 ) {
                Map<String, Object> signFamilyMap = signFamilyList.get(0);
                resultMap.put("signFamilyAdminTeamName", signFamilyMap.get("teamName"));
                resultMap.put("familyHospitalName", signFamilyMap.get("hospital_name"));//家庭医生所在医院
                Integer familyUnfinishCount1 = rehabilitationDetailDao.unfinishItemByDoctor(signFamilyMap.get("doctor") + "", patientCode, 1);
                Integer familyFinishCount1 = rehabilitationDetailDao.findItemByDoctor(signFamilyMap.get("doctor") + "", patientCode);
                Integer familyServiceCount1 = rehabilitationDetailDao.completeServiceByDoctor(signFamilyMap.get("doctor") + "", patientCode, 1);
                if ((signFamilyMap.get("doctor") + "").equals(signFamilyMap.get("doctor_health") + "")) {
                    resultMap.put("signFamilyFinishItemCount", familyFinishCount1 - familyUnfinishCount1);//完成项目
                    resultMap.put("signFamilyServiceRecordCount", familyServiceCount1);//服务次数
                } else {
                    Integer familyUnfinishCount2 = rehabilitationDetailDao.unfinishItemByDoctor(signFamilyMap.get("doctor_health") + "", patientCode, 1);
                    Integer familyFinishCount2 = rehabilitationDetailDao.findItemByDoctor(signFamilyMap.get("doctor_health") + "", patientCode);
                    Integer familyServiceCount2 = rehabilitationDetailDao.completeServiceByDoctor(signFamilyMap.get("doctor_health") + "", patientCode, 1);
                    resultMap.put("signFamilyFinishItemCount", familyFinishCount1 - familyUnfinishCount1 + familyFinishCount2 - familyUnfinishCount2);//完成项目
                    resultMap.put("signFamilyServiceRecordCount", familyServiceCount1 + familyServiceCount2);//服务次数
                }
                //基础信息
                resultMap.put("hospitalName", signFamilyMap.get("hospital_name"));
                Integer age = IdCardUtil.getAgeForIdcard(signFamilyMap.get("idcard") + "");
                String sex = IdCardUtil.getSexForIdcard_new(signFamilyMap.get("idcard") + "");
                resultMap.put("age", age);
                resultMap.put("sex", "1".equals(sex) ? "男" : ("2".equals(sex) ? "女" : "未知"));
                resultMap.put("patientName", signFamilyMap.get("patientName"));
            }
           /* //疾病类型
            String diseaseSql = " select s.* from wlyy_patient_disease_server s where s.del=1 and s.patient='"+patientCode+"' and s.specialist_relation_code='"+specialistMap.get("id")+"' ";
            List<Map<String,Object>> diseaseList = jdbcTemplate.queryForList(diseaseSql);
            List<String> disease = new ArrayList<>();
            for(Map<String,Object> one2:diseaseList){
                disease.add(one2.get("disease_name")+"");
            }
            resultMap.put("diseaseList",disease);*/
            //计划列表
            List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatientAndCreateUser(patientCode,doctorCode);
            List<Map<String,Object>> rehabilitationPlanList = new ArrayList<>();
            for(PatientRehabilitationPlanDO one:list){
                Map<String,Object> planMap = new HashMap<>();
                planMap.put("planId",one.getId());
                //安排类型
                String planTypeName = null;
                Integer planTypeTemp = one.getPlanType();
                switch (planTypeTemp){
                    case 1:planTypeName="康复计划" ;break;
                    case 2:planTypeName="(转)社区医院" ;break;
                    case 3:planTypeName="(转)转家庭病床" ;break;
                }
                planMap.put("planTypeName",planTypeName);
                planMap.put("status",one.getStatus());//0已中止,1进行中,2已完成
                if(currentDoctorCode.equals(doctorCode)){
                    isOperator = 1;
                }
                planMap.put("isOperator",isOperator);
                //状态(0未完成,1已完成,2已预约)
                //今日待办
                Date beginTime = DateUtil.strToDateLong(DateUtil.getStringDateShort()+ " "+"00:00:00");
                Date endTime = DateUtil.strToDateLong(DateUtil.getStringDateShort()+ " "+"23:59:59");
                Integer todayBacklogCount = rehabilitationDetailDao.todayBacklogCount(one.getId(),beginTime,endTime);
                planMap.put("todayBacklogCount",todayBacklogCount);
                //已完成
                Integer finishedCount = rehabilitationDetailDao.completenessCount(1,one.getId(),beginTime,endTime);
                planMap.put("finishedCount",finishedCount);//已完成
                //未完成
                Integer notstartedCount = rehabilitationDetailDao.completenessCount(0,one.getId(),beginTime,endTime);//未完成
                Integer underwayCount = rehabilitationDetailDao.completenessCount(2,one.getId(),beginTime,endTime);//已预约
                Integer unfinishedCount = notstartedCount+underwayCount;
                planMap.put("unfinishedCount",unfinishedCount);//未完成
                //完成度(已完成/(已完成+未完成))
                Integer allFinishCount = rehabilitationDetailDao.findByStatusAndPlanId(1,one.getId());
                Integer allCount = rehabilitationDetailDao.findAllByPlanId(one.getId());
                planMap.put("allCount",allCount);//总数
                planMap.put("allFinishCount",allFinishCount);//全部已完成数
                rehabilitationPlanList.add(planMap);
            }
            resultMap.put("rehabilitationPlanList",rehabilitationPlanList);
            BasePatientDO p = basePatientDao.findById(patientCode);
            resultMap.put("patientPhoto",p.getPhoto());
            resultList.add(resultMap);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultList);
    }
    /**
     * 日历
     * @param searchTask 快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param status 任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode 登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailByPatient(String executeStartTime,String executeEndTime,String patient,Integer searchTask,Integer status,String doctorCode,String taskExecutor) throws Exception{
        List<Map<String,Object>> planList = getPatientAllRehabilitationPlan(patient);
        StringBuilder planCondition = new StringBuilder();
        planCondition .append("'"+planList.get(0).get("id").toString()+"'");
        for (int i=1;i<planList.size();i++){
            planCondition .append(",'"+planList.get(0).get("id").toString()+"'");
        }
        String sql = " select d.* from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  " +
                " where  d.plan_id in ("+planCondition+") " +
                "" ;
        if(StringUtils.isNotBlank(executeStartTime)){
            sql += " and d.execute_time>='"+executeStartTime+"' ";
        }
        if(StringUtils.isNotBlank(executeEndTime)){
            sql += " and d.execute_time<='"+executeEndTime+"' ";
        }
        if(searchTask!=null){
            if(searchTask==8){
                sql+=" and d.doctor='"+doctorCode+"' " ;
            }else {
                sql+=" and i.code="+searchTask+" " ;
            }
        }
        if(taskExecutor.equals("1")){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if(taskExecutor.equals("2")){//他人任务
            sql+="and d.doctor <>'"+doctorCode+"' ";
        }
        if(status!=null){
            sql+= " and d.status="+status;
        }
        sql += " ORDER BY d.execute_time ";
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
//        List<RehabilitationDetailDO> rehabilitationDetailList = rehabilitationDetailDao.findByPlanId(DateUtil.strToDate(executeStartTime),DateUtil.strToDate(executeEndTime),planId);
        Map<String,Map<String,Object>> map = new LinkedHashMap<>();
        for(Map<String,Object> one:rehabilitationDetailList){
            String executeTime = DateUtil.dateToStr((Date) one.get("execute_time"),DateUtil.YYYY_MM_DD);
            Map<String,Object> m = null;
            if(map.containsKey(executeTime)){
                m = map.get(executeTime);
                Map<String,Integer> family = null;
                Map<String,Integer> specialist = null;
                if(one.get("type")!=null){
                    if((Integer)one.get("type")==1){//家庭医生
                        if(m.containsKey("family")){
                            family = (Map<String,Integer>)m.get("family");
                        }else{
                            family = new HashMap<>();
                            family.put("all",0);
                            family.put("finish",0);
                        }
                        if((Integer)one.get("status")==1){
                            family.put("finish",family.get("finish")+1);
                        }
                        family.put("all",family.get("all")+1);
                        m.put("family",family);
                    }else if((Integer)one.get("type")==2){//专科医生
                        if(m.containsKey("specialist")){
                            specialist = (Map<String,Integer>)m.get("specialist");
                        }else{
                            specialist = new HashMap<>();
                            specialist.put("all",0);
                            specialist.put("finish",0);
                        }
                        if((Integer)one.get("status")==1){
                            specialist.put("finish",(specialist.get("finish"))+1);
                        }
                        specialist.put("all",(specialist.get("all"))+1);
                        m.put("specialist",specialist);
                    }
                }
            }else{
                m = new HashMap<>();
//                m.put("specialist",new HashMap<String,Object>());
                if(one.get("type")!=null){
                    if((Integer)one.get("type")==1){//家庭医生
                        Map<String,Integer> family = new HashMap<>();
                        family.put("all",0);
                        family.put("finish",0);
                        if((Integer)one.get("status")==1){
                            family.put("finish",family.get("finish")+1);
                        }
                        family.put("all",family.get("all")+1);
                        m.put("family",family);
                    }else if((Integer)one.get("type")==2){//专科医生
                        Map<String,Integer> specialist = new HashMap<>();
                        specialist.put("all",0);
                        specialist.put("finish",0);
                        if((Integer)one.get("status")==1){
                            specialist.put("finish",specialist.get("finish")+1);
                        }
                        specialist.put("all",specialist.get("all")+1);
                        m.put("specialist",specialist);
                    }
                }
            }
            //myTaskFlag,1:有自己任务,0:没有自己任务
            if(StringUtils.isNotEmpty(doctorCode)){
                if(m.containsKey("myTaskFlag")){
                    if((Integer)m.get("myTaskFlag")==0){
                        if(doctorCode.equals(one.get("doctor").toString())){
                            m.put("myTaskFlag",1);
                        }else{
                            m.put("myTaskFlag",0);
                        }
                    }
                }else{
                    if(doctorCode.equals(one.get("doctor").toString())){
                        m.put("myTaskFlag",1);
                    }else{
                        m.put("myTaskFlag",0);
                    }
                }
            }
            if(m.containsKey("planDetailIds")){
                m.put("planDetailIds",m.get("planDetailIds")+","+one.get("id"));
            }else{
                m.put("planDetailIds",one.get("id")+"");
            }
            map.put(executeTime,m);
        }
        /*List list = new ArrayList();
        for(String key : map.keySet()){
            Map<String,Object> result = map.get(key);
            result.put("executeTime", key);
            list.add(result);
        }*/
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
    }
    /**
     * 日历
     * @param planId 计划id
     * @param searchTask 快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param status 任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode 登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetail(String executeStartTime,String executeEndTime,String planId,Integer searchTask,Integer status,String doctorCode,String taskExecutor) throws Exception{
        String[] planIdlist = planId.split(",");
        StringBuilder planCondition = new StringBuilder();
        planCondition .append("'"+planIdlist[0]+"'");
        for (int i=1;i<planIdlist.length;i++){
            planCondition .append(",'"+planIdlist[i]+"'");
        }
        String sql = " select d.* from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  " +
                " where  d.plan_id in ("+planCondition+") " +
                " " ;
        if(StringUtils.isNotBlank(executeStartTime)){
            sql += " and d.execute_time>='"+executeStartTime+"' ";
        }
        if(StringUtils.isNotBlank(executeEndTime)){
            sql += " and d.execute_time<='"+executeEndTime+"' ";
        }
        if(searchTask!=null){
            if(searchTask==8){
                sql+=" and d.doctor='"+doctorCode+"' " ;
            }else {
                sql+=" and i.code="+searchTask+" " ;
            }
        }
        if(taskExecutor.equals("1")){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if(taskExecutor.equals("2")){//他人任务
            sql+="and d.doctor <>'"+doctorCode+"' ";
        }
        if(status!=null){
            sql+= " and d.status="+status;
        }
        sql += " ORDER BY d.execute_time ";
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
//        List<RehabilitationDetailDO> rehabilitationDetailList = rehabilitationDetailDao.findByPlanId(DateUtil.strToDate(executeStartTime),DateUtil.strToDate(executeEndTime),planId);
        Map<String,Map<String,Object>> map = new LinkedHashMap<>();
        for(Map<String,Object> one:rehabilitationDetailList){
            String executeTime = DateUtil.dateToStr((Date) one.get("execute_time"),DateUtil.YYYY_MM_DD);
            Map<String,Object> m = null;
            if(map.containsKey(executeTime)){
                m = map.get(executeTime);
                Map<String,Integer> family = null;
                Map<String,Integer> specialist = null;
                if(one.get("type")!=null){
                    if((Integer)one.get("type")==1){//家庭医生
                        if(m.containsKey("family")){
                            family = (Map<String,Integer>)m.get("family");
                        }else{
                            family = new HashMap<>();
                            family.put("all",0);
                            family.put("finish",0);
                        }
                        if((Integer)one.get("status")==1){
                            family.put("finish",family.get("finish")+1);
                        }
                        family.put("all",family.get("all")+1);
                        m.put("family",family);
                    }else if((Integer)one.get("type")==2){//专科医生
                        if(m.containsKey("specialist")){
                            specialist = (Map<String,Integer>)m.get("specialist");
                        }else{
                            specialist = new HashMap<>();
                            specialist.put("all",0);
                            specialist.put("finish",0);
                        }
                        if((Integer)one.get("status")==1){
                            specialist.put("finish",(specialist.get("finish"))+1);
                        }
                        specialist.put("all",(specialist.get("all"))+1);
                        m.put("specialist",specialist);
                    }
                }
            }else{
                m = new HashMap<>();
//                m.put("specialist",new HashMap<String,Object>());
                if(one.get("type")!=null){
                    if((Integer)one.get("type")==1){//家庭医生
                        Map<String,Integer> family = new HashMap<>();
                        family.put("all",0);
                        family.put("finish",0);
                        if((Integer)one.get("status")==1){
                            family.put("finish",family.get("finish")+1);
                        }
                        family.put("all",family.get("all")+1);
                        m.put("family",family);
                    }else if((Integer)one.get("type")==2){//专科医生
                        Map<String,Integer> specialist = new HashMap<>();
                        specialist.put("all",0);
                        specialist.put("finish",0);
                        if((Integer)one.get("status")==1){
                            specialist.put("finish",specialist.get("finish")+1);
                        }
                        specialist.put("all",specialist.get("all")+1);
                        m.put("specialist",specialist);
                    }
                }
            }
            //myTaskFlag,1:有自己任务,0:没有自己任务
            if(StringUtils.isNotEmpty(doctorCode)){
                if(m.containsKey("myTaskFlag")){
                    if((Integer)m.get("myTaskFlag")==0){
                        if(doctorCode.equals(one.get("doctor").toString())){
                            m.put("myTaskFlag",1);
                        }else{
                            m.put("myTaskFlag",0);
                        }
                    }
                }else{
                    if(doctorCode.equals(one.get("doctor").toString())){
                        m.put("myTaskFlag",1);
                    }else{
                        m.put("myTaskFlag",0);
                    }
                }
            }
            if(m.containsKey("planDetailIds")){
                m.put("planDetailIds",m.get("planDetailIds")+","+one.get("id"));
            }else{
                m.put("planDetailIds",one.get("id")+"");
            }
            map.put(executeTime,m);
        }
        /*List list = new ArrayList();
        for(String key : map.keySet()){
            Map<String,Object> result = map.get(key);
            result.put("executeTime", key);
            list.add(result);
        }*/
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
    }
    /**
     * 日历列表
     * @param planId 计划id
     * @param searchTask 快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param status 任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode 登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailList(String planId,Integer searchTask,Integer status,String doctorCode,String executeStartTime,String executeEndTime,String taskExecutor){
        String[] planIdlist = planId.split(",");
        StringBuilder planCondition = new StringBuilder();
        planCondition .append("'"+planIdlist[0]+"'");
        for (int i=1;i<planIdlist.length;i++){
            planCondition .append(",'"+planIdlist[i]+"'");
        }
        String sql = " select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id   " +
                " where  d.plan_id in ("+planCondition+" )AND  d.execute_time IS NOT NULL " +
                "   and d.execute_time <>'' " ;
        if(searchTask!=null){
            if(searchTask==8){//
                sql+="and d.doctor='"+doctorCode+"' ";
            }else {
                sql+=" and i.code="+searchTask+" " ;
            }/*else if(searchTask==5){
                sql+=" and i.reserve=1 " ;
            }*/
        }
        if("1".equals(taskExecutor)){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if("2".equals(taskExecutor)){//他人任务
            sql+="and d.doctor <>'"+doctorCode+"' ";
        }
        if (StringUtils.isNoneBlank(executeEndTime)&&StringUtils.isNoneBlank(executeStartTime)){
            sql+="and d.execute_time>='"+executeStartTime+"' and d.execute_time<='"+executeEndTime+"' ";
        }
        if(status!=null){
            sql+= "and d.status="+status;
        }
        sql +="  order by d.execute_time desc ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationDetailList);
    }
    /**
     * 日历列表
     * @param searchTask 快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param status 任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode 登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailListByPatient(String executeStartTime,String executeEndTime,String patient,Integer searchTask,Integer status,String doctorCode,String taskExecutor){
        List<Map<String,Object>> planList = getPatientAllRehabilitationPlan(patient);
        StringBuilder planCondition = new StringBuilder();
        planCondition .append("'"+planList.get(0).get("id").toString()+"'");
        for (int i=1;i<planList.size();i++){
            planCondition .append(",'"+planList.get(0).get("id").toString()+"'");
        }
        String sql = " select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id   " +
                " where  d.plan_id in ("+planCondition+" )AND  d.execute_time IS NOT NULL    and d.execute_time <>'' " ;
        if(searchTask!=null){
            if(searchTask==8){//
                sql+="and d.doctor='"+doctorCode+"' ";
            }else {
                sql+=" and i.code="+searchTask+" " ;
            }/*else if(searchTask==5){
                sql+=" and i.reserve=1 " ;
            }*/
        }
        if("1".equals(taskExecutor)){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if("2".equals(taskExecutor)){//他人任务
            sql+="and d.doctor <>'"+doctorCode+"' ";
        }
        if (StringUtils.isNoneBlank(executeEndTime)&&StringUtils.isNoneBlank(executeStartTime)){
            sql+="and d.execute_time>='"+executeStartTime+"' and d.execute_time<='"+executeEndTime+"' ";
        }
        if(status!=null){
            sql+= "and d.status="+status;
        }
        sql +="  order by d.execute_time desc ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationDetailList);
    }
    /**
     * 多个康复计划服务项目内容列表
     * @param planDetailIds
     * @return
     * @throws Exception
     */
    public ObjEnvelop serviceItemList(String planDetailIds,String doctorCode) throws Exception{
        String[] s = planDetailIds.split(",");
        String planDetailList = "";
        for(String one:s){
            planDetailList +=",'"+one+"'";
        }
        String planDetailResult = StringUtils.isNotEmpty(planDetailList)?planDetailList.substring(1):"";
        String sql = "select i.name,i.code,i.introduce,d.execute_time,d.hospital_name,d.id,d.status,d.type as detailType,d.expense,d.doctor as executeDoctor," +
                " d.doctor_name as executeDoctorName,p.patient ,p.id AS planId,p.create_user as createDoctor,p.create_user_name as createDoctorName, p.status as planStatus  " +
                " from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " where d.id in ("+planDetailResult+")     order BY d.execute_time ASC";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName(sql);
        List<Map<String,Object>> serviceItemList = jdbcTemplate.queryForList(sql);
//        if(serviceItemList.size()>0){
//            Map<String,Object> serviceItem = serviceItemList.get(0);
        List<Map<String,Object>> resultList = new ArrayList<>();
        for(Map<String,Object> one:serviceItemList){
            Map<String,Object> resultMap = new HashMap<>();
            Integer isMyTask = 0;
            if(StringUtils.isNotEmpty(doctorCode)&&doctorCode.equals(one.get("executeDoctor")+"")){
                isMyTask=1;
            }
            resultMap.put("isMyTask",isMyTask);//0不是自己的任务,1是自己的任务
//            if(!(one.get("specialistDoctor")+"").equals((one.get("create_user")+""))){
//                executeDoctorList.add(one.get("create_user_name")+"");
//            }
            List<String> executeDoctorList = new ArrayList<>();
            executeDoctorList.add(one.get("executeDoctorName")+"");
            resultMap.put("executeDoctorList",executeDoctorList);//执行医生名称列表
            resultMap.put("executeDoctorCode",one.get("executeDoctor")+"");//执行医生code
            resultMap.put("executeDoctorName",one.get("executeDoctorName")+"");//执行医生code
            resultMap.put("specialistDoctorCode",one.get("createDoctor")+"");//创建人(专科)医生code
            resultMap.put("specialistDoctorName",one.get("createDoctorName")+"");//创建人(专科)医生名字
            resultMap.put("title",one.get("name"));//项目标题
            resultMap.put("planDetaiId",one.get("id"));//计划服务项目id
            resultMap.put("planId",one.get("planId"));//计划id
            resultMap.put("shortExecuteTime",DateUtil.dateToStr((Date) one.get("execute_time"),DateUtil.HH_MM));//项目标题
            resultMap.put("content",one.get("content"));//项目内容
            resultMap.put("hospitalName",one.get("hospital_name"));//地点
            resultMap.put("executeTime",one.get("execute_time"));//执行时间
            DecimalFormat df = new DecimalFormat("0.00");
            resultMap.put("expense", one.get("expense")!=null?df.format(((Integer)one.get("expense")*1.00)):0);//收费
            resultMap.put("reserve",null);//是否需要预约(1预约、0不预约)
            resultMap.put("planStatus",one.get("planStatus"));//计划的状态
            Integer status = Integer.valueOf(one.get("status").toString());//状态(0未完成,1已完成,2已预约)
            String statusName = "";
            switch (status){
                case 0:{statusName="未完成";break;}
                case 1:{statusName="已完成";break;}
                case 2:{statusName="已预约";break;}
            }
            resultMap.put("statusName",statusName);//状态
            //指导与汇报
            List<GuidanceMessageLogDO> messageList = guidanceMessageLogDao.findByPlanDetailId(one.get("id").toString());
            List<Map<String,Object>> messageMapList = new ArrayList<>();
            for(GuidanceMessageLogDO one2:messageList){
                Map<String,Object> map = new HashMap<>();
                map.put("doctorName",one2.getDoctorName());
                map.put("adminTeamName",one2.getAdminTeamName());
                map.put("content",one2.getContent());
                map.put("contentType",one2.getContentType());
                map.put("createTime",DateUtil.dateToStr(one2.getCreateTime(),"MM-dd HH:mm"));
                messageMapList.add(map);
            }
           /* Integer itemType = (Integer) one.get("itemType");*/
            resultMap.put("messageList",messageMapList);//指导与汇报记录
            resultMap.put("patient",one.get("patient"));
            resultMap.put("itemType",one.get("code"));
            resultMap.put("detaiType",one.get("detaiType"));
            resultMap.put("status",status);//状态
            //是否完成任务
            List<RehabilitationOperateRecordsDO> operateList = rehabilitationOperateRecordsDao.findByRehabilitationDetailId(one.get("id").toString());
            Integer operate = 0;
            if(operateList.size()>0){
                operate =1;
                RehabilitationOperateRecordsDO temp = operateList.get(0);
                operate =1;
                Date completeTime = temp.getCompleteTime();
                String completeTimeStr = DateUtil.dateToStr(completeTime,DateUtil.YYYY_MM_DD_HH_MM);
                resultMap.put("completeTime",completeTimeStr);//完成时间
                resultMap.put("operatorDoctorName",temp.getDoctorName());//执行医生名称
                resultMap.put("node",temp.getNode());
                resultMap.put("relationRecordImg",(temp.getRelationRecordImg()!=null&&StringUtils.isNotEmpty(temp.getRelationRecordImg()))?(new JSONArray(temp.getRelationRecordImg())):null);//json格式
                resultMap.put("relationRecordCode",temp.getRelationRecordCode());
                resultMap.put("completeTimeShort",DateUtil.dateToStr(completeTime,"yyyy/MM/dd"));
            }
            resultMap.put("operate",operate);//是否完成任务(默认0:未完成,1:已完成)
            List<SignFamily> list = signFamilyDao.findByPatientAndExpensesStatusAndStatus(one.get("patient").toString(),"1",1);
            if(list.size()>0){
                resultMap.put("familyDoctorCode",list.get(0).getDoctor());
                resultMap.put("familyDoctorName",list.get(0).getDoctorName());
            }else{
                resultMap.put("familyDoctorCode","");
                resultMap.put("familyDoctorName","");
            }
            resultList.add(resultMap);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultList);
//        }
//        return MixEnvelop.getError("没有该服务项详情信息!");
    }
    /**
     * 康复计划服务项目确认页
     * @param planDetailId
     * @return
     * @throws Exception
     *
     */
    public ObjEnvelop serviceItem(String planDetailId,String doctorCode,String recordId) throws Exception{
        String sql = "select h.name as title,h.content as content,h.code as itemType,d.id,d.execute_time,d.hospital_name,d.status,d.type,d.expense,d.doctor as executeDoctor, " +
                " d.doctor_name as executeDoctorName,p.patient ,p.name as patientName,p.create_user as createDoctor,p.create_user_name as createDoctorName, p.status as planStatus," +
                " p.disease,p.disease_name as diseaseName,p.title as planTitle,d.plan_id as planId,d.relation_code as relationCode,d.frequency_code as frequencyCode,d.remark  "+
                " ,a.appointment_time appointmentTime,a.appointment_doctor appointmentDoctor,a.appointment_doctor_name appointmentDoctorName,d.reservation_type reservationType" +
                " from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id = h.code "+
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " LEFT JOIN wlyy_plan_detail_appointment a on d.id=.a.rehabilitation_plan_detail_id " +
                " where d.id = '"+planDetailId+"'";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        sql = TransforSqlUtl.wlyy_plan_detail_appointmentAppDoctorName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName(sql);
        System.out.println("sql===="+sql);
        List<Map<String,Object>> serviceItemList = jdbcTemplate.queryForList(sql);
        if (serviceItemList.size()==0){
            return ObjEnvelop.getSuccess(SpecialistMapping.api_success,new HashMap<>());
        }
        Map<String,Object> one = serviceItemList.get(0);
        Map<String,Object> resultMap = new HashMap<>();
        List<String> executeDoctorList = new ArrayList<>();
        Integer isMyTask = 0;
        //判断登陆者和执行医生是不是同一个人
        if(StringUtils.isNotEmpty(doctorCode)&&doctorCode.equals(one.get("executeDoctor")+"")){
            isMyTask=1;
        }
        // 协诊预约信息
        resultMap.put("appointmentTime",one.get("appointmentTime"));
        resultMap.put("appointmentDoctor",one.get("appointmentDoctor"));
        resultMap.put("appointmentDoctorName",one.get("appointmentDoctorName"));
        resultMap.put("reservationType",one.get("reservationType"));//复诊类型:1线上,2线下,3远程
        resultMap.put("frequencyCode",one.get("frequencyCode")+"");
        resultMap.put("isMyTask",isMyTask);//0不是自己的任务,1是自己的任务
//        if(!(one.get("specialistDoctor")+"").equals((one.get("create_user")+""))){
//            executeDoctorList.add(one.get("create_user_name")+"");
//        }
        List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(one.get("executeDoctor").toString());
        if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
            resultMap.put("executeDoctorDept",baseDoctorHospitalDO.get(0).getDeptCode());
            resultMap.put("executeDoctorDeptName",baseDoctorHospitalDO.get(0).getDeptName());
        }
        executeDoctorList.add(one.get("executeDoctorName")+"");//
        resultMap.put("remark",one.get("remark"));//备注
        resultMap.put("executeDoctorList",executeDoctorList);//执行医生名称列表
        resultMap.put("executeDoctorCode",one.get("executeDoctor")+"");//执行医生code
        resultMap.put("executeDoctorName",one.get("executeDoctorName")+"");//执行医生名称
        resultMap.put("specialistDoctorCode",one.get("createDoctor")+"");//创建人(专科)医生code
        resultMap.put("specialistDoctorName",one.get("createDoctorName")+"");//创建人(专科)医生名字
        resultMap.put("title",one.get("title"));//项目标题
        resultMap.put("shortExecuteTime",DateUtil.dateToStr((Date) one.get("execute_time"),DateUtil.HH_MM));//项目标题
        resultMap.put("content",one.get("content"));//项目内容
        resultMap.put("hospitalName",one.get("hospital_name"));//地点
        resultMap.put("executeTime",one.get("execute_time"));//执行时间
        DecimalFormat df = new DecimalFormat("0.00");
        resultMap.put("expense",one.get("expense")!=null?df.format(((Integer)one.get("expense")*1.00)):0);//收费
        resultMap.put("reserve",one.get("reserve"));//是否需要预约(1预约、0不预约)
        resultMap.put("planStatus",one.get("planStatus"));//计划的状态
        resultMap.put("relationCode",one.get("relationCode"));//业务关联code
        Integer status = Integer.valueOf(one.get("status").toString());//状态(0未完成,1已完成,2已预约)
        String statusName = "";
        switch (status){
            case 0:{statusName="未完成";break;}
            case 1:{statusName="已完成";break;}
            case 2:{statusName="已预约";break;}
            case 3:{statusName="待录入";break;}
        }
        resultMap.put("statusName",statusName);//状态名称
        resultMap.put("status",status);//状态
        resultMap.put("disease",one.get("disease"));
        resultMap.put("diseaseName",one.get("diseaseName"));
        resultMap.put("planTitle",one.get("planTitle"));
        resultMap.put("planId",one.get("planId"));
        //指导与汇报
        List<GuidanceMessageLogDO> messageList = guidanceMessageLogDao.findByPlanDetailId(one.get("id").toString());
        List<Map<String,Object>> messageMapList = new ArrayList<>();
        for(GuidanceMessageLogDO one2:messageList){
            Map<String,Object> map = new HashMap<>();
            map.put("doctorName",one2.getDoctorName());
            map.put("adminTeamName",one2.getAdminTeamName());
            map.put("content",one2.getContent());
            map.put("contentType",one2.getContentType());
            map.put("doctorType",one2.getDoctorType());//医生类型
            map.put("createTime",DateUtil.dateToStr(one2.getCreateTime(),"MM-dd HH:mm"));
            messageMapList.add(map);
        }
        resultMap.put("messageList",messageMapList);//指导与汇报记录
        resultMap.put("patient",one.get("patient"));
        resultMap.put("patientName",one.get("patientName"));
        resultMap.put("type",one.get("itemType"));//1扫码、0上传附件、2、健康教育,3、健康指导,4、随访
        //是否完成任务
        List<RehabilitationOperateRecordsDO> operateList = new ArrayList<>();
        if(StringUtils.isNoneBlank(recordId)){
            operateList= rehabilitationOperateRecordsDao.findByRehabilitationDetailIdAndId(one.get("id").toString(),recordId);
        }else {
            operateList= rehabilitationOperateRecordsDao.findByRehabilitationDetailId(one.get("id").toString());
        }
        Integer operate = 0;
        if(operateList.size()>0){
            RehabilitationOperateRecordsDO temp = operateList.get(0);
            operate =1;
            Date completeTime = temp.getCompleteTime();
            String completeTimeStr = DateUtil.dateToStr(completeTime,DateUtil.YYYY_MM_DD_HH_MM);
            resultMap.put("completeTime",completeTimeStr);//完成时间
            resultMap.put("operatorDoctorName",temp.getDoctorName());//执行医生名称
            resultMap.put("node",temp.getNode());
            resultMap.put("recordStatus",temp.getStatus());//操作记录
            resultMap.put("recordRelationCode",temp.getRelationCode());
            resultMap.put("recordFlag",temp.getFlag());
            resultMap.put("recordId",temp.getId());
            JSONArray imgs = new JSONArray();
            if (temp.getRelationRecordImg()!=null&&StringUtils.isNotEmpty(temp.getRelationRecordImg())){
                resultMap.put("relationRecordImg",(temp.getRelationRecordImg()!=null&&StringUtils.isNotEmpty(temp.getRelationRecordImg()))?(new JSONArray(temp.getRelationRecordImg())):null);//json格式
            }
            else{
                resultMap.put("relationRecordImg",imgs);
            }
         /*   if(itemType!=1&&itemType!=0){*/
                resultMap.put("relationRecordCode",temp.getRelationRecordCode());
                resultMap.put("completeTimeShort",DateUtil.dateToStr(completeTime,"yyyy/MM/dd"));
  /*          }*/
        }
        List<SignFamily> list = signFamilyDao.findByPatientAndExpensesStatusAndStatus(one.get("patient").toString(),"1",1);
        if(list.size()>0){
            resultMap.put("familyDoctorCode",list.get(0).getDoctor());
            resultMap.put("familyDoctorName",list.get(0).getDoctorName());
        }else{
            resultMap.put("familyDoctorCode","");
            resultMap.put("familyDoctorName","");
        }
        resultMap.put("operate",operate);//是否完成任务(默认0:未完成,1:已完成)
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
    }
    /**
     * 康复管理居民详情页
     * @param patientCode
     * @return
     */
    public ObjEnvelop patientRehabilitationDetail(String patientCode){
        Map<String,Object> resultMap = new HashMap<>();
        List<SignFamily> listFamiluy = signFamilyDao.findByPatientAndExpensesStatusAndStatus(patientCode,"1",1);
        String healthDoctor = null;
        String healthDoctorName =null;
        String generalDoctor = null;
        String generalDoctorName = null;
        String patientName = null;
        Integer age = null;
        String sex = null;
        String signHospitalName = null;
        org.json.JSONObject json = new org.json.JSONObject();
        String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+patientCode+"' and label_type=8";
        List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
        String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
        String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
        BasePatientDO patient = basePatientDao.findById(patientCode);
        if(listFamiluy.size()>0) {
            SignFamily signFamily = listFamiluy.get(0);
            healthDoctor = signFamily.getDoctorHealth();
            healthDoctorName = signFamily.getDoctorHealthName();
            generalDoctor = signFamily.getDoctor();
            generalDoctorName = signFamily.getDoctorName();
            patientName = signFamily.getName();
            signHospitalName = signFamily.getHospitalName();
        }
        //个人基础信息(康复机构)
        String patientInfoSql = " SELECT DISTINCT hospital_name from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " where p.patient='"+patientCode+"' and p.status=1 ";
        List<Map<String,Object>> patientInfoList = jdbcTemplate.queryForList(patientInfoSql);
        Map<String,Object> patientInfo = new HashMap<>();
        String rehabilitationOrg = "";
        for(Map<String,Object> one:patientInfoList){
            rehabilitationOrg+=","+one.get("hospital_name");
        }
        patientInfo.put("rehabilitationOrg",StringUtils.isNotEmpty(rehabilitationOrg)?rehabilitationOrg.substring(1):"");
        resultMap.put("patientInfo",patientInfo);
        //服务医生
        //完成项目=全部的服务项目-未完成的服务项目
        List<Map<String,Object>> serviceDoctorList = new ArrayList<>();
        //全科医生和健管师要是同一个人,就显示全科医生
  /*      if(!generalDoctor.equals(healthDoctor)){
*/
            if(StringUtils.isNotEmpty(healthDoctor)){
                Map<String,Object> healthDoctorMap =  new HashMap<>();
                healthDoctorMap.put("type","健管师");
                healthDoctorMap.put("doctorName",healthDoctorName);
                healthDoctorMap.put("doctorCode",healthDoctor);
                Integer healthUnfinishCount = rehabilitationDetailDao.unfinishItemByDoctor(healthDoctor,patientCode,1);
                Integer healthFinishCount = rehabilitationDetailDao.findItemByDoctor(healthDoctor,patientCode);
                Integer healthServiceCount = rehabilitationDetailDao.completeServiceByDoctor(healthDoctor,patientCode,1);
                healthDoctorMap.put("finishedItem",healthFinishCount-healthUnfinishCount);
                healthDoctorMap.put("serviceCount",healthServiceCount);
                serviceDoctorList.add(healthDoctorMap);
            }
/*        }*/
        if(StringUtils.isNotEmpty(generalDoctor)){
            Map<String,Object> generalDoctorMap =  new HashMap<>();
            generalDoctorMap.put("type","全科医生");
            generalDoctorMap.put("doctorName",generalDoctorName);
            generalDoctorMap.put("doctorCode",generalDoctor);
            Integer generalUnfinishCount = rehabilitationDetailDao.unfinishItemByDoctor(generalDoctor,patientCode,1);
            Integer generalFinishCount = rehabilitationDetailDao.findItemByDoctor(generalDoctor,patientCode);
            Integer generalServiceCount = rehabilitationDetailDao.completeServiceByDoctor(generalDoctor,patientCode,1);
            generalDoctorMap.put("finishedItem",generalFinishCount-generalUnfinishCount);
            generalDoctorMap.put("serviceCount",generalServiceCount);
            serviceDoctorList.add(generalDoctorMap);
        }
        String specialistRelationSql = "select DISTINCT d.doctor,d.doctor_name from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.type=2 and  p.patient='"+patientCode+"'";
        specialistRelationSql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName2(specialistRelationSql);
        List<Map<String,Object>> specialistRelationList = jdbcTemplate.queryForList(specialistRelationSql);
        BaseDoctorDO baseDoctorDO = null;
        for(Map<String,Object> one:specialistRelationList){
            String doctor = one.get("doctor")+"";
            String doctorName = one.get("doctor_name")+"";
            Integer unfinishCount = rehabilitationDetailDao.unfinishItemByDoctor(doctor,patientCode,1);
            Integer finishCount = rehabilitationDetailDao.findItemByDoctor(doctor,patientCode);
            Integer serviceCount = rehabilitationDetailDao.completeServiceByDoctor(doctor,patientCode,1);
            Map<String,Object> map =  new HashMap<>();
            map.put("finishedItem",finishCount-unfinishCount);
            map.put("serviceCount",serviceCount);
            map.put("doctorName",doctorName);
            map.put("doctorCode",doctor);
            map.put("type","专科医生");
            serviceDoctorList.add(map);
        }
        for (Map<String,Object> d:serviceDoctorList){
            BaseDoctorDO baseDoctorDO1 = baseDoctorDao.findById(d.get("doctorCode").toString());
            d.put("doctorPhoto",baseDoctorDO1!=null?baseDoctorDO1.getPhoto():"");
        }
        resultMap.put("serviceDoctorList",serviceDoctorList);
        //康复计划
        List<Map<String,Object>> planList = new ArrayList<>();
        List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatients(patientCode);
        Integer planUnderway = 0;//进行中
        Integer planFinish = 0;//已完成
        for(PatientRehabilitationPlanDO one:list){
            if(one.getStatus()==1){
                planUnderway+=1;
            }else if(one.getStatus()==2){
                planFinish+=1;
            }
            Map<String,Object> map =  new HashMap<>();
            //安排类型
            String planTypeName = null;
            Integer planTypeTemp = one.getPlanType();
            switch (planTypeTemp){
                case 1:planTypeName="康复计划" ;break;
                case 2:planTypeName="(转)社区医院" ;break;
                case 3:planTypeName="(转)转家庭病床" ;break;
            }
            map.put("createUser",one.getCreateUser());
            map.put("createUserName",one.getCreateUserName());
            map.put("planId",one.getId());
            map.put("planTypeName",planTypeName);
            String statusName = "";
            Integer status = one.getStatus();
            switch (status){
                case 0:{statusName="已中止";break;}
                case 1:{statusName="进行中";break;}
                case 2:{statusName="已完成";break;}
            }
            map.put("planTypeName",planTypeName);//安排类型名称
            map.put("statusName",statusName);//状态名称
            map.put("medicalRecordsCode",one.getMedicalRecordsCode());//住院code
            map.put("adviceContent",one.getAdviceContent());//康复建议
            //已完成
            Integer allFinishCount = rehabilitationDetailDao.findByStatusAndPlanId(1,one.getId());
            map.put("allFinishCount",allFinishCount);//已完成
            //完成度(已完成/(已完成+未完成))
            Integer allCount = rehabilitationDetailDao.findAllByPlanId(one.getId());
            map.put("allCount",allCount);//总数
            List<RehabilitationDetailDO> detailList = rehabilitationDetailDao.getAllRehabilitationDetail(one.getId());
            if(detailList.size()>0){
                Date executeTimeStart = detailList.get(0).getExecuteTime();
                Date executeTimeEnd = detailList.get(detailList.size()-1).getExecuteTime();
                String executeStart = DateUtil.dateToStr(executeTimeStart,"yyyy/MM/dd");
                String executeEnd = DateUtil.dateToStr(executeTimeEnd,"yyyy/MM/dd");
                map.put("time",executeStart+"-"+executeEnd);
            }else{
                map.put("time","");
            }
            planList.add(map);
        }
        resultMap.put("planList",planList);
        //康复计划-已完成、进行中
        resultMap.put("planUnderway",planUnderway);//进行中
        resultMap.put("planFinish",planFinish);//已完成
        resultMap.put("healthyCondition",healthyCondition);
        resultMap.put("healthyConditionType",healthyConditionType);
        resultMap.put("patientName",patientName);
        resultMap.put("signHospitalName",signHospitalName);
        age = IdCardUtil.getAgeForIdcard(patient.getIdcard());
        sex = IdCardUtil.getSexForIdcard_new(patient.getIdcard());
        resultMap.put("patientCode", patientCode);
        resultMap.put("patientName", patient.getName());
        resultMap.put("age",age);
        resultMap.put("sex",sex);
        resultMap.put("photo",patient.getPhoto());
        resultMap.put("mobile",patient.getMobile());
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
    }
    /**
     * 居民康复计划详情页-近期康复相关记录
     * @param patientCode
     * @param startTime
     * @param endTime
     */
    public ObjEnvelop recentPlanDetailRecord(String patientCode,String startTime,String endTime,Integer page, Integer pageSize) throws Exception{
        Map<String,Object> resultMap = new HashMap<>();
        //近期康复相关记录
//        String currentTime = DateUtil.getStringDate();
        String planDetailSql = " select d.*,h.name,h.code,s.complete_time from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id=h.code " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id" +
                " left join wlyy_rehabilitation_operate_records s on s.rehabilitation_detail_id=d.id " +
                " where d.status=1 and p.patient='"+patientCode+"' and d.frequency_code IS NOT NULL   AND d.frequency_code <>'' ";
        if(StringUtils.isNotEmpty(startTime)){
            planDetailSql += "  and d.execute_Time>='"+startTime+"' ";
        }
        if(StringUtils.isNotEmpty(endTime)){
            planDetailSql += "  and d.execute_time<='"+endTime+"' ";
        }
        planDetailSql += " ORDER BY s.complete_time DESC LIMIT "+(page-1)*pageSize+","+pageSize;
        planDetailSql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(planDetailSql);
        List<Map<String,Object>> planDetails = jdbcTemplate.queryForList(planDetailSql);
        List<Map<String,Object>> planDetailList = new ArrayList<>();
        for(Map<String,Object> one:planDetails){
            Date executeTimeDate = (Date)one.get("complete_time");
            String executeTime = DateUtil.dateToStr(executeTimeDate,"yyyy/MM/dd HH:mm");
            String content = one.get("code")+"";
            String title = one.get("name")+"";
            Integer status = (Integer)one.get("status");
            String statusName = "";
            switch (status){
                case 0:{statusName="未完成";break;}
                case 1:{statusName="已完成";break;}
                case 2:{statusName="已预约";break;}
            }
            String id = one.get("id").toString();
            Map<String,Object> map = new HashMap<>();
            map.put("id",id);//id
//            List<RehabilitationOperateRecordsDO> rehabilitationOperateRecords = rehabilitationOperateRecordsDao.findByRehabilitationDetailId(id);
//            Date completeTime = rehabilitationOperateRecords!=null&&rehabilitationOperateRecords.size()>0?rehabilitationOperateRecords.get(0).getCompleteTime():null;
//            String completeTimeStr =  completeTime!=null?DateUtil.dateToStr(completeTime,"yyyy/MM/dd HH:mm"):"";
            map.put("executeTime",executeTime);//执行时间
            map.put("title",title);//项目标题
            map.put("content",content);//项目内容
            map.put("statusName",statusName);//状态名称
            planDetailList.add(map);
        }
        resultMap.put("planDetailList",planDetailList);//康复相关记录列表
        String planDetailCountSql = " select d.status as num from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id=h.code" +
                "  LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where p.patient='"+patientCode+"'  ";
        List<Map<String,Object>> planDetailList2 = jdbcTemplate.queryForList(planDetailCountSql);
        Integer planDetailFinish = 0;
        Integer planDetailUnfinish = 0;
        for(Map<String,Object> one:planDetailList2){
            Integer status = (Integer)one.get("num");
            if(status==1){
                planDetailFinish+=1;
            }else{
                planDetailUnfinish+=1;
            }
        }
        resultMap.put("planDetailFinish",planDetailFinish);//已完成
        resultMap.put("planDetailUnfinish",planDetailUnfinish);//未完成
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
    }
    /**
     * 保存康复管理指导留言信息
     * @param messageId
     * @param doctor
     */
    @Transactional
    public Envelop saveGuidanceMessage(String messageId,String doctor,String content,String planDetailId,Integer contentType) throws Exception{
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        Integer doctorType =null;
        if (doctorDO!=null){
            List<BaseDoctorRoleDO> baseDoctorRoleDO = baseDoctorRoleDao.findByDoctorCode(doctor);
            if (baseDoctorRoleDO!=null){
                for (BaseDoctorRoleDO baseDoctorRoleDO1:baseDoctorRoleDO){
                    if ("specialist".equalsIgnoreCase(baseDoctorRoleDO1.getRoleCode())){
                        doctorType=1;
                        break;
                    }else {
                        doctorType=2;
                    }
                }
            }
        }
        List<String> patientList = rehabilitationDetailDao.findPatientById(planDetailId);
        String patient = patientList.size()>0?patientList.get(0):"";
        GuidanceMessageLogDO guidanceMessageLogDO = new GuidanceMessageLogDO();
        guidanceMessageLogDO.setMessageId(messageId);
        guidanceMessageLogDO.setPlanDetailId(planDetailId);
        guidanceMessageLogDO.setContent(content);
        guidanceMessageLogDO.setDoctor(doctor);
        guidanceMessageLogDO.setContentType(contentType);
        guidanceMessageLogDO.setDoctorType(doctorType);
        Integer adminTeamCode = null;
        String doctorName = null;
        if(doctorType==1){
            SpecialistPatientRelationDO specialistPatientRelationDO = specialistPatientRelationDao.findByPatientAndDoctor(doctor,patient);
            adminTeamCode = specialistPatientRelationDO.getTeamCode();
            doctorName = specialistPatientRelationDO.getDoctorName();
        }else if(doctorType==2){
            String signFamilySql = " select f.* from wlyy_sign_family f where f.status=1 and f.expenses_status='1' and f.patient='"+patient+"'";
            List<Map<String,Object>> signFamily = jdbcTemplate.queryForList(signFamilySql);
            adminTeamCode = (Integer)signFamily.get(0).get("admin_team_code");
            doctorName = signFamily.get(0).get("doctor_name").toString();
        }
        String adminTeamSql = " select t.* from base_team t where t.del='1' and t.id="+adminTeamCode;
        List<Map<String,Object>> adminTeam = jdbcTemplate.queryForList(adminTeamSql);
        String adminTeamName = adminTeam.get(0).get("name").toString();
        guidanceMessageLogDO.setAdminTeamCode(adminTeamCode);
        guidanceMessageLogDO.setAdminTeamName(adminTeamName);
        guidanceMessageLogDO.setDoctorName(doctorName);
        guidanceMessageLogDO.setCreateTime(new Date());
        guidanceMessageLogDO.setUpdateTime(new Date());
        guidanceMessageLogDao.save(guidanceMessageLogDO);
        return Envelop.getSuccess(SpecialistMapping.api_success);
    }
    /**
     * 康复管理-更新康复计划操作完成日志状态
     * @param planDetailId
     * @param status
     * @throws Exception
     */
    @Transactional
    public Envelop updateStatusRehabilitationOperate(Integer status,String planDetailId){
        if(rehabilitationOperateRecordsDao.updateStatus(status,planDetailId)>0){
           return Envelop.getSuccess(SpecialistMapping.api_success);
        }
        return Envelop.getError("更新失败!");
    }
    /**
     * app端居民详情服务医生列表
     * @param patientCode
     * @return
     */
    public ObjEnvelop serviceDoctorList(String patientCode){
        List<SignFamily> list = signFamilyDao.findByPatientAndExpensesStatusAndStatus(patientCode,"1",1);
        String healthDoctor = null;
        String healthDoctorName =null;
        String generalDoctor = null;
        String generalDoctorName = null;
        if(list!=null&&list.size()>0){
            SignFamily signFamily = list.get(0);
            healthDoctor = signFamily.getDoctorHealth();
            healthDoctorName = signFamily.getDoctorHealthName();
            generalDoctor = signFamily.getDoctor();
            generalDoctorName = signFamily.getDoctorName();
        }
        //服务医生
        //完成项目=全部的服务项目-未完成的服务项目
        List<Map<String,Object>> serviceDoctorList = new ArrayList<>();
        if(StringUtils.isNotEmpty(generalDoctor)){
            Map<String,Object> generalDoctorMap =  new HashMap<>();
            generalDoctorMap.put("type","全科医生");
            generalDoctorMap.put("doctorName",generalDoctorName);
            generalDoctorMap.put("doctorCode",generalDoctor);
            Integer generalUnfinishCount = rehabilitationDetailDao.unfinishItemByDoctor(generalDoctor,patientCode,1);
            Integer generalFinishCount = rehabilitationDetailDao.findItemByDoctor(generalDoctor,patientCode);
            Integer generalServiceCount = rehabilitationDetailDao.completeServiceByDoctor(generalDoctor,patientCode,1);
            generalDoctorMap.put("finishedItem",generalFinishCount-generalUnfinishCount);
            generalDoctorMap.put("serviceCount",generalServiceCount);
            serviceDoctorList.add(generalDoctorMap);
        }
        if(StringUtils.isNotEmpty(healthDoctor)){
            Map<String,Object> healthDoctorMap =  new HashMap<>();
            healthDoctorMap.put("type","健管师");
            healthDoctorMap.put("doctorName",healthDoctorName);
            healthDoctorMap.put("doctorCode",healthDoctor);
            Integer healthUnfinishCount = rehabilitationDetailDao.unfinishItemByDoctor(healthDoctor,patientCode,1);
            Integer healthFinishCount = rehabilitationDetailDao.findItemByDoctor(healthDoctor,patientCode);
            Integer healthServiceCount = rehabilitationDetailDao.completeServiceByDoctor(healthDoctor,patientCode,1);
            healthDoctorMap.put("finishedItem",healthFinishCount-healthUnfinishCount);
            healthDoctorMap.put("serviceCount",healthServiceCount);
            serviceDoctorList.add(healthDoctorMap);
        }
        String specialistRelationSql = "select DISTINCT d.doctor,d.doctor_name from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.type=2 AND d.doctor IS  NOT  NULL and  d.doctor <> ''  and  p.patient='"+patientCode+"'";
        specialistRelationSql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName2(specialistRelationSql);
        List<Map<String,Object>> specialistRelationList = jdbcTemplate.queryForList(specialistRelationSql);
        for(Map<String,Object> one:specialistRelationList){
            String doctor = one.get("doctor")+"";
            String doctorName = one.get("doctor_name")+"";
            Integer unfinishCount = rehabilitationDetailDao.unfinishItemByDoctor(doctor,patientCode,1);
            Integer finishCount = rehabilitationDetailDao.findItemByDoctor(doctor,patientCode);
            Integer serviceCount = rehabilitationDetailDao.completeServiceByDoctor(doctor,patientCode,1);
            Map<String,Object> map =  new HashMap<>();
            map.put("finishedItem",finishCount-unfinishCount);
            map.put("serviceCount",serviceCount);
            map.put("doctorName",doctorName);
            map.put("doctorCode",doctor);
            map.put("type","专科医生");
            serviceDoctorList.add(map);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,serviceDoctorList);
    }
    /**
     * app端、微信端计划的服务项目列表
     * @param planId
     * @param searchTask
     * @param status
     * @param executeStartTime
     * @param executeEndTime
     * @return
     */
    public ObjEnvelop appCalendarPlanDetailList(String planId,Integer searchTask,Integer status,String executeStartTime,String executeEndTime){
        Map<String,Object> resultMap = new HashMap<>();
        ObjEnvelop objEnvelop = calendarPlanDetailList(planId,searchTask,status,null,executeStartTime,executeEndTime,"0");
        Integer finishCount = rehabilitationDetailDao.findByStatusAndPlanId(1,planId);
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);
        resultMap.put("planDetailList",objEnvelop.getObj());
        resultMap.put("finishCount",finishCount);
        resultMap.put("allCount",allCount);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
    }
    /**
     * 每日康复服务通知
     * @param startTime
     * @param endTime
     * @return
     */
    public JSONArray dailyJob(String startTime,String endTime){
        String sql = "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 p.status=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' GROUP BY d.doctor,p.patient";
//        List<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        String doctorCode = "";
        String patientCode = "";
        List<String> listMap  = null;
        for(Map<String,Object> one:list){
            doctorCode = one.get("doctor")+"";
            patientCode = one.get("patient")+"";
            listMap = rehabilitationDetailDao.findByPatientAndDoctor(startTime,endTime,doctorCode,patientCode);
            String ids = "";
            for(String one2 : listMap){
                ids += ","+one2;
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        return new JSONArray(list);
    }
    /**
     * 明日康复计划提醒
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public JSONArray tomorrowJob(String startTime,String endTime){
        String sql = "select d.doctor,p.patient,count(1) as num,p.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 p.status=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' GROUP BY d.doctor,p.patient";
//        List<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        String doctorCode = "";
        String patientCode = "";
        List<String> listMap  = null;
        for(Map<String,Object> one:list){
            doctorCode = one.get("doctor")+"";
            patientCode = one.get("patient")+"";
            listMap = rehabilitationDetailDao.findByPatientAndDoctor(startTime,endTime,doctorCode,patientCode);
            String ids = "";
            for(String one2 : listMap){
                ids += ","+one2;
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        return new JSONArray(list);
    }
    /**
     * 每日康复计划提醒
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public JSONArray dailyByJob(String startTime,String endTime){
        String sql = "select d.doctor,p.patient,h.service_item_name AS serviceItemName,d.time_type AS timeType from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id left join wlyy_hospital_service_item h ON h.id=d.hospital_service_item_id where d.status!=1 and p.status=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' GROUP BY d.doctor,p.patient,d.execute_time";
//        List<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
         String doctorCode = "";
        String patientCode = "";
        List<String> listMap  = null;
       for(Map<String,Object> one:list){
            doctorCode = one.get("doctor")+"";
            patientCode = one.get("patient")+"";
            listMap = rehabilitationDetailDao.findByPatientAndDoctor(startTime,endTime,doctorCode,patientCode);
            String ids = "";
            for(String one2 : listMap){
                ids += ","+one2;
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        return new JSONArray(list);
    }
    /**
     * 更新康复计划项目操作日志并且确认完成更新status.
     * @param node
     * @param image
     * @param planDeatilId
     * @return
     */
    public Map<String,Object> updateNodeAndRelationRecordImg(String node,String image,String status,String planDeatilId,String relationCode)throws Exception{
        Map<String,Object> resultMap = new HashedMap();
        try{
            RehabilitationDetailDO detailDO = rehabilitationDetailDao.findById(planDeatilId);
            detailDO.setStatus(1);
            if (StringUtils.isNoneBlank(status)){
                detailDO.setStatus(Integer.parseInt(status));
            }
            detailDO.setUpdateTime(new Date());
            if (StringUtils.isNoneBlank(relationCode)){
                detailDO.setRelationCode(relationCode);
            }
            rehabilitationDetailDao.save(detailDO);
            if (StringUtils.isNoneBlank(image)&&StringUtils.isNoneBlank(node)){
                int j = rehabilitationOperateRecordsDao.updateNodeAndRelationRecordImg(node,image,planDeatilId);
            }
            else if (StringUtils.isNoneBlank(node)){
                int j = rehabilitationOperateRecordsDao.updateNodeByPlanDetailId(node,planDeatilId);
            }
            else if (StringUtils.isNoneBlank(image)){//
                int j = rehabilitationOperateRecordsDao.updateImagByPlanDetailId(image,planDeatilId);
            }
            else{//跟新为已完成
                int j = rehabilitationOperateRecordsDao.updateStatus(1,planDeatilId);
            }
            //如果整个计划的服务项都完成了,整个计划也完成了
            String allSql ="SELECT * FROM wlyy_rehabilitation_plan_detail where plan_id = (SELECT plan_id FROM `wlyy_rehabilitation_plan_detail` WHERE id='"+planDeatilId+"')";
            allSql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll(allSql);
            List<RehabilitationDetailDO> rehabilitationDetailDOList = jdbcTemplate.query(allSql,new BeanPropertyRowMapper<>(RehabilitationDetailDO.class));
            int allCount=0;
            String planId="";
            for (RehabilitationDetailDO rehabilitationDetailDO : rehabilitationDetailDOList){
                if (rehabilitationDetailDO.getStatus()==1){
                    allCount++;
                }
            }
            if (rehabilitationDetailDOList.size()>0 && rehabilitationDetailDOList.size()==allCount){
                planId = rehabilitationDetailDOList.get(0).getPlanId();
                patientRehabilitationPlanDao.updateStatusAndTimeById(2,planId, new Date());
            }
        }catch (Exception e){
            throw  new Exception("更新服务状态失败!");
        }
        //更新返回数据提供发送消息使用
        String sql ="SELECT" +
                " i.id as \"id\"," +
                " r.doctor_code," +
                " r.patient_code," +
                " pd.hospital" +
                " FROM" +
                " wlyy_rehabilitation_plan_detail pd" +
                " LEFT JOIN wlyy_rehabilitation_service_item i ON pd.hospital_service_item_id = i.id" +
                " LEFT JOIN wlyy_rehabilitation_operate_records r ON pd.id = r.rehabilitation_detail_id" +
                " WHERE" +
                " pd.id = '"+planDeatilId+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if (list!=null && list.size()>0){
            resultMap = list.get(0);
        }
        String itemSql ="SELECT evaluation,title FROM `wlyy_service_item` WHERE id='"+String.valueOf(resultMap.get("id"))+"'";
        List<Map<String,Object>> itemList = jdbcTemplate.queryForList(itemSql);
        if (itemList!=null && itemList.size()>0){
            resultMap.put("evaluation",itemList.get(0).get("evaluation"));
            resultMap.put("title",itemList.get(0).get("title"));
        }
        //保存wlyy_message
        List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(resultMap.get("doctor_code").toString());
        String hospotal = "";
        String patient = resultMap.get("patient_code").toString();
        String doctor = resultMap.get("doctor_code").toString();
        if (depts!=null&&depts.size()>0){
            hospotal=depts.get(0).getOrgCode();
        }
        SystemMessageDO message = new SystemMessageDO();
        message.setType("21");
        message.setSender(patient);
        message.setReceiver(doctor);
        message.setRelationCode(planDeatilId);
        specialistEvaluateSevice.sendMessage(message,hospotal,patient,null,null);
        //发送微信模板消息
        int evaluation = resultMap.get("evaluation")==null?0:Integer.parseInt(resultMap.get("evaluation").toString());
        if (evaluation == 1){
            String serviceItemId = resultMap.get("service_item_id").toString();
            String title = resultMap.get("title").toString();
            BasePatientDO p = basePatientDao.findById(patient);
            BaseDoctorDO doctor1 = baseDoctorDao.findById(doctor);
            String patientName = p.getName();
            String openId = p.getOpenid();
            /*WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_doctor_service","fwxmpj");
            String first = templateConfig.getFirst();
            first = first.replace("key1",(patientName==null?"":patientName));
            String keyword1 = templateConfig.getKeyword1();
            org.json.JSONObject json = new org.json.JSONObject();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            json.put("keyword1", title);
            json.put("keyword2",doctor1.getName());
            json.put("keyword3", sdf.format(new Date()));
            json.put("toUser", p.getCode());
            json.put("represented",p.getCode());//被代理人
            json.put("remark", "");
            json.put("doctor",doctor);
            json.put("planIds", planDetailId);
            first = first.replace("key2",title);
            json.put("first", first);
            if(StringUtils.isNotBlank(p.getOpenid())){
                pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 25, openId, p.getName(), json);
            }else {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(), p.getOpenid());
                if (jsonArray != null && jsonArray.length() > 0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        org.json.JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        org.json.JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        data.remove("first");
                        data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                        pushMsgTask.putWxMsg(accessTokenUtils.getAccessToken(), 25, member.getOpenid(), p.getName(), data);
                    }
                }
            }*/
        }
        return resultMap;
    }
    /**
     * 电话关怀拨打电话后生成对应记录
     * @param jsonStr
     */
    public RehabilitationOperateRecordsDO planDetailAfterCall(String jsonStr){
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        /*{
            "rehabilitationDetailId":"808080eb764ba46b017669712c640012",
                "doctorCode":"7e06886207e843948ae65d8f91d6ca97",
                "doctorName":"兰冠勇"
        }*/
        RehabilitationDetailDO rehabilitationDetailDO = rehabilitationDetailDao.findById(jsonObject.getString("rehabilitationDetailId"));
        PatientRehabilitationPlanDO patientRehabilitationPlanDO = patientRehabilitationPlanDao.findById(rehabilitationDetailDO.getPlanId());
        RehabilitationOperateRecordsDO rehabilitationOperateRecordsDO = new RehabilitationOperateRecordsDO();
        rehabilitationOperateRecordsDO.setId(getCode());
        if (rehabilitationDetailDO.getExecuteTime()!=null){
            rehabilitationOperateRecordsDO.setReserveTime(rehabilitationDetailDO.getExecuteTime());
        }
        rehabilitationOperateRecordsDO.setStatus(3);
        rehabilitationOperateRecordsDO.setRelationRecordImg("[]");
        rehabilitationOperateRecordsDO.setRehabilitationDetailId(rehabilitationDetailDO.getId());
        rehabilitationOperateRecordsDO.setPatientCode(patientRehabilitationPlanDO.getPatient());
        rehabilitationOperateRecordsDO.setPatientName(patientRehabilitationPlanDO.getName());
        rehabilitationOperateRecordsDO.setDoctorCode(jsonObject.getString("doctorCode"));
        rehabilitationOperateRecordsDO.setDoctorName(rehabilitationDetailDO.getDoctorName());
        rehabilitationOperateRecordsDO.setRelationRecordType(5);
        rehabilitationOperateRecordsDO.setCompleteTime(new Date());
        rehabilitationOperateRecordsDO.setCreateTime(new Date());
        rehabilitationOperateRecordsDO.setUpdateTime(new Date());
        if (StringUtils.isNoneBlank(rehabilitationDetailDO.getFrequencyCode())){//限定频次的
            rehabilitationDetailDO.setStatus(3);
            rehabilitationDetailDao.save(rehabilitationDetailDO);
//            rehabilitationOperateRecordsDO.setRelationRecordType(8);
        }
        return rehabilitationOperateRecordsDao.save(rehabilitationOperateRecordsDO);
    }
    /**
     * 更新康复计划项目状态
     * @param status
     * @param planDetailId
     * @return
     */
    public Envelop updatePlanDetailStatusById(Integer status,String planDetailId) throws Exception{
        if(rehabilitationDetailDao.updateStatusById(status,planDetailId)>0){
            return Envelop.getSuccess(SpecialistMapping.api_success);
        }
        return Envelop.getError("更新失败!");
    }
    public Envelop updatePlanDetailExecuteTimeById(Date executeTime,String planDetailId) throws Exception{
        if(rehabilitationDetailDao.updateExecuteTime(executeTime,planDetailId)>0){
            return Envelop.getSuccess(SpecialistMapping.api_success);
        }
        return Envelop.getError("更新失败!");
    }
    /**
     * 计划总进度
     * @return
     */
    public ObjEnvelop planSchedule(String planId,String patientCode){
        Map<String,Object> resultMap = new HashMap<>();
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);//计划总服务项目数
        Integer finishedCount = rehabilitationDetailDao.findByStatusAndPlanId(1,planId);
        PatientRehabilitationPlanDO p =patientRehabilitationPlanDao.findById(planId);
        List<DoctorPatientRelationDO> doctorPatientRelationDO= doctorPatientRelationDao.findByDoctorAndPatient(p.getCreateUser(),p.getPatient());
        List<RehabilitationDetailDO> details=rehabilitationDetailDao.findByPlanId(planId);
        String doctor="";
        String doctorName="";
        if (details!=null&&details.size()>0){
            doctor=details.get(0).getDoctor();
            doctorName=details.get(0).getDoctorName();
        }
        resultMap.put("allCount",allCount);
        resultMap.put("finishedCount",finishedCount);
        resultMap.put("specialistPatientRelationDO",doctorPatientRelationDO);
        if (p!=null){
            resultMap.put("disease",p.getDisease());
            resultMap.put("diseaseName",p.getDiseaseName());
            resultMap.put("createUser",p.getCreateUser());
            resultMap.put("planTitle",p.getTitle());
            resultMap.put("status", p.getStatus());
            resultMap.put("isVerify", p.getIsVerify());
            resultMap.put("patientImg", p.getPatientImg());
            resultMap.put("adviceContent",p.getAdviceContent());
            resultMap.put("createTimeDate",DateUtil.dateToStr(p.getCreateTime(),"yyyy-MM-dd"));
            resultMap.put("createTime", DateUtil.dateToStr(p.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            resultMap.put("medicalRecordsCode",p.getMedicalRecordsCode());
            List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(p.getCreateUser());
            if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
                resultMap.put("createUserName",p.getCreateUserName());
                resultMap.put("createUserDept",baseDoctorHospitalDO.get(0).getDeptCode());
                resultMap.put("createUserDeptName",baseDoctorHospitalDO.get(0).getDeptName());
            }
            List<BaseDoctorHospitalDO> baseDoctorHospitalDOTo = baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (baseDoctorHospitalDOTo!=null&&baseDoctorHospitalDOTo.size()>0){
                resultMap.put("doctorName",doctorName);
                resultMap.put("doctor",doctor);
                resultMap.put("doctorDept",baseDoctorHospitalDOTo.get(0).getDeptCode());
                resultMap.put("doctorDeptName",baseDoctorHospitalDOTo.get(0).getDeptName());
            }
            PatientMedicalRecordsDO patientMedicalRecordsDO = patientMedicalRecordsDao.findByCode(p.getMedicalRecordsCode());
            resultMap.put("patientMedicalRecordsDO",patientMedicalRecordsDO);
        }
        BasePatientDO basePatientDO = basePatientDao.findById(patientCode);
        Integer age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
        String sex = IdCardUtil.getSexForIdcard_new(basePatientDO.getIdcard());
        resultMap.put("sex","1".equals(sex)?"男":("2".equals(sex)?"女":"未知"));
        resultMap.put("age",age);
        resultMap.put("patientPhoto",basePatientDO.getPhoto());
        resultMap.put("patientName",basePatientDO.getName());
        resultMap.put("patientCode",basePatientDO.getId());
        resultMap.put("idcard",basePatientDO.getIdcard());
//        resultMap.put("healthyCondition",healthyCondition);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
    }
    /**
     * 根据居民获取康复计划
     * @param patient
     * @return
     */
    public ObjEnvelop planListByPatient(String patient){
        List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatients(patient);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
    }
    /**
     * 医生已计划数,已完成计划数(居民数)
     * @param doctorCode
     * @return
     */
    public ObjEnvelop patientCount(String doctorCode){
        Integer count =patientRehabilitationPlanDao.patientCount(doctorCode);
        Integer finishCount = patientRehabilitationPlanDao.getFinishPatientCount(doctorCode);
        Map<String,Object> map = new HashMap<>();
        map.put("planCount",count);
        map.put("finishedPlanCount",finishCount);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
    }
    public JSONArray dailyJobReserve1(String startTime, String endTime){
        String sql = "select DISTINCT d.doctor,p.patient,d.hospital from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " left join wlyy_hospital_service_item h on d.hospital_service_item_id=h.id  " +
                " left join wlyy_service_item i on i.id =h.service_item_id "+
                " where d.status!=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' and i.reserve=1 and p.status!=0 and d.status=0 ";
//        List<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        String doctorCode = "";
        String patientCode = "";
//        List<String> listMap  = null;
        for(Map<String,Object> one:list){
            doctorCode = one.get("doctor")+"";
            patientCode = one.get("patient")+"";
            String sql2 ="select d.id from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                    " left join wlyy_hospital_service_item h on d.hospital_service_item_id=h.id " +
                    " left join wlyy_service_item i on i.id =h.service_item_id "+
                    " where d.status!=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' and i.reserve=1 and d.doctor='"+doctorCode+"' and p.patient='"+patientCode+"'";
            List<Map<String,Object>> list2 = jdbcTemplate.queryForList(sql2);
//            listMap = rehabilitationDetailDao.findByPatientAndDoctor(startTime,endTime,doctorCode,patientCode);
            String ids = "";
            for(Map<String,Object> one2 : list2){
                ids += ","+one2.get("id");
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        return new JSONArray(JSON.toJSONString(list));
    }
    /**
     * 根据ids获取数据
     *
     * @param ids
     * @return
     */
    public ObjEnvelop selectByIds(String ids){
        ObjEnvelop envelop = new ObjEnvelop();
        List idList = Arrays.asList(ids.split(","));
        StringBuffer buffer = new StringBuffer();
        for (int i =0;i<idList.size();i++){
            buffer.append("'"+idList.get(i)+"'").append(",");
        }
        buffer.deleteCharAt(buffer.length()-1);
        String sql = "select * from wlyy_rehabilitation_plan_detail where id in("+buffer+")";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll(sql);
        List<RehabilitationDetailDO> rehabilitationDetailDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(RehabilitationDetailDO.class));
        envelop.setObj(rehabilitationDetailDOS);
        return envelop;
    }
    /**
     * 查询频次列表
     *
     * @return
     */
    public List<Frequency> selectFrequences(){
        List<Frequency> frequencieList = frequencyDao.findByDel();
        return frequencieList;
    }
    public ObjEnvelop getServiceItemsAfterStop(String planId)throws Exception{
        Map<String,Object> reslutMap = new HashMap<>();
        String sql ="SELECT" +
                " p.patient," +
                " p.name," +
                " p.title," +
                " p.disease_name,p.abort_reason,p.abort_time,p.create_time,p.patient_img," +
                " a.*" +
                " FROM" +
                " wlyy_patient_rehabilitation_plan p" +
                " LEFT JOIN (" +
                "  SELECT" +
                "  d.id," +
                "  d.plan_id," +
                "  d.hospital," +
                "  d.hospital_name," +
                "  i.code as service_item_id," +
                "  i.name as service_item_name," +
                "  d.expense," +
                "  r.doctor_code," +
                "  r.doctor_name," +
                "  r.complete_time, " +
                "  i.code as item_type " +
                "  FROM" +
                "  wlyy_rehabilitation_plan_detail d" +
                "  LEFT JOIN wlyy_rehabilitation_service_item i ON d.hospital_service_item_id = i.code  "+
                "  LEFT JOIN wlyy_rehabilitation_operate_records r ON d.id = r.rehabilitation_detail_id" +
                "  WHERE" +
                "  r.`status` = 1" +
                " ) a ON p.id = a.plan_id" +
                " WHERE" +
                " p.id = '"+planId+"'";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_operate_recordsDoctorName(sql);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);//计划总服务项目数
        Integer finishCount = list.size();//完成服务项目数
        double totalExpense = 0;
        Set<String> hospitalSet = new HashSet();
        Set<String> serviceDoctor = new HashSet();
        DecimalFormat df = new DecimalFormat("0.00");
        for (Map<String,Object> map : list){
            double expense = 0;
            if (StringUtils.isNotEmpty(String .valueOf(map.get("expense"))) && !"null".equals(String .valueOf(map.get("expense")))){
                expense =Integer.valueOf(String .valueOf(map.get("expense")));
            }
            totalExpense += expense;
            map.put("expense",df.format(expense/100));
            //组装机构和服务医生
            if(map.get("hospital") != null){
                if(map.get("hospital_name") != null && !hospitalSet.contains(("hospital_name") + "")) {
                    hospitalSet.add(map.get("hospital_name") + "");
                }
            }
            if(map.get("doctor_code") != null){
                if(map.get("doctor_name") != null && !hospitalSet.contains(("doctor_name") + "")) {
                    serviceDoctor.add(map.get("doctor_name") + "");
                }
            }
        }
        reslutMap.put("totalExpense",df.format(totalExpense/100));
        reslutMap.put("allCount",allCount);
        reslutMap.put("finishCount",finishCount);
        reslutMap.put("serviceList",list);
        reslutMap.put("hospitalAll", hospitalSet.toString().replace("[","").replace("]","").replace(",", "、"));
        reslutMap.put("serviceDoctor", serviceDoctor.toString().replace("[","").replace("]","").replace(",", "、"));
        if (list!=null&&list.size()>0){
            reslutMap.put("patientName",list.get(0).get("name"));
            reslutMap.put("abortTime",list.get(0).get("abort_time"));
            reslutMap.put("hospitalName",list.get(0).get("hospital_name"));
            reslutMap.put("abortReason",list.get(0).get("abort_reason"));
            String patientCode = String.valueOf(list.get(0).get("patient"));
            reslutMap.put("patientCode", patientCode);
            reslutMap.put("disease_name", list.get(0).get("disease_name"));
            reslutMap.put("create_time", list.get(0).get("create_time"));
            reslutMap.put("patient_img", list.get(0).get("patient_img"));
            BasePatientDO patient = basePatientDao.findById(patientCode);
            if (patient!=null){
                reslutMap.put("openid", patient.getOpenid());
                reslutMap.put("ssc",patient.getSsc());
                reslutMap.put("mobile",patient.getMobile());
            }
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,reslutMap);
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public List<Map<String,Object>> getPatientAllRehabilitationPlan(String patient){
        String sql = "select p.team_code as teamCode,d.id as doctor,p.create_time as createTime,p.id,d.photo,p.title,d.idcard,YEAR (now()) - YEAR (substring(d.idcard, 7, 8)) AS age, d.sex,p.name,p.patient,p.disease_name,d.name as doctorName,p.advice_content as adviceContent,p.medical_records_code as medicalRecordsCode,p.create_time as create_time " +
                " FROM wlyy_patient_rehabilitation_plan p " +
                " LEFT JOIN base_doctor d ON d.id = p.create_user " +
                "WHERE p.patient='"+patient+"'";
        sql = sql +" union "+
                "SELECT p.team_code as teamCode,d.id AS doctor," +
                "p.create_time AS createTime," +
                "p.id," +
                "d.photo," +
                "p.title," +
                "d.idcard,YEAR (now())-YEAR (substring(d.idcard,7,8)) AS age," +
                "d.sex,p.name," +
                "p.patient," +
                "p.disease_name,"+
                "d.NAME AS doctorName," +
                "p.advice_content AS adviceContent," +
                "p.medical_records_code AS medicalRecordsCode," +
                "p.create_time AS create_time " +
                "FROM " +
                "wlyy_patient_rehabilitation_plan p " +
                "LEFT JOIN base_doctor d ON d.id=p.create_user" +
                " LEFT JOIN (" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code " +
                "FROM wlyy_doctor_patient_relation sr " +
                "JOIN wlyy_doctor_special_share se ON se.special_code=sr.id " +
                "WHERE sr.patient='"+patient+"') d " +
                "ON d.patient=p.patient WHERE " +
                "p.patient='"+patient+"' " +
                " "+
                "ORDER BY create_time DESC";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> result = new ArrayList<>();
        List<Map<String,Object>> hadManage = new ArrayList<>();
        for (Map<String,Object> mp:mapList){//获下转状态
            Date createTimeDate = DateUtil.strToDateLong(mp.get("createTime").toString());
            mp.put("createTimeDate",DateUtil.dateToStrShort(createTimeDate));
            String mpDoctor = mp.get("doctor").toString();
            String manageStatus;
            //获取最近完成服务
            sql = "select si.`code`,si.name,opr.complete_time update_time \n" +
                    "from wlyy_rehabilitation_plan_detail pd \n" +
                    "INNER  JOIN wlyy_rehabilitation_service_item si on si.`code` = pd.hospital_service_item_id \n" +
                    "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pd.id\n" +
                    "where plan_id='"+mp.get("id").toString()+"' and opr.`status` =1 ORDER BY opr.complete_time DESC ";
            List<Map<String,Object>> serverItems = jdbcTemplate.queryForList(sql);
            if(serverItems!=null&&serverItems.size()!=0){
                mp.put("completeServer",serverItems.get(0));
            }
            else{
                mp.put("completeServer","");
            }
            try {
                manageStatus = jdbcTemplate.queryForObject(sql,String.class);
            }catch (Exception e){
                manageStatus="0";
            }
            if (StringUtils.isBlank(manageStatus)||manageStatus.equals("0")){//已下转,即未接收
                mp.put("turnDownState",1);
                result.add(mp);
            }
            else{//已接受
                mp.put("turnDownState",2);
                hadManage.add(mp);
            }
        }
        result.addAll(hadManage);
        return  result;
    }
    public List<Map<String,Object>> selectByGuidance(String planId,String itemCode){
        String sql ="SELECT gm.* FROM wlyy_guidance_message_log gm LEFT JOIN wlyy_rehabilitation_plan_detail pd ON pd.id = gm.plan_detail_id " +
                "WHERE pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id = '"+itemCode+"' ORDER BY gm.create_time DESC ";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    @Transactional
    public String manageAllPlanByPatient(String patient,String doctor){
        String sql = "SELECT re.id,re.doctor,re.doctor_name as doctor_name,pl.id planId,pl.name as patientName,pl.create_user,pl.create_user_name specialDoctorName  \n" +
                "from  wlyy_patient_rehabilitation_plan pl \n" +
                "INNER JOIN  wlyy_doctor_patient_relation re\n" +
                "on pl.patient = re.patient \n" +
                "where   re.`status`>=0  \n" +
                "and  pl.patient ='"+patient+"' and (re.is_manage<>1 or re.is_manage is NULL) ";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        List<Map<String,Object>> planIds = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> planByCreate = jdbcTemplate.queryForList(sql+" GROUP BY pl.create_user");
        for (Map<String,Object> tmp:planIds){
            sql ="update wlyy_doctor_patient_relation set is_manage=1,manage_user ='"+doctor+"', manage_time ='"+DateUtil.getStringDate()+"' where id='"+tmp.get("id").toString()+"' ";
            jdbcTemplate.execute(sql);
        }
        BaseDoctorDO doctorObject = baseDoctorDao.findById(doctor);//家庭医生
        //接收患者时,给服务医生群组发送消息
        List<String> patientRelationDoctor = new ArrayList<>();
        for (Map<String,Object> tmp:planByCreate){
            try {
                if(!patientRelationDoctor.contains(tmp.get("doctor").toString())){
                    //guidanceService.sendSpecialistWeixinMessage(patient,tmp.get("doctor").toString(),2,null,null,null);
                    patientRelationDoctor.add(tmp.get("doctor").toString());
                }
                //患者服务医生群组发送Im消息
                com.alibaba.fastjson.JSONArray serverDoctorList =selectPlanServerDoctor(tmp.get("planId").toString(),doctor);
                int length = serverDoctorList.size();
                for (int i=0;i<length;i++){
                    JSONObject serverJson = serverDoctorList.getJSONObject(i);
                    if (serverJson.getString("type").equals("4")){
                        String sessionId = serverJson.getString("sessionId");
                        String message= tmp.get("specialDoctorName").toString()+"医生您好,我已确认接收管理患者"+tmp.get("patientName").toString()+",谢谢。";
                        imUtil.sendImMsg(doctor,doctorObject.getName(),sessionId,"1",message,"1","");
                    }
                }
                //发送模板消息
                /*if(messageService.getMessageNoticeSettingByMessageType(tmp.get("create_user").toString(),"1", MessageNoticeSetting.MessageTypeEnum.systemSwitch.getValue())) {
                    Doctor specialistDoctor = doctorDao.findByCode(tmp.get("create_user").toString());
                    if(StringUtils.isNoneBlank(specialistDoctor.getOpenid())){
                        Doctor SignDoctor = doctorDao.findByCode(doctor);
                        Patient p = patientDao.findByCode(patient);
                        //[医生姓名]医生您好,[医生姓名]医生已确认接收您的康复下转患者[患者姓名],请访问厦门i健康APP康复管理查看。
                        String first = specialistDoctor.getName() + "医生您好,"+SignDoctor.getName()+"医生已确认接收您的康复下转患者"
                                + p.getName() +",请访问厦门i健康APP康复管理查看。";
                        if (StringUtils.isNoneBlank(specialistDoctor.getOpenid())){
                            doctorAssistantUtil.sendWXTemplate(2,specialistDoctor.getOpenid(),first,"请及时处理","康复管理","已接收");
                        }
                    }
                }*/
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public com.alibaba.fastjson.JSONArray  selectPlanServerDoctor(String planId,String doctorCode) throws Exception{
        String sql ="SELECT t.patient,t.create_user FROM wlyy_patient_rehabilitation_plan t  where t.id='"+planId+"'";//专科
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        String patient = "";
        for (Map<String,Object> map:mapList){
            String doctor =map.get("create_user").toString();
            patient = map.get("patient").toString();
            JSONObject object = new JSONObject();
            BaseDoctorDO doctor1 = baseDoctorDao.findById(doctor);
            object.put("code",doctor1.getId());
            object.put("name",doctor1.getName());
            object.put("level",doctor1.getLevel());
            /*object.put("hospital",doctor1.getHospital());
            object.put("hospitalName",doctor1.getHospitalName());*/
            if (doctor1.getLevel()==1){
                object.put("levelName","专科医生");
            }else if (doctor1.getLevel()==2){
                object.put("levelName","全科医生");
            }
            object.put("photo",doctor1.getPhoto());
            object.put("idcard",doctor1.getIdcard());
            jsonArray.add(object);
        }
        /*SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if (signFamily!=null){
            org.json.JSONObject object = new org.json.JSONObject();
            BaseDoctorDO doctor1 = baseDoctorDao.findById(signFamily.getDoctor());
            object.put("code",doctor1.getId());
            object.put("name",doctor1.getName());
            if (doctor.getLevel()==1){
                object.put("levelName","专科医生");
            }else if (doctor.getLevel()==2){
                object.put("levelName","全科医生");
            }
            object.put("photo",doctor.getPhoto());
            object.put("idcard",doctor.getIdcard());
            object.put("hospital",doctor.getHospital());
            object.put("hospitalName",doctor.getHospitalName());
            array.put(object);
            org.json.JSONObject object1 = new org.json.JSONObject();
            if (StringUtils.isNoneBlank(signFamily.getDoctorHealth())){
                BaseDoctorDO doctor1 = baseDoctorDao.findById(signFamily.getDoctorHealth());
                object1.put("code",doctor1.getId());
                object1.put("name",doctor1.getName());
                object1.put("level",3);
                object1.put("levelName","健管师");
                object1.put("photo",doctor1.getPhoto());
                object1.put("idcard",doctor1.getIdcard());
                object.put("hospital",doctor1.getHospital());
                object.put("hospitalName",doctor1.getHospitalName());
                array.put(object1);
            }
        }*/
        StringBuilder serverGroupSessionId =new StringBuilder();//群聊session_id
        StringBuilder serverGroupSessionName =new StringBuilder();//群聊名称
        JSONObject participants = new JSONObject();//群聊成员
        if (jsonArray!=null){
            for(int i=0;i<jsonArray.size();i++){//获取服务医生P2P 未读消息以及session_id。
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                serverGroupSessionId.append(jsonObject.getString("code")+"_");
                serverGroupSessionName.append(jsonObject.getString("name")+"、");
                participants.put(jsonObject.getString("code"),0);
                if(jsonObject.getString("code").equals(doctorCode)){//
                    jsonObject.put("unRead",0);
                    jsonObject.put("sessionId","");
                    jsonObject.put("type","");
                    jsonObject.put("business_type","");
                    continue;
                }
                //服务医生间的消息获取
                JSONObject participantsP2P = new JSONObject();
                participantsP2P.put(doctorCode,0);
                participantsP2P.put(jsonObject.getString("code"),0);
                //获取登录医生与其他服务医生的session_id
                //{"data":{"business_type":1,"name":"余研","id":"3438fdc6c1082c7b3c3e93dc27da244b59b694dc","type":"2","create_date":1603436112458},"status":200}
                JSONObject result = imUtil.createSession(participantsP2P,"2",jsonObject.getString("name"),null);
                jsonObject.put("sessionId",result.getJSONObject("data").getString("id"));
                jsonObject.put("type",result.getJSONObject("data").getString("type"));
                jsonObject.put("business_type",result.getJSONObject("data").getInteger("business_type"));
                //获取未读消息
                result  = imUtil.getSessionUnreadMessageCount(jsonObject.getString("sessionId"),doctorCode);
                jsonObject.put("unRead",result.getInteger("count"));
            }
        }
        //服务医生群聊数据获取
       JSONObject groupObject = new JSONObject();
        if(StringUtils.isNoneBlank(serverGroupSessionId)&&StringUtils.isNoneBlank(serverGroupSessionName)){
            serverGroupSessionId.append("server_group");
            serverGroupSessionName=serverGroupSessionName.deleteCharAt(serverGroupSessionName.length()-1);
            if(imUtil.sessionIsExist(serverGroupSessionId+"")){//会话存在
                JSONObject result  = imUtil.getSessionUnreadMessageCount(serverGroupSessionId+"",doctorCode);
                groupObject.put("unRead",result.getInteger("count"));
            }
            else{
                JSONObject result = imUtil.createSession(participants,"4",serverGroupSessionName+"",serverGroupSessionId+"");
                groupObject.put("unRead",0);
            }
            groupObject.put("name",serverGroupSessionName);
            groupObject.put("sessionId",serverGroupSessionId.toString());
            groupObject.put("business_type",1);
            groupObject.put("type","4");
        }
        jsonArray.add(groupObject);
        return  jsonArray;
    }
    /**
     * 每天8点,16点的job
     * @param startTime
     * @param endTime
     * @throws Exception
     */
    public void dailyJobSendMessage(String startTime,String endTime,Integer type) throws Exception{
        JSONArray jsonArray = dailyJob(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        Integer num = null;
        String planDetailIds = null;
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            num = (Integer)jsonObject.get("num");//需要今日需要执行的项目数
            planDetailIds = jsonObject.get("planDetailIds")+"";
            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
            message1.setType(type.toString());
            message1.setReceiver(doctor);
            message1.setRelationCode(planDetailIds);
//            specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
        }
    }
    /**
     * 每天15点的job
     * @param startTime
     * @param endTime
     * @throws Exception
     */
    public void tomorrowJobSendMessage(String startTime,String endTime,Integer type) throws Exception{
        JSONArray jsonArray =tomorrowJob(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        Integer num = null;
        String planDetailIds = null;
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            num = (Integer)jsonObject.get("num");//需要今日需要执行的项目数
            planDetailIds = jsonObject.get("planDetailIds")+"";
            String planId = jsonObject.get("id")+"";
            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
            message1.setType(type.toString());
            message1.setReceiver(doctor);
            message1.setRelationCode(planDetailIds);
            message1.setReason(planId);
//            specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
        }
    }
    /**
     * 每15分钟的job
     *
     * @param startTime
     * @param endTime
     * @param type
     * @throws Exception
     */
    public void dailyByJobSendMessage(String startTime,String endTime,Integer type) throws Exception{
        JSONArray jsonArray = dailyByJob(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        Integer num = null;
        String serviceItemName = null;
        String planDetailIds = null;
        Long timeType = null;
        String nowDate = DateUtil.getStringDate();
        String date9 = DateUtil.getStringDateShort()+" 09:00:00";//白天
        String date21 = DateUtil.getStringDateShort()+" 21:00:00";//白天
        String date9s = DateUtil.getNextDay(DateUtil.getNowDate(),1)+" 09:00:00";//晚上
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            /*num = (Integer)jsonObject.get("num");//需要今日需要执行的项目数*/
            planDetailIds = jsonObject.get("planDetailIds")+"";
            serviceItemName = jsonObject.getString("serviceItemName");
            timeType = jsonObject.getLong("timeType");
            if (timeType!=null){
                if (timeType==1  && nowDate.compareTo(date9)==1&&nowDate.compareTo(date21)==-1){
                    SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
                    message1.setType(type.toString());
                    message1.setReceiver(doctor);
                    message1.setRelationCode(planDetailIds);
                    message1.setData(serviceItemName);
//                    specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
                }else if (timeType==2 && nowDate.compareTo(date21)==1&&nowDate.compareTo(date9s)==-1){
                    SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
                    message1.setType(type.toString());
                    message1.setReceiver(doctor);
                    message1.setRelationCode(planDetailIds);
                    message1.setData(serviceItemName);
//                    specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
                }else if (timeType==0){
                    SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
                    message1.setType(type.toString());
                    message1.setReceiver(doctor);
                    message1.setRelationCode(planDetailIds);
                    message1.setData(serviceItemName);
//                    specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
                }
            }
        }
    }
    public void dailyJobReserve(Integer num,Integer type) throws Exception{
        Long time = num*24*60*60*1000L;
        String startTime = DateUtil.dateToStrShort(new Date(new Date().getTime()+time))+" "+"00:00:00";
        String endTime = DateUtil.dateToStrShort(new Date(new Date().getTime()+time))+" "+"23:59:59";
        JSONArray jsonArray=dailyJobReserve1(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        String hospital ="";
        String planDetailIds = null;
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            hospital = jsonObject.get("hospital")+"";//医院
            planDetailIds = jsonObject.get("planDetailIds")+"";
            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
            message1.setType(type.toString());
            message1.setReceiver(doctor);
            message1.setRelationCode(planDetailIds);
//            specialistEvaluateSevice.sendMessage(message1,hospital,patient,num,null);
        }
    }
    public List<PatientMedicalRecordsDO> selectByMedicalCode(String code){
        String str[] = code.split(",");
        List<PatientMedicalRecordsDO> medicalRecordsDOS= new ArrayList<>();
        for (int i=0;i<str.length;i++){
            PatientMedicalRecordsDO medicalRecordsDO = medicalRecordsRehabilitationDao.findByCode(str[i]);
            medicalRecordsDOS.add(medicalRecordsDO);
        }
        return medicalRecordsDOS;
    }
    public List<Map<String,Object>> selectAllCompleteServiceItemsByPatient(String patient){
        List<Map<String,Object>> resutList = new ArrayList<>();
        String sql ="select A.id 'planId',pdl.id,pdl.frequency_code,A.patient,A.`name`,si.id 'code',si.`name` 'serviceName',opr.complete_time 'czrq' from  \n" +
                "(select p.team_code as teamCode,d.code as doctor,p.create_time as createTime,p.id,p.patient,p.name " +
                "from wlyy_patient_rehabilitation_plan p\n" +
                "LEFT JOIN base_doctor d ON d.id = p.create_user\n" +
                "WHERE p.patient='"+patient+"'\n" +
                "union\n" +
                "SELECT p.team_code as teamCode,d.CODE AS doctor,p.create_time AS createTime,p.id,p.patient,p.name " +
                "from \n" +
                " wlyy_patient_rehabilitation_plan p\n" +
                "LEFT JOIN base_doctor d ON d.id=p.create_user\n" +
                "LEFT JOIN (\n" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code \n" +
                "FROM wlyy_doctor_patient_relation sr \n" +
                "JOIN wlyy_doctor_special_share se ON se.special_code=sr.id \n" +
                "WHERE sr.patient='"+patient+"') d \n" +
                "ON d.patient=p.patient WHERE \n" +
                "p.patient='"+patient+"' \n" +
                "\n" +
                "ORDER BY createTime DESC)A \n" +
                "INNER  JOIN wlyy_rehabilitation_plan_detail pdl ON A.id = pdl.plan_id\n" +
                "INNER JOIN wlyy_rehabilitation_service_item si on pdl.hospital_service_item_id = si.id\n" +
                "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pdl.id\n" +
                "where pdl.hospital_service_item_id <>2 and  opr.`status`=1 order by opr.complete_time desc ";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> planDetailList = jdbcTemplate.queryForList(sql);
        resutList.addAll(planDetailList);
        //康复咨询
        sql= "select ct.consult,ct.type,ct.patient,ct.name,ct.czrq,ct.symptoms,top.`status`,top.end_time,top.evaluate,top.evaluate_time,top.reply,top.reply_time, '2' as 'serviceId','康复咨询' as 'serviceName'\n" +
                "from wlyy_consult_team ct\n" +
                "INNER JOIN im_internet_hospital.topics top on top.id = ct.consult \n" +
                "where ct.patient='"+patient+"' and ct.type=18 and ct.del=1";
        List<Map<String,Object>> kangFuList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:kangFuList){
            if (map.get("status").toString().equals("0")&&map.get("reply").toString().equals("0")){
                map.put("serviceStatus","未回复");
            }
            if (map.get("status").toString().equals("0")&&map.get("reply").toString().equals("1")){
                map.put("serviceStatus","未结束");
            }
            if (map.get("status").toString().equals("10")){//&&map.get("evaluate").toString().equals("0")
                map.put("serviceStatus","已结束");
            }
//            if (map.get("status").toString().equals("10")&&map.get("evaluate").toString().equals("1")){
//                map.put("serviceStatus","已结束");
//            }
        }
        resutList.addAll(kangFuList);
        Collections.sort(resutList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Timestamp map1value = (Timestamp) o1.get("czrq");
                Timestamp  map2value = (Timestamp) o2.get("czrq");
                int sort = 1;
                if (map1value.getTime() - map2value.getTime() > 0) {
                    return sort == 1 ? -1 : 1;
                } else if (map1value.getTime() - map2value.getTime() < 0) {
                    return sort == 1 ? 1 : -1;
                } else {
                    return 0;
                }
            }
        });
        return resutList;
    }
    public JSONArray getPlanDetailForModifing(String planId,String templateId){
        String sql;
        JSONArray result = new JSONArray();
        if(StringUtils.isBlank(templateId)){
            sql ="select id from wlyy_rehabilitation_plan_template where title='系统模板'";
            templateId = jdbcTemplate.queryForObject(sql,String.class);
        }
        sql = "select d.hospital_service_item_id as code,i.`name`\n" +
                "from wlyy_rehabilitation_template_detail d LEFT JOIN wlyy_rehabilitation_service_item i\n" +
                "ON i.`code` = d.hospital_service_item_id\n" +
                "where d.template_id = '"+templateId+"'";
        List<Map<String,Object>> templateDetailList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:templateDetailList){
            sql ="select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name \n" +
                    "from wlyy_rehabilitation_plan_detail d \n" +
                    "LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  \n" +
                    "where  d.plan_id ='"+planId+"' AND  d.execute_time IS NOT NULL  and d.execute_time <>''\n" +
                    "AND d.`status`<> 1\n" +
                    "and d.hospital_service_item_id ='"+map.get("code").toString()+"'\n" +
                    "ORDER BY hospital_service_item_id ASC,execute_time ASC;";
            sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
            List<Map<String,Object>> planDetailList = jdbcTemplate.queryForList(sql);
            org.json.JSONObject temp = new org.json.JSONObject();
            temp.put("counts",planDetailList.size());
            temp.put("code",map.get("code").toString());
            temp.put("name",map.get("name").toString());
            temp.put("list",planDetailList);
            result.put(temp);
        }
        return result;
    }
    public org.json.JSONObject selectBySpecialistDoctor(String level, String area, String doctor, String disease, Integer page, Integer pageSize, String doctorType, String patientInfo, String filterPlan, String turnDownState){
        Integer turnDownStateTotal_0=0;//全部
        Integer turnDownStateTotal_1=0;//已下转
        Integer turnDownStateTotal_2=0;//已接受
        Integer turnDownStateTotal_3=0;//未下转
        org.json.JSONObject resultObj = new org.json.JSONObject();
        BaseDoctorDO doctorObj = baseDoctorDao.findById(doctor);
        List<Map<String, Object>> result = new ArrayList<>();
        String sql = "SELECT DISTINCT pr.id,p.`name`,plan.id as planId, p.`id` as code, p.idcard,p.photo, plan.disease,plan.disease_name,YEAR (now()) - YEAR (substring(p.idcard, 7, 8)) as age," +
                "p.sex,pr.doctor AS specialist,pr.doctor_name AS specialistName,pr.disease_code,pr.doctor_name ," +
                "pr.doctor, pr.health_doctor, pr.health_doctor_name, pr.is_manage,pr.manage_user,pr.manage_time FROM" +
                " base_doctor doc,`wlyy_doctor_patient_relation` pr" +
                " LEFT JOIN base_patient p ON p.`id` = pr.patient ";
        //关联居民计划表
        if("1".equals(filterPlan)){
            sql = sql + " INNER JOIN `wlyy_patient_rehabilitation_plan` plan on plan.patient = pr.patient ";
        }
        sql =sql+ " WHERE  doc.`id` = pr.doctor  ";
        String sqlCondition = "";
        if (doctorType.equalsIgnoreCase("1")){
            sqlCondition +=" AND pr.doctor = '"+doctor+"'";
        }else {
            sqlCondition +=" AND (pr.doctor = '"+doctor+"' or pr.health_doctor = '"+doctor+"') ";
        }
        if(StringUtils.isNoneBlank(patientInfo)){
            sqlCondition +=" AND (p.idcard like '%"+patientInfo+"%' OR p.`name`like '%"+patientInfo+"%') ";
        }
       /* if (level.equalsIgnoreCase("1")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.city='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("2")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.town='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("3")){
            sqlCondition +=" and sf.hospital = '"+area+"' ";
        }*/
        /*if (StringUtils.isNoneBlank(disease)){
            sqlCondition +=" and pr.id IN (SELECT pds.specialist_relation_code FROM wlyy_patient_disease_server pds WHERE  pds.del=1 and pds.disease ='"+disease+"')";
        }*/
        //LIMIT+(page-1)*pageSize+","+pageSize
        sqlCondition += " ORDER BY pr.create_time DESC  ";
        sql += sqlCondition;
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        System.out.println("mapList"+sql);
        for (Map<String,Object> map:mapList){
            BasePatientDO patientDo = basePatientDao.findById(map.get("code").toString());
            List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (depts!=null&&depts.size()>0){
                map.put("dept_code",depts.get(0).getDeptCode());
                map.put("dept_name",depts.get(0).getDeptName());
            }
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(patientDo.getIdcard(),patientDo.getBirthday());
            map.put("age",age);
            String specialistRelationCode = map.get("id").toString();
            String relationManageState = map.get("is_manage")==null?"0":map.get("is_manage").toString();//管理状态
            /*List<PatientDiseaseServer> diseaseServers = patientDiseaseServerDao.findBySpecialistRelationCodeAndDel(specialistRelationCode,"1");
            StringBuffer diseaseName = new StringBuffer();
            for (int i=0;i<diseaseServers.size();i++){
                diseaseName.append(diseaseServers.get(i).getDiseaseName()+",");
            }
            if(StringUtils.isNoneBlank(diseaseName)){
                diseaseName.deleteCharAt(diseaseName.length()-1);
            }
            map.put("disease_name",diseaseName);*/
            if(StringUtils.isBlank(relationManageState)||!relationManageState.equals("1")){//未进行管理
                map.put("turnDownState", 1);//已下转
                turnDownStateTotal_1+=1;
                turnDownStateTotal_0+=1;
                if(turnDownState.equals("1")||turnDownState.equals("0")){
                    result.add(map);
                }
            }
            else{
                map.put("turnDownState", 2);//已管理
                turnDownStateTotal_2+=1;
                turnDownStateTotal_0+=1;
                if(turnDownState.equals("2")||turnDownState.equals("0")){
                    result.add(map);
                }
            }
        }
        //家医端未下转(签约居民,但是还未下转的居民) 专科医生端未下转(与未下转列表同-去除未家签)
        if (doctorType.equalsIgnoreCase("1")){//专科
            sql = "select null as id,p.`name`,p.`id` as code,p.idcard,p.photo,YEAR (now()) - YEAR (substring(p.idcard, 7, 8)) AS age, p.sex,d.create_user AS specialist,d.create_user_name AS specialistName,\n" +
                    " d.doctor_name,d.doctor,d.health_doctor,d.health_doctor_name,null as is_manage,null as manage_user,null as manage_time \n" +
                    "from wlyy_doctor_patient_relation d,base_patient p ,base_doctor doc where doc.`id` = d.create_user AND d.create_user='"+doctor+"' ";
        }
        sqlCondition="";
        if(StringUtils.isNoneBlank(patientInfo)){
            sqlCondition +=" AND (p.idcard like '%"+patientInfo+"%' OR p.`name`like '%"+patientInfo+"%') ";
        }
       /* if (level.equalsIgnoreCase("1")){
            sqlCondition +=" and s.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.city='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("2")){
            sqlCondition +=" and s.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.town='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("3")){
            sqlCondition +=" and s.hospital = '"+area+"' ";
        }*/
        if (StringUtils.isNoneBlank(disease)){
            sqlCondition +=" AND d.patient in (select patient from wlyy_patient_disease_server pds where pds.del=1 and pds.disease ='"+disease+"') ";
        }
        sql  = sql + sqlCondition ;
        if (doctorType.equalsIgnoreCase("1")){//专科
            sql = sql+ " \n" +
                    " AND d.patient = p.id  \n" +
                    "AND d.patient NOT IN ( SELECT i.patient FROM wlyy_patient_rehabilitation_plan i, base_patient p \n" +
                    "WHERE i.create_user='"+doctor+"' AND i. STATUS != 0  AND p. id = i.patient    \n" +
                    "GROUP BY i.patient ORDER BY i.create_time DESC) GROUP BY d.patient ORDER BY d.create_time DESC ";
        }
        List<Map<String, Object>> mapList12 = jdbcTemplate.queryForList(sql);
        System.out.println("mapList2"+sql);
        for (Map<String, Object> map : mapList12) {
            List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (depts!=null&&depts.size()>0){
                map.put("dept_code",depts.get(0).getDeptCode());
                map.put("dept_name",depts.get(0).getDeptName());
            }
            BasePatientDO patientDo = basePatientDao.findById(map.get("code").toString());
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(patientDo.getIdcard(),patientDo.getBirthday());
            map.put("age",age);
            map.put("disease_name", "暂无");
            map.put("turnDownState",3);//未下
            turnDownStateTotal_3+=1;
            turnDownStateTotal_0+=1;
            if(turnDownState.equals("3")||turnDownState.equals("0")){
                result.add(map);
            }
        }
        org.json.JSONObject turnDownStateObj = new org.json.JSONObject();
        turnDownStateObj.put("stateAll",turnDownStateTotal_0);//全部
        turnDownStateObj.put("stateDown",turnDownStateTotal_1);//已下转
        turnDownStateObj.put("stateReceive",turnDownStateTotal_2);//已接受
        turnDownStateObj.put("stateNotDown",turnDownStateTotal_3);//未下转
        resultObj.put("showList",result);
        resultObj.put("turnDownState",turnDownStateObj);
        return resultObj;
    }
    /**
     * 康复管理-生成康复下转专科医生二维码
     * @param doctorCode
     * @param teamCode
     * @param teamName
     * @return
     * @throws Exception
     */
    public String createSpecialDoctorQrCode(String doctorCode,String teamCode,String teamName) throws Exception{
        Map<String, Object> param = new HashedMap();
        String fileUrl = "";
        String appId="";
        //生成二维码图片
        String contentJsonStr="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+""+"%2fwx%2fhtml%2fkfgl%2fhtml%2frecover_manage.html%3FdoctorCode%3D"+doctorCode+"%26teamCode%3D"+teamCode+"%26teamName%3D"+teamName+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        InputStream ipt = QrcodeUtil.createQrcode(contentJsonStr, 300, "png");
        if (isneiwang) {
            // 圖片列表
            List<String> tempPaths = new ArrayList<String>();
            try {
                ObjectNode imgNode = fastDFSUtil.upload(ipt, "png", "plan_service_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 = "" + urls;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                //fileUrl = "" + CommonUtil.PrescriptionQRCodetoNeiWang(ipt);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println("服务码-----------1"+fileUrl);
        param.put("doctorCode", doctorCode);
        param.put("imageUrl",fileUrl);
        return fileUrl;
    }
    public org.json.JSONObject selectBySpecialistDoctor1(String level, String area, String doctor, String disease, Integer page, Integer pageSize, String doctorType, String patientInfo, String filterPlan, String turnDownState){
        Integer turnDownStateTotal_0=0;//全部
        Integer turnDownStateTotal_1=0;//已下转
        Integer turnDownStateTotal_2=0;//已接受
        Integer turnDownStateTotal_3=0;//未下转
        org.json.JSONObject resultObj = new org.json.JSONObject();
        List<Map<String, Object>> result = new ArrayList<>();
        String sql = "select DISTINCT t.id as \"id\"," +
                " p.name as \"name\"," +
                " p.id as \"code\"," +
                " p.idcard as \"idcard\"," +
                " p.photo as \"photo\"," +
                " p.sex as \"sex\"," +
                " t.disease as \"disease\"," +
                " t.disease_name as \"disease_name\"," +
                " YEAR (now()) - YEAR (substring(p.idcard, 7, 8)) as age," +
                " d.doctor as \"doctor\"," +
                " d.doctor_name as \"doctor_name\"," +
                " t.create_user as \"create_user\"," +
                " t.create_user_name as \"create_user_name\"," +
                " t.create_time as \"create_time\"," +
                " t.is_verify as \"is_verify\"" +
                " from wlyy_patient_rehabilitation_plan t left  join wlyy_rehabilitation_plan_detail d on t.id =d.plan_id" +
                " left join base_doctor doc on d.doctor=doc.id LEFT JOIN base_patient p ON p.`id` = t.patient" +
                " where 1=1 " ;
        if(StringUtils.isNoneBlank(patientInfo)){
            sql +=" AND (p.idcard like '%"+patientInfo+"%' OR p.`name`like '%"+patientInfo+"%') ";
        }
        if (doctorType.equalsIgnoreCase("1")){
            sql +=" AND d.doctor = '"+doctor+"'";
        }else {
            sql +=" AND (d.doctor = '"+doctor+"' or t.create_user = '"+doctor+"') ";
        }
       /* if (level.equalsIgnoreCase("1")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.city='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("2")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.town='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("3")){
            sqlCondition +=" and sf.hospital = '"+area+"' ";
        }*/
        /*if (StringUtils.isNoneBlank(disease)){
            sqlCondition +=" and pr.id IN (SELECT pds.specialist_relation_code FROM wlyy_patient_disease_server pds WHERE  pds.del=1 and pds.disease ='"+disease+"')";
        }*/
        //LIMIT+(page-1)*pageSize+","+pageSize
        sql += " ORDER BY p.create_time DESC  ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql,page,pageSize);
        System.out.println("mapList"+sql);
        for (Map<String,Object> map:mapList){
            BasePatientDO patientDo = basePatientDao.findById(map.get("code").toString());
            List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (depts!=null&&depts.size()>0){
                map.put("dept_code",depts.get(0).getDeptCode());
                map.put("dept_name",depts.get(0).getDeptName());
            }
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(patientDo.getIdcard(),patientDo.getBirthday());
            map.put("age",age);
            String specialistRelationCode = map.get("id").toString();
            String relationManageState = map.get("is_verify")==null?"0":map.get("is_verify").toString();//管理状态
            /*List<PatientDiseaseServer> diseaseServers = patientDiseaseServerDao.findBySpecialistRelationCodeAndDel(specialistRelationCode,"1");
            StringBuffer diseaseName = new StringBuffer();
            for (int i=0;i<diseaseServers.size();i++){
                diseaseName.append(diseaseServers.get(i).getDiseaseName()+",");
            }
            if(StringUtils.isNoneBlank(diseaseName)){
                diseaseName.deleteCharAt(diseaseName.length()-1);
            }
            map.put("disease_name",diseaseName);*/
            if(StringUtils.isBlank(relationManageState)||!relationManageState.equals("1")){
                map.put("turnDownState", 1);//已确认
                turnDownStateTotal_1+=1;
                turnDownStateTotal_0+=1;
                if(turnDownState.equals("1")||turnDownState.equals("0")){
                    result.add(map);
                }
            }
            else{
                map.put("turnDownState", 2);//未确认
                turnDownStateTotal_2+=1;
                turnDownStateTotal_0+=1;
                result.add(map);
            }
        }
        org.json.JSONObject turnDownStateObj = new org.json.JSONObject();
        turnDownStateObj.put("stateAll",turnDownStateTotal_0);//全部
        turnDownStateObj.put("stateDown",turnDownStateTotal_1);//已下转
        turnDownStateObj.put("stateReceive",turnDownStateTotal_2);//已接受
        turnDownStateObj.put("stateNotDown",turnDownStateTotal_3);//未下转
        resultObj.put("showList",result);
        resultObj.put("turnDownState",turnDownStateObj);
        return resultObj;
    }
    public List<Map<String,Object>> calendarPlanDetailItems(String executeStartTime, String executeEndTime, String planId, Integer searchTask, Integer status, String doctorCode) throws Exception{
        String sqlCondition = "";
        if (searchTask!=null){
            if(searchTask==8){
                sqlCondition+="and d.doctor='"+doctorCode+"' ";
            }else {
                sqlCondition+=" and i.code="+searchTask+" " ;
            }
        }
        if(status!=null){
            sqlCondition  += "and d.status="+status;
        }//服务项目
        String sql = " select d.id,d.plan_id as planId,i.code,i.name,p.patient,d.frequency_code,DATE_FORMAT(d.create_time,'%Y-%m-%d %H:%i:%s') as createTime from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p ON p.id=d.plan_id " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  " +
                " where   d.plan_id='"+planId+"' "+sqlCondition+"  group by i.code";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:mapList){
            String sql1 = "SELECT d.frequency_code,d.plan_id as planId ,d.id,DATE_FORMAT(d.create_time,'%Y-%m-%d %H:%i:%s') AS createTime " +
                    "FROM wlyy_rehabilitation_plan_detail d " +
                    "WHERE d.plan_id = '"+planId+"' and d.hospital_service_item_id='"+map.get("code")+"'ORDER BY d.create_time DESC";
            List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sql1);
            if (mapList1!=null&&mapList1.size()!=0){
                Map<String,Object> map1 = mapList1.get(0);
                map.put("frequency_code",map1.get("frequency_code"));
                map.put("planId",map1.get("planId"));
                map.put("id",map1.get("id"));
                map.put("createTime",map1.get("createTime"));
            }
        }
        for (Map<String,Object> map:mapList){
            if (!StringUtils.isNoneBlank(map.get("frequency_code").toString())){//
                String sqlCount = "SELECT ror.id,MAX(ror.complete_time) as date,count(*) as total FROM `wlyy_rehabilitation_operate_records` ror, " +
                        "wlyy_rehabilitation_plan_detail pd WHERE pd.id = ror.rehabilitation_detail_id " +
                        "AND pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id='"+map.get("code")+"' AND ror.`status`=1 ";
                List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sqlCount);
                int count = 0;
               /* if (map.get("code").toString().equalsIgnoreCase("6")){
                    String allPlanSql = "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,\n" +
                            "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,\n" +
                            "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,\n" +
                            "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,\n" +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                            "and wf.patient_code = '"+map.get("patient")+"' order by wf.followup_plan_date desc";
                    List<Map<String , Object>> allPlanList = jdbcTemplate.queryForList(allPlanSql);
                    count = allPlanList.size();
                }*/
                /*if (map.get("code").toString().equalsIgnoreCase("7")){
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`, \n" +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime \n" +
                            "FROM wlyy_prescription pr LEFT JOIN wlyy_patient p ON pr.patient = p.`code` WHERE 1=1 AND pr.patient = '"+map.get("patient")+"' AND pr.status = 100 GROUP BY pr.`code`;";
                    List<Map<String , Object>> allPrescrList = jdbcTemplate.queryForList(allPrescrSql);
                    count = allPrescrList.size();
                }
                if (mapList1!=null && mapList1.size()!=0){
                    Map<String,Object> map1 = mapList1.get(0);
                    map.put("compeletTotal",new Integer(map1.get("total").toString()) + count );
                    map.put("firstDate",map1.get("date"));
                }*/
            }else {
                int codeCount = 0 ;
               /* if (map.get("code").toString().equalsIgnoreCase("6")){ //康复随访
                    //该居民的所有随访计划,需要同步展示到康复计划-康复随访内
                    String allPlanSql = "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,\n" +
                            "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,\n" +
                            "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,\n" +
                            "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,\n" +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                            "and wf.patient_code = '"+map.get("patient")+"' order by wf.followup_plan_date desc";
                    List<Map<String , Object>> allPlanList = jdbcTemplate.queryForList(allPlanSql);
                    codeCount = allPlanList.size();
                    map.put("allPlanList",allPlanList);
                }
                if (map.get("code").toString().equalsIgnoreCase("7")){ //康复复诊
                    //居民的处方续方,需要同步展示到康复计划-康复复诊内
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`, \n" +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime \n" +
                            "FROM wlyy_prescription pr LEFT JOIN wlyy_patient p ON pr.patient = p.`code` WHERE 1=1 AND pr.patient = '"+map.get("patient")+"' AND pr.status = 100 GROUP BY pr.`code`;";
                    List<Map<String , Object>> allPrescrList = jdbcTemplate.queryForList(allPrescrSql);
                    codeCount = allPrescrList.size();
                    map.put("allPrescrList",allPrescrList);
                }*/
                String sqlCount="SELECT\n" +
                        "\tCOUNT(pd.id) AS total ,\n" +
                        "\tCOUNT(CASE WHEN pd.`status`=1 THEN 1 ELSE NULL END) AS compeletTotal\n" +
                        "FROM\n" +
                        "\t wlyy_rehabilitation_plan_detail pd\n" +
                        "WHERE\n" +
                        "\t pd.plan_id = '"+planId+"' " +
                        "AND pd.hospital_service_item_id='"+map.get("code")+"' and (pd.frequency_code IS NOT NULL AND pd.frequency_code<>'')\n";
                List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sqlCount);
                if (mapList1!=null && mapList1.size()!=0){
                    Map<String,Object> map1 = mapList1.get(0);
                    map.put("total",new Integer(map1.get("total").toString()) + codeCount);
                    map.put("compeletTotal",new Integer(map1.get("compeletTotal").toString()) + codeCount);
                }
                String dateSql = "SELECT  MAX(CASE WHEN pd.`status`=1 THEN pd.execute_time ELSE NULL END) AS firstDate FROM wlyy_rehabilitation_plan_detail pd " +
                        "WHERE  pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id='"+map.get("code")+"'";
                List<Map<String,Object>> mapList2 = jdbcTemplate.queryForList(dateSql);
                if (mapList2!=null && mapList2.size()!=0){
                    Map<String,Object> map1 = mapList2.get(0);
                    map.put("firstDate",map1.get("firstDate"));
                    String condition = "";
                    if (map1.get("firstDate")!=null&&StringUtils.isNoneBlank(map1.get("firstDate").toString())){
                        condition = "and pd.execute_time >='"+map1.get("firstDate").toString()+"'";
                    }
                    String dateSql1 = "SELECT pd.execute_time as lastDate  FROM wlyy_rehabilitation_plan_detail pd " +
                            "WHERE  pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id='"+map.get("code")+"' and pd.status=0  "+condition+" order by pd.execute_time ASC ";
                    List<Map<String,Object>> mapList3 = jdbcTemplate.queryForList(dateSql1);
                    if (mapList3!=null&&mapList3.size()!=0){
                        Map<String,Object> map2 = mapList3.get(0);
                        map.put("lastDate",map2.get("lastDate"));
                    }else {
                        map.put("lastDate",null);
                    }
                }
            }
            if (map.get("code").toString().equalsIgnoreCase("2"))
            {//康复咨询
                //总康复咨询数量
                String sqlTotal = "select count(*)\n" +
                        "from wlyy_consult a,wlyy_consult_team b where a.id = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18";
                Integer consultTotal = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
               /* String healthCount = "SELECT * FROM wlyy_patient_reservation WHERE incidental_msg_type = 0 AND source = 4 AND patient = '"+map.get("patient")+"' ORDER BY start_time DESC";
                List<Map<String , Object>> healthList = jdbcTemplate.queryForList(healthCount);
                map.put("healthList",healthList);
                map.put("total",consultTotal + healthList.size());*/
                //完成康复咨询数量
               /* sqlTotal = "select count(*)\n" +
                        "from wlyy_consult a,wlyy_consult_team b where a.code = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18 and b.`status`=1";
                consultTotal = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
                map.put("compeletTotal",consultTotal + healthList.size());*/
                //上次发起时间
                String sqlTemp ="select a.czrq\n" +
                        "from wlyy_consult a,wlyy_consult_team b where a.id = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18 order by a.czrq desc limit 1";
                List<Map<String,Object>> czrqMap = jdbcTemplate.queryForList(sqlTemp);
                if(czrqMap.size()!=0){
                    if(czrqMap.get(0).get("czrq")!=null){
                        map.put("lastDate",czrqMap.get(0).get("czrq").toString());
                    }
                }
                else{
                    map.put("lastDate",null);
                }
               /* //未回复康复咨询数量
                sqlTotal="SELECT count(*) FROM wlyy.wlyy_consult_team a WHERE a.type = 18\n" +
                        "AND EXISTS ( SELECT DISTINCT t.id consultId FROM "+imDBName+".topics t, "+imDBName+".participants p, "+imDBName+".doctors d, "+imDBName+".sessions s \n" +
                        "WHERE p.participant_id = d.id AND t.session_id = p.session_id AND t.session_id = s.id\n" +
                        "AND s.type =18  AND t.`reply` = 0  AND a.consult = t.id\n" +
                        "and a.id in( select b.id from wlyy_consult a,wlyy_consult_team b \n" +
                        "where a.code = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18 )\n" +
                        ")";
                Integer noReplay = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
                map.put("noReplay",noReplay);*/
            }
        }
        return mapList;
    }
    public PatientRehabilitationPlanDO confirmManage(String patient,String signDoctor,String specialist,String relationId,String planId) throws Exception {
        String sqlCondition;
        if (StringUtils.isNoneBlank(relationId)){
            sqlCondition=" and pr.id='"+relationId+"' ";
        }
        else{
            sqlCondition=" and pr.doctor = '"+specialist+ "'";
        }
        PatientRehabilitationPlanDO patientRehabilitationPlanDO = patientRehabilitationPlanDao.findById(planId);
        if (patientRehabilitationPlanDO!=null){
            patientRehabilitationPlanDO.setIsVerify("1");
            patientRehabilitationPlanDao.save(patientRehabilitationPlanDO);
            String specialistSql = "select pr.doctor,pr.patient from wlyy_doctor_patient_relation pr where pr.patient='"+patient+"' "+sqlCondition;
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(specialistSql);
            if (mapList!=null&&mapList.size()!=0){
                Map<String,Object> map = mapList.get(0);
                String doctor = (String)map.get("doctor");
                String patient1 = (String)map.get("patient");
                //guidanceService.sendSpecialistWeixinMessage(patient1,doctor,2,null,null,null);
            }
            //下转患者被家庭医生确认管理时,专科医生收到推送
            /*if(messageService.getMessageNoticeSettingByMessageType(specialist,"1", MessageNoticeSetting.MessageTypeEnum.systemSwitch.getValue())) {
                Doctor specialistDoctor = doctorDao.findByCode(specialist);
                if(StringUtils.isNoneBlank(specialistDoctor.getOpenid())){
                    Doctor doctor = doctorDao.findByCode(signDoctor);
                    Patient p = patientDao.findByCode(patient);
                    //[医生姓名]医生您好,[医生姓名]医生已确认接收您的康复下转患者[患者姓名],请访问厦门i健康APP康复管理查看。
                    String first = specialistDoctor.getName() + "医生您好,"+doctor.getName()+"医生已确认接收您的康复下转患者"
                            + p.getName() +",请访问厦门i健康APP康复管理查看。";
                    doctorAssistantUtil.sendWXTemplate(2,specialistDoctor.getOpenid(),first,"请及时处理","康复管理","已接收");
                }
            }*/
            //确认管理给管理医生群组发送消息
           /* if (StringUtils.isNoneBlank(planId)){
                try {
                    JSONArray serverDoctorList =selectPlanServerDoctor(planId,signDoctor);
                    int length = serverDoctorList.length();
                    BaseDoctorDO doctor = baseDoctorDao.findById(signDoctor);
                    Patient p = patientDao.findByCode(patient);
                    Doctor specialistDoctor = doctorDao.findByCode(specialist);
                    for (int i=0;i<length;i++){
                        org.json.JSONObject serverJson = serverDoctorList.getJSONObject(i);
                        if (serverJson.getString("type").equals("4")){
                            String sessionId = serverJson.getString("sessionId");
                            String message= specialistDoctor.getName()+"医生您好,我已确认接收管理患者"+p.getName()+",谢谢。";
                            ImUtill.sendImMsg(signDoctor,doctor.getName(),sessionId,"1",message,"1");
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }*/
        }
        return patientRehabilitationPlanDO;
    }
    public org.json.JSONObject selectByPlanDetaiId(String patient, String planId, String code, Integer page, Integer pagesize){
        org.json.JSONObject object = new org.json.JSONObject();
        String sql ="SELECT\n" +
                " DATE_FORMAT(r.complete_time,'%Y-%m-%d %H:%i:%s') AS completeTime," +
                " r.doctor_code AS doctorCode," +
                " r.doctor_name AS doctorName," +
                " r.`status`," +
                " r.id as recordId," +
                " si.`name`," +
                " si.`code`," +
                " pd.plan_id," +
                " pd.id," +
                " r.relation_code as relationCode," +
                " r.flag " +
                "FROM " +
                " wlyy_rehabilitation_operate_records r " +
                "LEFT JOIN wlyy_rehabilitation_plan_detail pd ON r.rehabilitation_detail_id = pd.id " +
                "LEFT JOIN wlyy_rehabilitation_service_item si ON si.code= pd.hospital_service_item_id " +
                "LEFT JOIN base_doctor d ON d.id = r.doctor_code " +
                "WHERE " +
                " pd.plan_id = '"+planId+"' " +
                " AND pd.hospital_service_item_id = '"+code+"' " +
                "ORDER BY " +
                " r.complete_time DESC " ;
        sql = TransforSqlUtl.wlyy_rehabilitation_operate_recordsDoctorName(sql);
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        String sqlCount ="SELECT\n" +
                "\tCOUNT(*) as total\n" +
                "FROM\n" +
                "\t wlyy_rehabilitation_operate_records r\n" +
                "LEFT JOIN wlyy_rehabilitation_plan_detail pd ON r.rehabilitation_detail_id = pd.id\n" +
                "LEFT JOIN wlyy_rehabilitation_service_item si ON si.code= pd.hospital_service_item_id\n" +
                "LEFT JOIN base_doctor d ON d.id = r.doctor_code\n" +
                "WHERE\n" +
                "\t pd.plan_id = '"+planId+"'\n" +
                "\t\tAND pd.hospital_service_item_id = '"+code+"'\n";
        List<Map<String,Object>> maps = jdbcTemplate.queryForList(sqlCount);
        /*String followupSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as completeTime,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate,\n" +
                "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,\n" +
                "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,\n" +
                "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,\n" +
                "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                "and wf.patient_code = '"+patient+"' ";
        List<Map<String,Object>> followupList = jdbcTemplate.queryForList(followupSql);
        mapList.addAll(followupList);*/
        Collections.sort(mapList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Timestamp map1value = (Timestamp) o1.get("completeTime");
                Timestamp map2value = (Timestamp) o2.get("completeTime");
                int sort = 1;
                if (map1value.getTime() - map2value.getTime() > 0) {
                    return sort == 1 ? -1 : 1;
                } else if (map1value.getTime() - map2value.getTime() < 0) {
                    return sort == 1 ? 1 : -1;
                } else {
                    return 0;
                }
            }
        });
        object.put("list",startPage(mapList,page,pagesize));
        object.put("total",new Integer(maps.get(0).get("total").toString()) );
        object.put("page",page);
        object.put("pagesize",pagesize);
        return  object;
    }
    /**
     * 开始分页
     * @param list
     * @param pageNum 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List startPage(List list, Integer pageNum,
                                 Integer pageSize) {
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }
    /**
     * 获取康复服务项目列表
     * @return
     * @param name
     */
    public List<Map<String, Object>> getServiceItemList(String name) {
        String sql = "SELECT code,`name` FROM `wlyy_rehabilitation_service_item` ";
        if(StringUtils.isNotBlank(name)){
            sql += "where name like '%" + name + "%' ";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public List<PatientMedicalRecordsDO> getNewRehabilitation(String patient,String doctorCode) throws Exception {
        //智业中山同步病历
        String result = "";
        List<PatientMedicalRecordsDO> query = new ArrayList<>();
        BasePatientDO patient1 = basePatientDao.findById(patient);
        BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
        String orgCode="";
        List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(doctorCode);
        if(baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
            orgCode=baseDoctorHospitalDO.get(0).getOrgCode();
        }
        if (demoFlag) {//demoFlag
            result = patientRecordService.getJosnFileResullt("event" + "2");
        } else {
            org.json.JSONObject jsonEvent = new org.json.JSONObject();
            List<Map<String, String>> resultMap = patientRecordService.getAllEvent_new(patient, "2", "1", "1", "2010-10-10 00:00:00",orgCode);
            jsonEvent.put("data", JSON.parseArray(JSON.toJSONString(resultMap)));
            result = jsonEvent.toString();
        }
        com.alibaba.fastjson.JSONObject rejson = com.alibaba.fastjson.JSONObject.parseObject(result);
        com.alibaba.fastjson.JSONArray temlist = rejson.getJSONArray("data");
        if (temlist.size() != 0) {//存在病历信息
            com.alibaba.fastjson.JSONObject tem = temlist.getJSONObject(0);
            /**
             * {
             "orgName": "厦门大学附属心血管病医院",
             "createTime": "2013-09-26 10:13:38",
             "patient": "386a35b8d17a47cbab6174ae7952b9b6",
             "orgCode": "182",
             "dataFrom": "1",
             "id": "9f35ff1f-f683-4f3c-a0a5-7ff8ef3df89e",
             "eventType": "2",
             "dianosis": "高血压2级",
             "eventDate": "2013-09-26 10:13:38"
             }
             */
            PatientMedicalRecordsDO pmr = new PatientMedicalRecordsDO();
            pmr.setHospitalName(tem.getString("orgName"));
            pmr.setHospital(tem.getString("orgCode"));
            if (demoFlag) {//测试获取为病历模板 hospitalcode获取为自己的code
                pmr.setHospital("ac02a9b87a3611e69f7c005056850d66");//
            }
//        pmr.setDischargeDiagnosis(re.getDiagnosis());
            pmr.setDischargeDiagnosisName(tem.getString("dianosis"));
//        pmr.setAdmittingDiagnosis(re.getDiagnosis());
            pmr.setJwpatient(tem.getString("patient"));
            pmr.setAdmittingDiagnosisName(tem.getString("dianosis"));
            pmr.setEvent(tem.getString("id"));
            pmr.setDataFrom(tem.getString("dataFrom"));
            pmr.setAdvice("出院继续观察");
            if (tem.getString("dataFrom").equals("4"))//3中山 4智业
            {
                try {
                    String html = rehabilitationInfoService.getEmrContentByRID(tem.getString("patient"),tem.getString("id"),tem.getString("orgCode"));
                    if (StringUtils.isNoneBlank(html)){
                        List<String> tmp = HtmlUtil.getTagContent(html,"xid=\"diagnosis.in\" diagpop=\"1\">" + "(.*?)</TD>");
                        String diagnosisIn =tmp.size()>0?tmp.get(0):"";
                        tmp = HtmlUtil.getTagContent(html,"xid=\"diagnosis.out\" diagpop=\"1\">" + "(.*?)</TD>");
                        String diagnosisOut =tmp.size()>0?tmp.get(0):"";
                        if (StringUtils.isNoneBlank(diagnosisIn)){//入院诊断
                            pmr.setAdmittingDiagnosisName(diagnosisIn);
                        }
                        if (StringUtils.isNoneBlank(diagnosisOut)){//出院诊断
                            pmr.setDischargeDiagnosisName(diagnosisOut);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (tem.getString("dataFrom").equals("3"))//3中山 4智业
            {
                try {
                    com.alibaba.fastjson.JSONObject zsResult = zsRehabilitationInfoService.zsHospitalRecordDetail(tem.getString("patient"),tem.getString("id"));
                    com.alibaba.fastjson.JSONObject zsResultData = zsResult.getJSONObject("data");
                    if (zsResult.getInteger("status")==200&&zsResultData!=null){
                        if(zsResultData.containsKey("入院诊断")&&StringUtils.isNoneBlank(zsResultData.getString("入院诊断"))){
                            pmr.setDischargeDiagnosisName(zsResultData.getString("入院诊断"));
                        }
                        if (zsResultData.containsKey("出院诊断")&&StringUtils.isNoneBlank(zsResultData.getString("出院诊断"))){
                            pmr.setAdmittingDiagnosisName(zsResultData.getString("出院诊断"));
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
//        pmr.setDiseaseCode(diseaseObj.getString("disease"));//疾病code
//        pmr.setDiseaseName(diseaseObj.getString("diseaseName"));//疾病名称
            String jsonData = JSON.toJSONString(pmr);
            //创建居民住院病历
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO = objectMapper.readValue(jsonData, PatientMedicalRecordsDO.class);
            PatientMedicalRecordsDO patientMedicalRecordsDO1 = rehabilitationInfoService.createMedicalRecords(doctorCode, patient, patient1.getName(), patientMedicalRecordsDO, null);
            if (patientMedicalRecordsDO1 != null) { //创建病历成功
                query.add(patientMedicalRecordsDO1);
                return query;
            }
        }
        String sql = "SELECT pmrr.* FROM wlyy_patient_medical_records_rehabilitation pmrr WHERE pmrr.patient = '"+patient+"' and (data_from=3 or  data_from=4) GROUP BY id DESC LIMIT 0,1";//find_in_set('"+diseaseCode+"',disease)
        query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PatientMedicalRecordsDO.class));
        return query;
    }
    public List<Map<String,Object>> selectPlanByPatient(String patient, Integer status, String planId,String doctor){
        if (StringUtils.isNoneBlank(planId)){
            String planSql = "select p.patient " +
                    " FROM wlyy_patient_rehabilitation_plan p where p.id='"+planId+"' ";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(planSql);
            if (maps!=null&&maps.size()!=0){
                Map<String,Object> map = maps.get(0);
                patient = map.get("patient").toString();
            }
        }
        String sql = "select d.id as doctor,p.create_time as createTime,p.id,d.photo,p.title,d.idcard,YEAR (now()) - YEAR (substring(d.idcard, 7, 8)) AS age, d.sex,p.name,p.patient,d.name as doctorName,p.advice_content as adviceContent,p.medical_records_code as medicalRecordsCode,p.create_time as create_time " +
                " FROM wlyy_patient_rehabilitation_plan p " +
                " LEFT JOIN base_doctor d ON d.id = p.create_user " +
                "WHERE p.patient='"+patient+"'";
        if (status!=null){
            sql +=" and p.status ="+status;
        }
        if (StringUtils.isNoneBlank(doctor)){
            BaseDoctorDO doctor1 = baseDoctorDao.findById(doctor);
            if (doctor1!=null&&doctor1.getLevel()==1){
                sql +=" and p.create_user ='"+doctor+"'";
            }
        }
        /*sql+=" union ";
        sql+=" SELECT d.CODE AS doctor," +
                "p.create_time AS createTime," +
                "p.id," +
                "d.photo," +
                "p.title," +
                "d.idcard,YEAR (now())-YEAR (substring(d.idcard,7,8)) AS age," +
                "d.sex,p.name," +
                "p.patient," +
                "d.NAME AS doctorName," +
                "d.dept_name AS deptName," +
                "hospital_name AS hospitalName," +
                "p.advice_content AS adviceContent," +
                "p.medical_records_code AS medicalRecordsCode," +
                "p.create_time AS create_time " +
                "FROM " +
                "wlyy_patient_rehabilitation_plan p " +
                "LEFT JOIN base_doctor d ON d.id=p.create_user" +
                " LEFT JOIN (" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code " +
                "FROM wlyy_doctor_patient_relation sr " +
                "JOIN wlyy_doctor_special_share se ON se.special_code=sr.id " +
                "WHERE se.doctor='"+doctor+"' " +
                "AND sr.patient='"+patient+"') d " +
                "ON d.patient=p.patient WHERE " +
                "p.patient='"+patient+"' " +
                "AND d.team_code=p.team_code ";
*/
        sql+=" ORDER BY create_time DESC ";
        //sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:mapList){
            List<BaseDoctorHospitalDO> depts=baseDoctorHospitalDao.findByDoctorCode(map.get("doctor").toString());
            if(depts!=null&&depts.size()>0){
                map.put("deptCode",depts.get(0).getDeptCode());
                map.put("deptName",depts.get(0).getDeptName());
                map.put("orgCode",depts.get(0).getOrgCode());
                map.put("orgName",depts.get(0).getOrgName());
            }
            String sqlSpecilist = "select * from wlyy_doctor_patient_relation where doctor = '"+map.get("doctor")+"' and patient ='"+patient+"' and status=1";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(sqlSpecilist);
            map.put("specialist",maps);
        }
        return mapList;
    }
}

+ 1409 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanService.java

@ -0,0 +1,1409 @@
package com.yihu.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.team.BaseTeamMemberDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.DoctorPatientRelationDao;
import com.yihu.jw.rehabilitation.RehabilitationOperateRecordsDao;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.specialist.PatientSignInfoVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.sign.dao.MessagesDao;
import com.yihu.jw.team.BaseDoctorTeamMemberDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.rehabilitation.dao.*;
import com.yihu.rehabilitation.vo.TemplateDetailVo;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.security.MD5;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * Created by humingfen on 2018/8/22.
 */
@Service
@Transactional
public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitationPlanDO, PatientRehabilitationPlanDao> {
    @Value("${specialist.url}")
    private String specialistUrl;
    @Autowired
    private SpecialistEvaluateSevice specialistEvaluateSevice;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FrequencyDao frequencyDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private PatientRehabilitationPlanDao patientRehabilitationPlanDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RehabilitationDetailDao rehabilitationDetailDao;
    @Value("${neiwang.enable}")
    private Boolean isneiwang;  //如果不是内网项目要转到到内网wlyy在上传
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @Autowired
    FileUploadService fileUploadService;
    @Value("${testPattern.sign}")
    private String isClose;
    @Value("${testPattern.remote_inner_url}")
    private String remote_inner_url;
    @Autowired
    private WechatDao wechatDao;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private RehabilitationOperateRecordsDao rehabilitationOperateRecordsDao;
    @Autowired
    private BaseOrgDao baseOrgDao;
    @Autowired
    private BaseDoctorTeamMemberDao baseDoctorTeamMemberDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private DoctorPatientRelationDao doctorPatientRelationDao;
    @Autowired
    private RehabilitationPlanTemplateDao templateDao;
    @Autowired
    private RehabilitationTemplateDetailDao templateDetailDao;
    @Autowired
    private RehabilitationServiceItemDao serviceItemDao;
    @Autowired
    StringRedisTemplate redisTemplate;
    public Envelop updatePatientImgById(String planId, String patientImg) {
        if(patientRehabilitationPlanDao.updatePatientImgById(planId,patientImg) > 0){
            return Envelop.getSuccess(SpecialistMapping.api_success);
        }
        return Envelop.getError("更新失败!");
    }
    /*public JSONArray findTemplateInfo(String doctor, String patient) throws Exception {
        Map<String, Object> param = new HashedMap();
        Long adminTeamId = null;
        AdminTeam team = teamService.findByLeaderCode(doctor);
        if(StringUtils.isBlank(patient)){
            adminTeamId = team.getId();
            param.put("adminTeamCode", adminTeamId);
        }else {
            param.put("doctor", doctor);
            param.put("patient", patient);
        }
        HttpResponse response = null;
        try {
            response = HttpUtils.doGet(specialistUrl + "svr-specialist/findRehabilitationPlanTemplate", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject rs = new JSONObject(response.getContent());
        if ("success".equals(rs.getString("message"))) {
            return rs.getJSONArray("detailModelList");
        }
        throw new Exception("请求获取模板列表失败!");
    }*/
    public List<RehabilitationDetailDO> createRehabilitationDetail(List<RehabilitationDetailDO> details, String planId,String createUser,String createUserName) {
        for(RehabilitationDetailDO detail : details) {
            /*List<String> list = new ArrayList<>();
            list.add(detail.getHospitalServiceItemId());
            HospitalServiceItemDO hospitalServiceItemDO = hospitalServiceItemService.selectById(list).getDetailModelList().get(0);
            detail.setHospital(hospitalServiceItemDO.getHospital());
            detail.setHospitalName(hospitalServiceItemDO.getHospitalName());
            detail.setExpense(hospitalServiceItemDO.getExpense());*/
            detail.setPlanId(planId);
            detail.setCreateTime(new Date());
            detail.setStatus(0);
            detail.setUpdateTime(new Date());
            detail.setCreateUser(createUser);
            detail.setCreateUserName(createUserName);
        }
        return (List<RehabilitationDetailDO>)rehabilitationDetailDao.save(details);
    }
    //code,timeType,executeTimes
    public String createRehabilitationPlan(String json, BaseDoctorDO doctor) throws Exception {
        JSONObject object = new JSONObject(json);
        String patient = object.getString("patient");
        String relationId=object.getString("relationId");
        String teamCode=object.getString("teamCode");
        BasePatientDO patientDo  = patientDao.findById(patient);
        if (patientDo==null){
            BasePatientDO basePatientDO = new BasePatientDO();
            basePatientDO.setName(object.getString("patientName"));
            basePatientDO.setIdcard(object.getString("idCard"));
            basePatientDO.setMobile(object.getString("mobile"));
            patientDo = saveUnSignPatient(basePatientDO);
        }
        String patientName="";
        if(patientDo!=null){
            patientName = patientDo.getName();
        }
        JSONArray array = object.getJSONArray("detail");
        for (int z=0;z<array.length();z++){
            JSONObject jsonObject = array.getJSONObject(z);
            Long timeType = jsonObject.getLong("timeType");
            Frequency frequency = frequencyDao.findByCode(jsonObject.getString("frequencyCode"));
            String executeTimes = jsonObject.getString("executeTimes");
            String[] executeTime = executeTimes.split(",");
            List<String> list = new ArrayList<>();
            if (StringUtils.isNoneBlank(executeTimes)){
                for (int i=0;i<executeTime.length;i++){
                    List<String> times = getFrequencyDate(frequency.getCode(),executeTime[i],frequency.getUnit(),frequency.getTime(),timeType);
                    for (int j=0;j<times.size();j++){
                        if (list!=null&&list.size()!=0){
                            if (!list.contains(times.get(j))){
                                list.add(times.get(j));
                            }
                        }else {
                            list.add(times.get(j));
                        }
                    }
                }
                StringBuffer buffer = new StringBuffer();
                if(list!=null&&list.size()!=0){
                    for (int i=0;i<list.size();i++){
                        buffer.append(list.get(i)+",");
                    }
                    if (StringUtils.isNoneBlank(buffer)){
                        buffer.deleteCharAt(buffer.length()-1);
                    }
                }
                jsonObject.put("executeTime",buffer);
            }
            jsonObject.remove("executeTimes");
        }
        object.put("createUser", doctor.getId());
        object.put("createUserName", doctor.getName());
        String planDetails = array.toString();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        List<RehabilitationDetailDO> details = objectMapper.readValue(planDetails, new TypeReference<List<RehabilitationDetailDO>>(){});
        PatientRehabilitationPlanDO planDO = objectMapper.readValue(json.toString(), PatientRehabilitationPlanDO.class);
        planDO.setCreateUser(doctor.getId());
        planDO.setCreateUserName(doctor.getName());
        planDO = createPatientRehabilitationPlan(planDO);
        details = createRehabilitationDetail(details, planDO.getId(),doctor.getId(),doctor.getName());
        //康复计划创建完给执行者发送消息
        String planId = null;
        if (planDO!=null){
            planId=planDO.getId();
        }
        HashSet set = new HashSet();
        for ( RehabilitationDetailDO rehabilitationDetailDO : details) {
            if (!set.contains(rehabilitationDetailDO.getDoctor())) {
                set.add(rehabilitationDetailDO.getDoctor());
                SystemMessageDO message = new SystemMessageDO();
                message.setSender(doctor.getId());
                message.setType("19");
                message.setRelationCode(rehabilitationDetailDO.getPlanId());
                message.setReceiver(rehabilitationDetailDO.getDoctor());
                message.setReason(doctor.getName());
                specialistEvaluateSevice.sendMessage(message, rehabilitationDetailDO.getHospital(), patient, null,null);
                //pushMsgTask.put(rehabilitationDetailDO.getDoctor(),"20", "康复计划创建消息", "您的居民"+patientName+"的康复计划已配置完成,点击查看", "");
            }
        }
        DoctorPatientRelationDO doctorPatientRelationDO = doctorPatientRelationDao.findOne(relationId);
        if (null!=doctorPatientRelationDO){
            if (doctorPatientRelationDO.getIsManage()==null||doctorPatientRelationDO.getIsManage()==0){
                doctorPatientRelationDO.setDoctor(doctor.getId());
                doctorPatientRelationDO.setDoctorName(doctor.getName());
                doctorPatientRelationDO.setIsManage(0);
            }
            doctorPatientRelationDO.setTeamCode(teamCode);
            doctorPatientRelationDO.setIsdeal("1");
            doctorPatientRelationDao.save(doctorPatientRelationDO);
        }
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        //推送消息到IM
        if (signFamily != null && !set.contains(signFamily.getDoctor())) {
            //pushMsgTask.put(signFamily.getDoctor(),"20", "康复计划创建消息", "您的居民"+patientName+"的康复计划已配置完成,点击查看", "");
        }
        return planId;
    }
    public MixEnvelop<String,String> createServiceQrCode(String planDetailId, String doctorCode) throws  Exception{
        //更新到康复计划居民关系表中
        Map<String, Object> param = new HashedMap();
        String fileUrl = "";
        String sql ="SELECT service_qr_code FROM wlyy_specialist.wlyy_rehabilitation_plan_detail where id='"+planDetailId+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null && list.size()>0){
            fileUrl = String.valueOf(list.get(0).get("service_qr_code"));
        }
        if (StringUtils.isEmpty(fileUrl) || "null".equals(fileUrl)){
            //生成二维码图片
            WxWechatDO wxWechatDO = wechatDao.findById(wxId);
            String appId="";
            String wechat_base_url="";
            if (wxWechatDO!=null){
                appId=wxWechatDO.getAppId();
                wechat_base_url=wxWechatDO.getBaseUrl();
            }
            String contentJsonStr="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+wechat_base_url+"/wx/html/kfgl/html/confirm-service.html"+"?paramStr="+planDetailId+","+doctorCode+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            InputStream ipt = QrcodeUtil.createQrcode(contentJsonStr, 300, "png");
            UploadVO uploadVO = new UploadVO();
            String originalFilename ="plan_service_qrcode" + System.currentTimeMillis()+".png";
            if (isClose.equalsIgnoreCase("1")){
                Map<String, Object> map = fileUploadService.uploadImg(new MockMultipartFile(originalFilename,originalFilename,"", ipt));
                uploadVO.setFullUri(map.get("accessory").toString());
            }else if(isClose.equals("2")){
                //内网上传
                String rs = fileUploadService.request(remote_inner_url,new MockMultipartFile(originalFilename,originalFilename,"", ipt),null);
                com.alibaba.fastjson.JSONObject json = JSON.parseObject(rs);
                uploadVO = objectMapper.readValue(json.getJSONObject("obj").toJSONString(),UploadVO.class);
            }else {
                // 得到文件的完整名称  xxx.txt
                /*InputStream inputStream = ipt;*/
                uploadVO = fileUploadService.uploadStream(ipt,originalFilename,fastdfs_file_url);
            }
            fileUrl = uploadVO.getFullUri();
        }
        System.out.println("服务码-----------1"+fileUrl);
        String sqlUpdate = "update wlyy_rehabilitation_plan_detail set service_qr_code='" + fileUrl + "' where id='" + planDetailId + "'";
        jdbcTemplate.update(sqlUpdate);
        return MixEnvelop.getSuccess("获取二维码成功!",fileUrl);
    }
    public Map<String,Object> checkAfterQrCode(String planDetailId,String patietCode)throws Exception{
        Map<String,Object> map = new HashedMap();
        int result = 0;
        String name= "";
        String sql ="SELECT p.patient,p.name FROM `wlyy_rehabilitation_plan_detail` pd LEFT JOIN wlyy_patient_rehabilitation_plan p ON pd.plan_id = p.id WHERE pd.id='"+planDetailId+"'";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if (list!=null && list.size()>0){
            if (String.valueOf(list.get(0).get("patient")).equals(patietCode)){
                result =200;
            }else {
                result = -1;
                name=String.valueOf(list.get(0).get("name"));
            }
        }else {
            result = -10000;
        }
        map.put("code",result);
        if (StringUtils.isNotBlank(name)){
            map.put("name",name);
        }
        return map;
    }
    public PatientRehabilitationPlanDO createPatientRehabilitationPlan(PatientRehabilitationPlanDO planDO) {
        planDO.setCreateTime(new Date());
        planDO.setStatus(1);
        planDO.setIsVerify("0");
        planDO.setUpdateTime(new Date());
        return patientRehabilitationPlanDao.save(planDO);
    }
    public List<String> getFrequencyDate(String code,String date,String unit,String time,Long timeType) throws ParseException {
        List<String> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = date+":00";
        Date date6 = DateUtil.strToDateLong(nowDate);
        String date9 = sdf.format(date6)+" 09:00:00";//白天
        String date21 = sdf.format(date6)+" 21:00:00";//白天
        String date9s = DateUtil.getNextDay(date6,1)+" 09:00:00";//晚上
        Calendar calendar = Calendar.getInstance();
        if (unit.equalsIgnoreCase("D")&&!code.equalsIgnoreCase("qod")){
            String[] str = time.split(",");
            for (int i=0;i<str.length;i++){
                Date date1 = sdf.parse(date);
                calendar.setTime(date1);
                String lastDay = sdf.format(calendar.getTime()) + " "+str[i];
                list.add(lastDay);
            }
        }else if (unit.equalsIgnoreCase("D")&&code.equalsIgnoreCase("qod")){
            Date date1 = sdf.parse(date);
            calendar.setTime(date1);
            calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) +1);
            String lastDay = sdf.format(calendar.getTime()) + " "+time;
            list.add(lastDay);
        }else if (unit.equalsIgnoreCase("H")&&code.equalsIgnoreCase("q0.5h")){
            Date date1 = sdf.parse(date);
            calendar.setTime(date1);
            String endTime = null;
            String lastDay = null;
            if (timeType == 0){
                lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
                endTime = sdf.format(calendar.getTime()) + " 23:59:59";
            }else if ( timeType == 1){
                lastDay = date9;
                endTime = date21;
            }else if (timeType == 2){
                lastDay = date21;
                endTime = date9s;
            }
            Date date2 = sdf1.parse(lastDay);
            Date date3 = sdf1.parse(endTime);
            Long time1 = date2.getTime();
            for (int i=0;i<47;i++){
                time1 += 30*60*1000;
                String day = sdf1.format(time1);
                Date date4 = sdf1.parse(day);
                if (date4.compareTo(date3)==-1 || date4.compareTo(date3) == 0){
                    list.add(day);
                }
            }
        }else if (unit.equalsIgnoreCase("H")&& code.equalsIgnoreCase("q2h")){
            Date date1 = sdf.parse(date);
            calendar.setTime(date1);
      /*      String lastDay = sdf.format(calendar.getTime()) + " 00:00:00";*/
            String endTime = null;
            String lastDay = null;
            if (timeType == 0){
                lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
                endTime = sdf.format(calendar.getTime()) + " 23:59:59";
            }else if ( timeType == 1){
                lastDay = date9;
                endTime = date21;
            }else if (timeType == 2){
                lastDay = date21;
                endTime = date9s;
            }
            Date date2 = sdf1.parse(lastDay);
            Date date3 = sdf1.parse(endTime);
            calendar.setTime(date2);
            for (int i=0;i<11;i++){
                calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+2);
                Date date4 = sdf1.parse(sdf1.format(calendar.getTime()));
                System.out.print(sdf1.format(calendar.getTime()));
                if (date4.compareTo(date3)==-1||date4.compareTo(date3) == 0){
                    list.add(sdf1.format(calendar.getTime()));
                }
            }
        }else if (unit.equalsIgnoreCase("H")&&code.equalsIgnoreCase("q3h")){
            Date date1 = sdf.parse(date);
            calendar.setTime(date1);
            //String lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
            String endTime = null;
            String lastDay = null;
            if (timeType == 0){
                lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
                endTime = sdf.format(calendar.getTime()) + " 23:59:59";
            }else if ( timeType == 1){
                lastDay = date9;
                endTime = date21;
            }else if (timeType == 2){
                lastDay = date21;
                endTime = date9s;
            }
            Date date2 = sdf1.parse(lastDay);
            Date date3 = sdf1.parse(endTime);
            calendar.setTime(date2);
            for (int i=0;i<7;i++){
                calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+3);
                Date date4 = sdf1.parse(sdf1.format(calendar.getTime()));
                if (date4.compareTo(date3)==-1||date4.compareTo(date3) == 0){
                    list.add(sdf1.format(calendar.getTime()));
                }
            }
        }else if (unit.equalsIgnoreCase("H")&&code.equalsIgnoreCase("q4h")){
            Date date1 = sdf.parse(date);
            calendar.setTime(date1);
            //String lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
            String endTime = null;
            String lastDay = null;
            if (timeType == 0){
                lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
                endTime = sdf.format(calendar.getTime()) + " 23:59:59";
            }else if ( timeType == 1){
                lastDay = date9;
                endTime = date21;
            }else if (timeType == 2){
                lastDay = date21;
                endTime = date9s;
            }
            Date date2 = sdf1.parse(lastDay);
            Date date3 = sdf1.parse(endTime);
            calendar.setTime(date2);
            for (int i=0;i<5;i++){
                calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+4);
                Date date4 = sdf1.parse(sdf1.format(calendar.getTime()));
                if (date4.compareTo(date3)==-1||date4.compareTo(date3) == 0){
                    list.add(sdf1.format(calendar.getTime()));
                }
            }
        }else if (unit.equalsIgnoreCase("H")&&code.equalsIgnoreCase("qh")){
            Date date1 = sdf.parse(date);
            calendar.setTime(date1);
            //String lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
            String endTime = null;
            String lastDay = null;
            if (timeType == 0){
                lastDay = sdf.format(calendar.getTime()) + " 00:00:00";
                endTime = sdf.format(calendar.getTime()) + " 23:59:59";
            }else if ( timeType == 1){
                lastDay = date9;
                endTime = date21;
            }else if (timeType == 2){
                lastDay = date21;
                endTime = date9s;
            }
            Date date2 = sdf1.parse(lastDay);
            Date date3 = sdf1.parse(endTime);
            calendar.setTime(date2);
            for (int i=0;i<23;i++){
                calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+1);
                Date date4 = sdf1.parse(sdf1.format(calendar.getTime()));
                if (date4.compareTo(date3)==-1||date4.compareTo(date3) == 0){
                    list.add(sdf1.format(calendar.getTime()));
                }
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_1")){
            String date2 = DateUtil.getWeek(date,"1")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_2")){
            String date2 = DateUtil.getWeek(date,"2")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_3")){
            String date2 = DateUtil.getWeek(date,"3")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_4")){
            String date2 = DateUtil.getWeek(date,"4")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_5")){
            String date2 = DateUtil.getWeek(date,"5")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_6")){
            String date2 = DateUtil.getWeek(date,"6")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("qw_7")){
            String date2 = DateUtil.getWeek(date,"7")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("tiw135")){
            String date2 = DateUtil.getWeek(date,"1")+" 08:00:00";
            String date4 = DateUtil.getWeek(date,"3")+" 08:00:00";
            String date5 = DateUtil.getWeek(date,"5")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
            if (date4.compareTo(date3)==1){
                list.add(date2);
            }
            if (date5.compareTo(date3) == 1){
                list.add(date2);
            }
        }else if (unit.equalsIgnoreCase("W")&&code.equalsIgnoreCase("tiw246")){
            String date2 = DateUtil.getWeek(date,"2")+" 08:00:00";
            String date4 = DateUtil.getWeek(date,"4")+" 08:00:00";
            String date5 = DateUtil.getWeek(date,"6")+" 08:00:00";
            Date date1 = new Date();
            String date3 = sdf1.format(date1);
            if (date2.compareTo(date3)==1){
                list.add(date2);
            }
            if (date4.compareTo(date3)==1){
                list.add(date2);
            }
            if (date5.compareTo(date3) == 1){
                list.add(date2);
            }
        }
        return list;
    }
    public String deleteTemplate(String templateId) {
        Map<String, Object> param = new HashedMap();
        param.put("id", templateId);
        HttpResponse response = null;
        try {
            response = HttpUtils.doPost(specialistUrl + "svr-specialist/deleteRehabilitationPlanTemplate", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject rs = new JSONObject(response.getContent());
        return rs.getString("message");
    }
    /**
     * 更新计划的状态
     * @param planId
     * @param status
     * @throws Exception
     */
    public void updatePlanStatusById(String planId, Integer status,String abortReason) throws Exception{
        Map<String, Object> param = new HashedMap();
        param.put("planId", planId);
        param.put("status", status);
        param.put("abortReason",abortReason);
        HttpResponse response = HttpUtils.doPost(specialistUrl + "svr-specialist/updatePlanStatusById", param);
        JSONObject result = new JSONObject(response.getContent());
        if (result.getInt("status")==200 && status==0){
            List<SystemMessageDO> messageList = new ArrayList<>();
            Map<String,String> recieveMap = new HashMap<>();
            JSONObject jsonObject =result.getJSONObject("obj");
            String patientCode = jsonObject.getString("patient");
            String patientName = jsonObject.getString("name");
            String diseaseName = jsonObject.getString("diseaseName");
            String createDoctorCode = jsonObject.getString("createUser");
            JSONArray detailModelList = result.getJSONArray("detailModelList");
            for (Object obj : detailModelList) {
                JSONObject detail = (JSONObject) obj;
                String doctor = detail.getString("doctor");
                if (!createDoctorCode.equals(doctor)){
                    if (!recieveMap.containsKey(doctor)){
                        recieveMap.put(doctor,detail.getString("doctorName"));
                    }
                }
            }
            SignFamily signFamily = signFamilyDao.findByPatient(patientCode);
            if (signFamily!=null){
                if (!recieveMap.containsKey(signFamily.getDoctor())){
                    recieveMap.put(signFamily.getDoctor(),signFamily.getDoctorName());
                }
            }
            for (Map.Entry<String,String> entry : recieveMap.entrySet()){
                //推送消息到IM
                //pushMsgTask.put(entry.getKey(),"20", "康复计划中止消息", "您的居民"+patientName+",已中止"+diseaseName+"康复计划,点击查看原因", "");
                SystemMessageDO message = initMessage(patientName,entry.getKey(),entry.getValue(),"system","system","康复计划-中止提醒","您的居民"+patientName+",已中止"+diseaseName+"康复计划,点击查看原因。",planId,29);
                messageList.add(message);
            }
            messageDao.save(messageList);
            /*Message message = new Message();
            message.setCzrq(new Date());
            message.setCreateTime(new Date());
            message.setContent("您的"+patientName+"签约居民,已中止康复计划,点击查看原因。");
            message.setRead(1);//设置未读
            if (signFamily!=null){
                message.setReceiver(signFamily.getDoctor());//设置接受医生的code
                message.setReceiverName(signFamily.getDoctorName());
            }
            message.setSender("system");//设置发送的用户
            message.setSenderName("system");
            message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
            message.setSenderPhoto("");
            message.setTitle("康复计划-中止提醒");
            message.setType(29);//康复计划中止消息提醒
            message.setReadonly(1);//是否只读消息
            message.setRelationCode(planId);
            message.setOver("1");//未处理
            message.setState(1);
            message.setData("");
            message.setDel("1");*/
            //推送消息到IM
           // pushMsgTask.put(signFamily.getDoctor(),"20", "康复计划中止消息", "您的"+patientName+"签约居民,已中止康复计划,点击查看原因", "");
        }
        if(result.getInt("status")!=200){
            throw new Exception("请求微服务失败!");
        }
    }
    private SystemMessageDO initMessage(String patientName, String doctor, String doctorName, String sender, String senderName, String title, String content, String relatioenCode, int type){
        SystemMessageDO message = new SystemMessageDO();
        message.setCreateTime(new Date());
        message.setContent("您的服务居民"+patientName+",已中止康复计划,点击查看原因。");
        message.setIsRead("1");//设置未读
        message.setReceiver(doctor);//设置接受医生的code
        message.setReceiverName(doctorName);
        message.setSender(sender);//设置发送的用户
        message.setSenderName(senderName);
        message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
        message.setSenderPhoto("");
        message.setTitle(title);
        message.setType(String.valueOf(type));//康复计划中止消息提醒
        message.setReadonly(1);//是否只读消息
        message.setRelationCode(relatioenCode);
        message.setOver("0");//未处理
        message.setState(1);
        message.setData("");
        message.setDel("1");
        return message;
    }
    public JSONObject getServiceItemsAfterStop(String planId)throws Exception{
        Map<String, Object> param = new HashedMap();
        param.put("planId", planId);
        HttpResponse response = HttpUtils.doGet(specialistUrl + "svr-specialist/getServiceItemsAfterStop", param);
        JSONObject result = new JSONObject(response.getContent());
        JSONObject jsonObject = new JSONObject();
        if(result.getInt("status")!=200){
            throw new Exception("请求微服务失败!");
        }
        if (result.getInt("status")==200){
            jsonObject = result.getJSONObject("obj");
            JSONArray jsonArray = jsonObject.getJSONArray("serviceList");
            if (jsonArray!=null && jsonArray.length()>0){
                jsonObject.put("patientName",jsonArray.getJSONObject(0).get("name"));
                jsonObject.put("abortTime",jsonArray.getJSONObject(0).get("abort_time"));
                jsonObject.put("hospitalName",jsonArray.getJSONObject(0).get("hospital_name"));
                jsonObject.put("abortReason",jsonArray.getJSONObject(0).get("abort_reason"));
                String patientCode = String.valueOf(jsonArray.getJSONObject(0).get("patient"));
                jsonObject.put("patientCode", patientCode);
                jsonObject.put("disease_name", jsonArray.getJSONObject(0).get("disease_name"));
                jsonObject.put("create_time", jsonArray.getJSONObject(0).get("create_time"));
                jsonObject.put("patient_img", jsonArray.getJSONObject(0).get("patient_img"));
                BasePatientDO patient = patientDao.findById(patientCode);
                if (patient!=null){
                    jsonObject.put("openid", patient.getOpenid());
                    jsonObject.put("ssc",patient.getSsc());
                    jsonObject.put("mobile",patient.getMobile());
                }
            }
        }
        return jsonObject;
    }
    /**
     * 更新居民签名照/证件照
     * @param planId
     * @throws Exception
     *//*
    public void updatePatientImgById(String planId, String patientImg) throws Exception {
        Map<String, Object> param = new HashedMap();
        param.put("planId", planId);
        param.put("patientImg", patientImg);
        HttpResponse response = HttpUtils.doPost(specialistUrl + "svr-specialist/updatePatientImgById", param);
        JSONObject result = new JSONObject(response.getContent());
        if(result.getInt("status")!=200){
            throw new Exception("请求微服务失败!");
        }
    }*/
    public void sendWxTemplate(String accessToken, String planId, String doctorCode, JSONObject jsonObject) {
        BaseDoctorDO d = doctorDao.findById(doctorCode);
        JSONObject json = new JSONObject();
        String patient = jsonObject.getString("patientCode");
        String patientName = jsonObject.get("patientName") + "";
        json.put("first", patientName + "您好,您有一个康复计划已完成,请确认接收。");
        json.put("toUser", patient);
        json.put("represented", patient);//被代理人
        json.put("keyword1", jsonObject.get("disease_name") + "康复计划");
        json.put("keyword2", d.getName());
        json.put("keyword3", DateUtil.dateToStr(new Date ((Long) jsonObject.get("create_time")), "yyyy/MM/dd") + "-" + DateUtil.dateToStr(new Date(), "yyyy/MM/dd"));
        json.put("remark", "完成的康复项清单已发送给您,点击此消息可查看。");
        json.put("planId", planId);
        if (!jsonObject.isNull("openid")) {
            //pushMsgTask.putWxMsg(accessToken, 27, jsonObject.get("openid") + "", patientName, json);
        }/*else {
            try {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openid);
                if (jsonArray != null && jsonArray.length() > 0) {
                    Patient p = patientDao.findByCode(patient);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject data = json;
                        data.remove("toUser");
                        data.put("toUser", member.getCode());
                        data.remove("first");
                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, (int) j.get("relation"), p.getName()));
                        pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 27, member.getOpenid(), p.getName(), data);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
    }
    public BasePatientDO saveUnSignPatient(BasePatientDO basepatientDO){
        basepatientDO.setDel("1");
        basepatientDO.setLocked(0);
        basepatientDO.setEnabled(1);
        String salt = randomString(5);
        basepatientDO.setSalt(salt);
        basepatientDO.setPassword(MD5.md5Hex(basepatientDO.getIdcard().substring(12,18) + "{" + salt + "}"));
        basepatientDO=patientDao.save(basepatientDO);
        return basepatientDO;
    }
    public RehabilitationOperateRecordsDO saveRehabilitationRecord(RehabilitationOperateRecordsDO rehabilitationOperateRecordsDO){
        RehabilitationDetailDO rehabilitationDetailDO = rehabilitationDetailDao.findById(rehabilitationOperateRecordsDO.getRehabilitationDetailId());
        if (!StringUtils.isNoneBlank(rehabilitationOperateRecordsDO.getId())){
            rehabilitationOperateRecordsDO.setId(getCode());
        }
        if (rehabilitationDetailDO.getExecuteTime()!=null){
            rehabilitationOperateRecordsDO.setReserveTime(rehabilitationDetailDO.getExecuteTime());
        }
        rehabilitationOperateRecordsDO.setCompleteTime(new Date());
        rehabilitationOperateRecordsDO.setCreateTime(new Date());
        rehabilitationOperateRecordsDO.setUpdateTime(new Date());
        rehabilitationOperateRecordsDO.setStatus(rehabilitationOperateRecordsDO.getStatus());
        if (StringUtils.isEmpty(rehabilitationOperateRecordsDO.getPatientName())){
            String sql ="select name from base_patient where id='"+rehabilitationOperateRecordsDO.getPatientCode()+"'";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            if (list!=null && list.size()>0){
                rehabilitationOperateRecordsDO.setPatientName(String.valueOf(list.get(0).get("name")));
            }
        }
        return rehabilitationOperateRecordsDao.save(rehabilitationOperateRecordsDO);
    }
    /**
     * 更新康复计划项目状态
     * @param status
     * @param planId
     * @return
     */
    public MixEnvelop updatePlanStatusById(Integer status, String planId) throws Exception{
        if(status == 1) {
            if (patientRehabilitationPlanDao.updateStatusById(status, planId) > 0) {
                return MixEnvelop.getSuccess(SpecialistMapping.api_success, patientRehabilitationPlanDao.findById(planId));
            }
        }else if(status == 2){
            if (patientRehabilitationPlanDao.updateStatusAndTimeById(2,planId, new Date()) > 0) {
                return MixEnvelop.getSuccess(SpecialistMapping.api_success, patientRehabilitationPlanDao.findById(planId));
            }
        }
        return MixEnvelop.getError("更新失败!");
    }
    public MixEnvelop abortPlanById(String planId,String abortReason){
        PatientRehabilitationPlanDO patientRehabilitationPlanDO=patientRehabilitationPlanDao.findById(planId);
        List<RehabilitationDetailDO> detailDOList = rehabilitationDetailDao.findByPlanIdAndStatus(planId,0);
        if(null!=patientRehabilitationPlanDO){
            patientRehabilitationPlanDO.setAbortReason(abortReason);
            patientRehabilitationPlanDO.setAbortTime(new Date());
            patientRehabilitationPlanDO.setStatus(0);
            patientRehabilitationPlanDO.setUpdateTime(new Date());
            patientRehabilitationPlanDao.save(patientRehabilitationPlanDO);
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientRehabilitationPlanDO,detailDOList);
        }
        return MixEnvelop.getError("更新失败!");
    }
    public ObjEnvelop findServiceItemByDoctor(String doctor){
        String teamCode="";
        String orgCode="";
        List<BaseTeamMemberDO> baseTeamMemberDO = baseDoctorTeamMemberDao.findUseDoctorCode(doctor);
        if (baseTeamMemberDO!=null&&baseTeamMemberDO.size()>0){
            teamCode= baseTeamMemberDO.get(0).getTeamCode();
        }
        List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(doctor);
        if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
            orgCode= baseDoctorHospitalDO.get(0).getOrgCode();
        }
        String packageSql = "select m.service_package_id as \"servicePackageId\"," +
                " n.name as \"name\"" +
                "from base_service_package_item m left join base_service_package n on" +
                " m.service_package_id = n.id where 1=1 and m.service_package_id !='system' ";
        if(StringUtils.isNoneBlank(teamCode)){
            packageSql+= " and m.team_code ='"+teamCode+"'";
        }else {
            return  null;
        }
        if(StringUtils.isNoneBlank(orgCode)){
            packageSql+= " and m.org_code ='"+orgCode+"'";
        }else {
            return  null;
        }
        packageSql+=" group by m.service_package_id,n.name ";
        List<Map<String,Object>> listPackage = hibenateUtils.createSQLQuery(packageSql);
        for (Map<String,Object> map:listPackage){
            if (map.get("servicePackageId")!=null){
                String sql = "select t.id as \"id\"," +
                        " t.code as \"code\"," +
                        " t.name as \"name\"," +
                        " t.service_package_id as \"servicePackageId\"," +
                        " t.price as \"price\"," +
                        " t.fee_type as \"feeType\"," +
                        " t.org_code as \"orgCode\"," +
                        " t.org_name as \"orgName\"," +
                        " t.introduce as \"introduce\"," +
                        " t.del as \"del\"," +
                        " t.team_code as \"teamCode\"," +
                        " t.team_name as \"teamName\"," +
                        " t.create_time as \"createTime\"," +
                        " t.dict_id as \"dictId\"" +
                        " from base_service_package_item t where 1=1 and t.service_package_id !='system' ";
                if (StringUtils.isNoneBlank(teamCode)) {
                    sql += " and t.team_code ='" + teamCode + "'";
                }
                if (StringUtils.isNoneBlank(orgCode)) {
                    sql += " and t.org_code ='" + orgCode + "'";
                }
                sql+=" and t.service_package_id = '"+map.get("servicePackageId").toString()+"'";
                List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
                map.put("itemList",list);
            }
        }
        return ObjEnvelop.getSuccess("操作成功",listPackage);
    }
    public  List<Map<String, Object>>  findServiceItemInBase(String code,String name,String teamCode){
        String sql = "select t.id as \"id\"," +
                " t.code as \"code\"," +
                " t.name as \"name\"," +
                " t.service_package_id as \"servicePackageId\"," +
                " t.price as \"price\"," +
                " t.fee_type as \"feeType\"," +
                " t.org_code as \"orgCode\"," +
                " t.org_name as \"orgName\"," +
                " t.introduce as \"introduce\"," +
                " t.del as \"del\"," +
                " t.team_code as \"teamCode\"," +
                " t.team_name as \"teamName\"," +
                " t.create_time as \"createTime\"," +
                " t.dict_id as \"dictId\"" +
                " from base_service_package_item t where 1=1 and t.service_package_id ='system' and t.del ='1'";
        if (StringUtils.isNoneBlank(teamCode)) {
            sql += " and t.team_code ='" + teamCode + "'";
        }
        if (StringUtils.isNoneBlank(code)) {
            sql += " and t.code ='" + code + "'";
        }
        if (StringUtils.isNoneBlank(name)) {
            sql += " and t.name ='" + name + "'";
        }
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }
    public  List<Map<String,Object>> findDoctorTeams(String doctor){
        String sql = "select a.id as \"id\", " +
                " a.org_code as \"orgCode\"," +
                " a.org_name as \"orgName\"," +
                " a.name as \"name\"," +
                " a.leader_code as \"leaderCode\"," +
                " a.team_num as \"teamNum\"," +
                " a.qrcode as \"qrcode\"," +
                " a.del as \"del\"," +
                " a.create_time as \"createTime\"" +
                " from base_team a left join base_team_member b " +
                " on a.id = b.team_code where a.del ='1' ";
        if (StringUtils.isNotBlank(doctor)){
            sql+=" and b.doctor_code ='"+doctor+"'";
        }else{
            return null;
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }
    public List<Map<String,Object>> findDoctorByTeams(String teamCode){
        String sql = "select b.id as \"id\"," +
                " t.id as \"doctorId\"," +
                " t.name as \"doctorName\"," +
                " b.team_code as \"teamcode\"," +
                " b.org_code as \"orgcode\"" +
                "from base_team_member b left join base_doctor t on b.doctor_code = t.id" +
                " where b.del =1 ";
        if (StringUtils.isNotBlank(teamCode)){
            sql+=" and b.team_code ='"+teamCode+"'";
        }else{
            return null;
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }
    public ObjEnvelop createRehabilitationTemplate(RehabilitationPlanTemplateDO templateDO) {
        templateDO.setCreateTime(new Date());
        templateDO.setDel(1);
        templateDO.setUpdateTime(new Date());
        templateDO = templateDao.save(templateDO);
        String templateId = templateDO.getId();
        String user = templateDO.getCreateUser();
        String userName = templateDO.getCreateUserName();
        //默认新增服务项
        String sql = "SELECT code from wlyy.system_dict WHERE `dict_name` = 'default_service_item_id'";
        List<String> list = jdbcTemplate.queryForList(sql,String.class);
        if(list!=null&&list.size()>0){
            list.stream().forEach(code->{
                RehabilitationTemplateDetailDO detailDO = new RehabilitationTemplateDetailDO();
                detailDO.setTemplateId(templateId);
                detailDO.setHospitalServiceItemId(code);
                detailDO.setCreateUser(user);
                detailDO.setCreateUserName(userName);
                detailDO.setCreateTime(new Date());
                detailDO.setUpdateTime(new Date());
                templateDetailDao.save(detailDO);
            });
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,templateDO.getId());
    }
    public ObjEnvelop createRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details) {
        for(RehabilitationTemplateDetailDO detail : details){
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            templateDetailDao.save(detail);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    public ObjEnvelop updateRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details) {
        String templateId = details.get(0).getTemplateId();
        if(templateId != null && templateId.length() > 0){
            templateDetailDao.deleteByTemplateId(templateId);
        }
        for(RehabilitationTemplateDetailDO detail : details){
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            templateDetailDao.save(detail);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    public MixEnvelop findRehabilitationPlanTemplate(Long adminTeamCode, String doctor, String patient) {
        List<RehabilitationPlanTemplateDO> list = templateDao.findByAdminTeamCode(adminTeamCode);
        return MixEnvelop.getSuccessList(SpecialistMapping.api_success, list);
    }
    /**
     * 根据模板id修改康复模板删除状态
     * @param id
     * @return
     */
    public ObjEnvelop deleteRehabilitationPlanTemplate(String id) {
        templateDao.updateDelById(id);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    /**
     * 根据模板id获取机构服务项目id,然后找出具体服务项目内容
     * @param templateId
     * @return
     */
    public ListEnvelop findTemplateDetailByTemplateId(String templateId) {
        List<TemplateDetailVo> resultList = new ArrayList<>();
        List<RehabilitationTemplateDetailDO>  list = templateDetailDao.findTemplateDetailByTemplateId(templateId);
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, List<RehabilitationTemplateDetailDO>> map = list.stream().collect(Collectors.groupingBy(RehabilitationTemplateDetailDO::getHospitalServiceItemId));
        for (String code : map.keySet()){
            TemplateDetailVo detailVo = new TemplateDetailVo();
            detailVo.setCode(code);
            detailVo.setId(code);
            detailVo.setList(map.get(code));
            for (RehabilitationServiceItemDO item:itemDOList){
                if(code.equals(item.getCode())){
                    detailVo.setName(item.getName());
                    break;
                }
            }
            resultList.add(detailVo);
        }
        return ListEnvelop.getSuccess(SpecialistMapping.api_success,resultList);
    }
    public List<RehabilitationServiceItemDO> findSystemTemplateList(){
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        return itemDOList;
    }
    public List<RehabilitationDetailDO> createRehabilitationDetail(List<RehabilitationDetailDO> details, String planId) {
        for(RehabilitationDetailDO detail : details) {
            /*List<String> list = new ArrayList<>();
            list.add(detail.getHospitalServiceItemId());
            HospitalServiceItemDO hospitalServiceItemDO = hospitalServiceItemService.selectById(list).getDetailModelList().get(0);
            detail.setHospital(hospitalServiceItemDO.getHospital());
            detail.setHospitalName(hospitalServiceItemDO.getHospitalName());
            detail.setExpense(hospitalServiceItemDO.getExpense());*/
            detail.setPlanId(planId);
            detail.setCreateTime(new Date());
            detail.setStatus(0);
            detail.setUpdateTime(new Date());
        }
        return (List<RehabilitationDetailDO>)rehabilitationDetailDao.save(details);
    }
    public void deleteDetailByPlanIdAndHospitalServiceItemId(String planId, String hospitalServiceItemId, Date dateShort) {
        rehabilitationDetailDao.deleteDetailByPlanIdAndHospitalServiceItemId(planId, hospitalServiceItemId, dateShort);
    }
    public void deleteDetailByPlanId(String planId, Date dateShort) {
        rehabilitationDetailDao.deleteDetailByPlanId(planId, dateShort);
    }
    public List<RehabilitationDetailDO> updateRehabilitationPlan(String json, BaseDoctorDO doctor,String updateStatus) throws Exception {
        JSONObject object = new JSONObject(json);
        JSONArray array = object.getJSONArray("detail");
        for (int z=0;z<array.length();z++){
            JSONObject jsonObject = array.getJSONObject(z);
            Long timeType = jsonObject.getLong("timeType");
            Frequency frequency = frequencyDao.findByCode(jsonObject.getString("frequencyCode"));
            String executeTimes = jsonObject.getString("executeTimes");
            BaseDoctorDO doctor1 = doctorDao.findById(jsonObject.getString("doctor"));
            if(StringUtils.isNotBlank(executeTimes)) {
                List<String> list = new ArrayList<>();
                String[] executeTime = executeTimes.split(",");
                for (int i = 0; i < executeTime.length; i++) {
                    List<String> times = getFrequencyDate(frequency.getCode(), executeTime[i], frequency.getUnit(), frequency.getTime(), timeType);
                    for (int j = 0; j < times.size(); j++) {
                        if (list != null && list.size() != 0) {
                            if (!list.contains(times.get(j))) {
                                list.add(times.get(j));
                            }
                        } else {
                            list.add(times.get(j));
                        }
                    }
                }
                StringBuffer buffer = new StringBuffer();
                if (list != null && list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        buffer.append(list.get(i) + ",");
                    }
                    if (StringUtils.isNoneBlank(buffer)) {
                        buffer.deleteCharAt(buffer.length() - 1);
                    }
                }
                jsonObject.put("executeTime", buffer);
            }
            jsonObject.remove("executeTimes");
        }
        object.put("createUser", doctor.getId());
        object.put("createUserName", doctor.getName());
        String planId = object.getString("planId");
        String hospitalServiceItemId = object.getString("hospitalServiceItemId");
        //删除该服务项目今日之后未完成的计划
        if(StringUtils.isBlank(updateStatus)||updateStatus.equals("0")){//单个服务的修改
            deleteDetailByPlanIdAndHospitalServiceItemId(planId, hospitalServiceItemId, DateUtil.getDateShort(new Date()));
        }
        else{
           deleteDetailByPlanId(planId, DateUtil.getDateShort(new Date()));
        }
        JSONArray array1 = new JSONArray();
        for(Object planDetail : object.getJSONArray("detail")) {
            String expense="";
            JSONObject j = (JSONObject)planDetail;
            if (j.get("expense") instanceof Integer){
                expense= String.valueOf(j.getInt("expense"));
            }
            else{
                expense = j.getString("expense");
                if(expense.contains(".")){
                    int pointIndex = expense.indexOf(".");
                    expense = expense.substring(0,pointIndex);
                }
            }
            j.put("expense",expense);
            if(j.has("executeTime")) {
                String executeTime = j.get("executeTime").toString();
                String[] result = null;
                if (executeTime.contains(",")) {
                    result = executeTime.split(",");
                } else {
                    result = new String[1];
                    result[0] = executeTime;
                }
                int len = result.length;
                while (len > 0) {
                    len--;
                    JSONObject temp = new JSONObject(j.toString());
                    temp.put("executeTime", result[len]);
                    temp.put("createUser", object.get("createUser"));
                    temp.put("createUserName", object.get("createUserName"));
                    array1.put(temp);
                }
            }else {
                j.put("createUser", object.get("createUser"));
                j.put("createUserName", object.get("createUserName"));
                array1.put(j);
            }
        }
        String planDetails = array1.toString();
        ObjectMapper object1 = new ObjectMapper();
        object1.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        List<RehabilitationDetailDO> details = object1.readValue(planDetails, new TypeReference<List<RehabilitationDetailDO>>(){});
        details = createRehabilitationDetail(details, planId);
        String updateTime = DateUtil.dateToStr(details.get(0).getCreateTime(),"yyyy-MM-dd hh:mm:ss");
        //康复计划修改 日志添加
        String sql ="INSERT INTO wlyy_patient_rehabilitation_plan_log(id,plan_id,create_user,create_user_name,create_time) " +
                "VALUES('"+getCode()+"','"+planId+"','"+doctor.getId()+"','"+ doctor.getName()+"','"+updateTime+"')";
        jdbcTemplate.execute(sql);
        return details;
    }
    /**
     * 获取康复计划修改记录
     * @param planId
     * @return
     */
    public List<Map<String,Object>> getRehabilitationPlanLog(String planId){
        String sql ="select * from wlyy_patient_rehabilitation_plan_log where plan_id = '"+planId+"' ORDER BY create_time DESC";
        List<Map<String,Object>> planLogList = jdbcTemplate.queryForList(sql);
        return planLogList;
    }
    /**
     * 查询单个居民信息
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public JSONObject getPatient(String patient,String doctor) throws Exception {
        JSONObject json = new JSONObject();
//        Patient p = patientDao.findByCode(patient);
        BasePatientDO p = patientDao.findById(patient);
        if (p == null) {
            throw new Exception("patient info can not find");
        }
        // 设置患者标识
        json.put("code", p.getId());
        // 设置患者姓名
        json.put("name", p.getName());
        // 设置患者手机号
        json.put("mobile", p.getMobile());
        // 设置患者微信openid
        json.put("openid", StringUtils.isNotEmpty(p.getOpenid()) ? p.getOpenid() : "");
        json.put("openidTime",DateUtil.dateToStr(p.getOpenidTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));
        // 设置患者联系电话
        json.put("phone", p.getPhone());
        // 设置患者头像
        json.put("photo", p.getPhoto());
        // 设置患者年龄
        json.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(),p.getBirthday()));
        // 设置患者性别
        json.put("sex", p.getSex());
        // 身份证号
        json.put("idcard", p.getIdcard());
        //1.4.2新增medicareNumber
        //json.put("medicareNumber", p.());
        // 设置患者居住省份
        json.put("provinceName", p.getProvinceName());
        json.put("cityName", p.getCityName());
        json.put("townName", p.getTownName());
        json.put("streetName", p.getStreetName());
        // 设置患者地址
        json.put("address", p.getAddress());
        // 社保号
        json.put("ssc", p.getSsc());
        //病情类型:0健康,1高血压,2糖尿病,(1,2)高血压+糖尿病
       /* json.put("disease",p.getDisease());
        // 病情:0绿标,1黄标,2红标,
        json.put("diseaseCondition",p.getDiseaseCondition());*/
        //预警状态
        json.put("standardStatus",p.getStandardStatus());
        //设备状态:0未绑定,1血糖仪,2血压仪,3血糖仪+血压仪
       /* json.put("deviceType",p.getDeviceType()==null?"":p.getDeviceType());
        //20190719 增加返回字段:档案状态(-2冻结 1未管理 2死亡3 正常4 高危)
        json.put("archiveStatus",p.getArchiveStatus() == null? "":p.getArchiveStatus().toString());
        // 专病类型,专病名称
        json.put("specialistDisease", p.getSpecialistDisease());
        json.put("specialistDiseaseName", p.getSpecialistDiseaseName());
*/
        if (json.has("expensesStatus") && (StringUtils.isEmpty(String.valueOf(json.get("expensesStatus"))) || String.valueOf(json.get("expensesStatus")).equals("0"))) {
            boolean epTime = false;
            try {
                epTime = redisTemplate.opsForSet().isMember("expenses:remind:set", p.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!epTime) {
                json.put("expensesRemindStatus", 0);
            } else {
                json.put("expensesRemindStatus", 1);
            }
        }
        boolean epTime = false;
        try {
            epTime = redisTemplate.opsForSet().isMember("wechat:focus:remind:set", p.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!epTime) {
            json.put("wechatFocusRemind", 0);
        } else {
            json.put("wechatFocusRemind", 1);
        }
        String timeKey = DateUtil.dateToStr(new Date(), "yyyyMMdd");
        String flag = redisTemplate.opsForValue().get("renew:" + timeKey + ":" + patient);
        if (StringUtils.isNotBlank(flag)) {
            json.put("isRemindRenew", "1");
        } else {
            json.put("isRemindRenew", "0");
        }
        //1.4.9  是否专科医生服务
        List<PatientSignInfoVO> patientSignInfoVOS =findPatientSignSpecialist(patient);
        if(patientSignInfoVOS!=null&&patientSignInfoVOS.size()>0){
            json.put("isSpecialist",1);
            json.put("specialistArray", patientSignInfoVOS);
        }else{
            json.put("isSpecialist",0);
        }
        //1.5.0 是否有康复计划
        List<PatientRehabilitationPlanDO> planList = planListByPatient(patient);
        if(planList!=null&&planList.size()>0){
            json.put("havePlan",1);
        }else{
            json.put("havePlan",0);
        }
        return json;
    }
    public List<PatientSignInfoVO> findPatientSignSpecialist(String patient){
        String sql = "SELECT " +
                " r.id AS relationCode, " +
                " r.patient, " +
                " r.team_code AS teamCode,r.patient_name as patientName" +
                // AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " r.patient_name AS patientName, " +
//                " d.name AS doctorName, " +
                ",d.name as doctorName"+
                // AesEncryptUtils.decryptMysql("d.name","doctorName") +
                " ,d.id AS doctor, " +
                " d.photo, " +
                " d.job_title_name AS job, " +
                " d.sex AS sex " +
                " FROM " +
                " wlyy_doctor_patient_relation r " +
                " JOIN base_doctor d ON r.doctor = d.id " +
                " WHERE  " +
                " r.patient ='"+patient+"' " +
                " AND r.`status`>=0 " ;
        //sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<PatientSignInfoVO> patientSignInfoVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientSignInfoVO.class));
        return patientSignInfoVOs;
    }
    /**
     * 根据居民获取康复计划
     * @param patient
     * @return
     */
    public List<PatientRehabilitationPlanDO> planListByPatient(String patient){
        List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatients(patient);
        return list;
    }
    public JSONArray findTemplateDetailInfo(String templateId) throws Exception {
        Map<String, Object> param = new HashedMap();
        param.put("templateId", templateId);
        HttpResponse response = null;
        try {
            response = HttpUtils.doGet(specialistUrl + "svr-specialist/findTemplateDetailByTemplateId", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject rs = new JSONObject(response.getContent());
        if (rs.getInt("status") == 200) {
            JSONArray result = rs.getJSONArray("detailModelList");
            for (int i=0;i<result.length();i++){
                JSONObject obj = result.getJSONObject(i);
                JSONObject reobj = obj.getJSONArray("list").getJSONObject(0);
                if(!reobj.isNull("expense")){
                    Integer expense  = reobj.getInt("expense");
                    obj.put("expense",expense);
                }
                else{
                    obj.put("expense",0);
                }
            }
            return rs.getJSONArray("detailModelList");
        }
        throw new Exception("请求获取模板明细列表失败!");
    }
}

+ 6 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanningService.java

@ -1,11 +1,14 @@
package com.yihu.rehabilitation.service;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.rehabilitation.RehabilitationPlanningDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.rehabilitation.RehabilitationPlanningVO;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.rehabilitation.dao.RehabilitationPlanningDao;
import com.yihu.utils.security.MD5;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -20,6 +23,8 @@ import java.util.List;
public class RehabilitationPlanningService extends BaseJpaService<RehabilitationPlanningDO, RehabilitationPlanningDao> {
    @Autowired
    private RehabilitationPlanningDao planningDao;
    @Autowired
    private BasePatientDao basePatientDao;
    /**
     * 分页查找康复计划
@ -76,4 +81,5 @@ public class RehabilitationPlanningService extends BaseJpaService<Rehabilitation
        oldPlanningDO.setDescription(planningDO.getDescription());
        planningDao.save(oldPlanningDO);
    }
}

+ 34 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ServiceException.java

@ -0,0 +1,34 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.rehabilitation.service;
/**
 * Service层公用的Exception.
 * 
 * 继承自RuntimeException, 从由Spring管理事务的函数中抛出时会触发事务回滚.
 * 
 * @author calvin
 */
public class ServiceException extends RuntimeException {
	private static final long serialVersionUID = 3583566093089790852L;
	public ServiceException() {
		super();
	}
	public ServiceException(String message) {
		super(message);
	}
	public ServiceException(Throwable cause) {
		super(cause);
	}
	public ServiceException(String message, Throwable cause) {
		super(message, cause);
	}
}

+ 280 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/SpecialistEvaluateSevice.java

@ -0,0 +1,280 @@
package com.yihu.rehabilitation.service;/**
 * Created by nature of king on 2018/8/28.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.rehabilitation.RehabilitationInformationDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.sign.dao.MessagesDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.rehabilitation.dao.RehabilitationInformationDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * @author wangzhinan
 * @create 2018-08-28 9:09
 * @desc 服务项目评论
 **/
@Service
@Transactional
public class SpecialistEvaluateSevice {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SpecialistEvaluateSevice.class);
    @Autowired
    private SystemMessageDao messageDao;
    @Value("${specialist.url}")
    private String specialistUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseOrgDao hospitalDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    /**
     * 添加评论
     *
     * @param object
     * @return
     */
    public JSONObject insert(JSONObject object){
        String response = null;
        String url =specialistUrl + "svr-specialist/createEvaluate";
        Map<String,String> params = new HashMap<>();
        params.put("evaluate",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 更新评论
     *
     * @param object
     * @return
     */
    public JSONObject update(JSONObject object){
        String response = null;
        String url =specialistUrl + "svr-specialist/updateEvaluate";
        Map<String,String> params = new HashMap<>();
        params.put("evaluate",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 获取评论
     *
     * @param object
     * @return
     */
    public JSONObject select(JSONObject object){
        String response = null;
        String url =specialistUrl + "svr-specialist/getEvaluate";
        Map<String,String> params = new HashMap<>();
        params.put("evaluate",object.toJSONString());
        try {
            response = httpClientUtil.httpPost(url,params);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return JSONObject.parseObject(response);
    }
    /**
     * 医生获取评分
     *
     * @param doctor
     * @return
     */
    public JSONObject selectByDoctor(String doctor){
        String response = null;
        String url =/*"http://localhost:10051/"*/specialistUrl + "svr-specialist/selectByDoctor";
        Map<String,String> params = new HashMap<>();
        params.put("doctor",doctor);
        try {
            response = httpClientUtil.httpPost(url,params);
            JSONObject object = JSONObject.parseObject(response);
            if (object.getInteger("status")==200){
                JSONObject jsonObject4 = object.getJSONObject("obj");
                JSONObject jsonObject = jsonObject4.getJSONObject("4");
                JSONObject jsonObject1 = jsonObject4.getJSONObject("5");
                JSONObject jsonObject2 = jsonObject4.getJSONObject("6");
                JSONObject jsonObject3 = jsonObject4.getJSONObject("7");
                JSONArray array = jsonObject.getJSONArray("evaluate");
                JSONArray array1 = jsonObject1.getJSONArray("evaluate");
                JSONArray array2 = jsonObject2.getJSONArray("evaluate");
                JSONArray array3 = jsonObject3.getJSONArray("evaluate");
                //全部
                for (int i=0;i<array.size();i++){
                    JSONObject object1 = array.getJSONObject(i);
                    String patient = object1.getJSONArray("patient").getString(0);
                    BasePatientDO patient1 = patientDao.findById(patient);
                    Integer age = IdCardUtil.getAgeForIdcard(patient1.getIdcard());
                    object1.put("patient1",patient1);
                    object1.put("age",age);
                }
                //好评
                for (int i=0;i<array1.size();i++){
                    JSONObject object1 = array1.getJSONObject(i);
                    String patient = object1.getJSONArray("patient").getString(0);
                    BasePatientDO patient1 = patientDao.findById(patient);
                    Integer age = IdCardUtil.getAgeForIdcard(patient1.getIdcard());
                    object1.put("patient1",patient1);
                    object1.put("age",age);
                }
                //中评
                for (int i=0;i<array2.size();i++){
                    JSONObject object1 = array2.getJSONObject(i);
                    String patient = object1.getJSONArray("patient").getString(0);
                    BasePatientDO patient1 = patientDao.findById(patient);
                    Integer age = IdCardUtil.getAgeForIdcard(patient1.getIdcard());
                    object1.put("patient1",patient1);
                    object1.put("age",age);
                }
                //差评
                for (int i=0;i<array3.size();i++){
                    JSONObject object1 = array3.getJSONObject(i);
                    String patient = object1.getJSONArray("patient").getString(0);
                    BasePatientDO patient1 = patientDao.findById(patient);
                    Integer age = IdCardUtil.getAgeForIdcard(patient1.getIdcard());
                    object1.put("patient1",patient1);
                    object1.put("age",age);
                }
            }
            return object;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return null;
        }
    }
    /**
     * 发送消息 type:19 受理提醒,20 待办工作提醒 21 服务进展提醒-已完成 22 服务进展提醒-未完成 23 服务进展提醒-待完成 24 收到协同任务 25 在线助手已接收 26 在线助手已退回 27 协同服务已完成
     */
    public JSONObject sendMessage(SystemMessageDO message, String hospitalCode, String patientCode, Integer num, JSONObject jsonObject){
        JSONObject object = new JSONObject();
        try {
            BaseOrgDO hospital = null;
            if(StringUtils.isNotEmpty(hospitalCode)){
                hospital = hospitalDao.findByCode(hospitalCode);
            }
            BasePatientDO patient = null;
            if (StringUtils.isNoneBlank(patientCode)){
                patient  = patientDao.findById(patientCode);
            }
//            Doctor sendDoctor = doctorDao.findByCode(message.getSender());
            BaseDoctorDO receiverDoctor = doctorDao.findById(message.getReceiver());
            if (  "19".equalsIgnoreCase(message.getType()) ){
                message.setOver("0");//未处理
                message.setType("19");
                message.setTitle("康复计划-受理提醒");
                message.setContent("您的居民"+patient.getName()+"已出院,"+/*(hospital!=null?hospital.getName():"")*/message.getReason()+"为他制定了新康复计划,请查看");
            }else if ("20".equalsIgnoreCase(message.getType()) ){
                message.setOver("1");//未处理
                message.setType("20");
                message.setTitle("康复计划-待办工作提醒");
                if(num==0){
                    message.setContent("您的居民"+patient.getName()+"今天计划到"+(hospital!=null?hospital.getName():"")+"复诊,请查看");
                }else{
                    message.setContent("您的居民"+patient.getName()+num+"天后计划到"+(hospital!=null?hospital.getName():"")+"复诊,请查看");
                }
            }else if ("21".equalsIgnoreCase(message.getType()) ){
                message.setOver("0");//未处理
                message.setType("21");
                message.setTitle("康复计划-服务进展提醒");
                message.setContent("您的居民"+patient.getName()+"已完成康复计划今日项目,请查看");
            }else if ("22".equalsIgnoreCase(message.getType())){
                message.setOver("1");//未处理
                message.setType("22");
                message.setTitle("康复计划-服务进展提醒");
                message.setContent("服务时间提醒!您的居民"+patient.getName()+"该进行"+message.getData()+"了。");
            }else if ("23".equalsIgnoreCase(message.getType())){
                message.setOver("1");//未处理
                message.setType("23");
                message.setTitle("康复计划-服务定时提醒");
                message.setContent("您的居民"+patient.getName()+"明天有"+num+"个康复项目需完成,您可以修改定时提醒!");
            }else if ("24".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setType("24");
                message.setTitle("收到协同任务");
                message.setContent("您接收到“"+jsonObject.getString("type")+"”协同服务:"+jsonObject.getString("content").substring(0,19));
            }else if ("25".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setType("25");
                message.setTitle("在线助手已接收");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手接收,负责人:"+jsonObject.getString("customerName")+",联系方式:"+jsonObject.getString("phone")+"。");
            }else if ("26".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setType("26");
                message.setTitle("在线助手已退回");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手退回。原因:"+jsonObject.getString("returnedRemark"));
            }else if ("27".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setType("27");
                message.setTitle("协同服务已完成");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已完成。");
            }
            message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
//            message.setSenderName(sendDoctor.getName());
//            message.setSenderPhoto(sendDoctor.getPhoto());
//            message.setSex(sendDoctor.getSex());
            message.setReadonly(1);//是否只读消息
            message.setDel("1");
            message.setState(1);
            message.setIsRead("1");
            message.setReceiverName(receiverDoctor.getName());
            message.setData(patientCode);
            message.setCreateTime(new Date());
            messageDao.save(message);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return object;
    }
}

File diff suppressed because it is too large
+ 157 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ZsRehabilitationInfoService.java


+ 285 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/message/RehabilitationMessageService.java

@ -0,0 +1,285 @@
package com.yihu.rehabilitation.service.message;
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.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidanceDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationDetailDO;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.util.HttpClientUtil;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.rehabilitation.dao.RehabilitationGuidanceDao;
import com.yihu.rehabilitation.service.RehabilitationInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.transaction.Transactional;
import java.util.*;
/**
 * 消息业务处理类
 *
 * @author George
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class RehabilitationMessageService {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(RehabilitationMessageService.class);
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private RehabilitationGuidanceDao rehabilitationGuidanceDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private RehabilitationMessageService messageService;
    /*@Value("${doctorAssistant.api}")
    private String doctorAssistant;
    @Value("${doctorAssistant.target_url}")
    private String targetUrl;*/
    /*@Value("${hlwyy.url}")
    private String hlwyyUrl;*/
    private final String MESSAGE_NOTICESETTING = "wlyy:message:setting:";
   /* @Value("${im.im_list_get}")
    private String im_list_get;
    @Value("${specialist.url}")
    private String specialistUrl;*/
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private ImUtil imUtill;
    /**
     * 设置待办消息已处理
     *
     * @param id
     * @param type
     */
    public int setSpecialistOver(String id,Integer type){
        if (type == 22 || type==23){
            int result = 0;
            SystemMessageDO message = messageDao.findOne(id);
            List<RehabilitationDetailDO>  list =selectByIds(message.getRelationCode());
            Integer count = 0;
            if (list!=null){
                for (int i =0;i<list.size();i++){
                    if (list.get(i).getStatus() == 1){
                        count = count+1;
                    }
                }
                if (count == list.size()){
                    result = messageDao.setSpecialistById(id);
                }else {
                    result = messageDao.setSpecialistReadById(id);
                }
            }
            return result;
        } else if (type == 16) {
            //16.专科医生申请签约消息,点击处理时只改变只读状态,处理状态在调消息审批时处理
            return messageDao.setSpecialistReadById(id);
        } else if (type == 35) {
            //35  疾病筛查通知
            return messageDao.setSpecialistById(id);
        }else if (type == 36) {
            //36  康复下转居民推送提醒
            return messageDao.setSpecialistById(id);
        }else {
            return messageDao.setSpecialistById(id);
        }
    }
    public List<RehabilitationDetailDO> selectByIds(String ids){
        ObjEnvelop envelop = new ObjEnvelop();
        List idList = Arrays.asList(ids.split(","));
        StringBuffer buffer = new StringBuffer();
        for (int i =0;i<idList.size();i++){
            buffer.append("'"+idList.get(i)+"'").append(",");
        }
        buffer.deleteCharAt(buffer.length()-1);
        String sql = "select * from wlyy_rehabilitation_plan_detail where id in("+buffer+")";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll(sql);
        List<RehabilitationDetailDO> rehabilitationDetailDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(RehabilitationDetailDO.class));
        return rehabilitationDetailDOS;
    }
    /**
      * 康复计划-微信模板发送
     * @param patientCode 居民code
     * @param doctorCode 专科医生code
     * @param type 1康复指导2康复下转3复诊提醒4上门服务提醒5家签提醒
     * @param relationCode 业务关联code
     * @param planId 计划id
     * @throws Exception
     */
    public void sendSpecialistWeixinMessage(String patientCode,String doctorCode,Integer type,String relationCode,String planId,String reservationType) throws Exception {
        //康复指导
        BasePatientDO patient = patientDao.findById(patientCode);
        BaseDoctorDO doctor = doctorDao.findById(doctorCode);
        String name = "";
        String doctorName="";
        String familyDoctorName = "";
        String first="";
        String content="";
        String remarl="";
        String url="";
        org.json.JSONObject json = new org.json.JSONObject();
        if (patient!=null){
            name=patient.getName();
        }
        if (doctor!=null){
            doctorName = doctor.getName();
        }
        Integer sendType = null;
        if (type==1){
            RehabilitationguidanceDO rehabilitationguidanceDO = rehabilitationGuidanceDao.findByCode(relationCode);
            first=patient.getName() + ",您好!您的家庭医生发来一篇健康文章!";
            content= "《" + rehabilitationguidanceDO.getTitle() + "》";
            remarl="请及时阅读";
            url="kfgl/html/plan-item-detail.html?planIds="+planId+"";
            json.put("toUser", patientCode);
            json.put("first", patient.getName() + ",您好!您的家庭医生发来一篇健康文章!");
            json.put("represented",patientCode);//被代理人
            json.put("id", planId);
            json.put("date", DateUtil.getStringDate());
            json.put("doctorName", doctor.getName());
            json.put("content", "《" + rehabilitationguidanceDO.getTitle() + "》");
            json.put("remark", "请及时阅读");
            json.put("url",  "kfgl/html/plan-item-detail.html?planIds="+planId+"");
            sendType = 36;
        }else if (type==2){
            //反馈处理30
            sendType=30;
            String sql = "SELECT pr.manage_time as manageTime,pr.is_manage as isManage " +
                    "FROM wlyy_specialist.`wlyy_specialist_patient_relation` pr " +
                    "where pr.doctor = '"+doctorCode+"' and pr.patient = '"+patientCode+"' and pr.sign_status=1 and pr.`status`=1";
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
            String manageTime = "";
            for (Map<String,Object> map:mapList){
                manageTime = DateUtil.dateToStrLong((Date)map.get("manageTime"));
            }
            json.put("first", patient.getName() + ",您好!您已成功签约专科医生“"+doctorName+"”,"+doctorName+"医生(专科医生)和"+familyDoctorName+"(全科医生)将为您提供康复管理服务");
            json.put("toUser", patientCode);
            json.put("represented",patientCode);//被代理人
            json.put("keyword1", manageTime);
            json.put("keyword2", "康复下转");
            json.put("remark", "请及时阅读");
            json.put("relationCode",1);
            json.put("url",  "kfgl/html/recover_manage.html");
            first=patient.getName() + ",您好!您已成功签约专科医生“"+doctorName+"”,"+doctorName+"医生(专科医生)和"+familyDoctorName+"(全科医生)将为您提供康复管理服务";
            remarl="请及时阅读";
            url="kfgl/html/recover_manage.html";
            json.put("toUser", patientCode);
        }else if (type==3){
            //复诊提醒3
            //更新复诊类型
            if(StringUtils.isNoneBlank(reservationType)){
                String updSql = "update wlyy_rehabilitation_plan_detail set reservation_type = "+reservationType +" where id = '"+relationCode+"'";
                jdbcTemplate.execute(updSql);
            }
            sendType=11;//待办事项
            String sql = "select pd.id,pd.execute_time as executeTime from wlyy_rehabilitation_plan_detail pd " +
                    "where pd.id ='"+relationCode+"' and pd.hospital_service_item_id='7' and pd.status <>1 order by pd.execute_time desc ";
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
            String excuteTime="";
            if (mapList!=null&&mapList.size()!=0){
                excuteTime = DateUtil.dateToStrLong((Date)mapList.get(0).get("executeTime"));
            }
            if (StringUtils.isNoneBlank(excuteTime)){
                json.put("first", patient.getName() + ",您好!您的下次复诊时间是["+excuteTime+"],请按时安排就诊。您可点击“查看详情”,提前预约就诊");
                first=patient.getName() + ",您好!您的下次复诊时间是["+excuteTime+"],请按时安排就诊。您可点击“查看详情”,提前预约就诊";
            }else {
                json.put("first", patient.getName()+",您好!"+doctor.getName()+"医生提醒您预约复诊。您可点击“查看详情”,提前预约就诊");
                first=patient.getName()+",您好!"+doctor.getName()+"医生提醒您预约复诊。您可点击“查看详情”,提前预约就诊";
            }
            json.put("toUser", patientCode);
            json.put("represented",patientCode);//被代理人
            json.put("keyword1", "复诊预约");
            json.put("keyword2", ""+DateUtil.getStringDate()+"");
            json.put("remark", "请及时阅读");
            json.put("url",  "wdyy/html/appointment-register.html");
            remarl="请及时阅读";
            url="wdyy/html/appointment-register.html";
        }else if (type==4){
            //上门服务提醒 4
            sendType=11;//待办事项
            String sql = "select pd.id,pd.execute_time as executeTime from wlyy_rehabilitation_plan_detail pd " +
                    "where pd.id ='"+relationCode+"' and pd.hospital_service_item_id='4' and pd.status <>1 order by pd.execute_time desc ";
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
            String excuteTime="";
            String detailId = "";
            if (mapList!=null&&mapList.size()!=0){
                excuteTime = DateUtil.dateToStrLong((Date)mapList.get(0).get("executeTime"));
            }
            if(StringUtils.isNoneBlank(excuteTime)){
                json.put("first", patient.getName() + ",您好!您的下次上门诊疗服务时间是["+excuteTime+"],请按时预约上门诊疗服务。您可点击“查看详情”,提前预约就诊");
                first=patient.getName() + ",您好!您的下次上门诊疗服务时间是["+excuteTime+"],请按时预约上门诊疗服务。您可点击“查看详情”,提前预约就诊";
            }else {
                json.put("first", patient.getName()+",您好!"+doctor.getName()+"医生提醒您预约上门服务。您可点击“查看详情”,提前预约就诊");
                first=patient.getName()+",您好!"+doctor.getName()+"医生提醒您预约上门服务。您可点击“查看详情”,提前预约就诊";
            }
            json.put("toUser", patientCode);
            json.put("represented",patientCode);//被代理人
            json.put("keyword1", "上门诊疗服务预约");
            json.put("keyword2",DateUtil.getStringDate());
            json.put("remark", "请及时阅读");
            json.put("url",  "smfw/html/toAppointment.html?relationCode="+relationCode+"");
            remarl="请及时阅读";
            url="smfw/html/toAppointment.html?relationCode="+relationCode+"";
        }else if (type==5){
            //家签提醒 5
            sendType=11;//待办事项
            String sql = "select pd.id,pd.execute_time as executeTime from wlyy_rehabilitation_plan_detail pd " +
                    "where pd.plan_id ='"+planId+"' and pd.hospital_service_item_id='4' and pd.status <>1 order by pd.execute_time desc ";
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
            String excuteTime="";
            if (mapList!=null&&mapList.size()!=0){
                excuteTime = DateUtil.dateToStrLong((Date)mapList.get(0).get("executeTime"));
            }
            json.put("first", patient.getName() + ",您好!为方便为您提供康复管理服务,请先选择合适的社区和家庭医生进行签约");
            json.put("toUser", patientCode);
            json.put("represented",patientCode);//被代理人
            json.put("keyword1", "家庭医生签约");
            json.put("keyword2",  DateUtil.getStringDate());
            json.put("remark", "请及时阅读");
            json.put("url",  "qygl/html/signing-welcome.html");
            first= patient.getName() + ",您好!为方便为您提供康复管理服务,请先选择合适的社区和家庭医生进行签约";
            remarl="请及时阅读";
            url= "qygl/html/signing-welcome.html";
        }
        logger.info("微信模板入参:"+sendType+"=="+json.toString());
        rehabilitationInfoService.sendWechatMessage(patient.getId(),first,content,remarl,url);
    }
}

+ 38 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/HtmlUtil.java

@ -0,0 +1,38 @@
package com.yihu.rehabilitation.util;
import org.apache.commons.lang3.StringEscapeUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by liub on 2020/12/10.
 */
public class HtmlUtil {
    public static List<String> getTagContent(String source, String regString) {
        List<String> result = new ArrayList<String>();
        Matcher m = Pattern.compile(regString).matcher(source);
        while (m.find()) {
            try {
                String r = StringEscapeUtils.unescapeHtml3(URLDecoder.decode(m.group(1),"utf-8"));
                result.add(r);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public static  void main(String[] args){
        try {
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

+ 440 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/RHHttpClientUtil.java

@ -0,0 +1,440 @@
package com.yihu.rehabilitation.util;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@Component
public class RHHttpClientUtil {
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param chatSet 编码格式
     * @return
     */
    public String post(String url, List<NameValuePair> params, String chatSet) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, chatSet);
            httppost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 发送get请求
     *
     * @param url     请求地址
     * @param chatSet 编码格式
     * @return
     */
    public String get(String url, String chatSet) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * http调用方法,(健康之路开放平台)
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public String httpPost(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时时间
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            if (params != null && params.size() > 0) {
                List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
                    valuePairs.add(nameValuePair);
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse resp = httpclient.execute(httpPost);
            try {
                HttpEntity entity = resp.getEntity();
                String respContent = EntityUtils.toString(entity, "UTF-8").trim();
                return respContent;
            } finally {
                resp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            httpclient.close();
        }
    }
    /**
     * 获取加密后参数集合(健康之路开放平台)
     *
     * @param params
     * @return
     */
    public Map<String, String> getSecretParams(Map<String, String> params, String appId, String secret) {
        String timestamp = Long.toString(System.currentTimeMillis());
        params.put("timestamp", timestamp);
        StringBuilder stringBuilder = new StringBuilder();
        // 对参数名进行字典排序  
        String[] keyArray = params.keySet().toArray(new String[0]);
        Arrays.sort(keyArray);
        // 拼接有序的参数名-值串  
        stringBuilder.append(appId);
        for (String key : keyArray) {
            stringBuilder.append(key).append(params.get(key));
        }
        String codes = stringBuilder.append(secret).toString();
        String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
        // 添加签名,并发送请求  
        params.put("appId", appId);
        params.put("sign", sign);
        return params;
    }
    public String postBody(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    /*public String postBodyAuthorization(String url, String token, ModelVo model) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", token);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Accept",MediaType.ALL_VALUE);
        String str = "{\"model\":"+com.alibaba.fastjson.JSONObject.toJSONString(model)+"}";
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(str, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }*/
    public String getBodyAuthorization(String url, String token, String str) throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url+str);
        httpGet.addHeader("Authorization","Bearer"+" "+token);
        httpGet.addHeader("Type",MediaType.APPLICATION_JSON_VALUE);
        httpGet.addHeader("Accept",MediaType.ALL_VALUE);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String strss = EntityUtils.toString(entity, "UTF-8") ;
        return strss;
    }
    public String postAPPLICATIONFORMURLENCODEDVALUE(String url, String params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.ALL_VALUE.toString());
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    public String postBodyRawText(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.ALL_VALUE.toString());
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        String str = "grant_type=client_credentials&client_id=publichealth&client_secret=0139FE698142877D227DFAA7300638C3";
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(str, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    public String postBodyRawForm(String url, String params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<>(0);
        pairs.add(new BasicNameValuePair("object",params));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String ret = EntityUtils.toString(entity);
//        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Accept", MediaType.ALL_VALUE.toString());
//        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
//        String str = "object=UlTrAcqBvZs9AS2IDMigquTqBcE64vxGqSvFLSe+a4VYYs4nbv3UX26NMA+ECNHJGL5RqAMvwP6aO/Wzf++fV9RYGgfvQVmleCZsSXsY/tw=";
//        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<>(str, headers);
//        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    public String getBodyRawForm(String url, String params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> pairs = new ArrayList<>(0);
        pairs.add(new BasicNameValuePair("object",params));
        String entityString = EntityUtils.toString(new UrlEncodedFormEntity(pairs,Consts.UTF_8));
//        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
        HttpGet httpGet = new HttpGet(url+"?"+entityString);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String ret = EntityUtils.toString(entity);
        return ret;
    }
    private static String encode(String value) throws UnsupportedEncodingException {
        return URLEncoder.encode(value, "UTF-8");
    }
    public  void putBody(String url, JSONObject params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
        restTemplate.put(url, formEntity, String.class);
    }
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @return
     */
    public String iotPostBody(String url, String params) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params, headers);
        String ret = restTemplate.postForObject(url, formEntity, String.class);
        return ret;
    }
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @return
     */
    public String zsPostHeader(String url, com.alibaba.fastjson.JSONObject params, Map<String,Object> headerMap) {
        String chatSet = "UTF-8";
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        try {
            StringEntity entity1=new StringEntity(params.toJSONString(),"UTF-8");
            entity1.setContentEncoding("UTF-8");
            entity1.setContentType("application/json");
            httppost.setEntity(entity1);
            for(String str:headerMap.keySet()){
                httppost.addHeader(str,headerMap.get(str).toString());
            }
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 发送post请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param chatSet 编码格式
     * @param headerMap 请求头
     * @return
     */
    public  String headerPost(String url, List<NameValuePair> params, String chatSet,Map<String,Object> headerMap) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(params, chatSet);
            httppost.setEntity(uefEntity);
            for(String str:headerMap.keySet()){
                httppost.addHeader(str,headerMap.get(str).toString());
            }
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public  String get(String url, String chatSet,Map<String,Object> headerMap) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            url= url.replaceAll(" ", "%20");
            HttpGet httpget = new HttpGet(url);
            for(String str:headerMap.keySet()){
                httpget.addHeader(str,headerMap.get(str).toString());
            }
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, chatSet);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

+ 47 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/vo/TemplateDetailVo.java

@ -0,0 +1,47 @@
package com.yihu.rehabilitation.vo;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationTemplateDetailDO;
import java.util.List;
/**
 * Created by yeshijie on 2020/8/7.
 */
public class TemplateDetailVo {
    private String id;//兼容之前的版本
    private String code;
    private String name;
    private List<RehabilitationTemplateDetailDO> list;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<RehabilitationTemplateDetailDO> getList() {
        return list;
    }
    public void setList(List<RehabilitationTemplateDetailDO> list) {
        this.list = list;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
}

+ 258 - 9
svr/svr-rehabilitation/src/main/resources/application.yml

@ -3,8 +3,8 @@ server:
  port: 10055
spring:
  application:
    name:  svr-rehabilitation  #注册到发现服务的id 如果id一样 eurika会自动做负载
  #application:
   # name:  svr-rehabilitation  #注册到发现服务的id 如果id一样 eurika会自动做负载
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
@ -67,22 +67,271 @@ fast-dfs:
---
spring:
  profiles: jwdev
  fastDFS:
    fastdfs_file_url: http://172.19.103.54:80/
    datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://172.26.0.104/base?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true&useSSL=false
      username: ssgg
      password: ssgg@jkzl2019
neiwang:
  enable: true
  datasource:
    url: jdbc:mysql://172.19.103.77:3306/rehabilitation?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: root
    password: 123456
basedb:
  name: wlyy
specialist:
  url: http://localhost:10051/
server:
  server_url: http://weixin.xmtyw.cn/wlyy-dev/
activemq:
  broker-url: tcp://172.26.0.116:61616
  user: admin
  password: admin
  redis:
    host: 172.26.0.253 # Redis server host.
    port: 6379 # Redis server port.
fastDFS:
  fastdfs_file_url: http://172.19.103.54:80/
  fastdfs_file_url: http://172.26.0.110:8888/
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
wechat:
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
# 短信验证码发送的客户端标识,居民端
sms:
  clientId: EwC0iRSrcP
myFamily:
  qrCodeFailurTime: 2
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: true
#支付支付
pay:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
# 上传文件临时路径配置
FileTempPath:
  upload_temp_path : /var/local/temp
  image_path : /var/local/upload/images
  voice_path : /var/local/upload/voice
  chat_file_path : /var/local/upload/chat
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
  sign: 0
  remote_inner_url: 172.16.100.240:10023/open/fileUpload/upload_stream
wlyy:
  url: http://ehr.yihu.com/wlyy/
qywx:
  url: 2
  id: 1
express:
  sf_url: http://mrds-admin-ci.sit.sf-express.com:45478
  sf_code: HD000001
  sf_check_word: AAAABBBBCCCCDDDD
  #datasource:
  #  url: jdbc:mysql://172.19.103.77:3306/rehabilitation?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
   # username: root
   # password: 123456
#fastDFS:
  #fastdfs_file_url: http://172.19.103.54:80/
---
spring:
  profiles: jwtest
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.26.0.104/base?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true&useSSL=false
    username: ssgg
    password: ssgg@jkzl2019
neiwang:
  enable: true
basedb:
  name: wlyy
specialist:
  url: http://localhost:10051/
server:
  server_url: http://weixin.xmtyw.cn/wlyy-dev/
activemq:
  broker-url: tcp://172.26.0.116:61616
  user: admin
  password: admin
  redis:
    host: 172.26.0.253 # Redis server host.
    port: 6379 # Redis server port.
fastDFS:
  fastdfs_file_url: http://172.19.103.54:80/
  fastdfs_file_url: http://172.26.0.110:8888/
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
wechat:
  id: xm_ykyy_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
# 短信验证码发送的客户端标识,居民端
sms:
  clientId: EwC0iRSrcP
myFamily:
  qrCodeFailurTime: 2
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: true
#支付支付
pay:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
# 上传文件临时路径配置
FileTempPath:
  upload_temp_path : /var/local/temp
  image_path : /var/local/upload/images
  voice_path : /var/local/upload/voice
  chat_file_path : /var/local/upload/chat
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
  sign: 0
  remote_inner_url: 172.16.100.240:10023/open/fileUpload/upload_stream
wlyy:
  url: http://ehr.yihu.com/wlyy/
qywx:
  url: 2
  id: 1
express:
  sf_url: http://mrds-admin-ci.sit.sf-express.com:45478
  sf_code: HD000001
  sf_check_word: AAAABBBBCCCCDDDD
sign:
  check_upload: http://59.61.92.90:8072/wlyy_service
  check_upload_sign: http://59.61.92.90:8072/wlyy_sign
---
spring:
  profiles: jwprod
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://172.26.0.104/base?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true&useSSL=false
    username: ssgg
    password: ssgg@jkzl2019
neiwang:
  enable: true
basedb:
  name: wlyy
specialist:
  url: http://localhost:10051/
server:
  server_url: http://weixin.xmtyw.cn/wlyy-dev/
activemq:
  broker-url: tcp://172.26.0.116:61616
  user: admin
  password: admin
  redis:
    host: 172.26.0.253 # Redis server host.
    port: 6379 # Redis server port.
fastDFS:
  fastdfs_file_url: http://172.19.103.54:80/
  fastdfs_file_url: http://172.26.0.110:8888/
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
wechat:
  id: xm_zsyy_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
# 短信验证码发送的客户端标识,居民端
sms:
  clientId: EwC0iRSrcP
myFamily:
  qrCodeFailurTime: 2
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: true
#支付支付
pay:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://172.26.0.105:3000/
  data_base_name: im_internet_hospital
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
  type:
    Statistics: hlw_quota_test
  host:  http://172.26.0.55:9000
  tHost: 172.26.0.55:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
# 上传文件临时路径配置
FileTempPath:
  upload_temp_path : /var/local/temp
  image_path : /var/local/upload/images
  voice_path : /var/local/upload/voice
  chat_file_path : /var/local/upload/chat
#文件服务器上传配置 0本地,1.I健康,2.内网调用
testPattern:
  sign: 0
  remote_inner_url: 172.16.100.240:10023/open/fileUpload/upload_stream
wlyy:
  url: http://ehr.yihu.com/wlyy/
qywx:
  url: 2
  id: 1
express:
  sf_url: http://mrds-admin-ci.sit.sf-express.com:45478
  sf_code: HD000001
  sf_check_word: AAAABBBBCCCCDDDD

+ 17 - 8
svr/svr-rehabilitation/src/main/resources/bootstrap.yml

@ -1,43 +1,52 @@
##优先读取 boostarap配置 然后在读取application。yml的配置
spring:
  #从发现服务里面取配置服务的信息
  application:
    name: svr-rehabilitation
  cloud:
    config:
      failFast: true #启动快速失败 即链接不到配置服务就启动失败
      username: jw
      password: jkzl
      discovery:
        enabled: true #使用发现服务
        service-id: svr-configurations #配置服务的名字
---
spring:
  profiles: jwdev
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.26.0.107:1221}
      label: ${wlyy.spring.config.label:jwdev}
##发现服务的地址
eureka:
  client:
    serviceUrl:
      #http://账号:密码@127.0.0.1:8761/eureka/
      defaultZone: http://jw:jkzl@172.19.103.33:8761/eureka/
      defaultZone: http://jw:jkzl@172.26.0.107:8761/eureka/
---
spring:
  profiles: jwtest
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.26.0.107:1221}
      label: ${wlyy.spring.config.label:jwdev}
eureka:
  client:
    serviceUrl:
      #http://账号:密码@127.0.0.1:8761/eureka/
      defaultZone: http://jw:jkzl@172.19.103.33:8761/eureka/
      #http://账号:密码@127.0.0.1:8761/eureka/          172.19.103.33:8761
      defaultZone: http://jw:jkzl@172.26.0.107:8761/eureka/
---
spring:
  profiles: jwprod
  cloud:
    config:
      uri: ${wlyy.spring.config.uri:http://172.16.1.42:1221}
      label: ${wlyy.spring.config.label:master}
eureka:
  client: