Bladeren bron

康复下转接口搬运

wangjun 4 jaren geleden
bovenliggende
commit
edf4e4760c
48 gewijzigde bestanden met toevoegingen van 7370 en 32 verwijderingen
  1. 14 3
      business/base-service/src/main/java/com/yihu/jw/internet/service/InternetCommonService.java
  2. 15 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/GuidanceMessageLogDao.java
  3. 13 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/RehabilitationDetailAppointmentDao.java
  4. 38 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/RehabilitationOperateRecordsDao.java
  5. 41 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/SpecialistPatientRelationDao.java
  6. 15 0
      business/base-service/src/main/java/com/yihu/jw/security/RSADao.java
  7. 258 0
      business/base-service/src/main/java/com/yihu/jw/sign/dao/MessagesDao.java
  8. 26 0
      business/base-service/src/main/java/com/yihu/jw/team/BaseDoctorTeamDao.java
  9. 42 0
      business/base-service/src/main/java/com/yihu/jw/team/BaseDoctorTeamMemberDao.java
  10. 3 0
      business/base-service/src/main/java/com/yihu/jw/wechat/dao/JsapiTicketDao.java
  11. 8 0
      business/base-service/src/main/java/com/yihu/jw/wechat/dao/WxAccessTokenDao.java
  12. 6 0
      common/common-entity/pom.xml
  13. 0 3
      common/common-entity/src/main/java/com/yihu/jw/entity/base/wx/WxAccessTokenDO.java
  14. 118 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeam.java
  15. 77 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamFunction.java
  16. 70 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMember.java
  17. 48 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMemberAuthority.java
  18. 49 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMemberRole.java
  19. 77 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamRole.java
  20. 119 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/Frequency.java
  21. 73 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationAdviceDO.java
  22. 31 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/RSA.java
  23. 208 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/SystemConf.java
  24. 72 0
      common/common-entity/src/main/java/com/yihu/jw/entity/wlyyinfo/WechatTag.java
  25. 51 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/rehabilitation/RehabilitationRequestMapping.java
  26. 78 5
      svr/svr-rehabilitation/pom.xml
  27. 8 1
      svr/svr-rehabilitation/src/main/java/com/yihu/SvrRehabilitationApplication.java
  28. 5 1
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/config/jpa/RehabilitationJpa.java
  29. 3 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanningController.java
  30. 98 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitaionInfoController.java
  31. 415 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationManageController.java
  32. 209 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationPlanController.java
  33. 264 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/patient/PatientRehabilitationManageController.java
  34. 21 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/FrequencyDao.java
  35. 58 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientRehabilitationPlanDao.java
  36. 20 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationAdviceDao.java
  37. 94 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationDetailDao.java
  38. 461 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/SignFamilyDao.java
  39. 176 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationInfoService.java
  40. 1727 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationManageService.java
  41. 887 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanService.java
  42. 6 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanningService.java
  43. 34 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ServiceException.java
  44. 279 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/SpecialistEvaluateSevice.java
  45. 221 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/HttpUtil.java
  46. 639 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/ImUtill.java
  47. 178 11
      svr/svr-rehabilitation/src/main/resources/application.yml
  48. 17 8
      svr/svr-rehabilitation/src/main/resources/bootstrap.yml

+ 14 - 3
business/base-service/src/main/java/com/yihu/jw/internet/service/InternetCommonService.java

@ -1,5 +1,6 @@
package com.yihu.jw.internet.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -134,7 +135,15 @@ public class InternetCommonService extends BaseJpaService<InternetUpErrorLogDO,
        getBaseSurperviseDict();
        WsapiProxy proxy = new WsapiProxy();
        proxy.setEndpoint(url);
        logger.info("入参:"+JSONUtils.toString(params));
        JSONObject jsonObject= new JSONObject();
        if (params!=null&&params.size()>0){
            jsonObject= params.getJSONObject(0);
            jsonObject.put("docimg","");
            jsonObject.put("doc_cert","");
            jsonObject.put("cert_doc_prac","");
        }
        logger.info("入参:"+jsonObject.toString());
        Wsapi wsapi = proxy.getWsapi();
//        logger.info("postToInter:"+JSONUtils.toString(new String[] {token, params.toString()}));
@ -772,7 +781,8 @@ public class InternetCommonService extends BaseJpaService<InternetUpErrorLogDO,
               "JOIN "+base+".topics t ON t.id = b.consult\n" +
               "WHERE\n" +
               "\ta.id = b.consult\n" +
               " AND a.symptoms IS NOT NULL AND b.status=1 ";
               " AND a.symptoms IS NOT NULL AND b.status=1 " +
               "  and c.doctor not in ('402803816babc778016babd0dee21112')";
        Map<String,Object> params = new HashedMap();
@ -1578,7 +1588,8 @@ public class InternetCommonService extends BaseJpaService<InternetUpErrorLogDO,
                "JOIN "+base+".topics t ON t.id = b.consult\n" +
                "WHERE\n" +
                "\ta.id = b.consult\n" +
                "AND a.symptoms IS NOT NULL AND b.status=1";
                "AND a.symptoms IS NOT NULL AND b.status=1 " +
                " and c.doctor not in ('402803816babc778016babd0dee21112')";
        if(StringUtils.isNotBlank(startDate)){
            wlzxSql =  wlzxSql + "  and a.czrq >=:startDate ";

+ 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);
}

+ 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);
}

+ 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);
}

+ 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>

+ 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)

+ 118 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeam.java

@ -0,0 +1,118 @@
package com.yihu.jw.entity.hospital.doctor;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
 * 医生行政团队。
 *
 * @author Sand
 */
@Entity
@Table(name = "wlyy_admin_team")
public class AdminTeam extends IdEntity {
    private String name;
    private Date createTime;
    private String leaderCode;
    private boolean available;
    private String orgCode;
    private String orgName;
    private String townCode;
    private String townName;
    private String mappingCode;
    public String getName() {
        return name;
    }
    @Column(name = "name")
    public void setName(String name) {
        this.name = name;
    }
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    @Column(name = "create_time")
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getOrgCode() {
        return orgCode;
    }
    @Column(name = "org_code")
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
    public String getLeaderCode() {
        return leaderCode;
    }
    @Column(name = "leader_id")
    public void setLeaderCode(String leaderCode) {
        this.leaderCode = leaderCode;
    }
    public boolean isAvailable() {
        return available;
    }
    @Column(name = "available")
    public void setAvailable(boolean available) {
        this.available = available;
    }
    @Column(name = "mapping_code")
    public String getMappingCode() {
        return mappingCode;
    }
    public void setMappingCode(String mappingCode) {
        this.mappingCode = mappingCode;
    }
    @Transient
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    @Transient
    public String getTownCode() {
        return townCode;
    }
    public void setTownCode(String townCode) {
        this.townCode = townCode;
    }
    @Transient
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
}

+ 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;
    }
}

+ 70 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/hospital/doctor/AdminTeamMember.java

@ -0,0 +1,70 @@
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;
/**
 * 医生行政团队成员。
 *
 * @author Sand
 */
@Entity
@Table(name = "wlyy_admin_team_member")
public class AdminTeamMember extends IdEntity {
    private long teamId;
    private String doctorCode;
    private Date joinTime;
    private boolean available;
    private String qrcode;
    public long getTeamId() {
        return teamId;
    }
    @Column(name = "team_id")
    public void setTeamId(long teamId) {
        this.teamId = teamId;
    }
    public String getDoctorCode() {
        return doctorCode;
    }
    @Column(name = "doctor_id")
    public void setDoctorCode(String doctorCode) {
        this.doctorCode = doctorCode;
    }
    @JsonFormat(pattern = "yyyy-MM-dd hh:mm", timezone = "GMT+08:00")
    public Date getJoinTime() {
        return joinTime;
    }
    @Column(name = "join_time")
    public void setJoinTime(Date joinTime) {
        this.joinTime = joinTime;
    }
    public boolean isAvailable() {
        return available;
    }
    @Column(name = "available")
    public void setAvailable(boolean available) {
        this.available = available;
    }
    @Column(name = "qrcode")
    public String getQrcode() {
        return qrcode;
    }
    public void setQrcode(String qrcode) {
        this.qrcode = qrcode;
    }
}

+ 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;
    }
}

+ 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;
    }
}

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

@ -32,6 +32,57 @@ 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 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";

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

@ -102,22 +102,95 @@
			<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>
	</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>
				<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>
				<artifactId>maven-compiler-plugin</artifactId>
				<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);
	}
}

+ 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);
    }
}
*/

+ 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());
        }
    }
}

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

@ -0,0 +1,98 @@
package com.yihu.rehabilitation.controller.doctor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.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.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("创建/编辑康复建议模板")
    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("删除康复建议模板")
    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("操作成功");
        } 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 = "patient", value = "居民code", required = false)
                                 @RequestParam(value = "patient", required = false)String wxId){
        try {
            rehabilitationInfoService.sendSFWxTemplate(patient,wxId);
            return success("发送成功");
        } catch (Exception e) {
           e.printStackTrace();
            return failed("发送失败");
        }
    }
}

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

@ -0,0 +1,415 @@
package com.yihu.rehabilitation.controller.doctor;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
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.service.RehabilitationManageService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.util.ImUtill;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
/**
 * 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 ImUtill imUtill;
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @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) {
            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());
        }
    }
    @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,ImUtill.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());
        }
    }
}

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

@ -0,0 +1,209 @@
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.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.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.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
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;
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.createRehabilitationPlan, method = RequestMethod.POST)
    @ApiOperation(value = "创建居民康复计划")
    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);
            rehabilitationPlanService.saveRehabilitationRecord(rehabilitationOperateRecordsDO);
            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());
        }
    }
}

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

@ -0,0 +1,264 @@
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.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.specialist.SpecialistMapping;
import com.yihu.rehabilitation.service.RehabilitationManageService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.util.ImUtill;
import com.yihu.rehabilitation.web.BaseController;
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 = "/patient/specialist/rehabilitation", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "居民端-康复管理")
public class PatientRehabilitationManageController extends EnvelopRestEndpoint {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private ImUtill imUtill;
    @Autowired
    private RehabilitationPlanService rehabilitationPlanService;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @RequestMapping(value = "patientRehabilitationDetail", method = RequestMethod.GET)
    @ApiOperation("康复管理-微信端-居民详情页")
    public ObjEnvelop patientRehabilitationDetail(){
        try {
            return  rehabilitationManageService.patientRehabilitationDetail(getUID());
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "calendarPlanDetail", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按日历展示")
    public ObjEnvelop calendarPlanDetail(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                     @RequestParam(value = "executeStartTime", required = true)String executeStartTime,
                                     @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                     @RequestParam(value = "executeEndTime", required = true)String executeEndTime,
                                     @ApiParam(name = "planId", value = "计划id", required = true)
                                     @RequestParam(value = "planId", required = true)String planId,
                                     @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、复诊,4、随访)", required = false)
                                     @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                     @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                     @RequestParam(value = "status", required = false)Integer status){
        try {
            return rehabilitationManageService.calendarPlanDetail(executeStartTime,executeEndTime,planId,searchTask,status,null,null);
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "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 = "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 = "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 = "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 = "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 = "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 = "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 = "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 = "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 = "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 = SpecialistMapping.serviceItem.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);
}

+ 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.executeTime<=?1 and d.executeTime>=?2 and d.planId=?3")
    List<RehabilitationDetailDO> findByPlanId(Date executeStartTime, Date executeEndTime, String planId);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor=?1 and p.patient=?2  and d.status!=?3",nativeQuery = true)
    Integer unfinishItemByDoctor(String doctor, String patient, Integer status);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor in (?1,?2) and p.patient=?3  and d.status!=?4",nativeQuery = true)
    Integer unfinishItemByDoctor(String generalDoctor, String healthDoctor, String patient, Integer status);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor=?1 and p.patient=?2",nativeQuery = true)
    Integer findItemByDoctor(String doctor, String patient);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor in (?1,?2) and p.patient=?3",nativeQuery = true)
    Integer findItemByDoctor(String generalDoctor, String healthDoctor, String patient);
//    @Query("select count(distinct serviceItemId) from RehabilitationDetailDO d left join PatientRehabilitationPlanDO p on d.planId=p.id where doctor=?1 and p.patient=?2 ")
//    Integer finishItemByDoctor(String doctor,String patient);
//
    @Query(value ="select count(1) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where doctor=?1 and p.patient=?2  and d.status=?3",nativeQuery = true)
    Integer completeServiceByDoctor(String doctor, String patient, Integer status);
    @Query(value ="select count(1) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where doctor in (?1,?2) and p.patient=?3  and d.status=?4",nativeQuery = true)
    Integer completeServiceByDoctor(String generalDoctor, String healthDoctor, String patient, Integer status);
    RehabilitationDetailDO findById(String planDetailId);
    @Query(value ="select d.doctor,p.patient,count(1) as num from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.status!=1 and d.execute_time>=?1 and d.execute_time<=?2 GROUP BY d.doctor,p.patient",nativeQuery = true)
    List<Map> dailyJob(String startTime, String endTime);
    @Query(value = "select d.id from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.status!=1 and d.execute_time>=?1 and d.execute_time<=?2 and d.doctor=?3 and p.patient=?4",nativeQuery = true)
    List<String> findByPatientAndDoctor(String startTime, String endTime, String doctorCode, String patientCode);
    @Modifying
    @Query("update RehabilitationDetailDO t set t.status = ?1 where t.id=?2 ")
    int updateStatusById(Integer status, String id);
    @Modifying
    @Query("update RehabilitationDetailDO t set t.status = ?1,t.relationCode=?3 where t.id=?2 ")
    int updateStatusAndRelationCodeById(Integer status, String id, String relationCode);
    @Query(value ="select p.patient from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.id=?1",nativeQuery = true)
    List<String> findPatientById(String planDetailId);
    @Query
    List<RehabilitationDetailDO> findByPlanIdAndStatus(String planId, int status);
    @Modifying
    @Query("update RehabilitationDetailDO t set t.executeTime = ?1 where t.id=?2 ")
    int updateExecuteTime(Date executeTime, String id);
    @Modifying
    @Query("delete from RehabilitationDetailDO t where t.planId = ?1 and t.hospitalServiceItemId = ?2 and (t.executeTime > ?3 OR t.executeTime is null OR t.executeTime<>'')  and t.status <> 1 ")
    void deleteDetailByPlanIdAndHospitalServiceItemId(String planId, String hospitalServiceItemId, Date dateShort);
    @Modifying
    @Query("delete from RehabilitationDetailDO t where t.planId = ?1 and (t.executeTime > ?2 OR t.executeTime is null OR t.executeTime<>'')  and t.status <> 1 ")
    void deleteDetailByPlanId(String planId, Date dateShort);
    @Query("select d from RehabilitationDetailDO d where d.planId = ?1 and d.type=?2 and d.doctor=?3 and d.status<>?4 ")
    List<RehabilitationDetailDO> findByPlanIdAndTypeAndDoctorAndStatusNot(String planId, Integer type, String doctor, Integer status);
}

+ 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);*/
}

+ 176 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationInfoService.java

@ -0,0 +1,176 @@
package com.yihu.rehabilitation.service;
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.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.BasePatientWechatDo;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxPushLogDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionExpressageDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionInfoDO;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
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.wechat.WeixinMessagePushUtils;
import com.yihu.jw.wechat.dao.BasePatientWechatDao;
import com.yihu.jw.wechat.dao.WxPushLogDao;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
import com.yihu.jw.wechat.service.WxAccessTokenService;
import com.yihu.rehabilitation.dao.RehabilitationAdviceDao;
import com.yihu.rehabilitation.dao.SignFamilyDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
 * Created by humingfen on 2020/2/26.
 */
@Service
@Transactional
public class RehabilitationInfoService {
    private static final Logger logger = LoggerFactory.getLogger(RehabilitationInfoService.class);
    @Autowired
    private RehabilitationAdviceDao adviceDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorMappingDao doctorMappingDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WeixinMessagePushUtils weixinMessagePushUtils;
    @Autowired
    private BasePatientWechatDao basePatientWechatDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WxPushLogDao wxPushLogDao;
    /**
     * 新增或编辑康复建议模板
     * @param doctorCode
     * @param code 模板code
     * @param name
     * @param content
     */
    public void createAdvice(String doctorCode, String code, String name, String content) {
        RehabilitationAdviceDO adviceDO = null;
        //判断是新增还是编辑
        if (StringUtils.isNotBlank(code)) {
            adviceDO = adviceDao.findByCode(code);
        } else {
            adviceDO = new RehabilitationAdviceDO();
            adviceDO.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
            BaseDoctorDO doctor = doctorDao.findById(doctorCode);
            adviceDO.setCreateUser(doctorCode);
            adviceDO.setCreateUserName(doctor.getName());
        }
        adviceDO.setName(name);
        adviceDO.setContent(content);
        adviceDO.setCreateTime(new Date());
        adviceDao.save(adviceDO);
    }
    public void deleteAdvice(Long id) {
        adviceDao.delete(id);
    }
    /**
     * 获取医生创建康复建议模板及系统模板
     * @param doctorCode
     * @return
     */
    public List<RehabilitationAdviceDO> getAdviceListByDoctor(String doctorCode) {
        List<RehabilitationAdviceDO> list = adviceDao.findByDoctor(doctorCode);
        return list;
    }
    /**
     * 发送顺丰物流提醒模板消息
     * @param patient
     */
    public void sendSFWxTemplate(String patient,String wechatId){
        String patienName = "";
        BasePatientDO basePatientDO = patientDao.findById(patient);
        if (basePatientDO!=null){
            patienName = basePatientDO.getName();
        }
        List<BasePatientWechatDo> ps = new ArrayList<BasePatientWechatDo>();
        if (StringUtils.isNotEmpty(patient)){
            ps = basePatientWechatDao.findByWechatIdAndPatientId(wechatId, patient);
        }
        if (ps.isEmpty()) {
            return;
        }
        WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
        String scene = "sfxxtx";
        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndSceneAndStatus(wechatId, "template_sf_msg_notice", scene, 1);
        BeanUtils.copyProperties(config, newConfig);
       /* newConfig.setFirst(config.getFirst().replace("key1",remindMsg));
        newConfig.setKeyword1(config.getKeyword1().replace("key1",patienName).replace("key2",drugName));
        newConfig.setKeyword2("顺丰快递");
        newConfig.setKeyword3(mailNo);
        newConfig.setKeyword4(remindMsg);
        newConfig.setRemark(config.getRemark());
        newConfig.setUrl(newConfig.getUrl().replace("key1",outpatientId).replace("key2",prescriptionId));*/
        logger.info("=======setUrl========" + newConfig.getUrl());
        WxAccessTokenDO wxAccessTokenDO = wxAccessTokenService.getWxAccessTokenById(wechatId);
        for (BasePatientWechatDo one : ps) {
            logger.info("发送的消息="+ com.alibaba.fastjson.JSONObject.toJSONString(newConfig));
            try {
                logger.info("调用微信模板消息接口的入参:AccessToken="+wxAccessTokenDO.getAccessToken()+"---Openid="+one.getOpenid());
                weixinMessagePushUtils.putWxMsg(wxAccessTokenDO.getAccessToken(), one.getOpenid(), newConfig);
                logger.info("发送成功");
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("发送失败,error="+e.getMessage());
            }
            //保存发送模板记录,
            WxPushLogDO wxPushLogDO = new WxPushLogDO();
            wxPushLogDO.setCreateTime(new Date());
            wxPushLogDO.setOpenid(one.getOpenid());
            wxPushLogDO.setReceiver(patient);
            wxPushLogDO.setWechatId(wechatId);
            wxPushLogDO.setReceiverName(patienName);
            wxPushLogDO.setScene(scene);
            wxPushLogDao.save(wxPushLogDO);
        }
    }
}

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

@ -0,0 +1,1727 @@
package com.yihu.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
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.patient.Message;
import com.yihu.jw.entity.patient.Patient;
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.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.GuidanceMessageLogDao;
import com.yihu.jw.rehabilitation.RehabilitationDetailAppointmentDao;
import com.yihu.jw.rehabilitation.RehabilitationOperateRecordsDao;
import com.yihu.jw.rehabilitation.SpecialistPatientRelationDao;
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.date.DateUtil;
import com.yihu.rehabilitation.dao.FrequencyDao;
import com.yihu.rehabilitation.dao.PatientRehabilitationPlanDao;
import com.yihu.rehabilitation.dao.RehabilitationDetailDao;
import com.yihu.rehabilitation.dao.SignFamilyDao;
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.Transactional;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Created by 刘文彬 on 2018/8/16.
 */
@Service
@Transactional
public class RehabilitationManageService {
    @Value("${basedb.name}")
    private String basedb;
    @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;
    /**
     * 预约协诊
     * @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;
        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 "+basedb+".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_specialist_patient_relation r join wlyy_patient_rehabilitation_plan p on r.patient=p.patient where r.sign_status ='1' and 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 "+basedb+".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_specialist_patient_relation r left join "+basedb+".wlyy_admin_team t on r.team_code=t.id left join "+basedb+".dm_hospital h on t.org_code=h.code where r.sign_status ='1' and 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+specialistFinishCount2-specialistUnfinishCount2);//完成项目
            resultMap.put("specialistServiceRecordCount",specialistServiceCount1+specialistServiceCount2);//服务次数
            //家庭医生(包括全科医生、健管师)
            String signFamilySql = "SELECT f.*,t.name as teamName FROM "+basedb+".wlyy_sign_family f LEFT JOIN "+basedb+".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 "+basedb+".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 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 ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        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(taskExecutor.equals("1")){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if(taskExecutor.equals("2")){//他人任务
            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.content,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);
        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")+"");
//        }
        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 "+basedb+".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 "+basedb+".wlyy_admin_team t where t.available=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 ObjEnvelop 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 ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
    }
    /**
     * 明日康复计划提醒
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public ObjEnvelop 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 ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
    }
    /**
     * 每日康复计划提醒
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public ObjEnvelop 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 ObjEnvelop.getSuccess(SpecialistMapping.api_success,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.service_item_id," +
                " r.doctor_code," +
                " r.patient_code," +
                " pd.hospital" +
                " FROM" +
                " wlyy_rehabilitation_plan_detail pd" +
                " LEFT JOIN wlyy_hospital_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("service_item_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
        String hospotal = resultMap.get("hospital").toString();
        String patient = resultMap.get("patient_code").toString();
        String doctor = resultMap.get("doctor_code").toString();
        Message message = new Message();
        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(jsonObject.getString("doctorName"));
        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("更新失败!");
    }
    /**
     * 计划总进度
     * @param planId
     * @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);
        SpecialistPatientRelationDO specialistPatientRelationDO;
        if (p.getTeamCode()!= null) {
             specialistPatientRelationDO = specialistPatientRelationDao.findByTeamCodeAndPatient(p.getTeamCode(),p.getPatient());
        }
        else {
             specialistPatientRelationDO = specialistPatientRelationDao.findByDoctorAndPatient(p.getCreateUser(),p.getPatient());
        }
        resultMap.put("allCount",allCount);
        resultMap.put("finishedCount",finishedCount);
        resultMap.put("specialistPatientRelationDO",specialistPatientRelationDO);
        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("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());
        }
        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());
        String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+basePatientDO.getId()+"' 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);
        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 ObjEnvelop dailyJobReserve(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 ObjEnvelop.getSuccess(SpecialistMapping.api_success,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("-", "");
    }
}

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

@ -0,0 +1,887 @@
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.patient.Message;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationDetailDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.RehabilitationOperateRecordsDao;
import com.yihu.jw.restmodel.iot.common.UploadVO;
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.specialist.SpecialistMapping;
import com.yihu.jw.sign.dao.MessagesDao;
import com.yihu.jw.team.BaseDoctorTeamMemberDao;
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.FrequencyDao;
import com.yihu.rehabilitation.dao.PatientRehabilitationPlanDao;
import com.yihu.rehabilitation.dao.RehabilitationDetailDao;
import com.yihu.rehabilitation.dao.SignFamilyDao;
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.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.*;
/**
 * 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 MessagesDao 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;
    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) {
        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);
    }
    //code,timeType,executeTimes
    public String createRehabilitationPlan(String json, BaseDoctorDO doctor) throws Exception {
        JSONObject object = new JSONObject(json);
        String patient = object.getString("patient");
        BasePatientDO patientDo  = null;
        if (!StringUtils.isNoneBlank(patient)){
            BasePatientDO basePatientDO = new BasePatientDO();
            basePatientDO.setName(object.getString("patientName"));
            basePatientDO.setIdcard(object.getString("idCard"));
            basePatientDO.setMobile(object.getString("mobile"));
            patientDo = saveUnSignPatient(basePatientDO);
        }else {
            patientDo = patientDao.findById(patient);
        }
        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<>();
            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.remove("executeTimes");
            jsonObject.put("executeTime",buffer);
        }
        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 = createPatientRehabilitationPlan(planDO);
        details = createRehabilitationDetail(details, planDO.getId());
        //康复计划创建完给执行者发送消息
        String planId = null;
        HashSet set = new HashSet();
        for ( RehabilitationDetailDO rehabilitationDetailDO : details) {
            if (!set.contains(rehabilitationDetailDO.getDoctor())) {
                set.add(rehabilitationDetailDO.getDoctor());
                planId = rehabilitationDetailDO.getPlanId();
                Message message = new Message();
                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+"的康复计划已配置完成,点击查看", "");
            }
        }
        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(inputStream,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.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<Message> 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+"康复计划,点击查看原因", "");
                Message 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 Message initMessage(String patientName,String doctor,String doctorName,String sender,String senderName,String title,String content,String relatioenCode,int type){
        Message message = new Message();
        message.setCzrq(new Date());
        message.setCreateTime(new Date());
        message.setContent("您的服务居民"+patientName+",已中止康复计划,点击查看原因。");
        message.setRead(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(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 code='"+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_item 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);
    }
}

+ 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);
	}
}

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

@ -0,0 +1,279 @@
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.patient.Message;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.rehabilitation.RehabilitationInformationDO;
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 MessagesDao 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(Message 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 (message.getType() == 19 ){
                message.setOver("0");//未处理
                message.setType(19);
                message.setTitle("康复计划-受理提醒");
                message.setContent("您的居民"+patient.getName()+"已出院,"+/*(hospital!=null?hospital.getName():"")*/message.getReason()+"为他制定了新康复计划,请查看");
            }else if (message.getType() == 20){
                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 (message.getType() == 21){
                message.setOver("0");//未处理
                message.setType(21);
                message.setTitle("康复计划-服务进展提醒");
                message.setContent("您的居民"+patient.getName()+"已完成康复计划今日项目,请查看");
            }else if (message.getType() == 22){
                message.setOver("1");//未处理
                message.setType(22);
                message.setTitle("康复计划-服务进展提醒");
                message.setContent("服务时间提醒!您的居民"+patient.getName()+"该进行"+message.getData()+"了。");
            }else if (message.getType() == 23){
                message.setOver("1");//未处理
                message.setType(23);
                message.setTitle("康复计划-服务定时提醒");
                message.setContent("您的居民"+patient.getName()+"明天有"+num+"个康复项目需完成,您可以修改定时提醒!");
            }else if (message.getType() == 24){
                message.setOver("1");
                message.setType(24);
                message.setTitle("收到协同任务");
                message.setContent("您接收到“"+jsonObject.getString("type")+"”协同服务:"+jsonObject.getString("content").substring(0,19));
            }else if (message.getType() == 25){
                message.setOver("1");
                message.setType(25);
                message.setTitle("在线助手已接收");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手接收,负责人:"+jsonObject.getString("customerName")+",联系方式:"+jsonObject.getString("phone")+"。");
            }else if (message.getType() == 26){
                message.setOver("1");
                message.setType(26);
                message.setTitle("在线助手已退回");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手退回。原因:"+jsonObject.getString("returnedRemark"));
            }else if (message.getType() == 27){
                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.setRead(1);
            message.setCzrq(new Date());
            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
+ 221 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/HttpUtil.java


+ 639 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/ImUtill.java

@ -0,0 +1,639 @@
package com.yihu.rehabilitation.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * Created by 卓 on 2017/1/13.
 */
@Component
public class ImUtill {
    @Autowired
    private com.yihu.jw.util.http.HttpClientUtil HttpClientUtil;
    @Value("${im.im_list_get}")
    private String im_host;
    public enum ContentType {
        plainText("信息", "1"),
        image("图片信息", "2"),
        audio("创建处方", "3"),
        article("文章信息", "4"),
        goTo("跳转信息,求组其他医生或者邀请其他医生发送的推送消息", "5"),
        topicBegin("议题开始", "6"),
        topicEnd("议题结束", "7"),
        personalCard("个人名片", "18"),
        messageForward("消息转发", "19"),
        topicInto("进入议题", "14"),
        video("视频", "12"),
        system("系统消息", "13"),
        prescriptionCheck("续方审核消息消息", "15"),
        prescriptionBloodStatus("续方咨询血糖血压咨询消息", "16"),
        prescriptionFollowupContent("续方咨询随访问卷消息", "17"),
        Rehabilitation("康复计划发送","20"),
        Reservation("转诊预约发送","21"),
        Know("已知悉","22");
        private String name;
        private String value;
        ContentType(String name, String value) {
            this.name = name;
            this.value = value;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }
    /**
     * 发送消息
     * @param senderId 发送者的code
     * @param receiverId 接受者code
     * @param contentType 消息类型 1二维码内容
     * @param content 消息内容
     * @return
     */
    public String sendMessage(String senderId,String receiverId,String contentType,String content){
        String imAddr = im_host + "api/v2/message/send";
        JSONObject params = new JSONObject();
        params.put("sender_id", senderId);
        params.put("sender_name", receiverId);
        params.put("content_type", contentType);
        params.put("content", content);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 获取医生统计数据
     * status reply 为空值是是该医生总咨询量
     *
     * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
     * @param adminTeamCode
     * @param status
     * @param reply
     * @return
     */
    public String getConsultData(String user, Integer adminTeamCode, Integer status, Integer reply) {
        String imAddr = im_host + "api/v2/sessions/topics/count/reply";
        imAddr = imAddr + "?user=" + user;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (adminTeamCode != null) {
            imAddr += ("&adminTeamCode=" + adminTeamCode);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    public void updateTopics(String topicId, String jsonValue) {
        String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
        JSONObject params = new JSONObject();
        params.put("topic_id", topicId);
        params.put("data", jsonValue);
        HttpClientUtil.putBody(imAddr, params);
    }
    /**
     * 当前医生下当前团队列表接口
     * 获取团队内医生的健康咨询状况
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @param user          团队就把团队的医生合并起来用,隔开(医生编码)
     * @param adminTeamCode 行政团队code
     * @param page
     * @param pagesize
     * @param status
     * @param reply
     * @return
     */
    public String getTeamConsultByStatus(String user, Integer adminTeamCode, Integer status, Integer reply, int page, int pagesize) {
        String imAddr = im_host + "api/v2/sessions/healthTeamTopics";
        imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
        if (adminTeamCode != null) {
            imAddr += ("&adminTeamCode=" + adminTeamCode);
        }
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 列表接口
     * 获取团队内医生的健康咨询状况
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @param user     团队就把团队的医生合并起来用,隔开(医生编码)
     * @param page
     * @param pagesize
     * @param status
     * @param reply
     * @return
     */
    public String getConsultByStatus(String user, Integer status, Integer reply, int page, int pagesize) {
        String imAddr = im_host + "api/v2/sessions/healthTopics";
        imAddr = imAddr + "?user=" + user + "&page=" + page + "&pagesize=" + pagesize;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 咨询列表
     * @param user
     * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * @param reply
     * @param type 1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
     * @param page
     * @param pagesize
     * @return
     */
    public String getConsultByStatusAndType(String user,Integer status,Integer reply,Integer type,String patientName,String startTime,String endTime,int page,int pagesize){
        String imAddr = im_host + "api/v2/sessions/topicListByType";
        imAddr = imAddr + "?user="+user + "&page=" + page + "&pagesize=" + pagesize;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        if (type != null) {
            imAddr += ("&type=" + type);
        }
        if (patientName != null) {
            imAddr += ("&patientName=" + patientName);
        }
        if (startTime != null) {
            imAddr += ("&startTime=" + startTime);
        }
        if (endTime != null) {
            imAddr += ("&endTime=" + endTime);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 咨询列表总数
     * @param user
     * @param status status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * @param reply
     * @param type 1、三师咨询,2、家庭医生咨询,6、患者名医咨询 7医生名医咨询 8续方咨询 10医生发起的求助
     * @return
     */
    public String getConsultCountByStatusAndType(String user,Integer status,Integer reply,Integer type,String patientName,String startTime,String endTime){
        String imAddr = im_host + "api/v2/sessions/topicListCountByType";
        imAddr = imAddr + "?user="+user;
        if (status != null) {
            imAddr += ("&status=" + status);
        }
        if (reply != null) {
            imAddr += ("&reply=" + reply);
        }
        if (type != null) {
            imAddr += ("&type=" + type);
        }
        if (patientName != null) {
            imAddr += ("&patientName=" + patientName);
        }
        if (startTime != null) {
            imAddr += ("&startTime=" + startTime);
        }
        if (endTime != null) {
            imAddr += ("&endTime=" + endTime);
        }
        String response = HttpClientUtil.get(imAddr, "UTF-8");
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public String sendImMsg(String from, String fromName, String sessionId, String contentType, String content, String businessType) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("session_id", sessionId);
        params.put("business_type", businessType);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 更新会话状态
     *
     * @param sessionId 会话ID
     * @param status    状态
     */
    public String updateSessionStatus(String sessionId, String status) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
        JSONObject params = new JSONObject();
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 更新会话状态
     *
     * @param sessionId 会话ID
     * @param status    状态
     */
    public String updateTopicEvaluate(String sessionId, String status) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/status?status=" + status + "&sessionId=" + sessionId;
        JSONObject params = new JSONObject();
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }
    /**
     * 发送消息给IM
     *
     * @param from        来自
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public String sendTopicIM(String from, String fromName, String topicId, String contentType, String content, String agent) {
        String url = im_host + "api/v2/sessions/topic/" + topicId + "/messages";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("topic_id", topicId);
        params.put("agent", agent);
        String response = HttpClientUtil.postBody(url, params);
        return response;
    }
    /**
     * 发送进入im消息
     * IM: ParticipantUpdate:'/:session_id/participant/update'
     *
     * @param from
     * @param sessionId
     * @param topicId
     * @return
     */
    public String sendIntoTopicIM(String from, String sessionId, String topicId, String content, String intoUser, String intoUserName) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/into";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("topic_id", topicId);
        params.put("into_user", intoUser);
        params.put("into_user_name", intoUserName);
        params.put("content", content);
        String response = HttpClientUtil.postBody(url, params);
        return response;
    }
    /**
     * 更新会话成员(新增或删除)
     * @param sessionId 会话id
     * @param user 新增的成员id
     * @param oldUserId  删除的成员id
     */
    public String updateParticipant(String sessionId, String user,String oldUserId) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId );
        params.put("user_id", user );
        if(!StringUtils.isEmpty(oldUserId)){
            params.put("old_user_id", oldUserId);
        }
       return HttpClientUtil.postBody(imAddr, params);
    }
    /**
     * 更新消息内容
     * @param sessionId 会话id
     * @param sessionType 会话类型
     * @param msgId  消息id
     * @param content  消息内容
     */
    public String updateMessage(String sessionId, String sessionType,String msgId,String content) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages/"+ msgId +"/update";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId );
        params.put("session_type", sessionType );
        params.put("message_id", msgId );
        params.put("content", content );
       return HttpClientUtil.postBody(imAddr, params);
    }
    /**
     * 结束议题
     *
     * @param topicId     议题ID
     * @param endUser     结束人
     * @param endUserName 结束人名字
     * @param sessionId   会话ID
     */
    public JSONObject endTopics(String sessionId, String endUser, String endUserName, String topicId) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/topics/" + topicId + "/ended";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        params.put("end_user", endUser);
        params.put("end_user_name", endUserName);
        params.put("topic_id", topicId);
        String ret = HttpClientUtil.postBody(imAddr, params);
        JSONObject obj = null;
        try {
            obj = JSONObject.parseObject(ret);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }
    /**
     * 议题邀请人员
     *
     * @param user      结束人名字
     * @param sessionId 会话ID
     */
    public void updateTopicUser(String sessionId, String user) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
        JSONObject params = new JSONObject();
        params.put("user", user + ":" + 0);
        HttpClientUtil.putBody(imAddr, params);
    }
    /**
     * 创建议题
     *
     * @param topicId      议题ID
     * @param topicName    议题名称
     * @param participants 成员
     */
    public JSONObject createTopics(String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
        String imAddr = im_host + "api/v2/sessions/" + topicId + "/topics";
        JSONObject params = new JSONObject();
        params.put("topic_id", topicId);
        params.put("topic_name", topicName);
        params.put("participants", participants.toString());
        params.put("messages", messages.toString());
        params.put("session_id", sessionId);
        params.put("session_type", sessionType);
        String ret = HttpClientUtil.postBody(imAddr, params);
        JSONObject obj = null;
        try {
            obj =  JSONObject.parseObject(ret);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }
    /**
     * 判断会话是否存在
     */
    public Boolean sessionIsExist(String sessionId) {
        Boolean re = false;
        String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
        JSONObject params = new JSONObject();
        String ret = HttpClientUtil.get(url, "UTF-8");
        JSONObject obj = null;
        try {
            obj = JSONObject.parseObject(ret);
            if(obj.getInteger("status")==200&&sessionId.equals(obj.getString("sessionId"))){
                re = true;
            }
        } catch (Exception e) {
            return null;
        }
        return re;
    }
    /**
     * 创建会话(system)
     */
    public JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
        String imAddr = im_host + "api/v2/sessions";
        JSONObject params = new JSONObject();
        params.put("participants", participants.toString());
        params.put("session_name", sessionName);
        params.put("session_type", sessionType);
        params.put("session_id", sessionId);
        String ret = HttpClientUtil.postBody(imAddr, params);
        JSONObject obj = null;
        try {
            obj = JSONObject.parseObject(ret);
        } catch (Exception e) {
            return null;
        }
        return obj;
    }
    /**
     * 获取会话实例的消息对象
     *
     * @param senderId
     * @param senderName
     * @param title
     * @param description
     * @param images
     * @param agent
     * @return
     */
    public JSONObject getCreateTopicMessage(String senderId, String senderName, String title, String description, String images, String agent) {
        JSONObject messages = new JSONObject();
        messages.put("description", description);
        messages.put("title", title);
        messages.put("img", images);
        messages.put("sender_id", senderId);
        messages.put("sender_name", senderName);
        messages.put("agent", agent);
        return messages;
    }
    public JSONObject getTopicMessage(String topicId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
        String url = im_host
                + "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
                + "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
        try {
            String ret = HttpClientUtil.get(url, "UTF-8");
            JSONObject obj = JSONObject.parseObject(ret);
            if (obj.getInteger("status") == -1) {
                throw new RuntimeException(obj.getString("message"));
            } else {
                return obj.getJSONObject("data");
            }
        } catch (Exception e) {
            return null;
        }
    }
    public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
        try {
            String ret = HttpClientUtil.get(url, "UTF-8");
            JSONArray obj = JSONArray.parseArray(ret);
            return obj;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 删除对应的成员信息在MUC模式中
     *
     * @param userId
     * @param oldUserId
     * @param sessionId
     * @return
     */
    public JSONObject deleteMucUser(String userId, String oldUserId, String sessionId) throws Exception {
        String url = im_host + "api/v2/sessions/" + sessionId + "/participant/update";
        try {
            JSONObject params = new JSONObject();
            params.put("user_id", userId);
            params.put("old_user_id", oldUserId);
            params.put("session_id", sessionId);
            String ret = HttpClientUtil.postBody(url, params);
            JSONObject obj = JSONObject.parseObject(ret);
            if (obj.getInteger("status") == -1) {
                throw new RuntimeException("人员更换失败!");
            } else {
                return obj;
            }
        } catch (Exception e) {
            throw new RuntimeException("人员更换失败!");
        }
    }
    /**
     * 获取议题
     *
     * @param topicId
     * @return
     */
    public JSONObject getTopic(String topicId) throws Exception {
        String url = im_host + "api/v2/sessions/topics/" + topicId + "?topic_id=" + topicId;
        try {
            String ret = HttpClientUtil.get(url, "utf-8");
            JSONObject obj = JSONObject.parseObject(ret);
            if (obj.getInteger("status") == -1) {
                throw new RuntimeException("获取议题失败!");
            } else {
                return obj;
            }
        } catch (Exception e) {
            throw new RuntimeException("获取议题失败!");
        }
    }
    /**
     * 获取会话成员
     *
     * @param sessionId
     * @return
     * @throws Exception
     */
    public JSONArray getParticipants(String sessionId) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
        try {
            String ret = HttpClientUtil.get(url, "utf-8");
            return JSONArray.parseArray(ret);
        } catch (Exception e) {
            throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
        }
    }
    /**
     * 获取会话成员
     *
     * @param sessionId
     * @return
     * @throws Exception
     */
    public JSONArray getSessions(String sessionId) {
        String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
        try {
            String ret = HttpClientUtil.get(url, "utf-8");
            return JSONArray.parseArray(ret);
        } catch (Exception e) {
            throw new RuntimeException("获取议题失败!");
        }
    }
    public JSONObject cleanMessageToRedis(String sessionId){
        String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
        try {
            String ret = HttpClientUtil.get(url,"utf-8");
            return JSONObject.parseObject(ret);
        } catch (Exception e) {
            throw new RuntimeException("操作失败!");
        }
    }
    public JSONObject cleanMessageLastFetchTime(String sessionId, String userId){
        String url = im_host + "api/v2/message/cleanMessageLastFetchTimeToRedis?sessionId="+sessionId+"&userId="+userId;
        try {
            String ret = HttpClientUtil.get(url,"utf-8");
            return JSONObject.parseObject(ret);
        } catch (Exception e) {
            throw new RuntimeException("操作失败!");
        }
    }
    public static final String SESSION_TYPE_MUC = "1";
    public static final String SESSION_TYPE_P2P = "2";
    public static final String SESSION_TYPE_GROUP = "3";
    public static final String SESSION_TYPE_SYSTEM = "0";
    public static final String SESSION_TYPE_PRESCRIPTION = "8";//续方
    public static final String SESSION_TYPE_EXAMINATION = "9";//在线复诊
    public static final String SESSION_TYPE_ONDOOR_NURSING = "11";//上门护理
    public static final String SESSION_STATUS_PROCEEDINGS = "0";
    public static final String SESSION_STATUS_END = "1";
    public static final String CONTENT_TYPE_TEXT = "1";
}

+ 178 - 11
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,189 @@ fast-dfs:
---
spring:
  profiles: jwdev
  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/
  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
  #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
---
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: