Selaa lähdekoodia

康复下转代码-还没改完

suqinyi 1 vuosi sitten
vanhempi
commit
bcd93daa23
74 muutettua tiedostoa jossa 17229 lisäystä ja 69 poistoa
  1. 291 0
      business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java
  2. 53 0
      common/common-entity/src/main/java/com/yihu/jw/entity/followup/FollowupClassDrugs.java
  3. 342 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPatientInfoDO.java
  4. 66 0
      common/common-entity/src/main/java/com/yihu/jw/entity/util/TransforSqlUtl.java
  5. 29 0
      common/common-util/src/main/java/com/yihu/jw/util/html/HtmlUtil.java
  6. 170 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/async/AsynService.java
  7. 2 14
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java
  8. 1 18
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java
  9. 0 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java
  10. 0 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java
  11. 0 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationTempDao.java
  12. 1 4
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorOrderService.java
  13. 1 4
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/DoorServiceApplicationService.java
  14. 0 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorCommentService.java
  15. 5 14
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorPrescriptionService.java
  16. 1 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java
  17. 162 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowUpDao.java
  18. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowUpHospitalDao.java
  19. 25 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowUpMappingDao.java
  20. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupClassDrugsDao.java
  21. 23 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupContentDao.java
  22. 23 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupDrugsDao.java
  23. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupSignDao.java
  24. 3772 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowUpService.java
  25. 76 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/DiagnosisInformationController.java
  26. 531 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java
  27. 651 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationPlanController.java
  28. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/GuidanceMessageLogDao.java
  29. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientDiagnosisInformationDao.java
  30. 13 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientDischargeDao.java
  31. 58 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientRehabilitationPlanDao.java
  32. 11 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientRehabilitationPlanLogDao.java
  33. 13 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationDetailAppointmentDao.java
  34. 94 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationDetailDao.java
  35. 38 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationOperateRecordsDao.java
  36. 28 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPatientInfoDao.java
  37. 23 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPlanTemplateDao.java
  38. 16 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationServiceItemDao.java
  39. 18 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationTemplateDetailDao.java
  40. 12 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/TemplateJsonDao.java
  41. 63 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/DiagnosisInformationService.java
  42. 1034 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/PatientRecordService.java
  43. 913 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java
  44. 1718 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationManageService.java
  45. 595 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationPlanService.java
  46. 1902 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/SynchronizePatientService.java
  47. 47 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/vo/TemplateDetailVo.java
  48. 557 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistController.java
  49. 126 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistEvaluateController.java
  50. 248 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistHospitalServiceItemController.java
  51. 83 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistScreenResultController.java
  52. 236 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistServiceItemController.java
  53. 58 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistServiceItemOperateLogController.java
  54. 12 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/PatientHospitalRecordDao.java
  55. 16 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistEvaluateDao.java
  56. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistEvaluateLabelDao.java
  57. 15 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistEvaluateScoreDao.java
  58. 22 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistHospitalServiceItemDao.java
  59. 41 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistPatientRelationDao.java
  60. 27 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistServiceItemDao.java
  61. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistServiceItemOperateLogDao.java
  62. 17 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/FileUploadService.java
  63. 413 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistEvaluateService.java
  64. 417 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistHospitalServiceItemService.java
  65. 263 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistScreenResultService.java
  66. 1450 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistService.java
  67. 64 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistServiceItemOperateLogService.java
  68. 219 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistServiceItemService.java
  69. 1 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wechat/WechatPushLogDao.java
  70. 1 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wechat/WechatTemplateConfigDao.java
  71. 1 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wechat/WxAccessTokenLogDao.java
  72. 2 3
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wx/service/AccessTokenService.java
  73. 1 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/task/PushMsgTask.java
  74. 7 0
      svr/svr-visit-behind/src/main/resources/application.yml

+ 291 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/team/dao/WlyySignFamilyDao.java

@ -2,12 +2,303 @@ package com.yihu.jw.hospital.team.dao;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.team.WlyyAdminTeamDO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
public interface WlyySignFamilyDao extends JpaRepository<SignFamily, Integer>, JpaSpecificationExecutor<SignFamily> {
    @Query("select count(*) from SignFamily  t where t.doctor=?1 and t.status=1")
    Integer getCountByDoctorCode(String doctor);
    @Query("select count(1) 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);
    @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 findByCodeAndType(String code, Integer type);
    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 Patient p,SignFamily a where a.doctorHealth = ?1  and a.adminTeamId=?2 and a.patient =p.code and a.type = 2 and a.status >= 0")
    List<Patient> findByDoctorHealthPatient(String doctor, Long team);
    @Query("select p from Patient p,SignFamily a where a.doctor = ?1 and a.adminTeamId=?2 and a.patient =p.code and a.type = 2 and a.status >= 0")
    List<Patient> findByDoctorPatient(String doctor, Long team);
    @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.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.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);
    // 拒绝解约
    @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 a.patient = ?2")
    int updateOpenidByPatient(String openid, String patient);
    // 查询已签约的总数
    @Query("select count(1) 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(1) from SignFamily a where (a.doctor = ?1 or a.doctorHealth = ?1) and a.status = 0 and a.type = 2")
    int countAmountUnsignByDoctor(String doctor);
    @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 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("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,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.patient = p.code 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,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and p.name like ?2 and a.patient = p.code 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,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and a.patient = p.code 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,Patient p where (a.doctor = ?1 or a.doctorHealth = ?1) and a.type = ?2 and p.name like ?3 and a.patient = p.code 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.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 = ?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(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);
    //      完成缴费后更新签约开始时间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 );
    //查询65岁以上一年内未体检且未系统提醒的签约居民
    @Query(value = "SELECT DISTINCT t1.* FROM wlyy_sign_family t1 LEFT JOIN wlyy_physical_examination_records r ON r.patient_code=t1.patient WHERE r.patient_code IS NULL " +
            " AND t1.STATUS>0 AND t1.hospital=?1 AND(YEAR(curdate())-IF(length(idcard)=18,substring(idcard,7,4),IF(length(idcard)=15,concat('19',substring(idcard,7,2)),NULL)))>=65 " +
            " AND t1.idcard NOT IN(SELECT DISTINCT s.idcard FROM wlyy_sign_family s,wlyy_old_people_physical_examination o WHERE s.hospital=?1 AND s.`status`>0 AND s.idcard=o.id_card " +
            " AND o.medical_time>?2 )ORDER BY t1.openid DESC,CONVERT(t1.NAME USING gbk) ",nativeQuery = true)
    List<SignFamily> findExaminationByHospital(String hospital,Date examinationTime);
    //查询wlyy_sign_family有续签却未同步到wlyy_sign_family_renew_log数据
    @Query(value = "SELECT f.* FROM wlyy_sign_family f LEFT JOIN wlyy_sign_family_renew_log r ON f.`code` = r.sign_code WHERE r.sign_code IS NULL  " +
            " AND f.renew_flag IN (1, 2) AND f.`status` IN (1, 2)  ",nativeQuery = true)
    List<SignFamily> findRenew();
    //根据身份证号查询最近的已到期签约数据
    @Query(value = "SELECT f.* FROM wlyy_sign_family f WHERE f.idcard = ?1 and f.`status` = -4 ORDER BY sign_year desc LIMIT 0,1 ",nativeQuery = true)
    SignFamily findLatelyRenew(String idcard);
    //查询wlyy_sign_family有效签约且居民的医疗保险号为空的数据
    @Query(value = "select a.idcard from wlyy_sign_family a left join wlyy_patient b on a.idcard = b.idcard where a.hospital = ?1 and (a.type = 2 or a.type = 1) " +
            "and a.status = 1 and a.expenses_status = 1 and (b.medicare_number is null or b.medicare_number = '')", nativeQuery = true)
    List<String> findIdcardByStatus(String hospital);
    /**
     * 判断是否已存在待处理签约
     */
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 2 and a.status = 0")
    SignFamily findByIdcardPre(String idcard);
    /**
     * 判断是否存在去年签约
     */
    @Query("select a from SignFamily a where a.idcard = ?1 and a.signYear=?2 and a.type = 2 and (a.status= -4 or a.status>0) and a.expensesStatus = '1'")
    SignFamily findOldSign(String idcard,String signYear);
    /**
     * 【临时】清洗
     */
    List<SignFamily> findByRenewFlag(String renewflag);
    /**
     * 【临时】清洗未扣费
     */
    @Query("select a from SignFamily a where a.status>0 and a.expensesStatus='0' and a.signYear='2017'")
    List<SignFamily> findNoExpenses(Pageable pageable);
    /**
     * 【临时】退费
     */
    @Query("select a from SignFamily a where a.status>0 and a.expensesStatus='3' and a.signYear='2017'")
    List<SignFamily> findReCharge();
    /**
     * 通过医生原有团队是否有签约
     */
    @Query("select a from SignFamily a where a.doctor = ?1 and a.adminTeamId =?2 and a.status > 0")
    List<SignFamily> findByDoctorAndAdminTeamCode(String doctor,Long adminTeamCode);
    /**
     * 判断是否三师签约
     */
    @Query("select a from SignFamily a where a.idcard = ?1 and a.type = 1 and a.status > 0")
    SignFamily findSanshiByIdcard(String idcard);
}

+ 53 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/followup/FollowupClassDrugs.java

@ -0,0 +1,53 @@
package com.yihu.jw.entity.followup;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 疾病关联用药
 * @author hzp add 2016-12-07
 *
 */
@Entity
@Table(name = "wlyy_followup_class_drugs")
public class FollowupClassDrugs extends IdEntity {
	//随访类别:1.高血压 2.糖尿病
	private String followupClass;
	//药品代码
	private String drugsCode;
	//创建时间
	private Date createTime;
	public String getFollowupClass() {
		return followupClass;
	}
	public void setFollowupClass(String followupClass) {
		this.followupClass = followupClass;
	}
	public String getDrugsCode() {
		return drugsCode;
	}
	public void setDrugsCode(String drugsCode) {
		this.drugsCode = drugsCode;
	}
	@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;
	}
}

+ 342 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationPatientInfoDO.java

@ -0,0 +1,342 @@
package com.yihu.jw.entity.specialist.rehabilitation;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
/**
 * create by hmf on 2020/06/01 康复下转居民信息
 */
@Entity
@Table(name = "wlyy_rehabilitation_patient_info")
public class RehabilitationPatientInfoDO extends IdEntity {
    private String code;
    private String name;//姓名
    private String idcard;//身份证
    private String ssc;//社保卡
    private Integer sex;//性别1男2女0未知
    private Integer age;//年龄
    private String mobile;//电话
    private String address;//住址
    private Integer kid;//是否儿科:1是 0否,4岁以下儿童
    private String kidParents;//患者家属
    private String diagnosis;//出院诊断code
    private String diagnosisName;//出院诊断
    private String treatment;//主要病情摘要及诊疗经过
    private String result;//出院前检查结果
    private String guidance;//后续治疗康复指导建议
    private String summary;//出院小结
    private String crzq;//转诊日期
    private String hospitalCode;//医院CODE
    private String hospitalName;//医院名称
    private String jwHospitalCode;//社区医院CODE
    private String jwHospitalName;//社区医院名称
    private String hospitalDoctor;//转诊医生
    private Date createTime;//请求时间
    private Integer status;//是否分配下转:0未分配,1已分配(已下转列表),2创建计划过程失败,3患者无住院病历信息(等待重新下转),4不支持该医院自动下转,5同步居民失败,6下转列表(未下转-未签约)
    private String statusName;//是否分配下转:0未分配,1已分配(已下转列表),2创建计划过程失败,3患者无住院病历信息(等待重新下转),4不支持该医院自动下转,5同步居民失败,6下转列表(未下转)
    private String problemCode;//问题代码1001肺癌,1002慢性胃肠病,1003冠心病,1004慢性前列腺疾病,1005慢性乳腺疾病,
                               // 1006慢性阻塞性肺病,1007脂肪肝,1008慢性妇科炎症,1009脑卒中,1010慢性肾病
    private String diagnoseDoctor;//诊断医生
    private Date diagnoseTime;//诊断时间
    private String orgCode;
    private String orgName;//接收社区医院
    private String doctor;
    private String doctorName;//接收医生
    private Date receiveTime;//接收时间
    private Integer archiveStatus;//档案状态
    private String archiveStatusName;//档案状态
    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 getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getKid() {
        return kid;
    }
    public void setKid(Integer kid) {
        this.kid = kid;
    }
    public String getKidParents() {
        return kidParents;
    }
    public void setKidParents(String kidParents) {
        this.kidParents = kidParents;
    }
    public String getDiagnosis() {
        return diagnosis;
    }
    public void setDiagnosis(String diagnosis) {
        this.diagnosis = diagnosis;
    }
    public String getDiagnosisName() {
        return diagnosisName;
    }
    public void setDiagnosisName(String diagnosisName) {
        this.diagnosisName = diagnosisName;
    }
    public String getTreatment() {
        return treatment;
    }
    public void setTreatment(String treatment) {
        this.treatment = treatment;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
    public String getGuidance() {
        return guidance;
    }
    public void setGuidance(String guidance) {
        this.guidance = guidance;
    }
    public String getSummary() {
        return summary;
    }
    public void setSummary(String summary) {
        this.summary = summary;
    }
    public String getCrzq() {
        return crzq;
    }
    public void setCrzq(String crzq) {
        this.crzq = crzq;
    }
    public String getHospitalCode() {
        return hospitalCode;
    }
    public void setHospitalCode(String hospitalCode) {
        this.hospitalCode = hospitalCode;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getJwHospitalCode() {
        return jwHospitalCode;
    }
    public void setJwHospitalCode(String jwHospitalCode) {
        this.jwHospitalCode = jwHospitalCode;
    }
    public String getJwHospitalName() {
        return jwHospitalName;
    }
    public void setJwHospitalName(String jwHospitalName) {
        this.jwHospitalName = jwHospitalName;
    }
    public String getHospitalDoctor() {
        return hospitalDoctor;
    }
    public void setHospitalDoctor(String hospitalDoctor) {
        this.hospitalDoctor = hospitalDoctor;
    }
    @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 Integer getStatus() {
        return status;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getProblemCode() {
        return problemCode;
    }
    public void setProblemCode(String problemCode) {
        this.problemCode = problemCode;
    }
    public String getDiagnoseDoctor() {
        return diagnoseDoctor;
    }
    public void setDiagnoseDoctor(String diagnoseDoctor) {
        this.diagnoseDoctor = diagnoseDoctor;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getDiagnoseTime() {
        return diagnoseTime;
    }
    public void setDiagnoseTime(Date diagnoseTime) {
        this.diagnoseTime = diagnoseTime;
    }
    public String getOrgCode() {
        return orgCode;
    }
    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getReceiveTime() {
        return receiveTime;
    }
    public void setReceiveTime(Date receiveTime) {
        this.receiveTime = receiveTime;
    }
    @Transient
    public String getStatusName() {
        return statusName;
    }
    public void setStatusName(String statusName) {
        this.statusName = statusName;
    }
    @Transient
    public Integer getArchiveStatus() {
        return archiveStatus;
    }
    public void setArchiveStatus(Integer archiveStatus) {
        this.archiveStatus = archiveStatus;
    }
    @Transient
    public String getArchiveStatusName() {
        return archiveStatusName;
    }
    public void setArchiveStatusName(String archiveStatusName) {
        this.archiveStatusName = archiveStatusName;
    }
}

+ 66 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/util/TransforSqlUtl.java

@ -1,5 +1,12 @@
package com.yihu.jw.entity.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
/***
 * @ClassName: TransforSqlUtl
 * @Description:
@ -10,6 +17,7 @@ public class TransforSqlUtl {
    private static final boolean dbEncrypt=false; //不需要加密时 改为false即可,实体类注释需同时处理
    public static String wlyySpecialistPatientRelationLike(String sql,String ...replaceName){
        for (String tmp :replaceName){
            String str = "AES_DECRYPT(from_base64("+tmp+"),'jkzl2021ZJXL*#%a')";
@ -179,4 +187,62 @@ public class TransforSqlUtl {
        }
        return sql;
    }
    private static final String DBKEY = "jkzl2021ZJXL*#%a";
    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    public static String encrypt(String content, String encryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
            byte[] b = cipher.doFinal(content.getBytes("utf-8"));
            // 采用base64算法进行转码,避免出现中文乱码
            return Base64.encodeBase64String(b);
        }catch (Exception e){
            e.printStackTrace();
            return content;
        }
    }
    public static String decrypt(String encryptStr, String decryptKey) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
            // 采用base64算法进行转码,避免出现中文乱码
            byte[] encryptBytes = Base64.decodeBase64(encryptStr);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes);
        }catch (Exception e){
            e.printStackTrace();
            return encryptStr;
        }
    }
    public static String encryptContent(String content){
        if(content == null){
            return content;
        }
        if (dbEncrypt){
            content = encrypt(content, DBKEY);
        }
        return content  ;
    }
    public static String decryptContent(String encryptStr){
        if(StringUtils.isEmpty(encryptStr)){
            return encryptStr;
        }
        if (dbEncrypt){
            encryptStr = decrypt(encryptStr, DBKEY);
        }
        return encryptStr;
    }
}

+ 29 - 0
common/common-util/src/main/java/com/yihu/jw/util/html/HtmlUtil.java

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

+ 170 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/async/AsynService.java

@ -0,0 +1,170 @@
package com.yihu.jw.hospital.async;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yihu.jw.dict.service.FollowUpDictService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPatientInfoDO;
import com.yihu.jw.hospital.module.followup.service.FollowUpService;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
 * 异步方法
 * Created by yeshijie on 2022/8/8.
 */
@Service
public class AsynService {
    private Logger logger = LoggerFactory.getLogger(AsynService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FollowUpService followUpService;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
    @Autowired
    private ImUtil imUtill;
    //基卫服务地址
    @Value("${sign.check_upload}")
    private String jwUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    /**
     * 创建随访计划job
     * @param jsonArray
     */
    @Async
    public void createFollowJob(JSONArray jsonArray, String planId, SignFamily signFamily){
        //创建过期job
        StringBuilder insertSql = new StringBuilder("INSERT into wlyy_followup_job(followup_id,expired_time,status,type)VALUES ");
        boolean bl = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
            String time = "";
            if("6".equals(jsonObject.get("hospitalServiceItemId").toString()) && "1".equals(jsonObject.get("followupDetailType")!=null?jsonObject.get("followupDetailType").toString():"0")){
                if(!bl){
                    bl = true;
                    time=DateUtil.dateToStrLong(DateUtil.getPreDays(DateUtil.strToDate(jsonObject.get("executeTime").toString()), 5));
                }else {
                    time=DateUtil.dateToStrLong(DateUtil.getPreDays(DateUtil.strToDate(jsonObject.get("executeTime").toString()), 7));
                }
                insertSql.append("('"+jsonObject.get("id")+"','"+time+"',1,0),");
            }
            //厦心自动创建新增社区随访表单
            if("6".equals(jsonObject.get("hospitalServiceItemId").toString())){
                //创建康复随访
                JSONObject data = new JSONObject();
                data.put("date",jsonObject.get("executeTime").toString());
                data.put("type","2");
                data.put("doctor",signFamily.getDoctor());
                data.put("followupClass","21");
                data.put("type1","1");
                data.put("id",jsonObject.get("id")+"");
                JSONObject dataJson = new JSONObject();
                //dataJson: {"rehabilitationDetailId":"808080eb827bb19601827bfb355b0039","patientCode":"6ce60381c5b14ea0884ead2af1c2063a","patientName":"黄金坤"
                // ,"doctorCode":"1b9fa6e86c5e468cbd0f2aabade30c35","doctorName":"王清秀","relationRecordType":5,"relationRecordCode":"","status":0}
                dataJson.put("rehabilitationDetailId",jsonObject.get("id")+"");
                dataJson.put("patientCode",signFamily.getPatient());
                dataJson.put("patientName",signFamily.getName());
                dataJson.put("doctorCode",signFamily.getDoctor());
                dataJson.put("doctorName",signFamily.getDoctorName());
                dataJson.put("relationRecordType",5);
                dataJson.put("relationRecordCode","");
                dataJson.put("status",0);
                try {
                    followUpService.addFollowupPlanNew(signFamily.getDoctor(),signFamily.getPatient(),data,dataJson.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(bl){
            jdbcTemplate.execute(insertSql.substring(0,insertSql.length()-1)+";");
        }
        //创建提醒job
        //创建一条随访计划提醒
        String preDayStr = "";
        Date afterDate =DateUtil.strToDate(DateUtil.getStringDateShort()+" 10:00:00");
        if(afterDate.before(afterDate)){
            //早于上午十点
            preDayStr = DateUtil.dateToStrLong(afterDate);
        }else {
            //晚于上午十点
            preDayStr = DateUtil.dateToStrLong(DateUtil.getPreDays(afterDate,1));
        }
        String sql = "INSERT into wlyy_followup_job(followup_id,expired_time,status,type) VALUES ('"+planId+"','"+preDayStr+"',1,1)";
        jdbcTemplate.execute(sql);
    }
    /**
     * 发送消息
     */
    @Async
    public void sendMsg(String planId, SignFamily signFamily, BasePatientDO patient, BaseDoctorDO doctor, PatientMedicalRecordsDO patientMedicalRecordsDO1, RehabilitationPatientInfoDO re){
        try {
            org.json.JSONArray serverDoctorList = rehabilitationManageService.selectPlanServerDoctor(planId,signFamily.getDoctor());
            int length = serverDoctorList.length();
            BaseDoctorDO signDoctor = doctorDao.findById(signFamily.getDoctor()).orElse(null);
            for (int i=0;i<length;i++){
                JSONObject serverJson = serverDoctorList.getJSONObject(i);
                if (serverJson.getString("type").equals("4")){
                    String sessionId = serverJson.getString("sessionId");
                    JSONObject messageJson = new JSONObject();
                    String message= signDoctor.getName()+"医生您好,住院患者"+patient.getName()+"已出院,请您及时接收管理,保持联系,谢谢。";
                    messageJson.put("message",message);
                    messageJson.put("patientCode",patient.getId());
                    messageJson.put("patientName",patient.getName());
                    messageJson.put("medicalRecordDo", JSON.toJSONString(patientMedicalRecordsDO1));
                    imUtill.sendImMsg(doctor.getId(),doctor.getName(),sessionId,"3101",messageJson.toString(),"1");
                }
            }
        } catch (RuntimeException se) {
            se.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
        //厦心下转的居民给厦心推送居民签约信息
        if("12350200568420163H".equals(re.getHospitalCode())){
            xxSendPatientBaseInfo(re.getIdcard());
        }
    }
    /**
     * i健康推送患者信息给厦心集成平台
     * @param idCard
     */
    public void xxSendPatientBaseInfo(String idCard){
        try {
            String url = jwUrl +"/third/emr/xxSendPatientBaseInfo?idCard="+idCard;
            String re = httpClientUtil.get(url,"UTF-8");
            logger.info(idCard+":xxSendPatientBaseInfo:"+re);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

+ 2 - 14
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultService.java

@ -1,31 +1,19 @@
package com.yihu.jw.hospital.module.consult.service;
import com.alibaba.fastjson.JSON;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.util.AesEncryptUtils;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.order.dao.ConsultOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.http.HttpClientUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.*;
import java.util.Date;
import java.util.UUID;
@Component
@Transactional

+ 1 - 18
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/consult/service/ConsultTeamService.java

@ -7,12 +7,11 @@ import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.im.ConsultTeamLogDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorServiceOrderDao;
import com.yihu.jw.hospital.module.door.service.WlyyDoorServiceOrderService;
import com.yihu.jw.hospital.module.wechat.WechatTemplateConfigDao;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDiagnosisDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionExpressageDao;
@ -23,7 +22,6 @@ import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.im.dao.ConsultTeamDoctorDao;
import com.yihu.jw.im.dao.ConsultTeamLogDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.message.service.MessageService;
@ -31,37 +29,22 @@ import com.yihu.jw.order.dao.ConsultTeamOrderDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.utils.Clock;
import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**

+ 0 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/DoorOrderController.java

@ -1,5 +1,3 @@
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.door.WlyyDoorConclusionDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;

+ 0 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/controller/WlyyDoorServiceOrderController.java

@ -13,7 +13,6 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;

+ 0 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/dao/DoctorRegistrationTempDao.java

@ -5,7 +5,6 @@ import com.yihu.jw.entity.door.DoctorRegistrationTemp;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**

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

@ -1,6 +1,5 @@
package com.yihu.jw.hospital.module.door.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -15,7 +14,7 @@ import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.door.dao.*;
import com.yihu.jw.hospital.module.wechat.WechatTemplateConfigDao;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;
@ -25,7 +24,6 @@ import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.collections.CollectionUtils;
@ -45,7 +43,6 @@ import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.*;
import java.lang.Boolean;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

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

@ -3,25 +3,22 @@ package com.yihu.jw.hospital.module.door.service;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorServiceApplicationDo;
import com.yihu.jw.entity.door.WlyyDoorServiceVoucherDo;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.door.dao.DoorServiceApplicationDao;
import com.yihu.jw.hospital.module.door.dao.DoorServiceVoucherDao;
import com.yihu.jw.hospital.module.wechat.WechatTemplateConfigDao;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

+ 0 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorCommentService.java

@ -6,7 +6,6 @@ import com.yihu.jw.hospital.module.door.dao.WlyyDoorCommentDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

+ 5 - 14
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorPrescriptionService.java

@ -1,31 +1,20 @@
package com.yihu.jw.hospital.module.door.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.im.ConsultDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDO;
import com.yihu.jw.entity.door.WlyyDoorPrescriptionDrugDO;
import com.yihu.jw.entity.door.WlyyDoorServiceOrderDO;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.module.door.dao.DoorServiceOrderDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorPrescriptionDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorPrescriptionDetailDao;
import com.yihu.jw.hospital.module.door.dao.WlyyDoorPrescriptionDrugDao;
import com.yihu.jw.hospital.module.wechat.WechatTemplateConfigDao;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -34,8 +23,10 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
 * 上门服务开方相关业务

+ 1 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/door/service/WlyyDoorServiceOrderService.java

@ -15,7 +15,7 @@ import com.yihu.jw.hospital.HospitalDao;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.hospital.module.consult.service.ConsultTeamService;
import com.yihu.jw.hospital.module.door.dao.*;
import com.yihu.jw.hospital.module.wechat.WechatTemplateConfigDao;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.im.dao.ConsultDao;

+ 162 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowUpDao.java

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

+ 17 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowUpHospitalDao.java

@ -0,0 +1,17 @@
///*******************************************************************************
// * Copyright (c) 2005, 2014 springside.github.io
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// *******************************************************************************/
//package com.yihu.jw.hospital.module.followup.dao;
//
//
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//
//public interface FollowUpHospitalDao
//        extends PagingAndSortingRepository<FollowupHospital, Long>, JpaSpecificationExecutor<FollowupHospital> {
//
//
//}

+ 25 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowUpMappingDao.java

@ -0,0 +1,25 @@
package com.yihu.jw.hospital.module.followup.dao;
import com.yihu.jw.entity.followup.FollowupMapping;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 随访记录映射表
 * @author huangwenjie
 * @date 2017/10/23 14:05
 */
public interface FollowUpMappingDao extends PagingAndSortingRepository<FollowupMapping, Long>, JpaSpecificationExecutor<FollowupMapping> {
	
	List<FollowupMapping> findByNeedUpload(Integer needupload);
	
	FollowupMapping findByFollowupId(Integer followupid);
	
	@Modifying
	@Query("update FollowupMapping p set p.needUpload=?1 where p.followupId=?2")
	void updateNeedUploadByFollowupId(Integer needUpload, Integer followupId);
}

+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupClassDrugsDao.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.hospital.module.followup.dao;
import com.yihu.jw.entity.followup.FollowupClassDrugs;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface FollowupClassDrugsDao extends PagingAndSortingRepository<FollowupClassDrugs, Long>, JpaSpecificationExecutor<FollowupClassDrugs> {
}

+ 23 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupContentDao.java

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

+ 23 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupDrugsDao.java

@ -0,0 +1,23 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.hospital.module.followup.dao;
import com.yihu.jw.entity.followup.FollowupDrugs;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface FollowupDrugsDao extends PagingAndSortingRepository<FollowupDrugs, Long>, JpaSpecificationExecutor<FollowupDrugs> {
    @Modifying
    @Query("delete FollowupDrugs a where a.followupId=?1")
    int deleteByFollowupId(Long followupId) throws Exception;
    List<FollowupDrugs> findByFollowupId(Long followupId) throws Exception;
}

+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/dao/FollowupSignDao.java

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

+ 3772 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/followup/service/FollowUpService.java

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

+ 76 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/DiagnosisInformationController.java

@ -0,0 +1,76 @@
package com.yihu.jw.hospital.module.rehabilitation.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.specialist.rehabilitation.PatientDiagnosisInformationDO;
import com.yihu.jw.hospital.module.rehabilitation.service.DiagnosisInformationService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
/**
 * Created by humingfen on 2019/2/11.
 */
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "诊疗信息管理相关操作", description = "诊疗信息相关操作")
public class DiagnosisInformationController extends EnvelopRestEndpoint {
    @Autowired
    private DiagnosisInformationService diagnosisInformationService;
//    @Autowired
//    private Tracer tracer;
    @PostMapping(value = SpecialistMapping.diagnosisInformation.createDiagnosisInformation)
    @ApiOperation(value = "诊疗信息创建")
    public Envelop createDiagnosisInformation(@ApiParam(name = "diagnosisInformationJson", value = "实体JSON")
                                                       @RequestParam(value = "diagnosisInformationJson")String diagnosisInformationJson){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientDiagnosisInformationDO diagnosisInformationDO = objectMapper.readValue(diagnosisInformationJson, PatientDiagnosisInformationDO.class);
            return diagnosisInformationService.createDiagnosisInformation(diagnosisInformationDO);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.diagnosisInformation.findDiagnosisInformationByPlanId)
    @ApiOperation(value = "根据康复计划id查找诊疗信息")
    public Envelop findDiagnosisInformationByPlanId(@ApiParam(name = "planId", value = "康复计划id")
                                              @RequestParam(value = "planId") String planId){
        try {
            return diagnosisInformationService.findDiagnosisInformationByPlanId(planId);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.diagnosisInformation.findDiagnosisInformationByPatient)
    @ApiOperation(value = "查找居民诊疗信息记录")
    public Envelop findDiagnosisInformationByPatient(@ApiParam(name = "patient", value = "居民code")
                                                    @RequestParam(value = "patient") String patient,
                                                     @ApiParam(name = "page", value = "第几页")
                                                     @RequestParam(value = "page") Integer page,
                                                     @ApiParam(name = "size", value = "行数")
                                                         @RequestParam(value = "size") Integer size){
        try {
            return diagnosisInformationService.findDiagnosisInformationByPatient(patient, page, size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
        }
    }
}

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

@ -0,0 +1,531 @@
package com.yihu.jw.hospital.module.rehabilitation.controller;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.hospital.module.rehabilitation.dao.RehabilitationOperateRecordsDao;
import com.yihu.jw.hospital.module.rehabilitation.service.RehabilitationManageService;
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.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
//import org.springframework.cloud.sleuth.Tracer;
/**
 * Created by 刘文彬 on 2018/8/16.
 */
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "康复计划管理相关操作", description = "康复计划管理相关操作")
public class RehabilitationManageController {
    @Autowired
    private RehabilitationManageService rehabilitationManageService;
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private RehabilitationOperateRecordsDao rehabilitationOperateRecordsDao;
    @PostMapping(value = "synchronizePationSingle")
    @ApiOperation("手动重新下转")
    public String synchronizePationSingle(@ApiParam(name = "id", value = "id", required = true)
                                          @RequestParam(value = "id", required = true)Long id) {
        try {
            String res = synchronizePatientService.synchronizePationSingle(id);
            if(StringUtils.isBlank(res)){
                return success("操作成功,康复计划生成");
            }else {
                return error(-1,res);
            }
        } catch (Exception e) {
            return errorResult(e);
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.findRehabilitationPlanList)
    @ApiOperation(value = "康复管理-康复计划列表")
    public MixEnvelop findRehabilitationPlan(@ApiParam(name = "doctorType", value = "医生类型(1、专科医生,2、家庭医生)", required = true)
                                             @RequestParam(value = "doctorType", required = true)Integer doctorType,
                                             @ApiParam(name = "doctorCode", value = "医生code", required = true)
                                             @RequestParam(value = "doctorCode", required = true)String doctorCode,
                                             @ApiParam(name = "patientCondition", value = "居民条件,可以按身份证或者居民名称模糊匹配", required = false)
                                             @RequestParam(value = "patientCondition", required = false)String patientCondition,
                                             @ApiParam(name = "diseaseCode", value = "疾病类型code", required = false)
                                             @RequestParam(value = "diseaseCode", required = false)String diseaseCode,
                                             @ApiParam(name = "planType", value = "安排类型(1康复计划,2转社区医院,3转家庭病床)", required = false)
                                             @RequestParam(value = "planType", required = false)Integer planType,
                                             @ApiParam(name = "todaybacklog", value = "今日待办(1、今日待办,2、全部)", required = false)
                                             @RequestParam(value = "todaybacklog", required = false,defaultValue = "1")Integer todaybacklog,
                                             @ApiParam(name = "page", value = "第几页,从1开始", required = false)
                                             @RequestParam(value = "page", required = false,defaultValue = "1")Integer page,
                                             @ApiParam(name = "pageSize", value = "每页分页大小", required = false)
                                             @RequestParam(value = "pageSize", required = false,defaultValue = "10")Integer pageSize){
        try {
            return rehabilitationManageService.findRehabilitationPlan(doctorType,doctorCode,diseaseCode,planType,todaybacklog,patientCondition,page,pageSize);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.findRehabilitationPlanDetailList)
    @ApiOperation(value = "康复管理-康复计划详情列表")
    public ObjEnvelop findRehabilitationPlanDetailList(@ApiParam(name = "doctorCode", value = "医生code", required = true)
                                                       @RequestParam(value = "doctorCode", required = true)String doctorCode,
                                                       @ApiParam(name = "patientCode", value = "居民code", required = true)
                                                       @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            return rehabilitationManageService.findRehabilitationPlanDetailList(doctorCode,patientCode);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.calendarPlanDetail)
    @ApiOperation(value = "康复管理-康复计划按日历展示")
    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", required = true)String planId,
                                         @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                          @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                         @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status,
                                         @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                          @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                         @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                          @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            return rehabilitationManageService.calendarPlanDetail(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode,taskExecutor);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.calendarPlanDetailList)
    @ApiOperation(value = "康复管理-康复计划按列表展示")
    public ObjEnvelop calendarPlanDetailList(@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", required = true)String planId,
                                             @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)")
                                         @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                             @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)")
                                         @RequestParam(value = "status", required = false)Integer status,
                                             @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)")
                                         @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                             @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                         @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            return rehabilitationManageService.calendarPlanDetailList(planId,searchTask,status,doctorCode,executeStartTime,executeEndTime,taskExecutor);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.serviceItemList)
    @ApiOperation(value = "康复管理-多个康复计划服务项目内容信息列表")
    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 {
            return rehabilitationManageService.serviceItemList(planDetailIds,doctorCode);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.serviceItem)
    @ApiOperation(value = "康复管理-康复计划服务项目确认详情页")
    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 {
            return rehabilitationManageService.serviceItem(planDetailId,doctorCode,recordId);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = "appointmentConsultation")
    @ApiOperation(value = "康复管理-预约协诊")
    public ObjEnvelop appointmentConsultation(
            @ApiParam(name = "patient", value = "居民姓名", required = true)
            @RequestParam(value = "patient", required = true) String patient,
            @ApiParam(name = "doctor", value = "医生code-家医", required = true)
            @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "doctorName", value = "医生姓名", required = true)
            @RequestParam(value = "doctorName", required = true) String doctorName,
            @ApiParam(name = "appointmentDoctor", value = "医生code-专科", required = true)
            @RequestParam(value = "appointmentDoctor", required = true) String appointmentDoctor,
            @ApiParam(name = "appointmentDoctorName", value = "医生姓名", required = true)
            @RequestParam(value = "appointmentDoctorName", required = true) String appointmentDoctorName,
                                              @ApiParam(name = "sendTime", value = "发送时间", required = true)
                                              @RequestParam(value = "sendTime", required = true) String sendTime,
                                              @ApiParam(name = "planDetailId", value = "计划明细id", required = true)
                                              @RequestParam(value = "planDetailId", required = true) String planDetailId){
        try {
            return rehabilitationManageService.appointmentConsultation(patient,doctor, doctorName,appointmentDoctor,appointmentDoctorName, sendTime, planDetailId);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.rehabilitation.saveGuidanceMessage)
    @ApiOperation(value = "康复管理-保存指导留言")
    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 = true)String patientCode,
                                       @ApiParam(name = "doctorCode", value = "医生code", required = true)
                                       @RequestParam(value = "doctorCode", required = true)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 {
            return rehabilitationManageService.saveGuidanceMessage(messageId,doctorCode,doctorType,content,planDetailId,contentType);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.rehabilitation.updateStatusRehabilitationOperate)
    @ApiOperation(value = "康复管理-更新康复计划操作完成日志状态")
    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){
        try {
            return rehabilitationManageService.updateStatusRehabilitationOperate(status,planDetailId);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.patientRehabilitationDetail)
    @ApiOperation(value = "康复管理-居民详情页")
    public Envelop patientRehabilitationDetail(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                       @RequestParam(value = "patientCode", required = true)String patientCode,
                                               @ApiParam(name = "healthDoctor", value = "健管师医生code", required = false)
                                       @RequestParam(value = "healthDoctor", required = false)String healthDoctor,
                                               @ApiParam(name = "healthDoctorName", value = "健管师医生名称", required = false)
                                       @RequestParam(value = "healthDoctorName", required = false)String healthDoctorName,
                                               @ApiParam(name = "generalDoctor", value = "全科医生code", required = false)
                                       @RequestParam(value = "generalDoctor", required = false)String generalDoctor,
                                               @ApiParam(name = "generalDoctorName", value = "全科医生名称", required = false)
                                       @RequestParam(value = "generalDoctorName", required = false)String generalDoctorName){
        try {
            return rehabilitationManageService.patientRehabilitationDetail(patientCode,healthDoctor, healthDoctorName,generalDoctor,generalDoctorName);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.recentPlanDetailRecord)
    @ApiOperation(value = "居民康复计划详情页-近期康复相关记录")
    public Envelop 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();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.serviceDoctorList)
    @ApiOperation(value = "康复管理-医生端居民详情服务医生列表")
    public Envelop serviceDoctorList(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                               @RequestParam(value = "patientCode", required = true)String patientCode,
                                     @ApiParam(name = "healthDoctor", value = "健管师医生code", required = false)
                                               @RequestParam(value = "healthDoctor", required = false)String healthDoctor,
                                     @ApiParam(name = "healthDoctorName", value = "健管师医生名称", required = false)
                                               @RequestParam(value = "healthDoctorName", required = false)String healthDoctorName,
                                     @ApiParam(name = "generalDoctor", value = "全科医生code", required = false)
                                               @RequestParam(value = "generalDoctor", required = false)String generalDoctor,
                                     @ApiParam(name = "generalDoctorName", value = "全科医生名称", required = false)
                                               @RequestParam(value = "generalDoctorName", required = false)String generalDoctorName){
        try {
            return rehabilitationManageService.serviceDoctorList(patientCode,healthDoctor, healthDoctorName,generalDoctor,generalDoctorName);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.appCalendarPlanDetailList)
    @ApiOperation(value = "康复管理-app端、微信端计划的服务项目列表")
    public ObjEnvelop appCalendarPlanDetailList(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                             @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                                @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                             @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                                @ApiParam(name = "planId", value = "计划id", required = true)
                                             @RequestParam(value = "planId", required = true)String planId,
                                                @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、随访,3、复诊,4、健康教育)", required = false)
                                             @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                                @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                             @RequestParam(value = "status", required = false)Integer status){
        try {
            return rehabilitationManageService.appCalendarPlanDetailList(planId,searchTask,status,executeStartTime,executeEndTime);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.dailyJob)
    @ApiOperation(value = "每日康复服务通知")
    public ObjEnvelop dailyJob(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                @RequestParam(value = "startTime", required = true)String startTime,
                               @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                @RequestParam(value = "endTime", required = true)String endTime){
        try {
            return rehabilitationManageService.dailyJob(startTime,endTime);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.tomorrowJob)
    @ApiOperation(value = "明日康复服务通知")
    public ObjEnvelop tomorrowJob(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                               @RequestParam(value = "startTime", required = true)String startTime,
                                  @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                               @RequestParam(value = "endTime", required = true)String endTime){
        try {
            return rehabilitationManageService.tomorrowJob(startTime,endTime);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.dailyByJob)
    @ApiOperation(value = "每日康复计划提醒")
    public ObjEnvelop dailyByJob(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                               @RequestParam(value = "startTime", required = true)String startTime,
                                 @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                               @RequestParam(value = "endTime", required = true)String endTime){
        try {
            return rehabilitationManageService.dailyByJob(startTime,endTime);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.rehabilitation.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();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = "planDetailAfterCall")
    @ApiOperation(value = "康复管理-电话关怀拨打后生成记录对应怪坏记录")
    public MixEnvelop<RehabilitationOperateRecordsDO, RehabilitationOperateRecordsDO> planDetailAfterCall(
            @ApiParam(name = "dataJson", value = "实体json",defaultValue = "{\"rehabilitationDetailId\":\"808080eb764ba46b017669712c640012\",\"doctorCode\":\"7e06886207e843948ae65d8f91d6ca97\",\"doctorName\":\"兰冠勇\"}")
            @RequestParam(value = "dataJson", required = true)String dataJson){
        try {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationManageService.planDetailAfterCall(dataJson));
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.rehabilitation.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();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.rehabilitation.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();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return Envelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.planSchedule)
    @ApiOperation(value = "康复管理-计划总进度")
    public ObjEnvelop planSchedule(@ApiParam(name = "planId", value = "计划id", required = true)
                                                       @RequestParam(value = "planId", required = true)String planId){
        try {
            return rehabilitationManageService.planSchedule(planId);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.planListByPatient)
    @ApiOperation(value = "康复管理-根据居民获取康复计划")
    public ObjEnvelop planListByPatient(@ApiParam(name = "patientCode", value = "居民code", required = true)
                                   @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            return rehabilitationManageService.planListByPatient(patientCode);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.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();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.rehabilitation.dailyJobReserve)
    @ApiOperation(value = "10天、7天、5天、当天康复服务预约复诊通知")
    public ObjEnvelop dailyJobReserve(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                               @RequestParam(value = "startTime", required = true)String startTime,
                                      @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                               @RequestParam(value = "endTime", required = true)String endTime){
        try {
            return rehabilitationManageService.dailyJobReserve(startTime,endTime);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 查询康复服务项目
     * @param ids
     * @return
     */
    @PostMapping(value = SpecialistMapping.rehabilitation.selectByIds)
    @ApiOperation(value = "查询康复服务项目")
    public ObjEnvelop selectByIds(@ApiParam(name = "ids",value = "康复服务套餐明细表ids")
            @RequestParam(value = "ids",required = true)String ids){
        try {
            return rehabilitationManageService.selectByIds(ids);
        }catch (Exception e){
            e.printStackTrace();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(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();
            //tracer.getCurrentSpan().logEvent(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
    }
}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 651 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationPlanController.java


+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/GuidanceMessageLogDao.java

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

+ 17 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientDiagnosisInformationDao.java

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

+ 13 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientDischargeDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.hospital.module.rehabilitation.dao;
import com.yihu.jw.entity.rehabilitation.PatientDischargeDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by liub on 2020/9/16.
 */
public interface PatientDischargeDao extends PagingAndSortingRepository<PatientDischargeDO, Long>, JpaSpecificationExecutor<PatientDischargeDO> {
}

+ 58 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientRehabilitationPlanDao.java

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

+ 11 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/PatientRehabilitationPlanLogDao.java

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

+ 13 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationDetailAppointmentDao.java

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

+ 94 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationDetailDao.java

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

+ 38 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationOperateRecordsDao.java

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

+ 28 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPatientInfoDao.java

@ -0,0 +1,28 @@
package com.yihu.jw.hospital.module.rehabilitation.dao;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPatientInfoDO;
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 liub on 2020/11/4.
 */
public interface RehabilitationPatientInfoDao extends PagingAndSortingRepository<RehabilitationPatientInfoDO, Long>,
        JpaSpecificationExecutor<RehabilitationPatientInfoDO> {
    @Query(value = "select r from RehabilitationPatientInfoDO r where (r.status =0 or r.status is null )")
    List<RehabilitationPatientInfoDO> findUnDispation();
    @Query(value = "select r from RehabilitationPatientInfoDO r where r.status =?1")
    List<RehabilitationPatientInfoDO> findUnDispationByStatus(Integer status);
    @Modifying
    @Query(value = "update RehabilitationPatientInfoDO r set r.status=?1 where r.code = ?2")
    int updateState(Integer state, String code);
}

+ 23 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationPlanTemplateDao.java

@ -0,0 +1,23 @@
package com.yihu.jw.hospital.module.rehabilitation.dao;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationPlanTemplateDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface RehabilitationPlanTemplateDao extends PagingAndSortingRepository<RehabilitationPlanTemplateDO, String>, JpaSpecificationExecutor<RehabilitationPlanTemplateDO> {
    @Query("select t from RehabilitationPlanTemplateDO t where (t.adminTeamCode = ?1 or t.adminTeamCode is null) and t.del = 1 ORDER BY t.adminTeamCode,t.createTime DESC ")
    List<RehabilitationPlanTemplateDO> findByAdminTeamCode(Long adminTeamCode);
    @Modifying
    @Query("update RehabilitationPlanTemplateDO t set t.del = 0 where t.id = ?1")
    void updateDelById(String id);
    @Modifying
    @Query("delete RehabilitationPlanTemplateDO t  where t.id = ?1")
    void delete(String id);
}

+ 16 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationServiceItemDao.java

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

+ 18 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/RehabilitationTemplateDetailDao.java

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

+ 12 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/dao/TemplateJsonDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.hospital.module.rehabilitation.dao;
import com.yihu.jw.entity.specialist.rehabilitation.TemplateJson;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface TemplateJsonDao extends PagingAndSortingRepository<TemplateJson, String>,
        JpaSpecificationExecutor<TemplateJson> {
}

+ 63 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/DiagnosisInformationService.java

@ -0,0 +1,63 @@
package com.yihu.jw.hospital.module.rehabilitation.service;
import com.yihu.jw.entity.specialist.rehabilitation.PatientDiagnosisInformationDO;
import com.yihu.jw.hospital.module.rehabilitation.dao.PatientDiagnosisInformationDao;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
 * Created by humingfen on 2019/1/11.
 */
@Service
@Transactional
public class DiagnosisInformationService extends BaseJpaService<PatientDiagnosisInformationDO, PatientDiagnosisInformationDao> {
    @Autowired
    private PatientDiagnosisInformationDao diagnosisInformationDao;
    /**
     * 保存诊疗信息
     * @param diagnosisInformationDO
     * @return
     */
    public Envelop createDiagnosisInformation(PatientDiagnosisInformationDO diagnosisInformationDO) {
        Date date = new Date();
        diagnosisInformationDO.setCreateTime(date);
        diagnosisInformationDao.save(diagnosisInformationDO);
        return Envelop.getSuccess(SpecialistMapping.api_success);
    }
    /**
     * 根据康复计划查找诊疗信息
     * @param planId
     * @return
     */
    public ObjEnvelop findDiagnosisInformationByPlanId(String planId) {
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, diagnosisInformationDao.findByPlanId(planId));
    }
    /**
     * 获取居民诊疗信息记录
     * @param patient
     * @param page
     * @param size
     * @return
     */
    public PageEnvelop findDiagnosisInformationByPatient(String patient, Integer page, Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        Page<PatientDiagnosisInformationDO> list = diagnosisInformationDao.findByPatient(patient,pageRequest);
        return PageEnvelop.getSuccessListWithPage(SpecialistMapping.api_success, list.getContent(), page, size,list.getTotalElements());
    }
}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 1034 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/PatientRecordService.java


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 913 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationInfoService.java


+ 1718 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationManageService.java

@ -0,0 +1,1718 @@
package com.yihu.jw.hospital.module.rehabilitation.service;
import com.alibaba.fastjson.JSON;
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.door.SignFamily;
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.hospital.module.rehabilitation.dao.*;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistPatientRelationDao;
import com.yihu.jw.hospital.team.dao.WlyySignFamilyDao;
import com.yihu.jw.im.util.ImUtil;
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.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.text.DecimalFormat;
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
    ImUtil imUtil;
    @Autowired
    BaseDoctorDao doctorDao;
    @Autowired
    WlyySignFamilyDao signFamilyDao;
    /**
     * 预约协诊
     *
     * @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 doctorType   1.专科,2.家医
     * @param doctorCode
     * @param diseaseCode
     * @param planType
     * @param todaybacklog
     * @param page
     * @param pageSize
     * @return
     * @throws Exception
     */
    public MixEnvelop<Map<String, Object>, Map<String, Object>> findRehabilitationPlan(Integer doctorType, String doctorCode, String diseaseCode, Integer planType, Integer todaybacklog, String patientCondition, Integer page, Integer pageSize) throws Exception {
        String sql = " select DISTINCT p.* " +
                " from wlyy_specialist.wlyy_rehabilitation_plan_detail a INNER JOIN wlyy_specialist.wlyy_patient_rehabilitation_plan p " +
                " on a.plan_id = p.id  ";
        if (doctorType == 2) {//家医是根据签约关系过滤
            sql += " INNER JOIN wlyy.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 wlyy.wlyy_patient where  `code` = 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<>();
        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"));
                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.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.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);
            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_specialist.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,IF(d.followup_detail_type=1,'社区随访(厦心)',i.name) name,1 as flag from wlyy_specialist.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) {//
                if (StringUtils.isNotBlank(doctorCode)) {
                    sql += " and d.doctor='" + doctorCode + "' ";
                }
                //sql+=" and i.code="+searchTask+" " ;
            } 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);
        String planPatientSql = " SELECT p.patient FROM wlyy_specialist.wlyy_patient_rehabilitation_plan p " +
                "INNER JOIN wlyy.wlyy_sign_family f ON p.patient = f.patient  WHERE p.id in (" + planCondition + " ) " +
                "AND f.`status` = 1 AND f.expenses_status = 1 AND  f.doctor = '" + doctorCode + "' ";
        List<Map<String, Object>> patientCodeList = jdbcTemplate.queryForList(planPatientSql);
        List<Map<String, Object>> list = null;
        if (patientCodeList.size() > 0 && null != searchTask) {
            String patient = patientCodeList.get(0).get("patient").toString();
            if (7 == searchTask) { //处方续方 flag 用于判断 1.7.0.5 新增
                String cfxfSql = "SELECT LEFT ( pr.create_time, 19 ) AS executeTime ,LEFT ( pr.pres_create_time, 19 ) AS buildCreateTime , pr.doctor AS doctorCode, pr.doctor_name AS doctorNmae,pr.`status`," +
                        " pr.hospital_name, pr.hospital, p.`name` AS patientName,p.code AS patientCode,pr.`code` AS id,7 as code, 2 as flag " +
                        " FROM  wlyy.wlyy_prescription pr  LEFT JOIN wlyy.wlyy_patient p ON pr.patient = p.`code` WHERE " +
                        "  1 = 1  AND pr.STATUS = '100' AND p.code= '" + patient + "' GROUP BY  pr.CODE ";
                list = jdbcTemplate.queryForList(cfxfSql);
            }
            if (6 == searchTask) { //随访
                String sfSql = "SELECT DISTINCT DATE_FORMAT(wf.followup_date,'%Y/%m/%d %H:%i') followupDate,DATE_FORMAT(wf.followup_plan_date,'%Y/%m/%d %H:%i') executeTime,wf.doctor_code doctorCode,wf.followup_class followupClass, " +
                        " wf.patient_code AS patientCode,wf.patient_name AS patientName,wf.doctor_name doctorName,wf.`status` AS `status`,wf.org_name orgName," +
                        " wf.org_code orgCode,sd.value AS `value`, wf.followup_type  followupType,wf.id AS id, 6 AS code,2 as flag FROM  wlyy.wlyy_followup wf " +
                        " LEFT JOIN wlyy.system_dict sd ON wf.followup_type = sd.CODE " +
                        " AND sd.dict_name = 'FOLLOWUP_WAY_DICT' WHERE wf.status !=0  AND wf.patient_code = '" + patient + "' order by wf.followup_plan_date desc  ";
                list = jdbcTemplate.queryForList(sfSql);
            }
            if (list != null && list.size() > 0) rehabilitationDetailList.addAll(list);
        }
        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_specialist.wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_specialist.wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id " +
                " LEFT JOIN wlyy_specialist.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:已完成)
            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,d.followup_detail_type followupDetailType " +
                " from wlyy_specialist.wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_specialist.wlyy_rehabilitation_service_item h on d.hospital_service_item_id = h.code " +
                " LEFT JOIN wlyy_specialist.wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " LEFT JOIN wlyy_specialist.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("followupDetailType", one.get("followupDetailType"));
        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"));
            /*          }*/
        }
        resultMap.put("operate", operate);//是否完成任务(默认0:未完成,1:已完成)
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, resultMap);
    }
    /**
     * 康复管理居民详情页
     *
     * @param patientCode
     * @param healthDoctor
     * @param healthDoctorName
     * @param generalDoctor
     * @param generalDoctorName
     * @return
     */
    public ObjEnvelop patientRehabilitationDetail(String patientCode, String healthDoctor, String healthDoctorName, String generalDoctor, String generalDoctorName) {
        Map<String, Object> resultMap = new HashMap<>();
        //个人基础信息(康复机构)
        String patientInfoSql = " SELECT DISTINCT hospital_name from wlyy_specialist.wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_specialist.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_specialist.wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_specialist.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);
        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);
        }
        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);//已完成
        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_specialist.wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id=h.code" +
                " LEFT JOIN wlyy_specialist.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_specialist.wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id=h.code" +
                "  LEFT JOIN wlyy_specialist.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
     * @param doctorType 1、专科医生,2、家庭医生
     */
    @Transactional
    public Envelop saveGuidanceMessage(String messageId, String doctor, Integer doctorType, String content, String planDetailId, Integer contentType) throws Exception {
        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
     * @param healthDoctor
     * @param healthDoctorName
     * @param generalDoctor
     * @param generalDoctorName
     * @return
     */
    public ObjEnvelop serviceDoctorList(String patientCode, String healthDoctor, String healthDoctorName, String generalDoctor, String generalDoctorName) {
        //服务医生
        //完成项目=全部的服务项目-未完成的服务项目
        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_specialist.wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_specialist.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"));
        }
        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()).orElse(null);
        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) {
        Map<String, Object> resultMap = new HashMap<>();
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);//计划总服务项目数
        Integer finishedCount = rehabilitationDetailDao.findByStatusAndPlanId(1, planId);
        PatientRehabilitationPlanDO p = patientRehabilitationPlanDao.findById(planId).orElse(null);
        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());
        }
//        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;
    }
    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(",", "、"));
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, reslutMap);
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public JSONArray selectPlanServerDoctor(String planId, String doctorCode) throws Exception {
        String sql = "SELECT t.patient,t.create_user FROM wlyy_specialist.wlyy_patient_rehabilitation_plan t  where t.id='" + planId + "'";//专科
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        JSONArray array = new JSONArray();
        String patient = "";
        for (Map<String, Object> map : mapList) {
            String doctor = map.get("create_user").toString();
            patient = map.get("patient").toString();
            org.json.JSONObject object = new org.json.JSONObject();
            BaseDoctorDO doctor1 = doctorDao.findById(doctor).orElse(null);
            object.put("code", doctor1.getId());
            object.put("name", doctor1.getName());
            object.put("level", doctor1.getLevel());
            //先注释-20231212
//            object.put("hospital", doctor1.getHospital());
//            object.put("hospitalName", doctor1.getHospitalName());
            if (doctor1.getLevel() == 1) {
                object.put("levelName", "专科医生");
            } else if (doctor1.getLevel() == 2) {
                object.put("levelName", "全科医生");
            }
            object.put("photo", doctor1.getPhoto());
            object.put("idcard", doctor1.getIdcard());
            array.put(object);
        }
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if (signFamily != null) {
            JSONObject object = new JSONObject();
            BaseDoctorDO doctor = doctorDao.findById(signFamily.getDoctor()).orElse(null);
            object.put("code", doctor.getId());
            object.put("name", doctor.getName());
            object.put("level", doctor.getLevel());
            if (doctor.getLevel() == 1) {
                object.put("levelName", "专科医生");
            } else if (doctor.getLevel() == 2) {
                object.put("levelName", "全科医生");
            }
            object.put("photo", doctor.getPhoto());
            object.put("idcard", doctor.getIdcard());
//            object.put("hospital", doctor.getHospital());
//            object.put("hospitalName", doctor.getHospitalName());
            array.put(object);
            org.json.JSONObject object1 = new org.json.JSONObject();
            if (StringUtils.isNoneBlank(signFamily.getDoctorHealth())) {
                BaseDoctorDO doctor1 = doctorDao.findById(signFamily.getDoctorHealth()).orElse(null);
                object1.put("code", doctor1.getId());
                object1.put("name", doctor1.getName());
                object1.put("level", 3);
                object1.put("levelName", "健管师");
                object1.put("photo", doctor1.getPhoto());
                object1.put("idcard", doctor1.getIdcard());
//                object.put("hospital", doctor1.getHospital());
//                object.put("hospitalName", doctor1.getHospitalName());
                array.put(object1);
            }
        }
        StringBuilder serverGroupSessionId = new StringBuilder();//群聊session_id
        StringBuilder serverGroupSessionName = new StringBuilder();//群聊名称
        JSONObject participants = new JSONObject();//群聊成员
        for (Object object : array) {//获取服务医生P2P 未读消息以及session_id。
            org.json.JSONObject jsonObject = (org.json.JSONObject) object;
            serverGroupSessionId.append(jsonObject.getString("code") + "_");
            serverGroupSessionName.append(jsonObject.getString("name") + "、");
            participants.put(jsonObject.getString("code"), 0);
            if (jsonObject.getString("code").equals(doctorCode)) {//
                jsonObject.put("unRead", 0);
                jsonObject.put("sessionId", "");
                jsonObject.put("type", "");
                jsonObject.put("business_type", "");
                continue;
            }
            //服务医生间的消息获取
            JSONObject participantsP2P = new JSONObject();
            participantsP2P.put(doctorCode, 0);
            participantsP2P.put(jsonObject.getString("code"), 0);
            //获取登录医生与其他服务医生的session_id
            //{"data":{"business_type":1,"name":"余研","id":"3438fdc6c1082c7b3c3e93dc27da244b59b694dc","type":"2","create_date":1603436112458},"status":200}
            JSONObject result = ImUtil.createSession(participantsP2P, "2", jsonObject.getString("name"), null);
            jsonObject.put("sessionId", result.getJSONObject("data").getString("id"));
            jsonObject.put("type", result.getJSONObject("data").getString("type"));
            jsonObject.put("business_type", result.getJSONObject("data").get("business_type"));
            //获取未读消息
            result = imUtil.getSessionUnreadMessageCount(jsonObject.getString("sessionId"), doctorCode);
            jsonObject.put("unRead", result.get("count"));
        }
        //服务医生群聊数据获取
        JSONObject groupObject = new JSONObject();
        if (StringUtils.isNoneBlank(serverGroupSessionId) && StringUtils.isNoneBlank(serverGroupSessionName)) {
            serverGroupSessionId.append("server_group");
            serverGroupSessionName = serverGroupSessionName.deleteCharAt(serverGroupSessionName.length() - 1);
            if (imUtil.sessionIsExist(serverGroupSessionId + "")) {//会话存在
                JSONObject result = imUtil.getSessionUnreadMessageCount(serverGroupSessionId + "", doctorCode);
                groupObject.put("unRead", result.get("count"));
            } else {
                JSONObject result = ImUtil.createSession(participants, "4", serverGroupSessionName + "", serverGroupSessionId + "");
                groupObject.put("unRead", 0);
            }
            groupObject.put("name", serverGroupSessionName);
            groupObject.put("sessionId", serverGroupSessionId.toString());
            groupObject.put("business_type", 1);
            groupObject.put("type", "4");
        }
        array.put(groupObject);
        return array;
    }
}

+ 595 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationPlanService.java

@ -0,0 +1,595 @@
package com.yihu.jw.hospital.module.rehabilitation.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.rehabilitation.RehabilitationPlanningDO;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.module.rehabilitation.dao.*;
import com.yihu.jw.hospital.module.rehabilitation.vo.TemplateDetailVo;
import com.yihu.jw.hospital.module.specialist.service.SpecialistHospitalServiceItemService;
import com.yihu.jw.hospital.module.specialist.service.SpecialistService;
import com.yihu.jw.mysql.query.BaseJpaService;
import com.yihu.jw.restmodel.qvo.ParamQvo;
import com.yihu.jw.restmodel.specialist.PatientSignInfoVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
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 javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
/**
 * Created by humingfen on 2018/8/17.
 */
@Service
@Transactional
public class RehabilitationPlanService extends BaseJpaService<RehabilitationPlanningDO, RehabilitationPlanTemplateDao> {
    @Value("${base.url}")
    private String baseUrl;
    @Value("${basedb.name}")
    private String basedb;
    @Autowired
    private RehabilitationPlanTemplateDao templateDao;
    @Autowired
    private RehabilitationTemplateDetailDao templateDetailDao;
    @Autowired
    private PatientRehabilitationPlanDao patientRehabilitationPlanDao;
    @Autowired
    RehabilitationPlanService planService;
    @Autowired
    private RehabilitationDetailDao rehabilitationDetailDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FastDFSUtil fastDFSHelper;
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private RehabilitationOperateRecordsDao rehabilitationOperateRecordsDao;
    @Autowired
    private SpecialistHospitalServiceItemService hospitalServiceItemService;
    @Autowired
    private SpecialistService specialistService;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private RehabilitationServiceItemDao serviceItemDao;
    @Autowired
    TemplateJsonDao templateJsonDao;
    /**
     * 没有默认创建服务项
     *
     * @param templateDO
     * @return
     */
    public RehabilitationPlanTemplateDO createRehabilitationTemplateNew(RehabilitationPlanTemplateDO templateDO) {
        templateDO.setCreateTime(new Date());
        templateDO.setDel(1);
        templateDO.setUpdateTime(new Date());
        templateDO = templateDao.save(templateDO);
        return templateDO;
    }
    public ObjEnvelop createRehabilitationTemplate(RehabilitationPlanTemplateDO templateDO) {
        templateDO.setCreateTime(new Date());
        templateDO.setDel(1);
        templateDO.setUpdateTime(new Date());
        templateDO = templateDao.save(templateDO);
        String templateId = templateDO.getId();
        String user = templateDO.getCreateUser();
        String userName = templateDO.getCreateUserName();
        //默认新增服务项
        String sql = "SELECT code from wlyy.system_dict WHERE `dict_name` = 'default_service_item_id'";
        List<String> list = jdbcTemplate.queryForList(sql, String.class);
        if (list != null && list.size() > 0) {
            list.stream().forEach(code -> {
                RehabilitationTemplateDetailDO detailDO = new RehabilitationTemplateDetailDO();
                detailDO.setTemplateId(templateId);
                detailDO.setHospitalServiceItemId(code);
                detailDO.setCreateUser(user);
                detailDO.setCreateUserName(userName);
                detailDO.setCreateTime(new Date());
                detailDO.setUpdateTime(new Date());
                templateDetailDao.save(detailDO);
            });
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, templateDO.getId());
    }
    public ObjEnvelop createRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details) {
        for (RehabilitationTemplateDetailDO detail : details) {
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            templateDetailDao.save(detail);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, true);
    }
    public ObjEnvelop createRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details, String templateId) {
        for (RehabilitationTemplateDetailDO detail : details) {
            detail.setTemplateId(templateId);
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            try {
                templateDetailDao.save(detail);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, true);
    }
    public ObjEnvelop updateRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details) {
        String templateId = details.get(0).getTemplateId();
        if (templateId != null && templateId.length() > 0) {
            templateDetailDao.deleteByTemplateId(templateId);
        }
        for (RehabilitationTemplateDetailDO detail : details) {
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            templateDetailDao.save(detail);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, true);
    }
    public MixEnvelop findRehabilitationPlanTemplate(Long adminTeamCode, String doctor, String patient) {
        if (adminTeamCode == null && StringUtils.isNotBlank(doctor) && StringUtils.isNotBlank(patient)) {
            PatientSignInfoVO patientSignSpecialistInfo = (PatientSignInfoVO) specialistService.findPatientSignSpecialistInfo(patient, doctor).getObj();
            adminTeamCode = patientSignSpecialistInfo.getTeamCode();
        }
        List<RehabilitationPlanTemplateDO> list = templateDao.findByAdminTeamCode(adminTeamCode);
        return MixEnvelop.getSuccessList(SpecialistMapping.api_success, list);
    }
    /**
     * 根据模板id修改康复模板删除状态
     *
     * @param id
     * @return
     */
    public ObjEnvelop deleteRehabilitationPlanTemplate(String id) {
        //删除主表
        templateDao.delete(id);
        //detail也删除了
        templateDetailDao.deleteByTemplateId(id);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, true);
    }
    /**
     * 根据模板id获取机构服务项目id,然后找出具体服务项目内容
     *
     * @param templateId
     * @return
     */
    public ListEnvelop findTemplateDetailByTemplateId(String templateId) {
        List<TemplateDetailVo> resultList = new ArrayList<>();
        List<RehabilitationTemplateDetailDO> list = templateDetailDao.findTemplateDetailByTemplateId(templateId);
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, List<RehabilitationTemplateDetailDO>> map = list.stream().collect(Collectors.groupingBy(RehabilitationTemplateDetailDO::getHospitalServiceItemId));
        for (String code : map.keySet()) {
            TemplateDetailVo detailVo = new TemplateDetailVo();
            detailVo.setCode(code);
            detailVo.setId(code);
            detailVo.setList(map.get(code));
            for (RehabilitationServiceItemDO item : itemDOList) {
                if (code.equals(item.getCode())) {
                    detailVo.setName(item.getName());
                    for (RehabilitationTemplateDetailDO detailDO : detailVo.getList()) {
                        detailDO.setName(item.getName());
                    }
                    break;
                }
            }
            resultList.add(detailVo);
        }
        return ListEnvelop.getSuccess(SpecialistMapping.api_success, resultList);
    }
    public PatientRehabilitationPlanDO createPatientRehabilitationPlan(PatientRehabilitationPlanDO planDO) {
        planDO.setCreateTime(new Date());
        planDO.setStatus(1);
        planDO.setUpdateTime(new Date());
        //判断是否签约,如果签约 新增家签团队id
        try {
            String sql = "SELECT a.admin_team_code  from wlyy.wlyy_sign_family a WHERE patient = '" + planDO.getPatient() + "' and `status`>0 and expenses_status =1 order by id desc limit 1 ";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            if (list != null && list.size() > 0) {
                planDO.setAdminTeamCode(Long.valueOf(list.get(0).get("admin_team_code") + ""));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return patientRehabilitationPlanDao.save(planDO);
    }
    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.saveAll(details);
    }
    public MixEnvelop findServiceItemsByHospital(String doctorHospital, String signHospital) {
        JSONArray jsonArray = new JSONArray();
        List<String> list = new ArrayList<>();
        list.add(doctorHospital);
        List<HospitalServiceItemDO> docHospitalServiceItemDO = hospitalServiceItemService.selectByHospital(list).getDetailModelList();
        if (StringUtils.isNotBlank(signHospital)) {
            if (signHospital.equals(doctorHospital)) {
                for (Object object : docHospitalServiceItemDO) {
                    JSONObject json = (JSONObject) JSONObject.toJSON(object);
                    json.put("type", "社区");
                    jsonArray.add(json);
                }
            } else if (!signHospital.equals(doctorHospital)) {
                JSONArray array = new JSONArray();
                List<String> itemIds = new ArrayList<>();
                list.remove(0);
                list.add(signHospital);
                List<HospitalServiceItemDO> signHospitalServiceItemDO = hospitalServiceItemService.selectByHospital(list).getDetailModelList();
                HashSet signSet = new HashSet();
                for (HospitalServiceItemDO h : signHospitalServiceItemDO) {
                    signSet.add(h.getServiceItemId());
                }
                //将服务项目重复的都放入itemIds集合里,并在列表中删除该条数据
                List<HospitalServiceItemDO> temp = new ArrayList<>();
                temp.addAll(docHospitalServiceItemDO);
                for (HospitalServiceItemDO h : docHospitalServiceItemDO) {
                    int size = signSet.size();
                    String itemId = h.getServiceItemId();
                    signSet.add(itemId);
                    if (signSet.size() == size) {
                        itemIds.add(itemId);
                        temp.remove(h);
                    }
                }
                array.addAll(signHospitalServiceItemDO);
                array.addAll(temp);
                for (Object obj : array) {
                    //往实体类插入数据
                    JSONObject json = (JSONObject) JSONObject.toJSON(obj);
                    if (json.get("hospital").equals(signHospital)) {
                        json.put("type", "社区");
                    } else if (json.get("hospital").equals(doctorHospital)) {
                        json.put("type", "医院");
                    }
                    if (itemIds.contains(json.get("serviceItemId"))) {
                        json.put("type", "社区,医院");
                    }
                    jsonArray.add(json);
                }
            }
        } else {
            jsonArray.addAll(docHospitalServiceItemDO);
        }
        return MixEnvelop.getSuccessList(SpecialistMapping.api_success, jsonArray);
    }
    /**
     * 调用服务包创建接口
     *
     * @param planDO
     * @param details
     */
    public String addServicePackage(PatientRehabilitationPlanDO planDO, List<RehabilitationDetailDO> details) {
        JSONObject jsonData = new JSONObject();
        JSONObject servicePackageVO = new JSONObject();
        JSONObject signRecordVO = new JSONObject();
        JSONArray detailsVOList = new JSONArray();
        //服务项目数据
        for (RehabilitationDetailDO detail : details) {
            JSONObject detailsVO = new JSONObject();
            detailsVO.put("executionType", "1");
            detailsVO.put("executionTime", DateUtil.dateToStr(detail.getExecuteTime(), "yyyy-MM-dd hh:mm:ss"));
            List<String> hospitalServiceIds = new ArrayList<>();
            hospitalServiceIds.add(detail.getHospitalServiceItemId());
            HospitalServiceItemDO signHospitalServiceItemDO = hospitalServiceItemService.selectById(hospitalServiceIds).getDetailModelList().get(0);
            detailsVO.put("code", signHospitalServiceItemDO.getServiceItemId());
            detailsVO.put("name", signHospitalServiceItemDO.getSpecialistServiceItemDO().getTitle());
            detailsVOList.add(detailsVO);
        }
        //服务包数据
        servicePackageVO.put("detailsVOList", detailsVOList);
        servicePackageVO.put("num", detailsVOList.size());
        servicePackageVO.put("saasId", "xmihealth");
        servicePackageVO.put("name", planDO.getTitle());
        servicePackageVO.put("introduce", planDO.getTitle());
        servicePackageVO.put("creater", planDO.getCreateUser());
        servicePackageVO.put("type", "1");
        servicePackageVO.put("price", planDO.getTotalExpense());
        //签约记录数据
        signRecordVO.put("servicePackageName", planDO.getTitle());
        signRecordVO.put("patient", planDO.getPatient());
        signRecordVO.put("name", planDO.getName());
        PatientSignInfoVO patientSignInfoVO = (PatientSignInfoVO) specialistService.findPatientSignSpecialistInfo(planDO.getPatient(), planDO.getCreateUser()).getObj();
        signRecordVO.put("idcard", patientSignInfoVO.getIdcard());
        signRecordVO.put("ssc", patientSignInfoVO.getSsc());
        signRecordVO.put("signDoctor", patientSignInfoVO.getDoctor());
        signRecordVO.put("signDoctorName", patientSignInfoVO.getDoctorName());
        signRecordVO.put("hospital", patientSignInfoVO.getHospital());
        signRecordVO.put("hospitalName", patientSignInfoVO.getHospitalName());
        signRecordVO.put("adminTeamCode", patientSignInfoVO.getTeamCode());
        signRecordVO.put("price", planDO.getTotalExpense());
        signRecordVO.put("saasId", "xmihealth");
        jsonData.put("servicePackageVO", servicePackageVO);
        jsonData.put("signRecordVO", signRecordVO);
        String response = null;
        try {
            response = httpClientUtil.postBody(baseUrl + "base_rehabilitation/create", jsonData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject rs = JSONObject.parseObject(response);
        if ("success".equals(rs.getString("message"))) {
            return rs.getJSONObject("obj").getString("id");
        }
        return null;
    }
    public void updateServicePackageId(String planId, String servicePackageId) {
        patientRehabilitationPlanDao.updateServicePackageId(planId, servicePackageId);
    }
    public MixEnvelop<String, String> createServiceQrCode(String planDetailId, String doctorCode, String imageUrl) {
        //更新到康复计划居民关系表中
        String sql = "update wlyy_rehabilitation_plan_detail set service_qr_code='" + imageUrl + "' where id='" + planDetailId + "'";
        jdbcTemplate.update(sql);
        return MixEnvelop.getSuccess("获取二维码成功!", imageUrl);
    }
    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 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 " + basedb + ".wlyy_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).orElse(null);
        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("更新失败!");
    }
    /**
     * 根据标签和居民code查找康复计划
     *
     * @param patient
     * @param label
     * @return
     */
    public List<PatientRehabilitationPlanDO> selectByLabelAndPatient(String patient, String label) {
        return patientRehabilitationPlanDao.selectByDiseaseAndPatient(label, patient);
    }
    public Envelop updatePatientImgById(String planId, String patientImg) {
        if (patientRehabilitationPlanDao.updatePatientImgById(planId, patientImg) > 0) {
            return Envelop.getSuccess(SpecialistMapping.api_success);
        }
        return Envelop.getError("更新失败!");
    }
    public void deleteDetailByPlanIdAndHospitalServiceItemId(String planId, String hospitalServiceItemId, Date dateShort) {
        rehabilitationDetailDao.deleteDetailByPlanIdAndHospitalServiceItemId(planId, hospitalServiceItemId, dateShort);
    }
    public void deleteDetailByPlanId(String planId, Date dateShort) {
        rehabilitationDetailDao.deleteDetailByPlanId(planId, dateShort);
    }
    public HashMap<String, Object> findRehabilitationPlanTemplatenew(
            String templateId, String templateName, String status, String diseaseId, String type, String pageIf, int page, int pageSize) {
        String countSql = "select count(1) ";
        String detailSql = "SELECT \n" +
                "  (SELECT GROUP_CONCAT(b.`name`) FROM 	wlyy_rehabilitation_template_detail q \n" +
                "	 INNER JOIN wlyy_rehabilitation_service_item b ON q.hospital_service_item_id=b.`code` WHERE q.template_id=a.id) 'itemName',\n" +
                "	a.*\n";
        String sql = " FROM	wlyy_rehabilitation_plan_template a WHERE 1=1\n";
        String pageSql = "";
        if (StringUtils.isNotBlank(templateId)) {
            sql += " AND a.id = '" + templateName + "' ";
        }
        if (StringUtils.isNotBlank(templateName)) {
            sql += " AND a.title LIKE '%" + templateName + "%' ";
        }
        if (StringUtils.isNotBlank(status)) {
            sql += "  AND a.status='" + status + "' ";
        }
        if (StringUtils.isNotBlank(diseaseId)) {
            sql += "  AND a.disease_id='" + diseaseId + "' ";
        }
        if (StringUtils.isNotBlank(type)) {
            sql += "  AND a.type='" + type + "' ";
        }
        if (StringUtils.isNotBlank(pageIf)) {
            pageSql += " LIMIT " + (page - 1) * pageSize + "," + pageSize;
        }
        detailSql += sql + pageSql;
        countSql += sql;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(detailSql);
        Integer count = jdbcTemplate.queryForObject(countSql, Integer.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("list", list);
        return map;
    }
    public List<Map<String, Object>> findRehabilitationServiceItem(String itemName) {
        String sql = " SELECT * FROM base.wlyy_rehabilitation_service_item WHERE 1=1 ";
        if (StringUtils.isNotBlank(itemName)) {
            sql += " and `name` LIKE '%" + itemName + "%'";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    public TemplateJson saveTemplate(String templateName, String templateJson) {
        TemplateJson entity = new TemplateJson();
        entity.setCreateTime(new Date());
        entity.setTemplateName(templateName);
        entity.setTemplateJson(templateJson);
        templateJsonDao.save(entity);
        return entity;
    }
    public List<Map<String, Object>> findDiseaseList() {
        String sql = "SELECT * FROM base_disease_hospital WHERE `status`='1' ORDER BY sort ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    public List<Map<String, Object>> findSaveTemplate(String templateName) {
        String sql = "select * FROM template_json WHERE 1=1 ";
        if (StringUtils.isNotBlank(templateName)) {
            sql += " and template_name LIKE '%" + templateName + "%'  ";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    /**
     * 新增整个模板
     *
     * @param templateDO
     * @param details
     * @return
     */
    public ObjEnvelop saveRehabilitationPlanTemplateData(RehabilitationPlanTemplateDO templateDO, List<RehabilitationTemplateDetailDO> details) {
        RehabilitationPlanTemplateDO planTemplateDO = this.createRehabilitationTemplateNew(templateDO);
        this.createRehabilitationTemplateDetail(details, planTemplateDO.getId());
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success, true);
    }
    public RehabilitationPlanTemplateDO changeState(ParamQvo qvo) {
        RehabilitationPlanTemplateDO entity = templateDao.findById(qvo.getId()).orElse(null);
        if (entity != null) {
            entity.setStatus(qvo.getStatus());
            templateDao.save(entity);
            return entity;
        }
        return null;
    }
    public ListEnvelop findFrequencyList() {
        String sql = " SELECT * FROM `base`.`wlyy_frequency` WHERE del='1' ";
        List<Frequency> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Frequency.class));
        return ListEnvelop.getSuccess(SpecialistMapping.api_success, list);
    }
}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 1902 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/SynchronizePatientService.java


+ 47 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/vo/TemplateDetailVo.java

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

+ 557 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistController.java

@ -0,0 +1,557 @@
package com.yihu.jw.hospital.module.specialist.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistPatientRelationDao;
import com.yihu.jw.hospital.module.specialist.service.SpecialistService;
import com.yihu.jw.restmodel.specialist.*;
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 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.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * Created by Trick on 2018/4/25.
 */
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "专科医生相关操作", description = "专科医生相关操作")
public class SpecialistController extends EnvelopRestEndpoint {
    @Autowired
    private SpecialistService specialistService;
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SpecialistPatientRelationDao specialistPatientRelationDao;
    @PostMapping(value = SpecialistMapping.specialist.createSpecialistRelation)
    @ApiOperation(value = "创建专科医生与患者匹配关系")
    public MixEnvelop<Boolean, Boolean> createSpecialistPatientRelation(@ApiParam(name = "specialistPatientRelation", value = "实体JSON")
                                                                @RequestParam(value = "specialistPatientRelation", required = false)String specialistPatientRelation){
        try {
            SpecialistPatientRelationDO ps = toEntity(specialistPatientRelation, SpecialistPatientRelationDO.class);
            return specialistService.createSpecialistsPatientRelation(ps);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findSpecialistPatientRelation)
    @ApiOperation(value = "获取专科医生关系列表")
    public MixEnvelop<SpecialistPatientRelationVO, SpecialistPatientRelationVO> findSpecialistPatientRelation(@ApiParam(name = "doctor", value = "专科医生ID")
                                                                                  @RequestParam(value = "doctor", required = false)String doctor,
                                                                                                              @ApiParam(name = "page", value = "第几页,从1开始")
                                                                              @RequestParam(value = "page", required = false)Integer page,
                                                                                                              @ApiParam(name = "size", value = ",每页分页大小")
                                                                                  @RequestParam(value = "size", required = false)Integer size){
        try {
            return specialistService.findSpecialistPatientRelation(doctor,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findSpecialistPatientRelationCout)
    @ApiOperation(value = "获取专科医生下未分配标签居民数目")
    public MixEnvelop<Long, Long> findSpecialistPatientRelationCout(@ApiParam(name = "doctor", value = "医生") @RequestParam(required = true)String doctor){
        try {
            return specialistService.findSpecialistPatientRelationCout(doctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findNoLabelPatientRelation)
    @ApiOperation(value = "获取专科医生下未分配标签居民")
    public MixEnvelop<PatientRelationVO, PatientRelationVO> findNoLabelPatientRelation(@ApiParam(name = "doctor", value = "医生") @RequestParam(required = true)String doctor){
        try {
            return specialistService.findNoLabelPatientRelation(doctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.specialist.saveHealthAssistant)
    @ApiOperation(value = "保存配置居民计管师居民")
    public MixEnvelop<Boolean, Boolean> saveHealthAssistant(@ApiParam(name = "json", value = "计管师居民实体") @RequestParam(required = true)String json){
        try {
            List<SpecialistPatientRelationDO> info = (List<SpecialistPatientRelationDO>) JSONArray.parseArray(json, SpecialistPatientRelationDO.class);
            return specialistService.saveHealthAssistant(info);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findPatientRelatioByAssistant)
    @ApiOperation(value = "根据计管师获取居民信息")
    public MixEnvelop<PatientRelationVO, PatientRelationVO> findPatientRelatioByAssistant(@ApiParam(name = "doctor", value = "医生") @RequestParam(required = true)String doctor,
                                                                                          @ApiParam(name = "assistant", value = "计管师") @RequestParam(required = true)String assistant,
                                                                                          @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
                                                                                          @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size) {
        try {
            return specialistService.findPatientRelatioByAssistant(doctor,assistant,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.getPatientByLabel)
    @ApiOperation(value = "根据标签获取居民信息")
    public MixEnvelop<PatientLabelVO, PatientLabelVO> getPatientByLabel(@ApiParam(name = "doctor", value = "医生") @RequestParam(required = true)String doctor,
                                                                        @ApiParam(name = "labelType", value = "标签类型") @RequestParam(required = true)String labelType,
                                                                        @ApiParam(name = "teamCode", value = "医生当前所在团队") @RequestParam(required = true) String teamCode,
                                                                        @ApiParam(name = "labelCode", value = "标签code") @RequestParam(required = true)String labelCode,
                                                                        @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
                                                                        @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size,
                                                                        @ApiParam(name = "shareDoctor", value = "共管医生") @RequestParam(required = false)String shareDoctor
                                                                        ){
        try {
            return specialistService.getPatientByLabel(doctor,labelType,teamCode,labelCode,page,size,shareDoctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.getLabelpatientCount)
    @ApiOperation(value = "根据标签获取居民数量")
    public MixEnvelop<Long, Long> getLabelpatientCount(@ApiParam(name = "doctor", value = "医生") @RequestParam(required = true)String doctor,
                                                       @ApiParam(name = "labelType", value = "标签类型") @RequestParam(required = true)String labelType,
                                                       @ApiParam(name = "teamCode", value = "医生团队") @RequestParam(required = true)Long teamCode,
                                                       @ApiParam(name = "labelCode", value = "标签code") @RequestParam(required = true)String labelCode,
                                                       @ApiParam(name = "shareDoctor", value = "共管医生CODE") @RequestParam(required = false)String shareDoctor) {
        try {
            return specialistService.getLabelpatientCount(doctor,labelType,labelCode,teamCode,shareDoctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.getAssistantPatientCount)
    @ApiOperation(value = "根据计管获取居民数量")
    public MixEnvelop<Long, Long> getAssistantPatientCount(@ApiParam(name = "doctor", value = "医生") @RequestParam(required = true)String doctor,
                                                           @ApiParam(name = "assistant", value = "计管师医生") @RequestParam(required = true)String assistant) {
        try {
            return specialistService.getAssistantPatientCount(doctor,assistant);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.getDoctorPatientByName)
    @ApiOperation(value = "搜索专科医生居民")
    public MixEnvelop<PatientRelationVO, PatientRelationVO> getDoctorPatientByName(@ApiParam(name = "doctor", value = "医生code") @RequestParam(required = true)String doctor,
                                                                                   @ApiParam(name = "nameKey", value = "居民姓名模糊") @RequestParam(required = false)String nameKey,
                                                                                   @ApiParam(name = "teamCode", value = "医生当前所在团队") @RequestParam(required = true) String teamCode,
                                                                                   @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
                                                                                   @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size) {
        try {
            return specialistService.getDoctorPatientByName(doctor,nameKey,teamCode,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.getDoctorPatientByNameOrIdCard)
    @ApiOperation(value = "根据姓名或身份证号搜索专科医生居民")
    public MixEnvelop<PatientRelationVO, PatientRelationVO> getDoctorPatientByNameOrIdCard(@ApiParam(name = "doctor", value = "医生code") @RequestParam(required = true)String doctor,
                                                                                           @ApiParam(name = "filter", value = "居民姓名模糊") @RequestParam(required = false)String filter,
                                                                                           @ApiParam(name = "teamCode", value = "医生当前所在团队") @RequestParam(required = true) String teamCode,
                                                                                           @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
                                                                                           @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size) {
        try {
            return specialistService.getDoctorPatientByNameOrIdCard(doctor,filter,teamCode,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findPatientNoAssistant)
    @ApiOperation(value = "获取未分配计管师居民列表")
    public MixEnvelop<PatientRelationVO, PatientRelationVO> findPatientNoAssistant(@ApiParam(name = "doctor", value = "医生code") @RequestParam(required = true)String doctor,
                                                                                   @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
                                                                                   @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size){
        try {
            return specialistService.findPatientNoAssistant(doctor,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.specialist.signSpecialistTeam)
    @ApiOperation(value = "提交专科医生签约")
    public MixEnvelop<SpecialistTeamVO, SpecialistTeamVO> signSpecialistTeam(@ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient,
                                                                             @ApiParam(name = "patientName", value = "居民姓名") @RequestParam(required = true)String patientName,
                                                                             @ApiParam(name = "doctor", value = "医生code") @RequestParam(required = true)String doctor,
                                                                             @ApiParam(name = "doctorName", value = "医生姓名") @RequestParam(required = true)String doctorName,
                                                                             @ApiParam(name = "teamCode", value = "团队code") @RequestParam(required = true)Long teamCode) {
        try {
            return specialistService.signSpecialistTeam( patient,  patientName,  doctor,  doctorName,  teamCode);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.specialist.agreeSpecialistTeam)
    @ApiOperation(value = "专科医生审核")
    public MixEnvelop<Boolean, Boolean> agreeSpecialistTeam(@ApiParam(name = "state", value = "状态0为拒绝,1为同意") @RequestParam(required = true)String state,
                                                            @ApiParam(name = "relationCode", value = "关联code") @RequestParam(required = true)String relationCode,
                                                            @ApiParam(name = "remark", value = "审核失败原因") @RequestParam(required = false)String remark,
                                                            @ApiParam(name = "health_assistant", value = "计管医生CODE") @RequestParam(required = false)String health_assistant,
                                                            @ApiParam(name = "health_assistant_name", value = "计管医生名称") @RequestParam(required = false)String health_assistant_name) {
        try {
            return specialistService.agreeSpecialistTeam(state,relationCode,remark,health_assistant,health_assistant_name);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findPatientSigninfo)
    @ApiOperation(value = "获取签约信息")
    public MixEnvelop<PatientSignInfoVO, PatientSignInfoVO> findPatientSigninfo(String code){
        try {
            return specialistService.findPatientSigninfo(code);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findPatientTeamList)
    @ApiOperation(value = "获取居民所有有效签约团队信息")
    public MixEnvelop<SpecialistTeamVO, SpecialistTeamVO> findPatientTeamList(@ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient){
        try {
            return specialistService.findPatientTeamList(patient);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findPatientSignSpecialist)
    @ApiOperation(value = "获取居民所有有效签约医生信息")
    public MixEnvelop findPatientSignSpecialist(@ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient){
        try {
            return specialistService.findPatientSignSpecialist(patient);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.findPatientSignSpecialistInfo)
    @ApiOperation(value = "获取居民与当前专科医生有效签约信息")
    public MixEnvelop findPatientSignSpecialistInfo(@ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient,
                                                    @ApiParam(name = "doctor", value = "专科医生code") @RequestParam(required = true)String doctor) {
        try {
            return specialistService.findPatientSignSpecialistInfo(patient,doctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    
    @GetMapping(value = SpecialistMapping.specialist.findDoctorAndDoctorHealthBySpecialDoctor)
    @ApiOperation(value = "获取当前专科医生有关联的家庭医生和健管师列表")
    public MixEnvelop findDoctorAndDoctorHealthBySpecialDoctor(
            @ApiParam(name = "doctor", value = "专科医生code") @RequestParam(required = true)String doctor,
            @ApiParam(name = "name", value = "家庭医生姓名") @RequestParam(required = false)String name){
        try {
            return specialistService.findDoctorAndDoctorHealthBySpecialDoctor(doctor,name);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    
    @GetMapping(value = SpecialistMapping.specialist.findSpecialistSignFamilyPatientCout)
    @ApiOperation(value = "获取专科医生家庭医生共管居民数目")
    public MixEnvelop<Long, Long> findSpecialistSignFamilyPatientCout(
            @ApiParam(name = "specialdoctor", value = "专科医生") @RequestParam(required = true)String specialdoctor,
            @ApiParam(name = "familydoctor", value = "家庭医生") @RequestParam(required = true)String familydoctor
    ){
        try {
            return specialistService.findSpecialistSignFamilyPatientCout(specialdoctor,familydoctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    
    @GetMapping(value = SpecialistMapping.specialist.getSpecialistSignFamilyPatientByName)
    @ApiOperation(value = "搜索专科医生家庭医生共管居民")
    public MixEnvelop<PatientRelationVO, PatientRelationVO> getSpecialistSignFamilyPatientByName(
            @ApiParam(name = "specialdoctor", value = "专科医生") @RequestParam(required = true)String specialdoctor,
            @ApiParam(name = "familydoctor", value = "家庭医生") @RequestParam(required = true)String familydoctor,
            @ApiParam(name = "nameKey", value = "居民姓名模糊") @RequestParam(required = false)String nameKey,
            @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
            @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size) {
        try {
            return specialistService.getSpecialistSignFamilyPatientByName(specialdoctor,familydoctor,nameKey,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.getPatientAndDiseaseByDoctor)
    @ApiOperation(value = "根据医生code获取签约居民信息及签约疾病类型")
    public MixEnvelop getPatientAndDiseaseByDoctor(
            @ApiParam(name = "doctor", value = "医生code") @RequestParam(required = true)String doctor,
            @ApiParam(name = "patientInfo", value = "居民信息") @RequestParam(required = false)String patientInfo,
            @ApiParam(name = "disease", value = "疾病类型") @RequestParam(required = false)String disease,
            @ApiParam(name = "page", value = "第几页,1开始") @RequestParam(required = true)Integer page,
            @ApiParam(name = "size", value = "每页大小") @RequestParam(required = true)Integer size){
        try {
            return specialistService.getPatientAndDiseaseByDoctor(doctor, patientInfo, disease, page, size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
//    @PostMapping(value = SpecialistMapping.specialist.createArticle)
//    @ApiOperation(value = "创建专科医生健康文章")
//    public Envelop<Boolean> createSpecialistArticle(@ApiParam(name = "specialistArticle", value = "专科医生健康文章JSON")
//                                                    @RequestParam(value = "specialistArticle", required = false)String specialistArticle){
//        try {
//            SpecialistArticleDO ps = toEntity(specialistArticle, SpecialistArticleDO.class);
//            return specialistService.createSpecialistArticle(ps);
//        }catch (Exception e){
//            e.printStackTrace();
//            // tracer.getCurrentSpan().logEvent(e.getMessage())
//            return Envelop.getError(e.getMessage());
//        }
//    }
//    @PostMapping(value = SpecialistMapping.specialist.createConsult)
//    @ApiOperation(value = "创建专科医生咨询")
//    public Envelop<Boolean> createSpscialistConsult(@ApiParam(name = "specialistConsult", value = "专科医生咨询实体JSON")
//                                                    @RequestParam(value = "specialistConsult", required = false)String specialistConsult){
//        try {
//            SpecialistConsultDO ps = toEntity(specialistConsult, SpecialistConsultDO.class);
//            return specialistService.createSpscialistConsult(ps);
//        }catch (Exception e){
//            e.printStackTrace();
//            // tracer.getCurrentSpan().logEvent(e.getMessage())
//            return Envelop.getError(e.getMessage());
//        }
//    }
//    @PostMapping(value = SpecialistMapping.specialist.createSpecialists)
//    @ApiOperation(value = "创建专科医生")
//    public Envelop<Boolean> createSpecialists(@ApiParam(name = "specialists", value = "专科医生实体")
//                                              @RequestParam(value = "code", required = false)String specialists){
//        try {
//            List<SpecialistDO> infos = new ObjectMapper().readValue(specialists, new TypeReference<List<SpecialistDO>>(){});
//            return specialistService.createSpecialists(infos);
//        }catch (Exception e){
//            e.printStackTrace();
//            // tracer.getCurrentSpan().logEvent(e.getMessage())
//            return Envelop.getError(e.getMessage());
//        }
//    }
    @GetMapping(value = SpecialistMapping.specialist.searchPatientInSpecialist)
    @ApiOperation(value = "搜索注册居民")
    public MixEnvelop searchPatientInSpecialist(
            @ApiParam(name = "doctorCode", value = "医生code",required = true) @RequestParam(required = true)String doctorCode,
            @ApiParam(name = "keywords", value = "居民姓名,手机号,身份证") @RequestParam(required = false)String keywords,
            @ApiParam(name = "page", value = "第几页,1开始",defaultValue = "1") @RequestParam(required = true,defaultValue = "1")Integer page,
            @ApiParam(name = "pageSize", value = "每页大小",defaultValue = "5") @RequestParam(required = true,defaultValue = "5")Integer pageSize){
        try {
            return specialistService.searchPatientInSpecialistNew(doctorCode,keywords,page,pageSize);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.searchPatientInSpeciaInfo)
    @ApiOperation(value = "根据病人和医生id病人的家签信息、专科开通信息")
    public ObjEnvelop<Object> searchPatientInSpecialist(
            @ApiParam(name = "doctorCode", value = "医生code",required = true)
            @RequestParam(value = "doctorCode",required = true)String doctorCode,
            @ApiParam(name = "signStatus", value = "签约状态,待审核:0;未签约:-1",required = true)
            @RequestParam(value = "signStatus",required = true)String signStatus,
            @ApiParam(name = "patientCode", value = "居民id",required = true)
            @RequestParam(value = "patientCode",required = true)String patientCode){
        try {
            JSONObject object=specialistService.doctorForSpecialistInfoNew(signStatus,doctorCode,patientCode);
            return  success(object);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.specialist.createPatientInSpeciaRelation)
    @ApiOperation(value = "专科医生发起签约")
    public ObjEnvelop<SpecialistPatientRelationDO> createPatientInSpeciaRelation(
            @ApiParam(name = "jsonData", value = "签约关系json")
            @RequestParam(value = "jsonData") String jsonData) {
        try {
            SpecialistPatientRelationDO specialistPatientRelationDO=toEntity(jsonData, SpecialistPatientRelationDO.class);
            if(StringUtils.isBlank(specialistPatientRelationDO.getPatient())){
                return failed("病人编码不能为空!", ObjEnvelop.class);
            }
            if(StringUtils.isBlank(specialistPatientRelationDO.getPatientName())){
                return failed("病人姓名不能为空!", ObjEnvelop.class);
            }
//            if(StringUtils.isBlank(specialistPatientRelationDO.getDoctor())){
//                return failed("医生编码不能为空!",ObjEnvelop.class);
//            }
//            if(StringUtils.isBlank(specialistPatientRelationDO.getDoctorName())){
//                return failed("医生姓名不能为空!",ObjEnvelop.class);
//            }
            if(null==specialistPatientRelationDO.getTeamCode()){
                return failed("医生团队不能为空!", ObjEnvelop.class);
            }
//            specialistPatientRelationDO.setDoctor(getUID());
//            specialistPatientRelationDO.setDoctorName(getUNAME());
            List<SpecialistPatientRelationDO> list = specialistPatientRelationDao.findListByTeamAndPatient(specialistPatientRelationDO.getTeamCode(),specialistPatientRelationDO.getPatient());
            if (list.size()>0){
                return ObjEnvelop.getSuccess("success", list.get(0));
            }
            return specialistService.createPatientInSpeciaRelation(specialistPatientRelationDO);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = "/redisFindPatientTeamList")
    @ApiOperation(value = "text-redis获取居民所有有效签约团队信息")
    public ObjEnvelop<Boolean> redisFindPatientTeamList(@ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient){
        try {
            String key = "specialist_patient_relation:" +patient +"_"+ ":text";
            return success(redisTemplate.opsForValue().get(key)==null?false:true);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return failed(e.getMessage(), ObjEnvelop.class);
        }
    }
    @GetMapping(value = SpecialistMapping.specialist.updateRedisFindPatientTeamList)
    @ApiOperation(value = "更新-redis获取居民所有有效签约团队信息")
    public ObjEnvelop<Integer> updateRedisFindPatientTeamList(){
        try {
            return success(specialistService.updateRedisFindPatientTeamList());
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return failed(e.getMessage(), ObjEnvelop.class);
        }
    }
    /**
     * 根据共管医生和居民code查询专科签约信息
     * @param patient
     * @param doctor
     * @return
     */
    @GetMapping(value = SpecialistMapping.specialist.selectByAssistant)
    @ApiOperation(value = "根据共管医生和居民code查询专科签约信息")
    public MixEnvelop<SpecialistPatientRelationDO, SpecialistPatientRelationDO> selectByAssistant(
            @ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient,
            @ApiParam(name = "doctor", value = "共管医生code") @RequestParam(required = true)String doctor){
        try {
            MixEnvelop envelop = new MixEnvelop();
            envelop.setDetailModelList(specialistService.selectByAssistant(patient,doctor));
            return envelop;
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = SpecialistMapping.specialist.updatePatientSignSpecialistInfo)
    @ApiOperation(value = "更新居民专科医生有效签约信息")
    public Envelop updatePatientSignSpecialistInfo(@ApiParam(name = "patient", value = "居民code") @RequestParam(required = true)String patient,
                                                   @ApiParam(name = "doctor", value = "专科医生code") @RequestParam(required = true)String doctor,
                                                   @ApiParam(name = "doctorName", value = "专科医生姓名") @RequestParam(required = true)String doctorName) {
        try {
            return specialistService.updatePatientSignSpecialistInfo(patient,doctor, doctorName);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return Envelop.getError(e.getMessage());
        }
    }
    @PostMapping(value="/transferPatients")
    @ApiOperation(value = "专科端转移居民")
    public Envelop transferPatients(@ApiParam(name="teamCode",value = "医生所在团队",required = true)@RequestParam(value = "teamCode",required = true) String teamCode,
                                    @ApiParam(name="toTeamCode",value = "转移医生医生所在所在团队,跨团队时必传",required = true)@RequestParam(value = "toTeamCode",required = false) String toTeamCode,
                                    @ApiParam(name="doctorCode",value = "当前医生code",required = true)@RequestParam(value = "doctorCode",required = true)String doctorCode,
                                    @ApiParam(name="toDoctorCode",value = "接收患者医生code",required = true)@RequestParam(value = "toDoctorCode",required = true)String toDoctorCode,
                                    @ApiParam(name="patients",value = "患者JsonArray列表(包含code)",required = true)@RequestParam(value = "patients",required = true)String patients){
        try {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,specialistService.transferPatients(teamCode,toTeamCode,doctorCode, toDoctorCode, patients));
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return Envelop.getError(e.getMessage());
        }
    }
}

+ 126 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistEvaluateController.java

@ -0,0 +1,126 @@
package com.yihu.jw.hospital.module.specialist.controller;/**
 * Created by nature of king on 2018/8/27.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.SpecialistEvaluateDO;
import com.yihu.jw.hospital.module.specialist.service.SpecialistEvaluateService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * @author wangzhinan
 * @create 2018-08-27 14:17
 * @desc 评论
 **/
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "评价相关操作", description = "评价相关操作")
public class SpecialistEvaluateController extends EnvelopRestEndpoint {
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private SpecialistEvaluateService specialistEvaluateService;
    /**
     * 添加评价
     *
     * @param evaluate
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.createEvaluate)
    @ApiOperation(value = "添加评论")
    public MixEnvelop<SpecialistEvaluateDO, SpecialistEvaluateDO> create(@ApiParam(name = "evaluate", value = "评价")
                                                                           @RequestParam(value = "evaluate")String evaluate){
        try {
            JSONObject object = JSONObject.parseObject(evaluate);
            return specialistEvaluateService.createEvaluate(object);
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 获取评论
     *
     * @param evaluate
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.getEvaluate)
    @ApiOperation(value = "获取评论")
    public MixEnvelop<JSONObject,JSONObject> select(@ApiParam(name = "evaluate", value = "评价")
                                                                        @RequestParam(value = "evaluate")String evaluate){
        try {
            SpecialistEvaluateDO specialistEvaluateDO = toEntity(evaluate, SpecialistEvaluateDO.class);
            return specialistEvaluateService.selectByCondition(specialistEvaluateDO);
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 更新评价
     *
     * @param evaluate
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.updateEvaluate)
    @ApiOperation(value = "更新评价")
    public MixEnvelop<Boolean,Boolean> update(@ApiParam(name = "evaluate", value = "评价")
                                                                        @RequestParam(value = "evaluate")String evaluate){
        try {
            JSONArray array = JSONArray.parseArray(evaluate);
            List<SpecialistEvaluateDO> specialistEvaluateDOS = new ArrayList<>();
            for (int i = 0;i<array.size();i++){
                SpecialistEvaluateDO specialistEvaluateDO = toEntity(array.getString(i), SpecialistEvaluateDO.class);
                specialistEvaluateDOS.add(specialistEvaluateDO);
            }
            return specialistEvaluateService.update(specialistEvaluateDOS);
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 医生获取评分
     *
     * @param doctor
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectByDoctor)
    @ApiOperation(value = "医生获取评分")
    public MixEnvelop<JSONObject,JSONObject> selectByDoctor(@ApiParam(name = "doctor", value = "评价")
                                                    @RequestParam(value = "doctor")String doctor){
        try {
            return specialistEvaluateService.selectByDoctor(doctor);
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
}

+ 248 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistHospitalServiceItemController.java

@ -0,0 +1,248 @@
package com.yihu.jw.hospital.module.specialist.controller;/**
 * Created by nature of king on 2018/8/29.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.hospital.module.specialist.service.SpecialistHospitalServiceItemService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.DataUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @author wangzhinan
 * @create 2018-08-29 0:56
 * @desc
 **/
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "机构服务项目相关操作", description = "机构服务项目相关操作")
public class SpecialistHospitalServiceItemController extends EnvelopRestEndpoint {
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private SpecialistHospitalServiceItemService specialistHospitalServiceItemService;
    /**
     * 添加机构服务项目
     * @param hospitalServiceItem
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.createHospitalServiceItem)
    @ApiOperation(value = "添加机构服务项目")
    public MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> create(@ApiParam(name = "hospitalServiceItem", value = "机构服务项目")
                                                                        @RequestParam(value = "hospitalServiceItem")String hospitalServiceItem){
        try {
            JSONArray array = JSONArray.parseArray(hospitalServiceItem);
            List<HospitalServiceItemDO> hospitalServiceItemDOS = new ArrayList<>();
            for (int i =0 ; i<array.size();i++){
                JSONObject object = array.getJSONObject(i);
                object.replace("expense", DataUtils.doubleToInt(object.getDouble("expense")));
                HospitalServiceItemDO hospitalServiceItemDO = toEntity(object.toJSONString(), HospitalServiceItemDO.class);
                hospitalServiceItemDOS.add(hospitalServiceItemDO);
            }
            return specialistHospitalServiceItemService.insert(hospitalServiceItemDOS);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 根据医院Code查找机构服务项目
     *
     * @param hospitals
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectByHospital)
    @ApiOperation(value = "根据医院Code查找机构服务项目")
    public MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> selectByHospital(@ApiParam(name = "hospitals", value = "医院code集合")
                                                                          @RequestParam(value = "hospitals",required = false)String hospitals){
        try {
            JSONArray array = JSONArray.parseArray(hospitals);
            List<String> hospitalList = new ArrayList<>();
            if (array != null || array.size()!=0){
                for (int i =0 ;i<array.size();i++){
                    hospitalList.add(array.getString(i));
                }
            }
            MixEnvelop envelop = specialistHospitalServiceItemService.selectByHospital(hospitalList);
            List<HospitalServiceItemDO> hospitalServiceItemDOList = envelop.getDetailModelList();
            JSONArray array1 = new JSONArray();
            if (hospitalServiceItemDOList != null && hospitalServiceItemDOList.size()!=0){
                for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOList){
                    JSONObject object = (JSONObject) JSONObject.toJSON(hospitalServiceItemDO);
                    object.replace("expense", DataUtils.integerTransferDouble(hospitalServiceItemDO.getExpense()));
                    JSONObject jsonObject = object.getJSONObject("specialistServiceItemDO");
                    jsonObject.replace("threeHospitals", DataUtils.integerTransferDouble(hospitalServiceItemDO.getSpecialistServiceItemDO().getThreeHospitals()));
                    jsonObject.replace("twoHospitals",DataUtils.integerTransferDouble(hospitalServiceItemDO.getSpecialistServiceItemDO().getTwoHospitals()));
                    jsonObject.replace("oneHospitals",DataUtils.integerTransferDouble(hospitalServiceItemDO.getSpecialistServiceItemDO().getOneHospitals()));
                    array1.add(object);
                }
            }
            envelop.setDetailModelList(array1);
            return envelop;
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 根据id查找机构服务项目
     *
     * @param ids
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectById)
    @ApiOperation(value = "根据id查找机构服务项目")
    public MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> selectById(@ApiParam(name = "ids", value = "机构服务项目集合")
                                                                                    @RequestParam(value = "ids")String ids){
        try {
            JSONArray array = JSONArray.parseArray(ids);
            List<String> idList = new ArrayList<>();
            for (int i =0 ;i<array.size();i++){
                idList.add(array.getString(i));
            }
            MixEnvelop envelop = specialistHospitalServiceItemService.selectById(idList);
            List<HospitalServiceItemDO> hospitalServiceItemDOList = envelop.getDetailModelList();
            JSONArray array1 = new JSONArray();
            if (hospitalServiceItemDOList != null && hospitalServiceItemDOList.size()!=0){
                for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOList){
                    JSONObject object = (JSONObject) JSONObject.toJSON(hospitalServiceItemDO);
                    object.replace("expense", DataUtils.integerTransferDouble(hospitalServiceItemDO.getExpense()));
                    JSONObject jsonObject = object.getJSONObject("specialistServiceItemDO");
                    jsonObject.replace("threeHospitals", DataUtils.integerTransferDouble(hospitalServiceItemDO.getSpecialistServiceItemDO().getThreeHospitals()));
                    jsonObject.replace("twoHospitals",DataUtils.integerTransferDouble(hospitalServiceItemDO.getSpecialistServiceItemDO().getTwoHospitals()));
                    jsonObject.replace("oneHospitals",DataUtils.integerTransferDouble(hospitalServiceItemDO.getSpecialistServiceItemDO().getOneHospitals()));
                    array1.add(object);
                }
            }
            envelop.setDetailModelList(array1);
            return envelop;
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     *
     * @param serviceItemName
     * @param hospitals
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectByCondition)
    @ApiOperation(value = "根据条件查找机构服务项目")
    public MixEnvelop<JSONArray,JSONArray> selectByCondition(@ApiParam(name = "serviceItemName", value = "服务项目名称")
                                                                                    @RequestParam(value = "serviceItemName",required = false)String serviceItemName,
                                                             @ApiParam(name = "hospitals",value = "医院集合")
                                                                                     @RequestParam(value = "hospitals",required = false)String hospitals){
        try {
            JSONArray array = JSONArray.parseArray(hospitals);
            List<String> hospitalList = new ArrayList<>();
            for (int i =0 ;i<array.size();i++){
                hospitalList.add(array.getString(i));
            }
            return specialistHospitalServiceItemService.selectByCondition(serviceItemName,hospitalList);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     *
     * @param hospital
     * @param serviceItem
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.deleteHospitalItem)
    @ApiOperation(value = "删除机构服务项目")
    public MixEnvelop<Boolean,Boolean> delete(@ApiParam(name = "hospital", value = "医院code")
                                              @RequestParam(name = "hospital",required = false)String hospital,
                                              @ApiParam(name = "serviceItem", value = "服务项目code")
                                              @RequestParam(name = "serviceItem",required = false)String serviceItem,
                                              @ApiParam(name = "id", value = "机构服务项目id")
                                                  @RequestParam(name = "id",required = false)String id){
        try {
            return specialistHospitalServiceItemService.delete(hospital,serviceItem,id);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     *
     * @param hospital
     * @param docHospital
     * @param serviceItemName
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectByHospital1)
    @ApiOperation(value = "查询服务项目")
    public MixEnvelop<JSONArray,JSONArray> selectByHospital1(@ApiParam(name = "hospital", value ="社区code")
                                              @RequestParam(name = "hospital",required = false)String hospital,
                                                             @ApiParam(name = "docHospital", value = "医院code")
                                              @RequestParam(name = "docHospital")String docHospital,
                                                             @ApiParam(name = "serviceItemName", value = "服务项目名称")
                                              @RequestParam(name = "serviceItemName",required = false)String serviceItemName){
        try {
            return  specialistHospitalServiceItemService.selectByHospital1(hospital,docHospital,serviceItemName);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 机构服务项目导数据
     *
     * @param hospitalItems
     * @return
     */
    @RequestMapping(value = SpecialistMapping.serviceItem.importData2)
    @ResponseBody
    public MixEnvelop<Boolean,Boolean> importData(@ApiParam(name = "hospitalItems", value = "机构服务项目集合")
                                                  @RequestParam(value = "hospitalItems")String hospitalItems) {
        try {
            JSONArray array = JSONArray.parseArray(hospitalItems);
            List<HospitalServiceItemDO> hospitalServiceItemDOList = new ArrayList<>();
            for (int i = 0;i<array.size();i++){
                JSONObject object = array.getJSONObject(i);
                object.replace("expense", DataUtils.doubleToInt(object.getDouble("expense")));
                HospitalServiceItemDO hospitalServiceItemDO = toEntity(object.toJSONString(), HospitalServiceItemDO.class);
                hospitalServiceItemDOList.add(hospitalServiceItemDO);
            }
            return specialistHospitalServiceItemService.importData(hospitalServiceItemDOList);
        } catch (Exception e) {
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
}

+ 83 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistScreenResultController.java

@ -0,0 +1,83 @@
package com.yihu.jw.hospital.module.specialist.controller;
import com.yihu.jw.hospital.module.specialist.service.SpecialistScreenResultService;
import com.yihu.jw.hospital.module.specialist.service.SpecialistService;
import com.yihu.jw.restmodel.specialist.SurveyScreenResultVo;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
 * Created by zhangdan on 2018/7/6.
 */
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "专科医生疾病筛查相关操作", description = "专科医生疾病筛查相关操作")
public class SpecialistScreenResultController extends EnvelopRestEndpoint {
    @Autowired
    private SpecialistService specialistService;
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private SpecialistScreenResultService specialistScreenResultService;
    @GetMapping(value = SpecialistMapping.screen.getScreenResult)
    @ApiOperation(value = "专科医生获取筛查记录列表")
    public MixEnvelop<SurveyScreenResultVo, SurveyScreenResultVo> createSpecialistPatientRelation(@ApiParam(name = "doctor", value = "专科医生ID")@RequestParam(value = "doctor",required = false)String doctor,
                                                                                                  @ApiParam(value = "当前页")@RequestParam(value = "pageNo") int pageNo,
                                                                                                  @ApiParam(value = "显示记录数")@RequestParam(value = "pageSize") int pageSize,
                                                                                                  @ApiParam(value = "搜索居民的姓名或身份证") @RequestParam(value = "patientName", required = false) String patientName,
                                                                                                  @ApiParam(value = "1已跟踪 2已预约 3已接诊 4待处理")@RequestParam(value = "type",required = false) Integer type,
                                                                                                  @ApiParam(value = "是否高危预警(0否 1是)") @RequestParam(value = "isDanger", required = false) String isDanger,
                                                                                                  @ApiParam(value = "疾病类型") @RequestParam(value = "diseaseType", required = false) String diseaseType,
                                                                                                  @ApiParam(value = "传1则根据类型查一条数据")@RequestParam(value = "filterType",required = false,defaultValue = "0")Integer filterType,
                                                                                                  @ApiParam(value = "居民code")@RequestParam(required = false)String patientCode){
        try {
            return specialistScreenResultService.getScreenList(doctor,type,pageNo,pageSize,patientName, isDanger, diseaseType,filterType,patientCode);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.screen.getScreenCount)
    @ApiOperation(value = "专科医生首页--筛查已跟踪和已预约的数目")
    public MixEnvelop<Map<String,Object>, Map<String,Object>> findSpecialistPatientRelation(@ApiParam(name = "doctor", value = "专科医生ID")@RequestParam(value = "doctor")String doctor){
        try {
            return specialistScreenResultService.getResultCount(doctor);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @GetMapping(value = SpecialistMapping.screen.getScreenResultDetail)
    @ApiOperation(value = "查看筛查结果记录详情.")
    public MixEnvelop<Map<String,Object>, Map<String,Object>> getScreenResultDetail(@ApiParam(value = "筛查结果唯一code")@RequestParam(value = "code") String code) {
        try {
            return specialistScreenResultService.getScreenResultDetail(code);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
}

+ 236 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistServiceItemController.java

@ -0,0 +1,236 @@
package com.yihu.jw.hospital.module.specialist.controller;/**
 * Created by nature of king on 2018/8/17.
 */
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.SpecialistEvaluateDO;
import com.yihu.jw.entity.specialist.SpecialistServiceItemDO;
import com.yihu.jw.hospital.module.specialist.service.SpecialistServiceItemService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.DataUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @author wangzhinan
 * @create 2018-08-17 9:33
 * @desc 服务项目
 **/
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "服务项目相关操作", description = "服务项目相关操作")
public class SpecialistServiceItemController extends EnvelopRestEndpoint {
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private SpecialistServiceItemService specialistServiceItemService;
    /**
     * 服务项目列表查询
     *
     * @param serviceItem
     * @param page
     * @param pageSize
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.getServiceItem)
    @ApiOperation(value = "服务项目列表查询")
    public MixEnvelop<SpecialistServiceItemDO, SpecialistEvaluateDO> select(@ApiParam(name = "serviceItem", value = "服务项目JSON")
                                                       @RequestParam(value = "serviceItem")String serviceItem,
                                                                            @ApiParam(value = "当前页",name = "page")
                                                   @RequestParam(value = "page",defaultValue = "1") Integer page,
                                                                            @ApiParam(value = "显示记录数",name = "pageSize",defaultValue = "10")
                                                       @RequestParam(value = "pageSize") Integer pageSize){
        try {
            SpecialistServiceItemDO serviceItemDO = toEntity(serviceItem, SpecialistServiceItemDO.class);
            MixEnvelop envelop = specialistServiceItemService.select(serviceItemDO,page,pageSize);
            JSONArray array = new JSONArray();
            List<SpecialistServiceItemDO> specialistServiceItemDOS =  envelop.getDetailModelList();
            if (specialistServiceItemDOS != null && specialistServiceItemDOS.size()!=0){
                for (SpecialistServiceItemDO specialistServiceItemDO:specialistServiceItemDOS){
                    JSONObject jsonObject = (JSONObject)JSONObject.toJSON(specialistServiceItemDO);
                    jsonObject.replace("threeHospitals", DataUtils.integerTransferDouble(specialistServiceItemDO.getThreeHospitals()));
                    jsonObject.replace("twoHospitals",DataUtils.integerTransferDouble(specialistServiceItemDO.getTwoHospitals()));
                    jsonObject.replace("oneHospitals",DataUtils.integerTransferDouble(specialistServiceItemDO.getOneHospitals()));
                    array.add(jsonObject);
                }
            }
            envelop.setDetailModelList(array);
            return envelop;
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 服务项目添加
     *
     * @param serviceItem
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.createServiceItem)
    @ApiOperation(value = "服务项目添加")
    public MixEnvelop<Boolean,Boolean> insert(@ApiParam(name = "serviceItem", value = "服务项目JSON")
                                                       @RequestParam(value = "serviceItem")String serviceItem){
        try {
            JSONObject object = JSON.parseObject(serviceItem);
            if (object.getDouble("threeHospitals")!=null){
                object.replace("threeHospitals", DataUtils.doubleToInt(object.getDouble("threeHospitals")));
            }
            if (object.getDouble("twoHospitals")!=null){
                object.replace("twoHospitals",DataUtils.doubleToInt(object.getDouble("twoHospitals")));
            }
            if (object.getDouble("oneHospitals")!=null){
                object.replace("oneHospitals",DataUtils.doubleToInt(object.getDouble("oneHospitals")));
            }
            SpecialistServiceItemDO serviceItemDO = toEntity(object.toJSONString(), SpecialistServiceItemDO.class);
            return specialistServiceItemService.insert(serviceItemDO);
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 批量删除服务项目
     * @param ids
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.batchDelete)
    @ApiOperation(value = "批量删除服务项目")
    public MixEnvelop<Boolean,Boolean> batchDelete(@ApiParam(name="ids",value = "id集合")
                                        @RequestParam(value = "ids",required = false)String ids){
        try{
            MixEnvelop<Boolean,Boolean> envelop = new MixEnvelop<>();
            JSONArray array = JSONArray.parseArray(ids);
            List<String> itemIds = new ArrayList<>();
            for (int i = 0;i<array.size();i++){
                itemIds.add(array.getString(i));
            }
            specialistServiceItemService.batchDelete(itemIds);
            envelop.setObj(true);
            return envelop;
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 更新服务项目
     *
     * @param serviceItem
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.updateServiceItem)
    @ApiOperation(value = "服务项目更新")
    public MixEnvelop<Boolean,Boolean> udpate(@ApiParam(name = "serviceItem", value = "服务项目JSON")
                                              @RequestParam(value = "serviceItem")String serviceItem){
        try {
            JSONObject object = JSON.parseObject(serviceItem);
            if (object.getDouble("threeHospitals")!=null){
                object.replace("threeHospitals", DataUtils.doubleToInt(object.getDouble("threeHospitals")));
            }
            if (object.getDouble("twoHospitals")!=null){
                object.replace("twoHospitals",DataUtils.doubleToInt(object.getDouble("twoHospitals")));
            }
            if (object.getDouble("oneHospitals")!=null){
                object.replace("oneHospitals",DataUtils.doubleToInt(object.getDouble("oneHospitals")));
            }
            SpecialistServiceItemDO serviceItemDO = toEntity(object.toJSONString(), SpecialistServiceItemDO.class);
            return specialistServiceItemService.update(serviceItemDO);
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 根据医院code获取服务项目
     *
     * @param hospital
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectItemByHospital)
    @ApiOperation(value = "根据医院code获取服务项目")
    public MixEnvelop selectByHospital(@ApiParam(name = "hospital", value = "医院code")
                                              @RequestParam(value = "hospital")String hospital){
        try {
            MixEnvelop envelop = specialistServiceItemService.selectByHospital(hospital);
            JSONArray array = new JSONArray();
            List<SpecialistServiceItemDO> specialistServiceItemDOS =  envelop.getDetailModelList();
            if (specialistServiceItemDOS != null && specialistServiceItemDOS.size()!=0){
                for (SpecialistServiceItemDO specialistServiceItemDO:specialistServiceItemDOS){
                    JSONObject jsonObject = (JSONObject)JSONObject.toJSON(specialistServiceItemDO);
                    jsonObject.replace("threeHospitals", DataUtils.integerTransferDouble(specialistServiceItemDO.getThreeHospitals()));
                    jsonObject.replace("twoHospitals",DataUtils.integerTransferDouble(specialistServiceItemDO.getTwoHospitals()));
                    jsonObject.replace("oneHospitals",DataUtils.integerTransferDouble(specialistServiceItemDO.getOneHospitals()));
                    array.add(jsonObject);
                }
            }
            envelop.setDetailModelList(array);
            return envelop;
        }catch (Exception e){
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
    /**
     * 导数据
     *
     * @return
     */
    @RequestMapping(value = "importData1")
    @ResponseBody
    public MixEnvelop<Boolean,Boolean> importData(@ApiParam(name = "serviceItems", value = "服务项目集合")
                                                      @RequestParam(value = "serviceItems")String serviceItems) {
        try {
            JSONArray array = JSONArray.parseArray(serviceItems);
            List<SpecialistServiceItemDO> specialistServiceItemDOS = new ArrayList<>();
            for (int i = 0;i<array.size();i++){
                JSONObject object = array.getJSONObject(i);
                if (object.getDouble("threeHospitals")!=null){
                    object.replace("threeHospitals", DataUtils.doubleToInt(object.getDouble("threeHospitals")));
                }
                if (object.getDouble("twoHospitals")!=null){
                    object.replace("twoHospitals",DataUtils.doubleToInt(object.getDouble("twoHospitals")));
                }
                if (object.getDouble("oneHospitals")!=null){
                    object.replace("oneHospitals",DataUtils.doubleToInt(object.getDouble("oneHospitals")));
                }
                SpecialistServiceItemDO specialistServiceItemDO = toEntity(object.toJSONString(), SpecialistServiceItemDO.class);
                specialistServiceItemDOS.add(specialistServiceItemDO);
            }
            return specialistServiceItemService.importData(specialistServiceItemDOS);
        } catch (Exception e) {
            e.printStackTrace();
           // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
}

+ 58 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/controller/SpecialistServiceItemOperateLogController.java

@ -0,0 +1,58 @@
package com.yihu.jw.hospital.module.specialist.controller;
import com.yihu.jw.entity.specialist.SpecialistServiceItemOperateLogDO;
import com.yihu.jw.hospital.module.specialist.service.SpecialistServiceItemOperateLogService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author wangzhinan
 * @create 2018-09-01 15:15
 * @desc 操作记录
 **/
@RestController
@RequestMapping(SpecialistMapping.api_specialist_common)
@Api(tags = "服务项目操作记录相关操作", description = "服务项目操作记录相关操作")
public class SpecialistServiceItemOperateLogController extends EnvelopRestEndpoint {
//    @Autowired
//    private Tracer tracer;
    @Autowired
    private SpecialistServiceItemOperateLogService specialistServiceItemOperateLogService;
    /**
     * 查找服务项目操作记录
     *
     * @param operateLog
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = SpecialistMapping.serviceItem.selectByOperate)
    @ApiOperation(value = "服务项目操作记录查询")
    public MixEnvelop<SpecialistServiceItemOperateLogDO, SpecialistServiceItemOperateLogDO> select(@ApiParam(name = "operateLog", value = "操作记录JSON")
                                                                           @RequestParam(value = "operateLog")String operateLog,
                                                                                                   @ApiParam(value = "当前页",name = "page")
                                                                           @RequestParam(value = "page",defaultValue = "1") Integer page,
                                                                                                   @ApiParam(value = "显示记录数",name = "size",defaultValue = "10")
                                                                           @RequestParam(value = "size") Integer size){
        try {
            SpecialistServiceItemOperateLogDO specialistServiceItemOperateLogDO = toEntity(operateLog, SpecialistServiceItemOperateLogDO.class);
            return specialistServiceItemOperateLogService.select(specialistServiceItemOperateLogDO,page,size);
        }catch (Exception e){
            e.printStackTrace();
            // tracer.getCurrentSpan().logEvent(e.getMessage())
            return MixEnvelop.getError(e.getMessage());
        }
    }
}

+ 12 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/PatientHospitalRecordDao.java

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

+ 16 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistEvaluateDao.java

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

+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistEvaluateLabelDao.java

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

+ 15 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistEvaluateScoreDao.java

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

+ 22 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistHospitalServiceItemDao.java

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

+ 41 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistPatientRelationDao.java

@ -0,0 +1,41 @@
package com.yihu.jw.hospital.module.specialist.dao;
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);
}

+ 27 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistServiceItemDao.java

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

+ 17 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/dao/SpecialistServiceItemOperateLogDao.java

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

+ 17 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/FileUploadService.java

@ -0,0 +1,17 @@
package com.yihu.jw.hospital.module.specialist.service;//package com.yihu.jw.base.service.specialist;
//
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//
///**
// * @author zhangdan on 2018/08/22.
// */
//@Service
//public class FileUploadService{
//
//    @Value("${neiwang.wlyy}")
//    private String neiwangWlyy;  //内网的项目地址
//
//
//
//}

+ 413 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistEvaluateService.java

@ -0,0 +1,413 @@
package com.yihu.jw.hospital.module.specialist.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.SpecialistEvaluateDO;
import com.yihu.jw.entity.specialist.SpecialistEvaluateLabelDO;
import com.yihu.jw.entity.specialist.SpecialistEvaluateScoreDO;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistEvaluateDao;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistEvaluateLabelDao;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistEvaluateScoreDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.ISqlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
/**
 * @author wangzhinan
 * @create 2018-08-22 9:48
 * @desc 评论service
 **/
@Transactional
@Service
public class SpecialistEvaluateService extends EnvelopRestEndpoint {
    @Autowired
    private SpecialistEvaluateDao specialistEvaluateDao;
    @Autowired
    private SpecialistEvaluateLabelDao specialistEvaluateLabelDao;
    @Autowired
    private SpecialistEvaluateScoreDao specialistEvaluateScoreDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 添加评论
     *
     * @param jsonObject
     * @return
     */
    public MixEnvelop<SpecialistEvaluateDO, SpecialistEvaluateDO> createEvaluate(JSONObject jsonObject) throws IOException {
        MixEnvelop<SpecialistEvaluateDO, SpecialistEvaluateDO> envelop = new MixEnvelop<>();
        JSONArray evaluate = jsonObject.getJSONArray("evaluate");
        JSONArray evaluateLabel = jsonObject.getJSONArray("evaluateLabel");
        String patientCode = jsonObject.getString("patient");
        List<SpecialistEvaluateDO> specialistEvaluateDOList = new ArrayList<>();
        List<SpecialistEvaluateLabelDO> specialistEvaluateLabelDOS = new ArrayList<>();
        for (int i = 0;i<evaluate.size();i++){
            SpecialistEvaluateDO specialistEvaluateDO = toEntity(evaluate.getJSONObject(i).toJSONString(), SpecialistEvaluateDO.class);
            specialistEvaluateDOList.add(specialistEvaluateDO);
        }
        for (int i =0;i<evaluateLabel.size();i++){
            SpecialistEvaluateLabelDO specialistEvaluateLabelDO = toEntity(evaluateLabel.getJSONObject(i).toJSONString(), SpecialistEvaluateLabelDO.class);
            specialistEvaluateLabelDOS.add(specialistEvaluateLabelDO);
        }
        String doctor = null;
        String relationCode = null;
        String patient = null;
        Double total = 0d;
        if (specialistEvaluateDOList != null && specialistEvaluateDOList.size() != 0){
            for (SpecialistEvaluateDO specialistEvaluateDO:specialistEvaluateDOList){
                specialistEvaluateDO.setRelationType(1);
                specialistEvaluateDO.setPatient(patientCode);
                specialistEvaluateDO.setCreateTime(new Date());
                specialistEvaluateDO.setUpdateTime(new Date());
                doctor = specialistEvaluateDO.getDoctor();
                relationCode = specialistEvaluateDO.getRelationCode();
                patient = specialistEvaluateDO.getPatient();
                SpecialistEvaluateDO specialistEvaluateDO1 = specialistEvaluateDao.save(specialistEvaluateDO);
                SpecialistEvaluateLabelDO specialistEvaluateLabelDO = new SpecialistEvaluateLabelDO();
                specialistEvaluateLabelDO.setSaasId("dev");
                specialistEvaluateLabelDO.setContent(specialistEvaluateDO.getContent());
                specialistEvaluateLabelDO.setDoctor(specialistEvaluateDO1.getDoctor());
                specialistEvaluateLabelDO.setPatient(specialistEvaluateDO1.getPatient());
                specialistEvaluateLabelDO.setEvaluateType(1);
                specialistEvaluateLabelDO.setRelationCode(specialistEvaluateDO.getRelationCode());
                specialistEvaluateLabelDO.setFlag(specialistEvaluateDO.getFlag());
                specialistEvaluateLabelDO.setCreateTime(new Date());
                specialistEvaluateLabelDO.setUpdateTime(new Date());
                specialistEvaluateLabelDao.save(specialistEvaluateLabelDO);
                total = total + specialistEvaluateDO.getScore();
            }
        }
        if (specialistEvaluateLabelDOS.size()!=0&&specialistEvaluateLabelDOS != null){
            for (SpecialistEvaluateLabelDO specialistEvaluateLabelDO:specialistEvaluateLabelDOS){
                specialistEvaluateLabelDO.setSaasId("dev");
                specialistEvaluateLabelDO.setEvaluateType(1);
                specialistEvaluateLabelDO.setPatient(patientCode);
                specialistEvaluateLabelDao.save(specialistEvaluateLabelDO);
            }
        }
        double score = total/3;
        BigDecimal   b   =   new   BigDecimal(score);
        double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
        SpecialistEvaluateScoreDO specialistEvaluateScoreDO = new SpecialistEvaluateScoreDO();
        specialistEvaluateScoreDO.setRelationCode(relationCode);
        specialistEvaluateScoreDO.setEvaluateType(1);
        specialistEvaluateScoreDO.setDoctor(doctor);
        specialistEvaluateScoreDO.setSaasId("dev");
        specialistEvaluateScoreDO.setScore(f1);
        specialistEvaluateScoreDO.setCreateTime(new Date());
        specialistEvaluateScoreDO.setUpdateTime(new Date());
        specialistEvaluateScoreDao.save(specialistEvaluateScoreDO);
        return envelop;
    }
    /**
     * 查询评论
     *
     * @param specialistEvaluateDO
     * @return
     */
    public MixEnvelop<JSONObject,JSONObject> selectByCondition(SpecialistEvaluateDO specialistEvaluateDO){
        MixEnvelop<JSONObject,JSONObject> envelop = new MixEnvelop<>();
        String sql = ISqlUtils.getSql(specialistEvaluateDO,1,100,"*");
        List<SpecialistEvaluateDO> specialistEvaluateDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        String sql1 = "select * from wlyy_specialist_evaluate_label where doctor = '"+specialistEvaluateDO.getDoctor()+"' " +
                "and relation_code = '"+specialistEvaluateDO.getRelationCode()+"' and patient = '"+specialistEvaluateDO.getPatient()+"'";
        List<SpecialistEvaluateLabelDO> specialistEvaluateLabelDOS = jdbcTemplate.query(sql1,new BeanPropertyRowMapper(SpecialistEvaluateLabelDO.class));
        String sql2 = "select * from wlyy_specialist_evaluate_score where doctor = '"+specialistEvaluateDO.getDoctor()+"' " +
                "and relation_code = '"+specialistEvaluateDO.getRelationCode()+"'";
        List<SpecialistEvaluateScoreDO> specialistEvaluateScoreDOS = jdbcTemplate.query(sql2,new BeanPropertyRowMapper(SpecialistEvaluateScoreDO.class));
        JSONObject object = new JSONObject();
        object.put("score",specialistEvaluateScoreDOS);
        object.put("evaluate",specialistEvaluateDOS);
        object.put("evaluateLabel",specialistEvaluateLabelDOS);
        List<JSONObject> array = new ArrayList<>();
        array.add(object);
        envelop.setDetailModelList(array);
        return envelop;
    }
    /**
     * 更新评价
     *
     * @param specialistEvaluateDOList
     * @return
     */
    public MixEnvelop<Boolean,Boolean> update(List<SpecialistEvaluateDO> specialistEvaluateDOList){
        MixEnvelop<Boolean,Boolean> envelop = new MixEnvelop<>();
        String doctor = null;
        String relationCode = null;
        String patient = null;
        Double total = 0d;
        if (specialistEvaluateDOList != null && specialistEvaluateDOList.size() != 0){
            for (SpecialistEvaluateDO specialistEvaluateDO:specialistEvaluateDOList){
                specialistEvaluateDO.setSaasId("dev");
                specialistEvaluateDO.setRelationType(1);
                specialistEvaluateDO.setCreateTime(new Date());
                specialistEvaluateDO.setUpdateTime(new Date());
                doctor = specialistEvaluateDO.getDoctor();
                relationCode = specialistEvaluateDO.getRelationCode();
                patient = specialistEvaluateDO.getPatient();
                SpecialistEvaluateDO specialistEvaluateDO1 = specialistEvaluateDao.save(specialistEvaluateDO);
                SpecialistEvaluateLabelDO specialistEvaluateLabelDO = specialistEvaluateLabelDao.findById(specialistEvaluateDO.getLabelId()).orElse(null);
                specialistEvaluateLabelDO.setSaasId("dev");
                specialistEvaluateLabelDO.setContent(specialistEvaluateDO.getContent());
                specialistEvaluateLabelDO.setDoctor(specialistEvaluateDO1.getDoctor());
                specialistEvaluateLabelDO.setPatient(specialistEvaluateDO1.getPatient());
                specialistEvaluateLabelDO.setEvaluateType(1);
                specialistEvaluateLabelDO.setRelationCode(specialistEvaluateDO.getRelationCode());
                specialistEvaluateLabelDO.setCreateTime(new Date());
                specialistEvaluateLabelDO.setUpdateTime(new Date());
                specialistEvaluateLabelDao.save(specialistEvaluateLabelDO);
                total = total + specialistEvaluateDO.getScore();
            }
        }
        double score = total/3;
        BigDecimal   b   =   new   BigDecimal(score);
        double   f1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
        String sql2 = "select * from wlyy_specialist_evaluate_score where doctor = '"+doctor+"' " +
                "and relation_code = '"+relationCode+"'";
        List<SpecialistEvaluateScoreDO> specialistEvaluateScoreDOS = jdbcTemplate.query(sql2,new BeanPropertyRowMapper(SpecialistEvaluateScoreDO.class));
        SpecialistEvaluateScoreDO specialistEvaluateScoreDO = specialistEvaluateScoreDOS.get(0);
        specialistEvaluateScoreDO.setRelationCode(relationCode);
        specialistEvaluateScoreDO.setEvaluateType(1);
        specialistEvaluateScoreDO.setDoctor(doctor);
        specialistEvaluateScoreDO.setSaasId("dev");
        specialistEvaluateScoreDO.setScore(f1);
        specialistEvaluateScoreDO.setCreateTime(new Date());
        specialistEvaluateScoreDO.setUpdateTime(new Date());
        specialistEvaluateScoreDao.save(specialistEvaluateScoreDO);
        return envelop;
    }
    public MixEnvelop<JSONObject,JSONObject> selectByDoctor(String doctor){
        MixEnvelop<JSONObject,JSONObject> envelop = new MixEnvelop<>();
        JSONObject object = new JSONObject();
        String sql = "select AVG(score) AS total from wlyy_specialist_evaluate_score where doctor = '"+doctor+"'";
        String sql1 = "select AVG(score) AS total from wlyy_specialist_evaluate where doctor = '"+doctor+"' AND evaluate_type = 1";
        String sql2 =  "select AVG(score) AS total from wlyy_specialist_evaluate where doctor = '"+doctor+"' AND evaluate_type = 2";
        String sql3 =  "select AVG(score) AS total from wlyy_specialist_evaluate where doctor = '"+doctor+"' AND evaluate_type = 3";
        String sql4 = "select * from wlyy_specialist_evaluate where doctor = '"+doctor+"'";
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        Double totalScore = 0.0;
        if(rstotal!=null&&rstotal.size()>0){
            Object object1 = rstotal.get(0).get("total");
            if (object1!=null){
                totalScore = Double.parseDouble(object1.toString());
            }
        }
        List<Map<String,Object>> rstotal1 = jdbcTemplate.queryForList(sql1);
        Double totalScore1 = 0.0;
        if(rstotal1!=null&&rstotal1.size()>0){
            Object object1 = rstotal1.get(0).get("total");
            if (object1!=null){
                totalScore1 = Double.parseDouble(object1.toString());
            }
        }
        List<Map<String,Object>> rstotal2 = jdbcTemplate.queryForList(sql2);
        Double totalScore2 = 0.0;
        if(rstotal2!=null&&rstotal2.size()>0){
            Object object1 = rstotal2.get(0).get("total");
            if (object1!=null){
                totalScore2 = Double.parseDouble(object1.toString());
            }
        }
        List<Map<String,Object>> rstotal3 = jdbcTemplate.queryForList(sql3);
        Double totalScore3 = 0.0;
        if(rstotal3!=null&&rstotal3.size()>0){
            Object object1 = rstotal3.get(0).get("total");
            if (object1!=null){
                totalScore3 = Double.parseDouble(object1.toString());
            }
        }
        String sql5 = "select * from wlyy_specialist_evaluate WHERE doctor = '"+doctor+"'";
        String sql6 = "select * from wlyy_specialist_evaluate WHERE doctor IN (select doctor from wlyy_specialist_evaluate_score where score > 71 and doctor = '"+doctor+"')";
        String sql7 = "select * from wlyy_specialist_evaluate WHERE doctor IN (select doctor from wlyy_specialist_evaluate_score where score > 41 and score < 71 and doctor = '"+doctor+"')";
        String sql8 = "select * from wlyy_specialist_evaluate WHERE doctor IN (select doctor from wlyy_specialist_evaluate_score where score < 41 and doctor = '"+doctor+"')";
        List<SpecialistEvaluateDO> specialistEvaluateDOS = jdbcTemplate.query(sql5,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS1 = jdbcTemplate.query(sql5,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS3 = jdbcTemplate.query(sql6,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS4 = jdbcTemplate.query(sql6,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS5 = jdbcTemplate.query(sql7,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS6 = jdbcTemplate.query(sql7,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS7 = jdbcTemplate.query(sql8,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        List<SpecialistEvaluateDO> specialistEvaluateDOS8 = jdbcTemplate.query(sql8,new BeanPropertyRowMapper(SpecialistEvaluateDO.class));
        JSONArray array = new JSONArray();
        JSONArray array3 = new JSONArray();
        JSONArray array4 = new JSONArray();
        JSONArray array5 = new JSONArray();
        JSONObject object2 = new JSONObject();
        JSONObject object3 = new JSONObject();
        JSONObject object4 = new JSONObject();
        JSONObject object5 = new JSONObject();
        //全部
        for (int i=0;i<specialistEvaluateDOS.size();i++){
            JSONArray array1 = new JSONArray();
            JSONObject object1 = new JSONObject();
            boolean isTrue = false;
            SpecialistEvaluateDO specialistEvaluateDO = specialistEvaluateDOS.get(i);
            Set<String> set = new HashSet<>();
            Set<Double> scoreSet = new HashSet<>();
            for (int j=0;j<specialistEvaluateDOS1.size();j++){
                SpecialistEvaluateDO specialistEvaluateDO1 = specialistEvaluateDOS1.get(j);
                JSONObject jsonObject = new JSONObject();
                if (specialistEvaluateDO.getRelationCode().equals(specialistEvaluateDO1.getRelationCode())&&specialistEvaluateDO.getPatient().equals(specialistEvaluateDO1.getPatient())&&specialistEvaluateDO.getDoctor().equals(specialistEvaluateDO1.getDoctor())){
                    String scoreSql = "select * from wlyy_specialist_evaluate_score where relation_code = '"+specialistEvaluateDO1.getRelationCode()+"' and patient = '"+specialistEvaluateDO1.getPatient()+"'";
                    List<SpecialistEvaluateScoreDO> specialistEvaluateScoreDOS =jdbcTemplate.query(scoreSql,new BeanPropertyRowMapper(SpecialistEvaluateScoreDO.class));
                    if (specialistEvaluateScoreDOS != null && specialistEvaluateScoreDOS.size()!=0){
                        scoreSet.add(specialistEvaluateScoreDOS.get(0).getScore());
                    }
                    set.add(specialistEvaluateDO1.getPatient());
                    array1.add(specialistEvaluateDO1);
                }
            }
            object1.put("patient",set);
            for (Double value:scoreSet){
                if (value>71){
                    object1.put("flag","好评");
                }else if (value>41&&value<71){
                    object1.put("flag","中评");
                }else if (value<41){
                    object1.put("flag","差评");
                }
            }
            object1.put("score",scoreSet);
            object1.put("evaluate",array1);
            if (array1.size() !=0&&array1 != null){
                specialistEvaluateDOS1.removeAll(array1);
                array.add(object1);
            }
        }
        //好评
        for (int i=0;i<specialistEvaluateDOS3.size();i++){
            JSONArray array1 = new JSONArray();
            JSONObject object1 = new JSONObject();
            boolean isTrue = false;
            SpecialistEvaluateDO specialistEvaluateDO = specialistEvaluateDOS3.get(i);
            Set<String> set = new HashSet<>();
            Set<Double> scoreSet = new HashSet<>();
            for (int j=0;j<specialistEvaluateDOS4.size();j++){
                SpecialistEvaluateDO specialistEvaluateDO1 = specialistEvaluateDOS4.get(j);
                JSONObject jsonObject = new JSONObject();
                if (specialistEvaluateDO.getRelationCode().equals(specialistEvaluateDO1.getRelationCode())&&specialistEvaluateDO.getPatient().equals(specialistEvaluateDO1.getPatient())&&specialistEvaluateDO.getDoctor().equals(specialistEvaluateDO1.getDoctor())){
                    String scoreSql = "select * from wlyy_specialist_evaluate_score where relation_code = '"+specialistEvaluateDO1.getRelationCode()+"' and patient = '"+specialistEvaluateDO1.getPatient()+"'";
                    List<SpecialistEvaluateScoreDO> specialistEvaluateScoreDOS =jdbcTemplate.query(scoreSql,new BeanPropertyRowMapper(SpecialistEvaluateScoreDO.class));
                    if (specialistEvaluateScoreDOS != null && specialistEvaluateScoreDOS.size()!=0){
                        scoreSet.add(specialistEvaluateScoreDOS.get(0).getScore());
                    }
                    set.add(specialistEvaluateDO1.getPatient());
                    array1.add(specialistEvaluateDO1);
                }
            }
            object1.put("patient",set);
            object1.put("flag","好评");
            object1.put("score",scoreSet);
            object1.put("evaluate",array1);
            if (array1.size() !=0&&array1 != null){
                specialistEvaluateDOS4.removeAll(array1);
                array3.add(object1);
            }
        }
        //中评
        for (int i=0;i<specialistEvaluateDOS5.size();i++){
            JSONArray array1 = new JSONArray();
            JSONObject object1 = new JSONObject();
            boolean isTrue = false;
            SpecialistEvaluateDO specialistEvaluateDO = specialistEvaluateDOS5.get(i);
            Set<String> set = new HashSet<>();
            Set<Double> scoreSet = new HashSet<>();
            for (int j=0;j<specialistEvaluateDOS6.size();j++){
                SpecialistEvaluateDO specialistEvaluateDO1 = specialistEvaluateDOS6.get(j);
                JSONObject jsonObject = new JSONObject();
                if (specialistEvaluateDO.getRelationCode().equals(specialistEvaluateDO1.getRelationCode())&&specialistEvaluateDO.getPatient().equals(specialistEvaluateDO1.getPatient())&&specialistEvaluateDO.getDoctor().equals(specialistEvaluateDO1.getDoctor())){
                    String scoreSql = "select * from wlyy_specialist_evaluate_score where relation_code = '"+specialistEvaluateDO1.getRelationCode()+"' and patient = '"+specialistEvaluateDO1.getPatient()+"'";
                    List<SpecialistEvaluateScoreDO> specialistEvaluateScoreDOS =jdbcTemplate.query(scoreSql,new BeanPropertyRowMapper(SpecialistEvaluateScoreDO.class));
                    if (specialistEvaluateScoreDOS != null && specialistEvaluateScoreDOS.size()!=0){
                        scoreSet.add(specialistEvaluateScoreDOS.get(0).getScore());
                    }
                    set.add(specialistEvaluateDO1.getPatient());
                    array1.add(specialistEvaluateDO1);
                }
            }
            object1.put("patient",set);
            object1.put("flag","中评");
            object1.put("score",scoreSet);
            object1.put("evaluate",array1);
            if (array1.size() !=0&&array1 != null){
                specialistEvaluateDOS6.removeAll(array1);
                array4.add(object1);
            }
        }
        //差评
        for (int i=0;i<specialistEvaluateDOS7.size();i++){
            JSONArray array1 = new JSONArray();
            JSONObject object1 = new JSONObject();
            boolean isTrue = false;
            SpecialistEvaluateDO specialistEvaluateDO = specialistEvaluateDOS7.get(i);
            Set<String> set = new HashSet<>();
            Set<Double> scoreSet = new HashSet<>();
            for (int j=0;j<specialistEvaluateDOS8.size();j++){
                SpecialistEvaluateDO specialistEvaluateDO1 = specialistEvaluateDOS8.get(j);
                JSONObject jsonObject = new JSONObject();
                if (specialistEvaluateDO.getRelationCode().equals(specialistEvaluateDO1.getRelationCode())&&specialistEvaluateDO.getPatient().equals(specialistEvaluateDO1.getPatient())&&specialistEvaluateDO.getDoctor().equals(specialistEvaluateDO1.getDoctor())){
                    String scoreSql = "select * from wlyy_specialist_evaluate_score where relation_code = '"+specialistEvaluateDO1.getRelationCode()+"' and patient = '"+specialistEvaluateDO1.getPatient()+"'";
                    List<SpecialistEvaluateScoreDO> specialistEvaluateScoreDOS =jdbcTemplate.query(scoreSql,new BeanPropertyRowMapper(SpecialistEvaluateScoreDO.class));
                    if (specialistEvaluateScoreDOS != null && specialistEvaluateScoreDOS.size()!=0){
                        scoreSet.add(specialistEvaluateScoreDOS.get(0).getScore());
                    }
                    set.add(specialistEvaluateDO1.getPatient());
                    array1.add(specialistEvaluateDO1);
                }
            }
            object1.put("patient",set);
            object1.put("flag","差评");
            object1.put("score",scoreSet);
            object1.put("evaluate",array1);
            if (array1.size() !=0&&array1 != null){
                specialistEvaluateDOS8.removeAll(array1);
                array5.add(object1);
            }
        }
        String lableSql = "select * from wlyy_specialist_evaluate_label where doctor ='"+doctor+"' AND flag IN (2,3)";
        List<SpecialistEvaluateLabelDO> specialistEvaluateLabelDOS = jdbcTemplate.query(lableSql,new BeanPropertyRowMapper(SpecialistEvaluateLabelDO.class));
        Set<String> labelSet = new HashSet<>();
        for (SpecialistEvaluateLabelDO specialistEvaluateLabelDO:specialistEvaluateLabelDOS){
            labelSet.add(specialistEvaluateLabelDO.getContent());
        }
        object2.put("evaluate",array);
        object2.put("total",array.size());
        object3.put("evaluate",array3);
        object3.put("total",array3.size());
        object4.put("evaluate",array4);
        object4.put("total",array4.size());
        object5.put("evaluate",array5);
        object5.put("total",array5.size());
        object.put("label",labelSet);
        object.put("totalScore",totalScore);
        object.put("1",totalScore1);//1、服务效率,
        object.put("2",totalScore2);// 2、服务态度,
        object.put("3",totalScore3);// 3、专业程度
        object.put("4",object2);//全部
        object.put("5",object3);//好评
        object.put("6",object4);//中评
        object.put("7",object5);//差评
        envelop.setObj(object);
        return envelop;
    }
}

+ 417 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistHospitalServiceItemService.java

@ -0,0 +1,417 @@
package com.yihu.jw.hospital.module.specialist.service;/**
 * Created by nature of king on 2018/8/28.
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.SpecialistServiceItemDO;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistHospitalServiceItemDao;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistServiceItemDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.common.DataUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
 * @author wangzhinan
 * @create 2018-08-28 19:57
 * @desc 机构服务项目
 **/
@Service
@Transactional
public class SpecialistHospitalServiceItemService extends EnvelopRestEndpoint {
    @Autowired
    private SpecialistHospitalServiceItemDao specialistHospitalServiceItemDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SpecialistServiceItemDao specialistServiceItemDao;
    /**
     * 添加机构服务项目
     *
     * @param hospitalServiceItemDOS
     * @return
     */
    public MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> insert(List<HospitalServiceItemDO> hospitalServiceItemDOS){
        MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> envelop = new MixEnvelop<>();
        if (hospitalServiceItemDOS !=null && hospitalServiceItemDOS.size()!=0){
            for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS){
                hospitalServiceItemDO.setCreateTime(new Date());
                hospitalServiceItemDO.setUpdateTime(new Date());
                specialistHospitalServiceItemDao.save(hospitalServiceItemDO);
            }
        }
        envelop.setDetailModelList(hospitalServiceItemDOS);
        return envelop;
    }
    /**
     * 根据医院code查找数据
     *
     * @param hospitals
     * @return
     */
    public MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> selectByHospital(List<String> hospitals){
        MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> envelop = new MixEnvelop<>();
        StringBuffer buffer = new StringBuffer();
        if (hospitals!=null && hospitals.size()!=0){
            buffer.append(" and hospital in (");
            for (int i =0 ;i<hospitals.size();i++){
                buffer.append("'"+hospitals.get(i)+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            buffer.append(")");
        }else{
            buffer.append("");
        }
        String sql = "select * from wlyy_hospital_service_item where 1=1 "+buffer;
        List<HospitalServiceItemDO> hospitalServiceItemDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
        for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS){
            SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDao.findById(hospitalServiceItemDO.getServiceItemId()).orElse(null);
            hospitalServiceItemDO.setSpecialistServiceItemDO(specialistServiceItemDO);
        }
        envelop.setDetailModelList(hospitalServiceItemDOS);
        return envelop;
    }
    /**
     *
     * @param hospital
     * @param docHospital
     * @param serviceItemName
     * @return
     */
    public MixEnvelop<JSONArray,JSONArray> selectByHospital1(String hospital, String docHospital, String serviceItemName){
        MixEnvelop<JSONArray,JSONArray> envelop = new MixEnvelop<>();
        String sqlUtil = "";
        if (StringUtils.isNoneBlank(serviceItemName)||serviceItemName != null){
            sqlUtil=" AND service_item_id IN ( SELECT id FROM wlyy_service_item WHERE 1=1 and title LIKE '%"+serviceItemName+"%')";
        }
        List<HospitalServiceItemDO> hospitalServiceItemDOS1 = new ArrayList<>();
        if (StringUtils.isNoneBlank(hospital)&&hospital.equals(docHospital)){
            String sql1 = "select * from wlyy_hospital_service_item where 1=1 AND status = 1 AND imediate=1 AND hospital = '"+docHospital+"'"+sqlUtil;
            List<HospitalServiceItemDO> hospitalServiceItemDOList = jdbcTemplate.query(sql1,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
            for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOList){
                hospitalServiceItemDO.setFlag(3);
                hospitalServiceItemDOS1.add(hospitalServiceItemDO);
            }
        }else if (hospital == null || hospital == ""){
            String sql1 = "select * from wlyy_hospital_service_item where 1=1 AND status = 1 AND imediate=1 AND hospital = '"+docHospital+"'"+sqlUtil;
            List<HospitalServiceItemDO> hospitalServiceItemDOList = jdbcTemplate.query(sql1,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
            for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOList){
                hospitalServiceItemDO.setFlag(2);
                hospitalServiceItemDOS1.add(hospitalServiceItemDO);
            }
        }else{
            String sql = "select * from wlyy_hospital_service_item where 1=1 AND status = 1 AND imediate=1 AND hospital = '"+hospital+"' "+sqlUtil;
            List<HospitalServiceItemDO> hospitalServiceItemDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
            String sql1 = "select * from wlyy_hospital_service_item where 1=1 AND status = 1 AND imediate=1 AND hospital = '"+docHospital+"' "+sqlUtil;
            List<HospitalServiceItemDO> hospitalServiceItemDOList = jdbcTemplate.query(sql1,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
            if (hospitalServiceItemDOList != null && hospitalServiceItemDOList.size()!=0){
                for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOList){
                    boolean flag = false;
                    for (HospitalServiceItemDO hospitalServiceItemDO1 :hospitalServiceItemDOS){
                        boolean isTrue = false;
                        if (hospitalServiceItemDOS1 != null && hospitalServiceItemDOS1.size() != 0){
                            for (HospitalServiceItemDO hospitalServiceItemDO2:hospitalServiceItemDOS1){
                                if (hospitalServiceItemDO1.getServiceItemId().equals(hospitalServiceItemDO2.getServiceItemId())){
                                    if (hospitalServiceItemDO.getServiceItemId().equals(hospitalServiceItemDO1.getServiceItemId())){
                                        hospitalServiceItemDO2.setFlag(3);
                                    }
                                    isTrue = true;
                                }
                            }
                        }
                        if (hospitalServiceItemDO.getServiceItemId().equals(hospitalServiceItemDO1.getServiceItemId())){
                            if (isTrue==false){
                                hospitalServiceItemDO1.setFlag(3);
                                hospitalServiceItemDOS1.add(hospitalServiceItemDO1);
                                flag = true;
                            }
                        }else{
                            if (isTrue == false){
                                hospitalServiceItemDO1.setFlag(1);
                                hospitalServiceItemDOS1.add(hospitalServiceItemDO1);
                            }
                        }
                    }
                    if (flag==false){
                        boolean isTrue1 = false;
                        if (hospitalServiceItemDOS1 != null && hospitalServiceItemDOS1.size() != 0){
                            for (HospitalServiceItemDO hospitalServiceItemDO2:hospitalServiceItemDOS1){
                                if (hospitalServiceItemDO.getServiceItemId().equals(hospitalServiceItemDO2.getServiceItemId())){
                                    isTrue1 = true;
                                }
                            }
                        }
                        if (isTrue1 == false){
                            hospitalServiceItemDO.setFlag(2);
                            hospitalServiceItemDOS1.add(hospitalServiceItemDO);
                        }
                    }
                }
            }else {
                String sql3 = "select * from wlyy_hospital_service_item where 1=1 AND status = 1 AND imediate=1 AND hospital = '"+hospital+"'"+sqlUtil;
                List<HospitalServiceItemDO> hospitalServiceItemDOList1 = jdbcTemplate.query(sql3,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
                for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOList1){
                    hospitalServiceItemDO.setFlag(1);
                    hospitalServiceItemDOS1.add(hospitalServiceItemDO);
                }
            }
        }
        for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS1){
            SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDao.findById(hospitalServiceItemDO.getServiceItemId()).orElse(null);
            hospitalServiceItemDO.setSpecialistServiceItemDO(specialistServiceItemDO);
        }
        JSONArray array = new JSONArray();
        List<Integer> itemType = new ArrayList<>();
        for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS1){
            SpecialistServiceItemDO specialistServiceItemDO = hospitalServiceItemDO.getSpecialistServiceItemDO();
            if (itemType != null && itemType.size() != 0){
                for (int i=0;i<itemType.size();i++){
                    if (!itemType.contains(specialistServiceItemDO.getItemType())){
                        itemType.add(specialistServiceItemDO.getItemType());
                    }
                }
            }else {
                itemType.add(specialistServiceItemDO.getItemType());
            }
        }
        for (int i =0;i<itemType.size();i++){
            JSONObject object = new JSONObject();
            List<String> type = new ArrayList<>();
            for (int j = 0;j<hospitalServiceItemDOS1.size();j++){
                SpecialistServiceItemDO specialistServiceItemDO = hospitalServiceItemDOS1.get(j).getSpecialistServiceItemDO();
                if (itemType.get(i).equals(specialistServiceItemDO.getItemType())&& !type.contains(specialistServiceItemDO.getDiseaseItem())){
            type.add(specialistServiceItemDO.getDiseaseItem());
                }
            }
        JSONArray itemArray = new JSONArray();
        List<String> serviceItems = new ArrayList<>();
        if (type != null && type.size() != 0){
                for (int z =0 ;z<type.size();z++){
                    List<HospitalServiceItemDO> hospitalServiceItemDOS2 = new ArrayList<>();
                    JSONObject object1 =new JSONObject();
                    for (int j = 0;j<hospitalServiceItemDOS1.size();j++){
                        SpecialistServiceItemDO specialistServiceItemDO = hospitalServiceItemDOS1.get(j).getSpecialistServiceItemDO();
                        if (itemType.get(i).equals(specialistServiceItemDO.getItemType())){
                            if (type.get(z).equals(specialistServiceItemDO.getDiseaseItem())) {
                                hospitalServiceItemDOS2.add(hospitalServiceItemDOS1.get(j));
                            }
                        }
                    }
                    if (serviceItems!=null && serviceItems.size()!=0){
                        if (!serviceItems.contains(type.get(z))){
                            serviceItems.add(type.get(z));
                            object1.put("itemName",type.get(z));
                            object1.put("hospitalServiceItems",hospitalServiceItemDOS2);
                            itemArray.add(object1);
                        }else {
                            object1.put("itemName",type.get(z));
                            object1.put("hospitalServiceItems",hospitalServiceItemDOS2);
                            itemArray.add(object1);
                        }
                    }else {
                        serviceItems.add(type.get(z));
                        object1.put("itemName",type.get(z));
                        object1.put("hospitalServiceItems",hospitalServiceItemDOS2);
                        itemArray.add(object1);
                    }
                }
        }
        if (itemArray !=null && itemArray.size()!=0){
            JSONArray jsonArray = new JSONArray();
            for (int j = 0;j<itemArray.size();j++){
                JSONObject object1 = itemArray.getJSONObject(j);
                JSONObject jsonObject1 = new JSONObject();
                JSONArray array1 = object1.getJSONArray("hospitalServiceItems");
                JSONArray array2 = new JSONArray();
                for (int k=0;k<array1.size();k++){
                    JSONObject jsonObject = array1.getJSONObject(k);
                    jsonObject.replace("expense", DataUtils.integerTransferDouble(jsonObject.getInteger("expense")));
                    array2.add(jsonObject);
                }
                jsonObject1.put("itemName",object1.getString("itemName"));
                jsonObject1.put("hospitalServiceItems",array2);
                jsonArray.add(jsonObject1);
            }
            object.put("item",jsonArray);
        }else {
            object.put("item",itemArray);
        }
        object.put("itemType",itemType.get(i));
        array.add(object);
    }
    List<JSONArray> list = new ArrayList<>();
    list.add(array);
    envelop.setDetailModelList(list);
    return envelop;
    }
    /**
     * 根据id获取服务项目
     *
     * @param hospitalServiceItems
     * @return
     */
    public MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> selectById(List<String> hospitalServiceItems){
        MixEnvelop<HospitalServiceItemDO, HospitalServiceItemDO> envelop = new MixEnvelop<>();
        StringBuffer buffer = new StringBuffer();
        if(hospitalServiceItems != null && hospitalServiceItems.size()!=0){
            buffer.append(" and id in (");
            for (int i =0 ;i<hospitalServiceItems.size();i++){
                buffer.append("'"+hospitalServiceItems.get(i)+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            buffer.append(")");
        }
        String sql = "select * from wlyy_hospital_service_item where 1=1 "+buffer;
        List<HospitalServiceItemDO> hospitalServiceItemDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
        for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS){
            SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDao.findById(hospitalServiceItemDO.getServiceItemId()).orElse(null);
            hospitalServiceItemDO.setSpecialistServiceItemDO(specialistServiceItemDO);
        }
        envelop.setDetailModelList(hospitalServiceItemDOS);
        return envelop;
    }
    /**
     * 按条件查询机构服务项目
     *
     * @param serviceItemName 服务项目名称
     *
     * @param hospitals 医院code集合
     * @return
     */
    public MixEnvelop<JSONArray,JSONArray> selectByCondition(String serviceItemName, List<String> hospitals){
        MixEnvelop<JSONArray,JSONArray> envelop = new MixEnvelop<>();
        /*if (StringUtils.isNoneBlank(serviceItemName)||serviceItemName != null){
            String sql = "select * from wlyy_hospital_service_item where service_item_name = '"+serviceItemName+"' and status=1";
            List<HospitalServiceItemDO> hospitalServiceItemDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
            for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS){
                SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDao.findOne(hospitalServiceItemDO.getServiceItemId());
                hospitalServiceItemDO.setSpecialistServiceItemDO(specialistServiceItemDO);
            }
            JSONArray array = new JSONArray();
            for (int i =0 ;i<hospitalServiceItemDOS.size();i++){
                SpecialistServiceItemDO specialistServiceItemDO = hospitalServiceItemDOS.get(i).getSpecialistServiceItemDO();
                JSONObject object = new JSONObject();
                object.put("itemName",specialistServiceItemDO.getItemType());
                object.put("hospitalServiceItem",hospitalServiceItemDOS.get(i));
                array.add(object);
            }
            List<JSONArray> list = new ArrayList<>();
            list.add(array);
            envelop.setDetailModelList(list);
        }else {*/
        StringBuffer buffer = new StringBuffer();
        if(hospitals != null && hospitals.size()!=0){
            buffer.append(" and hospital in (");
            for (int i =0 ;i<hospitals.size();i++){
                buffer.append("'"+hospitals.get(i)+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            buffer.append(")");
        }
        String sql = "select * from wlyy_hospital_service_item where 1=1 AND status = 1"+buffer;
        List<HospitalServiceItemDO> hospitalServiceItemDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(HospitalServiceItemDO.class));
        for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS){
            SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDao.findById(hospitalServiceItemDO.getServiceItemId()).orElse(null);
            hospitalServiceItemDO.setSpecialistServiceItemDO(specialistServiceItemDO);
        }
        JSONArray array = new JSONArray();
        for (int i =0 ;i<hospitalServiceItemDOS.size();i++){
            SpecialistServiceItemDO specialistServiceItemDO = hospitalServiceItemDOS.get(i).getSpecialistServiceItemDO();
            JSONObject object = new JSONObject();
            object.put("itemName",specialistServiceItemDO.getItemType());
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hospitalServiceItemDOS.get(i));
            jsonObject.replace("expense", DataUtils.integerTransferDouble(hospitalServiceItemDOS.get(i).getExpense()));
            JSONObject object1 = jsonObject.getJSONObject("specialistServiceItemDO");
            object1.replace("threeHospitals", DataUtils.integerTransferDouble(hospitalServiceItemDOS.get(i).getSpecialistServiceItemDO().getThreeHospitals()));
            object1.replace("twoHospitals",DataUtils.integerTransferDouble(hospitalServiceItemDOS.get(i).getSpecialistServiceItemDO().getTwoHospitals()));
            object1.replace("oneHospitals",DataUtils.integerTransferDouble(hospitalServiceItemDOS.get(i).getSpecialistServiceItemDO().getOneHospitals()));
            object.put("hospitalServiceItem",jsonObject);
            array.add(object);
        }
        List<JSONArray> list = new ArrayList<>();
        list.add(array);
        envelop.setDetailModelList(list);
        return envelop;
    }
    /**
     * 删除机构服务项目
     *
     * @param hospital 医院code
     *
     * @param serviceItemId 服务项目id
     * @return
     */
    public MixEnvelop<Boolean,Boolean> delete(String hospital, String serviceItemId, String id){
        MixEnvelop<Boolean,Boolean> envelop = new MixEnvelop<>();
        if (StringUtils.isNoneBlank(hospital)){
            String sql = "update wlyy_hospital_service_item set status = 0 where hospital = '"+hospital+"'";
            jdbcTemplate.update(sql);
        }else if (StringUtils.isNoneBlank(serviceItemId)){
            String sql = "update wlyy_hospital_service_item set status = 0 where service_item_id = '"+serviceItemId+"'";
            jdbcTemplate.update(sql);
        }else if (StringUtils.isNoneBlank(id)){
            String sql = "update wlyy_hospital_service_item set status = 0 where id = '"+id+"'";
            jdbcTemplate.update(sql);
        }
        return envelop;
    }
    /**
     * 机构服务项目数据添加
     *
     * @param hospitalServiceItemDOS
     * @return
     */
    public MixEnvelop<Boolean,Boolean> importData(List<HospitalServiceItemDO> hospitalServiceItemDOS) {
        MixEnvelop<Boolean,Boolean> envelop = new MixEnvelop<>();
        if (hospitalServiceItemDOS != null && hospitalServiceItemDOS.size()!=0){
            for (HospitalServiceItemDO hospitalServiceItemDO:hospitalServiceItemDOS){
                List<SpecialistServiceItemDO> specialistServiceItemDOS = specialistServiceItemDao.findByTitleAndContent(hospitalServiceItemDO.getTitle(),hospitalServiceItemDO.getContent());
                if (specialistServiceItemDOS != null && specialistServiceItemDOS.size()!=0){
                    List<HospitalServiceItemDO> hospitalServiceItemDOList = specialistHospitalServiceItemDao.findByHospitalAndServiceItemId(hospitalServiceItemDO.getHospital(),specialistServiceItemDOS.get(0).getId());
                    if (hospitalServiceItemDOList != null && hospitalServiceItemDOList.size() !=0){
                        continue;
                    }else {
                        hospitalServiceItemDO.setStatus(1);
                        hospitalServiceItemDO.setImediate(0);
                        hospitalServiceItemDO.setSaasId("dev");
                        hospitalServiceItemDO.setId(UUID.randomUUID().toString());
                        hospitalServiceItemDO.setServiceItemId(specialistServiceItemDOS.get(0).getId());
                        hospitalServiceItemDO.setServiceItemName(specialistServiceItemDOS.get(0).getDiseaseItem());
                        hospitalServiceItemDO.setCreateTime(new Date());
                        hospitalServiceItemDO.setUpdateTime(new Date());
                        specialistHospitalServiceItemDao.save(hospitalServiceItemDO);
                    }
                }
            }
        }
        envelop.setObj(true);
        return envelop;
    }
}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 263 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistScreenResultService.java


+ 1450 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistService.java

@ -0,0 +1,1450 @@
package com.yihu.jw.hospital.module.specialist.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanLogDO;
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.hospital.module.rehabilitation.dao.*;
import com.yihu.jw.hospital.module.specialist.dao.*;
import com.yihu.jw.restmodel.specialist.*;
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.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
/**
 * Created by Trick on 2018/4/25.
 */
@Service
@Transactional
public class SpecialistService{
    @Autowired
    private SpecialistPatientRelationDao specialistPatientRelationDao;
    @Autowired
    private PatientHospitalRecordDao patientHospitalRecordDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${basedb.name}")
    private String basedb;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PatientRehabilitationPlanDao patientRehabilitationPlanDao;
    @Autowired
    private RehabilitationDetailDao rehabilitationDetailDao;
    @Autowired
    private RehabilitationDetailAppointmentDao rehabilitationDetailAppointmentDao;
    @Autowired
    private PatientRehabilitationPlanLogDao patientRehabilitationPlanLogDao;
    @Autowired
    private RehabilitationOperateRecordsDao rehabilitationOperateRecordsDao;
    public MixEnvelop<Boolean, Boolean> createSpecialistsPatientRelation(SpecialistPatientRelationDO specialistPatientRelationDO){
        specialistPatientRelationDao.save(specialistPatientRelationDO);
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    public MixEnvelop<SpecialistPatientRelationVO, SpecialistPatientRelationVO> findSpecialistPatientRelation(String doctor, Integer page, Integer size)throws ParseException {
        String sql = "SELECT " +
                " r.id, " +
                " r.doctor ,r.doctor_name AS doctor_name " +
                " ,r.saas_id AS sassId, " +
                " r.patient ,r.patient_name AS patient_name" +
                " ,r.health_doctor AS healthDoctor ,r.health_doctor_name AS healthDoctorName" +
                " ,r.sign_code AS signCode, " +
                " r.sign_year AS signYear, " +
                " r.sign_doctor AS sign_doctor ,r.sign_doctor_name AS signDoctorName" +
                " ,r.create_time AS createTime," +
                " r.status " +
                "FROM " +
                " wlyy_specialist_patient_relation r " +
                "WHERE " +
                " r.doctor = '"+doctor+"' AND r.status >=0  AND r.sign_status >0 ORDER BY r.create_time DESC LIMIT "+(page-1)*size+","+size;
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.doctor_name","r.patient_name","r.health_doctor_name","r.sign_doctor_name");
        List<SpecialistPatientRelationVO> specialistPatientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SpecialistPatientRelationVO.class));
        String sqlcount = "SELECT count(1) AS total " +
                "FROM " +
                " wlyy_specialist_patient_relation r " +
                "WHERE " +
                " r.doctor = '"+doctor+"'  AND r.status >=0  AND r.sign_status >0 ;";
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sqlcount);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success,specialistPatientRelationVOs,page,size,count);
    }
    public MixEnvelop<Long, Long> findSpecialistPatientRelationCout(String doctor){
        String sql = "SELECT " +
                " count(1) AS total " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " WHERE " +
                " r.doctor ='"+doctor+"'" +
                " AND r.patient " +
                " NOT IN ( " +
                " SELECT " +
                " patient " +
                " FROM " +
                " "+basedb+".wlyy_sign_patient_label_info i " +
                " WHERE " +
                " i.label_type = '7' AND " +
                " i.status = 1" +
                " )" +
                " AND r. STATUS >= 0 " +
                " AND r.sign_status > 0";
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,count);
    }
    public MixEnvelop<PatientRelationVO, PatientRelationVO> findNoLabelPatientRelation(String doctor){
        String sql ="SELECT " +
                " r.patient ,r.patient_name as patientName" +
                " ,IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.photo, " +
                " rd.create_time AS createTime ," +
                " p.sex " +
                " FROM " +
                " wlyy_specialist_patient_relation r JOIN "+basedb+".wlyy_patient p ON p.code = r.patient  " +
                " LEFT JOIN wlyy_patient_hospital_record rd ON r.discharge_record = rd.id " +
                " WHERE " +
                " r.doctor = '"+doctor+"' AND r.status >=0  AND r.sign_status >0" +
                " AND r.patient " +
                " NOT IN ( " +
                "  SELECT " +
                "   i.patient " +
                "  FROM " +
                "   "+basedb+".wlyy_sign_patient_label_info i " +
                "  WHERE " +
                "   i.label_type = '7' AND " +
                "   i.status = 1 " +
                " )";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<PatientRelationVO> patientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientRelationVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientRelationVOs);
    }
    public MixEnvelop<Boolean, Boolean> saveHealthAssistant(List<SpecialistPatientRelationDO> specialistPatientRelationDOs){
        for(SpecialistPatientRelationDO r : specialistPatientRelationDOs){
            SpecialistPatientRelationDO relationDO = specialistPatientRelationDao.findByDoctorAndPatient(r.getDoctor(),r.getPatient());
            if(relationDO!=null){
                relationDO.setHealthAssistant(r.getHealthAssistant());
                relationDO.setHealthAssistantName(r.getHealthAssistantName());
                specialistPatientRelationDao.save(relationDO);
            }
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    public MixEnvelop<PatientRelationVO, PatientRelationVO> findPatientRelatioByAssistant(String doctor , String assistant, Integer page, Integer size){
        String sql ="SELECT " +
                " r.patient ,r.patient_name as patientName" +
                " ,IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.photo ," +
                " p.sex," +
                " h.label_name as health, " +
                " h.label AS healthcode " +
                " FROM " +
                " wlyy_specialist_patient_relation r JOIN "+basedb+".wlyy_patient p ON p.`code` = r.patient " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  t.label, " +
                "  t.label_name, " +
                "  t.patient " +
                " FROM " +
                "  "+basedb+".wlyy_sign_patient_label_info t " +
                " WHERE " +
                "  t.label_type = '8' " +
                " AND t.`status` = '1' " +
                " ) h ON h.patient = r.patient " +
                " WHERE " +
                "  r.doctor = '"+doctor+"' AND r.status >=0  AND r.sign_status >0 "+
                " AND r.health_assistant = '"+assistant+"' LIMIT "+(page-1)*size+","+size;
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<PatientRelationVO> patientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientRelationVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientRelationVOs);
    }
    public MixEnvelop<PatientLabelVO, PatientLabelVO> getPatientByLabel(String doctor, String labelType, String teamCode, String labelCode, Integer page, Integer size, String shareDoctor){
        String sql="SELECT " +
                " p. CODE ,s.patient_name as name," +
                " p.sex," +
                " IFNULL( " +
                "  YEAR ( " +
                "   from_days(datediff(now(), p.birthday)) " +
                "  ), " +
                "  '未知' " +
                " ) age, " +
                " lb.labelName, " +
                " lb.labelType, " +
                " lb.label, " +
                " p.photo, " +
                " lb.labelName as health, " +
                " lb.label AS healthcode ," +
                " s.health_assistant AS healthAssistant,s.health_assistant_name as healthAssistantName " +
//                " s.health_assistant_name AS healthAssistantName," +
                " ,s.is_manage AS isManage," +
                " s.id AS specialCode" +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   i.label_type AS labelType, " +
                "   i.label, " +
                "   i.label_name AS labelName, " +
                "   i.patient " +
                "  FROM " +
                "   "+basedb+".wlyy_sign_patient_label_info i " +
                "  WHERE " +
                "   i.label = '"+labelCode+"' " +
                "  AND i.label_type = '"+labelType+"' " +
                "  AND i.`status` = '1' " +
                " ) lb " +
                " JOIN "+basedb+".wlyy_patient p ON p. CODE = lb.patient " +
                " JOIN wlyy_specialist_patient_relation s ON s.patient = lb.patient ";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"s.patient_name","s.health_assistant_name");
        if(StringUtils.isNotBlank(shareDoctor)){
            sql = sql + " JOIN "+basedb+".wlyy_doctor_special_share sp ON s.id = sp.special_code and sp.doctor = '"+shareDoctor+"' ";
        }
        sql = sql +" WHERE s.team_code ='" +teamCode+"' "+
                " AND s.status >=0  AND s.sign_status >0"+
                " LIMIT "+(page-1)*size+","+size;
        System.out.print("日志:"+sql);
        if("7".equals(labelType)){
            sql = "SELECT " +
                    "c.CODE,a.patient_name as name" +
//                    "c.NAME," +
                    ",c.sex," +
                    "IFNULL(YEAR (from_days(datediff(now(),c.birthday))),'未知') age," +
                    "c.photo,b.disease AS label," +
                    "b.disease_name AS labelName," +
                    "d.label_name AS health," +
                    "d.label AS healthcode," +
                    "a.health_assistant AS healthAssistant,a.health_assistant_name AS healthAssistantName," +
//                    "a.health_assistant_name AS healthAssistantName, " +
                    " a.is_manage AS isManage, " +
                    "a.id AS specialCode " +
                    "FROM wlyy_specialist.wlyy_specialist_patient_relation a " +
                    "JOIN "+basedb+".wlyy_patient_disease_server b ON a.id=b.specialist_relation_code AND b.disease=" +labelCode+" and b.del=1 "+
                    "JOIN "+basedb+".wlyy_patient c ON a.patient=c.CODE ";
            if(StringUtils.isNotBlank(shareDoctor)){
                sql = sql + " JOIN "+basedb+".wlyy_doctor_special_share sp ON a.id = sp.special_code and sp.doctor = '"+shareDoctor+"' ";
            }
            sql = sql +"LEFT JOIN "+basedb+".wlyy_sign_patient_label_info d ON a.patient=d.patient AND d.label_type=8 AND d.`status`=1" +
                    " WHERE a.sign_status> 0 AND a.`status`>=0 " +
//                    "AND a.doctor='"+doctor+"' OR a.health_assistant= '"+doctor+
                    " AND a.team_code ='" +teamCode+"' "+
                    " LIMIT "+(page-1)*size+","+size;
            sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"a.patient_name","a.health_assistant_name");
        }
        
        if("pending".equals(labelType)){
            sql = "SELECT " +
                    "c.CODE, a.patient_name as name" +
//                    "c.NAME," +
                    ",c.sex," +
                    "IFNULL(YEAR (from_days(datediff(now(),c.birthday))),'未知') age," +
                    "c.photo," +
                    "a.health_assistant AS healthAssistant,a.health_assistant_name as healthAssistantName" +
//                    "a.health_assistant_name AS healthAssistantName, " +
                    ",a.is_manage AS isManage " +
                    "FROM wlyy_specialist.wlyy_specialist_patient_relation a " +
                    "JOIN "+basedb+".wlyy_patient c ON a.patient=c.CODE " +
                    " WHERE a.sign_status> 0 AND a.`status`>=0 AND (a.is_manage = 0 or a.is_manage is null)" +
                    " AND a.team_code ='" +teamCode+"' "+
                    " LIMIT "+(page-1)*size+","+size;
            sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"a.patient_name","a.health_assistant_name");
        }
        List<PatientLabelVO> PatientLabelVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientLabelVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,PatientLabelVOs);
    }
    public MixEnvelop<Long, Long> getLabelpatientCount(String doctor, String labelType, String label, Long teamCode, String shareDoctor){
        String sql = "SELECT " +
                " COUNT(1) as total " +
                " FROM " +
                "   "+basedb+".wlyy_sign_patient_label_info i " +
                "  WHERE " +
                "   i.label = '"+label+"' "+
                "  AND i.label_type = '"+labelType+"' " +
                "  AND i.`status` = '1' " +
                " AND i.patient in ( " +
                " SELECT " +
                " a.patient AS patient " +
                " FROM " +
                " wlyy_specialist_patient_relation a ";
        if(StringUtils.isNotBlank(shareDoctor)){
            sql = sql + " JOIN wlyy.wlyy_doctor_special_share b ON b.special_code = a.id AND b.doctor = '"+shareDoctor+"' ";
        }
        sql = sql+" WHERE " +
                " a.team_code = '"+teamCode+"' " +
                " AND a.STATUS >= 0 " +
                " AND a.sign_status > 0)";
        System.out.print("日志:"+sql);
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,count);
    }
    public MixEnvelop<Long, Long> getAssistantPatientCount(String doctor, String assistant){
        String sql = "SELECT COUNT(1) AS total FROM wlyy_specialist_patient_relation r WHERE r.doctor ='"+doctor+"'  AND r.health_assistant = '"+assistant+"' AND r.status >=0  AND r.sign_status >0";
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,count);
    }
    public MixEnvelop<PatientRelationVO, PatientRelationVO> getDoctorPatientByName(String doctor, String nameKey, String teamCode, Integer page, Integer size){
        String sql ="SELECT " +
                " p.code AS patient,r.patient_name as patientName  " +
//                " p.`name` AS patientName, " +
                " ,p.photo, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.sex ," +
                " h.label_name as health, " +
                " h.label AS healthcode " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_patient p ON r.patient = p.`code` " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  t.label, " +
                "  t.label_name, " +
                "  t.patient " +
                " FROM " +
                "  "+basedb+".wlyy_sign_patient_label_info t ";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        String tmpSql = " WHERE " +
                "  t.label_type = '8' " +
                " AND t.`status` = '1' " +
                " ) h ON h.patient = r.patient " +
                " WHERE " +
                " r.doctor IN ( SELECT m.doctor_code FROM wlyy.wlyy_admin_team_member m WHERE m.team_id ='" +teamCode+
                "' ) " +
                " AND r.status >=0  AND r.sign_status >0 " +
                " AND " + "r.patient_name" + " LIKE '%"+nameKey+"%' "+
                " LIMIT "+(page-1)*size+","+size;
        tmpSql = TransforSqlUtl.wlyySpecialistPatientRelationLike(tmpSql,"r.patient_name");
        sql = sql+tmpSql;
        List<PatientRelationVO> patientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientRelationVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientRelationVOs);
    }
    public MixEnvelop<PatientRelationVO, PatientRelationVO> getDoctorPatientByNameOrIdCard(String doctor, String filter, String teamCode, Integer page, Integer size){
        String sql ="SELECT " +
                " p.code AS code,p.code patient,r.patient_name as patientName, " +
                " p.name AS name " +
                " ,p.photo, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.sex ," +
                " p.idcard ," +
                " h.label_name as health, " +
                " h.label AS healthcode " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_patient p ON r.patient = p.`code` " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  t.label, " +
                "  t.label_name, " +
                "  t.patient " +
                " FROM " +
                "  "+basedb+".wlyy_sign_patient_label_info t " ;
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        String sqlTmp=  " WHERE " +
                "  t.label_type = '8' " +
                " AND t.`status` = '1' " +
                " ) h ON h.patient = r.patient " +
                " WHERE " +
                " r.doctor IN ( SELECT m.doctor_code FROM wlyy.wlyy_admin_team_member m WHERE m.team_id ='" +teamCode+
                "' ) " +
                " AND r.status >=0  AND r.sign_status >0 " +
                " AND (" +  "r.patient_name"  + " LIKE '%"+filter+"%' OR p.idcard LIKE '%"+filter+"%') "+
                " LIMIT "+(page-1)*size+","+size;
        sqlTmp = TransforSqlUtl.wlyySpecialistPatientRelationLike(sqlTmp,"r.patient_name");
        sql = sql+sqlTmp;
        List<PatientRelationVO> patientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientRelationVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientRelationVOs);
    }
    public MixEnvelop<PatientRelationVO, PatientRelationVO> findPatientNoAssistant(String doctor, Integer page, Integer size){
        String sqlTotal ="SELECT " +
                " COUNT(1) AS total" +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_patient p ON r.patient = p.`code` " +
                " JOIN ( " +
                " SELECT " +
                "  t.label, " +
                "  t.label_name, " +
                "  t.patient " +
                " FROM " +
                "  "+basedb+".wlyy_sign_patient_label_info t " +
                " WHERE " +
                "  t.label_type = '8' " +
                " AND t.`status` = '1' " +
                " ) h ON h.patient = r.patient " +
                " WHERE " +
                " r.doctor='"+doctor+"' " +
                " AND r.status >=0  AND r.sign_status >0" +
                " AND r.health_assistant IS NULL ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sqlTotal);
        Long total = 0L;
        if(list!=null&&list.size()>0){
            total =  (Long) list.get(0).get("total");
        }
        String sql ="SELECT " +
                " p.code AS patient ,r.patient_name as patientName" +
                //AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " p.`name` AS patientName, " +
                " ,p.photo, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.sex, " +
                " h.label_name as health, " +
                " h.label AS healthcode " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_patient p ON r.patient = p.`code` " +
                " JOIN ( " +
                " SELECT " +
                "  t.label, " +
                "  t.label_name, " +
                "  t.patient " +
                " FROM " +
                "  "+basedb+".wlyy_sign_patient_label_info t " +
                " WHERE " +
                "  t.label_type = '8' " +
                " AND t.`status` = '1' " +
                " ) h ON h.patient = r.patient " +
                " WHERE " +
                " r.doctor='"+doctor+"' " +
                " AND r.status >=0  AND r.sign_status >0 " +
                " AND r.health_assistant IS NULL "+
                " LIMIT "+(page-1)*size+","+size;
        sql  = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<PatientRelationVO> patientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientRelationVO.class));
        return MixEnvelop.getSuccessList(SpecialistMapping.api_success,patientRelationVOs,total.intValue());
    }
    public MixEnvelop<SpecialistTeamVO, SpecialistTeamVO> signSpecialistTeam(String patient, String patientName, String doctor, String doctorName, Long teamCode){
        //1.查询该居民是否已经与该专科医生签约
        String checkDoctorSql = "SELECT " +
                " r.id AS relationCode," +
                " r.patient ,r.patient_name as patientName " +
                //AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " r.patient_name AS patientName, " +
                " ,r.team_code AS teamCode, " +
                " t.`name`, " +
                " d.photo ," +
                " d.code AS doctor, r.doctor_name as doctorName" +
               // AesEncryptUtils.decryptMysql("r.doctor_name","doctorName") +
//                " d.name AS doctorName" +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_admin_team t ON t.id = r.team_code " +
                " JOIN "+basedb+".wlyy_doctor d ON d. CODE = r.doctor " +
                " WHERE " +
                " r.patient = '"+patient+"' " +
                " AND r.doctor = '"+doctor+"' " +
                " AND r.`status` >= 0 " +
                " AND r.sign_status >=0 " +
                " AND t.available = '1' ";
        checkDoctorSql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(checkDoctorSql,"r.patient_name","r.doctor_name");
        List<SpecialistTeamVO> specialistTeamVOs = jdbcTemplate.query(checkDoctorSql,new BeanPropertyRowMapper(SpecialistTeamVO.class));
        if(specialistTeamVOs!=null&&specialistTeamVOs.size()>0){
            for(SpecialistTeamVO specialistTeamVO:specialistTeamVOs){
                List<AdminTeamMemberVO> adminTeamMemberVOs = findTeamMember(specialistTeamVO.getTeamCode());
                specialistTeamVO.setMembers(adminTeamMemberVOs);
            }
            return MixEnvelop.getSuccess(SpecialistMapping.doctor_exist,specialistTeamVOs.get(0));
        }
        //验证团队是否已经签约
        String checkTeamSql = "SELECT " +
                " r.id AS relationCode," +
                " r.patient ,r.patient_name as patientName" +
//                " r.patient_name AS patientName, " +
                " ,r.team_code AS teamCode, " +
                " t.`name`, " +
                " d.photo " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_admin_team t ON t.id = r.team_code " +
                " JOIN "+basedb+".wlyy_doctor d ON d. CODE = r.doctor " +
                " WHERE " +
                " r.patient = '"+patient+"' " +
                " AND r.team_code = " +teamCode+
                " AND r.`status` >=0 " +
                " AND r.sign_status >=0 " +
                " AND t.available = '1' ";
        checkTeamSql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(checkTeamSql,"r.patient_name");
        List<SpecialistTeamVO> teamVOs = jdbcTemplate.query(checkTeamSql,new BeanPropertyRowMapper(SpecialistTeamVO.class));
        if(teamVOs!=null&&teamVOs.size()>0){
            for(SpecialistTeamVO specialistTeamVO:teamVOs){
                List<AdminTeamMemberVO> adminTeamMemberVOs = findTeamMember(specialistTeamVO.getTeamCode());
                specialistTeamVO.setMembers(adminTeamMemberVOs);
            }
            return MixEnvelop.getSuccess(SpecialistMapping.team_exist,teamVOs.get(0));
        }
        //存储签约关系
        SpecialistPatientRelationDO relation = new SpecialistPatientRelationDO();
        relation.setDoctor(doctor);
        relation.setDoctorName(doctorName);
        relation.setPatient(patient);
        relation.setPatientName(patientName);
        relation.setTeamCode(teamCode.intValue());
        relation.setStatus("0");
        relation.setSignStatus("0");
        relation.setUpdateTime(new Date());
        relation.setCreateTime(new Date());
        relation.setUpdateTime(new Date());
        SpecialistPatientRelationDO relationDO = specialistPatientRelationDao.save(relation);
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,relationDO.getId());
    }
    public List<AdminTeamMemberVO> findTeamMember(Long teamId){
        String menberSql = "SELECT " +
                " m.doctor_code AS doctorCode ," +
                        " d.`name` AS doctorName " +
                " FROM " +
                " "+basedb+".wlyy_admin_team_member m " +
                " JOIN "+basedb+".wlyy_doctor d ON m.doctor_code = d.`code` " +
                " WHERE  " +
                " m.available='1' " +
                " AND m.team_id="+teamId;
        return jdbcTemplate.query(menberSql,new BeanPropertyRowMapper(AdminTeamMemberVO.class));
    }
    public MixEnvelop<Boolean, Boolean> agreeSpecialistTeam(String state, String relationCode, String remark, String health_assistant, String health_assistant_name){
        SpecialistPatientRelationDO relation = specialistPatientRelationDao.findById(relationCode).orElse(null);
        if("0".equals(state)){
            relation.setSignStatus("-2");
            relation.setStatus("-1");
            relation.setRemark(remark);
            specialistPatientRelationDao.save(relation);
        }else{
            relation.setSignStatus("1");
            relation.setHealthAssistant(health_assistant);
            relation.setHealthAssistantName(health_assistant_name);
            relation.setSignDate(new Date());
            specialistPatientRelationDao.save(relation);
            //签约成功之后,将签约关系保存在redis中
            String key = "specialist_patient_relation:" + relation.getPatient() +"_"+ ":text";
            redisTemplate.opsForValue().set(key,"true");
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,relation);
    }
    public MixEnvelop<PatientSignInfoVO, PatientSignInfoVO> findPatientSigninfo(String code){
        String sql = "SELECT " +
                " r.patient ,r.patient_name as patientName" +
               // AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " r.patient_name AS patientName, " +
                " ,r.doctor ,r.doctor_name as doctorName" +
                //AesEncryptUtils.decryptMysql("r.doctor_name","doctorName") +
//                " r.doctor_name AS doctorName, " +
                " ,d.hospital, " +
                " d.hospital_name AS hospitalName, " +
                " d.photo, " +
                " d.dept, " +
                " d.dept_name AS deptName, " +
                " t.`name` AS teamName, " +
                " t.id As teamCode, " +
                " r.create_time AS createTime," +
                " r.status," +
                " r.sign_status AS signStatus,  " +
                " r.team_code AS teamCode  " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_doctor d ON r.doctor = d.code " +
                " JOIN "+basedb+".wlyy_admin_team t ON t.id = r.team_code " +
                " WHERE " +
                " r.id = '"+code+"'";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name","r.doctor_name");
        List<PatientSignInfoVO> patientSignInfoVOs = jdbcTemplate.query(sql, new BeanPropertyRowMapper(PatientSignInfoVO.class));
        PatientSignInfoVO patientSignInfoVO = (null != patientSignInfoVOs && patientSignInfoVOs.size() > 0 ? patientSignInfoVOs.get(0) : new PatientSignInfoVO());
        return MixEnvelop.getSuccess(SpecialistMapping.api_success, patientSignInfoVO);
    }
    public MixEnvelop<SpecialistTeamVO, SpecialistTeamVO> findPatientTeamList(String patient){
        String sql = "SELECT " +
                " r.id AS relationCode, " +
                " r.patient, r.patient_name as patientName" +
               // AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " r.patient_name AS patientName, " +
                " ,r.team_code,r.sign_date , " +
                " t.`name` AS name," +
                " d.photo," +
                " md.code AS doctor,md.name as doctorName" +
              //  AesEncryptUtils.decryptMysql("md.name","doctorName") +
//                " md.name AS doctorName," +
                ",d.hospital,d.hospital_name " +
                " FROM " +
                " wlyy_specialist_patient_relation r  " +
                " JOIN "+basedb+".wlyy_admin_team t ON t.id = r.team_code " +
                " JOIN "+basedb+".wlyy_doctor d ON t.leader_code = d.`code` " +
                " JOIN "+basedb+".wlyy_doctor md ON md.code = r.doctor " +
                " WHERE " +
                " r.patient = '"+patient+"' " +
                " AND r.`status` >=0  " +
                " AND r.sign_status >0";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<SpecialistTeamVO> specialistTeamVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SpecialistTeamVO.class));
        if(specialistTeamVOs!=null&&specialistTeamVOs.size()>0){
            for(SpecialistTeamVO specialistTeamVO:specialistTeamVOs){
                List<AdminTeamMemberVO> adminTeamMemberVOs = findTeamMember(specialistTeamVO.getTeamCode());
                specialistTeamVO.setMembers(adminTeamMemberVOs);
            }
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,specialistTeamVOs);
    }
    public MixEnvelop findPatientSignSpecialist(String patient){
        String sql = "SELECT " +
                " r.id AS relationCode, " +
                " r.patient, " +
                " r.team_code AS teamCode,r.patient_name as patientName" +
               // AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " r.patient_name AS patientName, " +
//                " d.name AS doctorName, " +
                ",d.name as doctorName"+
               // AesEncryptUtils.decryptMysql("d.name","doctorName") +
                " ,d.code AS doctor, " +
                " d.photo, " +
                " d.dept, " +
                " d.dept_name AS deptName, " +
                " d.job_name AS job, " +
                " d.sex AS sex, " +
                " d.hospital, " +
                " d.hospital_name AS hospital_name, " +
                " d.`level` " +
                " FROM " +
                " wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_doctor d ON r.doctor = d.`code` " +
                " WHERE  " +
                " r.patient ='"+patient+"' " +
                " AND r.`status`>=0 " +
                " AND r.sign_status >0";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<PatientSignInfoVO> patientSignInfoVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientSignInfoVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientSignInfoVOs);
    }
    public MixEnvelop findPatientSignSpecialistInfo(String patient, String doctor){
        String sql = "SELECT p.idcard, " +
                "p.ssc, " +
                "r.*  FROM " +
                "(SELECT " +
                " r.id AS relationCode," +
                " r.patient, " +
                " r.team_code AS teamCode,r.patient_name as patientName" +
               // AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
                " ,r.health_assistant AS healthAssistant,r.health_assistant_name as healthAssistantName" +
                //AesEncryptUtils.decryptMysql("r.health_assistant_name","healthAssistantName") +
                " ,r.create_time AS createTime," +
//                AesEncryptUtils.decryptMysql("d.name","doctorName") +
                " d.name AS doctorName, " +
                " ,d.code AS doctor, " +
                " d.photo, " +
                " d.dept, " +
                " d.dept_name AS deptName, " +
                " d.hospital, " +
                " d.hospital_name AS hospital_name, " +
                " r.id AS specialCode, " +
                " d.`level` " +
                " FROM " +
                " wlyy_specialist.wlyy_specialist_patient_relation r " +
                " JOIN "+basedb+".wlyy_doctor d ON r.doctor = d.`code` " +
                " WHERE  " +
                " r.patient ='"+patient+"' " +
                " AND r.doctor in" +
                " (SELECT m.doctor_code FROM  wlyy.wlyy_admin_team_member m where m.team_id in  " +
                "  (SELECT dt.id FROM  wlyy.wlyy_admin_team dt LEFT JOIN  wlyy.wlyy_admin_team_member watm ON dt.id=watm.team_id  " +
                "  WHERE dt.available='1' AND watm.available='1' AND watm.doctor_code='"+doctor+"') AND  m.available='1')" +
//                " AND r.`status`>=0 " +
                " AND r.sign_status >0 ) r join "+basedb+".wlyy_patient p on r.patient = p.code order by p.czrq DESC ";
        sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name","r.health_assistant_name");
        List<PatientSignInfoVO> patientSignInfoVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientSignInfoVO.class));
        PatientSignInfoVO patientSignInfoVO = (null != patientSignInfoVOs && patientSignInfoVOs.size() > 0 )? patientSignInfoVOs.get(0):null;
        return MixEnvelop.getSuccess(SpecialistMapping.api_success, patientSignInfoVO);
    }
    
    public MixEnvelop findDoctorAndDoctorHealthBySpecialDoctor(String doctor, String name) {
    
        String sql = "";
        
        if(StringUtils.isNotBlank(name)){
            sql = "SELECT " +
                    "doctor.CODE AS CODE" +
//                    AesEncryptUtils.decryptMysql("doctor.name","name") +
                    ",doctor.NAME AS NAME" +
                    ",doctor.sex AS sex," +
                    "doctor.birthday AS birthday," +
                    "doctor.photo AS photo," +
                    "doctor.mobile AS mobile," +
                    "doctor.hospital AS hospital," +
                    "doctor.hospital_name AS hospitalName," +
                    "doctor.dept AS dept," +
                    "doctor.dept_name AS deptName," +
                    "doctor.job AS job," +
                    "doctor.job_name AS jobName," +
                    "doctor.LEVEL AS LEVEL," +
                    "doctor.qrcode AS qrcode," +
                    "doctor.czrq AS czrq," +
                    "doctor.del AS del," +
                    "doctor.idcard AS idcard " +
                    "FROM wlyy.wlyy_doctor doctor JOIN ( " +
                    "SELECT a.doctor AS doctorcode FROM wlyy.wlyy_sign_family a RIGHT JOIN ( " +
                    "SELECT patient FROM wlyy_specialist_patient_relation WHERE sign_status> 0 AND `status`>=0 AND doctor='"+doctor+"') b ON a.patient=b.patient WHERE a.`status`=1 AND a.expenses_status = 1 " +
                    "UNION  " +
                    "SELECT a.doctor_health AS doctorcode FROM wlyy.wlyy_sign_family a RIGHT JOIN ( " +
                    "SELECT patient FROM wlyy_specialist_patient_relation WHERE sign_status> 0 AND `status`>=0 AND doctor='"+doctor+"') b ON a.patient=b.patient WHERE a.`status`=1 AND a.expenses_status = 1 " +
                    ") " +
                    "t ON doctor.CODE=t.doctorcode and doctor.NAME like '%"+name+"%'";
        }else{
            sql = "SELECT " +
                    "doctor.CODE AS CODE" +
//                    AesEncryptUtils.decryptMysql("doctor.name","name") +
                    ",doctor.NAME AS NAME" +
                    ",doctor.sex AS sex," +
                    "doctor.birthday AS birthday," +
                    "doctor.photo AS photo," +
                    "doctor.mobile AS mobile," +
                    "doctor.hospital AS hospital," +
                    "doctor.hospital_name AS hospitalName," +
                    "doctor.dept AS dept," +
                    "doctor.dept_name AS deptName," +
                    "doctor.job AS job," +
                    "doctor.job_name AS jobName," +
                    "doctor.LEVEL AS LEVEL," +
                    "doctor.qrcode AS qrcode," +
                    "doctor.czrq AS czrq," +
                    "doctor.del AS del," +
                    "doctor.idcard AS idcard " +
                    "FROM wlyy.wlyy_doctor doctor JOIN ( " +
                    "SELECT a.doctor AS doctorcode FROM wlyy.wlyy_sign_family a RIGHT JOIN ( " +
                    "SELECT patient FROM wlyy_specialist_patient_relation WHERE sign_status> 0 AND `status`>=0 AND doctor='"+doctor+"') b ON a.patient=b.patient WHERE a.`status`=1 AND a.expenses_status = 1 " +
                    "UNION  " +
                    "SELECT a.doctor_health AS doctorcode FROM wlyy.wlyy_sign_family a RIGHT JOIN ( " +
                    "SELECT patient FROM wlyy_specialist_patient_relation WHERE sign_status> 0 AND `status`>=0 AND doctor='"+doctor+"') b ON a.patient=b.patient WHERE a.`status`=1 AND a.expenses_status = 1 " +
                    ") " +
                    "t ON doctor.CODE=t.doctorcode";
        }
        
        List<SignFamilyDoctorVO> patientSignInfoVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SignFamilyDoctorVO.class));
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientSignInfoVOs);
    }
    
    public MixEnvelop<Long,Long> findSpecialistSignFamilyPatientCout(String specialdoctor, String familydoctor) {
    
        String sql = "SELECT count(1) AS total " +
                "FROM wlyy.wlyy_sign_family a WHERE a.`status`=1 AND a.expenses_status=1 " +
                "AND patient IN (" +
                "SELECT patient FROM wlyy_specialist.wlyy_specialist_patient_relation WHERE sign_status> 0 AND `status`>=0 " +
                "AND doctor='"+specialdoctor+"') " +
                "AND (a.doctor='"+familydoctor+"' OR a.doctor_health='"+familydoctor+"') ";
    
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sql);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,count);
    }
    
    public MixEnvelop<PatientRelationVO, PatientRelationVO> getSpecialistSignFamilyPatientByName(String specialdoctor, String familydoctor, String nameKey, Integer page, Integer size) {
        String sql ="SELECT " +
                "p.CODE AS patient" +
//                AesEncryptUtils.decryptMysql("p.name","patientName") +
                ",p.`name` AS patientName" +
                ",p.photo," +
                "IFNULL(YEAR (from_days(datediff(now(),p.birthday))),'未知') age," +
                "p.sex " +
                "FROM wlyy.wlyy_patient p " +
                "JOIN ( " +
                " SELECT a.patient FROM wlyy.wlyy_sign_family a WHERE patient IN (" +
                "  SELECT patient FROM wlyy_specialist_patient_relation WHERE sign_status> 0 AND `status`>=0 " +
                "  AND doctor='"+specialdoctor+"') " +
                "  AND (a.doctor='"+familydoctor+"' OR a.doctor_health='"+familydoctor+"') ";
        if(StringUtils.isNotBlank(nameKey)){
            sql= sql + " AND  a.name LIKE '%"+nameKey+"%' ";
//            sql= sql + " AND " + AesEncryptUtils.decryptMysqlNo("a.name") + " LIKE '%"+nameKey+"%' ";
        }
        sql= sql +" AND a.`status`=1 AND a.expenses_status=1) s ON p.CODE=s.patient" +
                " LIMIT "+(page-1)*size+","+size;
    
        List<PatientRelationVO> patientRelationVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientRelationVO.class));
    
        return MixEnvelop.getSuccess(SpecialistMapping.api_success,patientRelationVOs);
    }
    public MixEnvelop getPatientAndDiseaseByDoctor(String doctor, String patientInfo, String disease, Integer page, Integer size) {
        String sql = "SELECT s.*, " +
                "p.idcard, " +
                "case p.sex WHEN 1 then '男' ELSE '女' END as sex, " +
                "IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                "p.birthday, " +
                "p.photo " +
//                "FROM (SELECT s.disease,s.disease_name,s.patient" + AesEncryptUtils.decryptMysql("s.patient_name","patient_name") + ",r.team_code from " +
                "FROM (SELECT s.disease,s.disease_name,s.patient s.patient_name,r.team_code from " +
                "(SELECT id, team_code FROM wlyy_specialist_patient_relation WHERE doctor='" + doctor + "' and sign_status > 0 and `status` >= 0) r " +
                "JOIN "+basedb+".wlyy_patient_disease_server s on r.id = s.specialist_relation_code WHERE s.del = 1) s " +
                "JOIN "+basedb+".wlyy_patient p on s.patient = p.`code` where p.`status` >0 ";
        if(StringUtils.isNotBlank(patientInfo)){
            sql += " and p.idcard like '%"+ patientInfo +"%' or patient_name  like '%" + patientInfo + "%'";
        }
        if(StringUtils.isNotBlank(disease)){
            sql = sql.replace("WHERE s.del = 1", "WHERE s.del = 1 and s.disease = '" + disease + "'");
        }
        sql += "ORDER BY p.czrq DESC LIMIT "+(page-1)*size+","+size;
        List<PatientDisseaseInfoVO> patientDisseaseInfoVO = jdbcTemplate.query(sql, new BeanPropertyRowMapper(PatientDisseaseInfoVO.class));
        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success, patientDisseaseInfoVO, page, size, (long) patientDisseaseInfoVO.size());
    }
    /**
     * 专科-模糊搜索注册居民(未与该医生所在团队医生签约的居民)
     * @param doctorCode
     * @param keywords
     */
    public MixEnvelop searchPatientInSpecialist(String doctorCode, String keywords, Integer page, Integer pageSize) throws Exception{
        String sql1 = " select count(1) as num ";
        String sql2 = " select p.name as name,p.idcard,p.code,p.photo ";
        String whereSql ="";
        if(!StringUtils.isEmpty(keywords)){
//            whereSql+=" and (p.name like '%"+keywords+"%' or p.idcard like '%"+keywords+"%' or p.mobile like '%"+keywords+"%') ";
            whereSql+=" and  p.mobile ='"+keywords+"'";
        }
        String centerSql =" from "+basedb+".wlyy_patient p  " +
                " WHERE p.code not in (SELECT r.patient FROM  wlyy_specialist.wlyy_specialist_patient_relation r WHERE r.sign_status = '1' " +
                " AND doctor in (SELECT m.doctor_code FROM  "+basedb+".wlyy_admin_team_member m where m.team_id in " +
                " (SELECT dt.id FROM  "+basedb+".wlyy_admin_team dt LEFT JOIN  "+basedb+".wlyy_admin_team_member watm ON dt.id=watm.team_id " +
                " WHERE dt.available='1' AND watm.available='1' AND watm.doctor_code='"+doctorCode+"') AND  m.available='1'))"
                +" AND p.openid IS NOT NULL "+
               whereSql;
        String countCenterSql =" from "+basedb+".wlyy_patient p " +
                " WHERE p.code not in (SELECT r.patient FROM  wlyy_specialist.wlyy_specialist_patient_relation r WHERE r.sign_status = '1'" +
                " AND doctor in (SELECT m.doctor_code FROM  "+basedb+".wlyy_admin_team_member m where m.team_id in " +
                " (SELECT dt.id FROM  "+basedb+".wlyy_admin_team dt LEFT JOIN  "+basedb+".wlyy_admin_team_member watm ON dt.id=watm.team_id " +
                " WHERE dt.available='1' AND watm.available='1' AND watm.doctor_code='"+doctorCode+"') AND  m.available='1'))"
                +" AND p.openid IS NOT NULL "+
                whereSql;
        String sqlCount=sql1+countCenterSql;
        String sql=sql2+centerSql+" LIMIT "+(page-1)*pageSize+","+pageSize;
        List<Map<String,Object>> map = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> countMap = jdbcTemplate.queryForList(sqlCount);
        List<Map<String,Object>> resultList = new ArrayList<>();
        Map m = null;
        Integer age = null;
        String sex = null;
        String sexName="";
        for(Map<String,Object> one:map){
            StringBuffer statusSql =new StringBuffer( " select CASE WHEN wsf.status ='-4' THEN '已到期' WHEN wsf.status ='0' THEN '待签约' WHEN wsf.status ='1' THEN '已签约' WHEN wsf.status ='2' THEN '已签约' WHEN wsf.status ='3' THEN '已签约' ELSE '待签约' END  status  ");
            statusSql.append("FROM wlyy.wlyy_sign_family wsf, (SELECT patient,Max(apply_date) applyDate FROM wlyy.wlyy_sign_family WHERE type = '2' AND patient='"+one.get("code")+"' GROUP BY patient) temp WHERE wsf.patient=temp.patient AND wsf.apply_date=temp.applyDate");
            List<Map<String,Object>> strMap= jdbcTemplate.queryForList(statusSql.toString());
            m = new HashMap();
            age = IdCardUtil.getAgeForIdcard(one.get("idcard")+"");
            sex = IdCardUtil.getSexForIdcard_new(one.get("idcard")+"");
            m.put("name",one.get("name"));
            m.put("age",age);
            m.put("sex",sex);
            m.put("status", !(null != strMap && strMap.size() > 0) ? "待签约" : strMap.get(0).get("status"));
            if("1".equals(sex)){
                sexName="男";
            }else if("2".equals(sex)){
                sexName="女";
            }else{
                sexName="未知";
            }
            m.put("sexName",sexName);
            m.put("patientCode",one.get("code"));
            m.put("photo",one.get("photo"));
            resultList.add(m);
        }
        Long co=Long.parseLong("100");
        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success,resultList,page,pageSize,countMap.size()>0?Long.valueOf(countMap.get(0).get("num")+""):0);
//        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success,resultList,page,pageSize,co);
    }
    /**
     * 病人的家签信息、专科开通信息
     * @param doctorCode 医生code
     * @param patientCode 病人id
     * @param signStatus 签约状态,待审核:0;未签约:-1
     */
    public JSONObject doctorForSpecialistInfo(String signStatus,String doctorCode, String patientCode)  throws Exception{
        JSONObject jsonObject = new JSONObject();
        SpecialistPatientRelationDO specialistPatientRelationDO = new SpecialistPatientRelationDO();
        //待审核
        if ("0".equals(signStatus)) {
            specialistPatientRelationDO = specialistPatientRelationDao.findByDoctorAndPatient(doctorCode, patientCode);
        }
        //1、获取居民基础信息
        String preSql = "SELECT p.name as name, p.photo as photo,p.idcard as idcard,p.mobile as mobile,p.medicare_number as medicareNumber,p.ssc as ssc," +
                " CASE  WHEN wd.name is null THEN '无' ELSE wd.name END as doctorName,CASE  WHEN wd.hospital_name is NULL THEN '无' ELSE wd.hospital_name END as hospitalName,CASE  WHEN wd.mobile is NULL THEN '无' ELSE wd.mobile END as doctorMobole ";
        String patientSql = " from " + basedb + ".wlyy_patient p LEFT JOIN " + basedb + ".wlyy_sign_family wsf " +
                " ON p.code=wsf.patient AND wsf.type='2' AND wsf.status='1' " +
                " LEFT JOIN " + basedb + ".wlyy_doctor wd ON wsf.doctor =wd.code WHERE p.code='" + patientCode + "'";
        //一个居民 生效的家签信息只会有一条
        Map<String, Object> map = jdbcTemplate.queryForMap(preSql + patientSql);
        map.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard")+""));
        String sexCode= IdCardUtil.getSexForIdcard_new(map.get("idcard")+"");
        String sexName="";
        if("1".equals(sexCode)){
            sexName="男";
        }else if("2".equals(sexCode)){
            sexName="女";
        }else{
            sexName="未知";
        }
        map.put("sex",sexName);
        jsonObject.put("patientInfo", map);
        //2、获取医生信息(所属医院、科室、姓名)
        String doctorSql = "SELECT wd.hospital_name as hospitalName,wd.dept_name as deptName,wd.name as name FROM " + basedb + ".wlyy_doctor wd WHERE wd.code='" + doctorCode + "'";
        jsonObject.put("doctorInfo", jdbcTemplate.queryForMap(doctorSql));
        //3、获取该医生所属团队及团队成员信息
        String teamSql = "SELECT at.name teamName, tm.team_id , tm.doctor_code, wd.NAME as doctorName  FROM " + basedb + ".wlyy_doctor wd LEFT JOIN  " + basedb + ".wlyy_admin_team_member tm ON wd. CODE = tm.doctor_code, " + basedb + ".wlyy_admin_team at " +
                "WHERE tm.team_id IN ( SELECT watm.team_id teamId FROM  " + basedb + ".wlyy_admin_team_member watm WHERE watm.doctor_code ='" + doctorCode + "'" + " AND watm.available = '1' ) AND tm.available='1' AND `at`.id=tm.team_id";
        List<Map<String, Object>> teamList = jdbcTemplate.queryForList(teamSql);
        Map<Integer, List<Map<String, Object>>> m = teamList.stream().collect(Collectors.groupingBy(tem -> ((Integer) tem.get("team_id")).intValue(), Collectors.toList()));
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Integer i : m.keySet()) {
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("teamId", i);
            objectMap.put("teamName", m.get(i).get(0).get("teamName"));
            objectMap.put("teamDoctors", m.get(i));
            //获取专科团队疾病标签
           String disSql = "SELECT wtdr.disease_code, wtdr.disease_name from  wlyy.wlyy_team_disease_relation wtdr WHERE wtdr.team_code ='" + i + "'" +"  AND wtdr.del='1'";
            //new BeanPropertyRowMapper(
            List<Map<String, Object>>  stringList = jdbcTemplate.queryForList(disSql);
            String areaSql = "SELECT wpds.disease FROM wlyy.wlyy_patient_disease_server wpds WHERE wpds.patient='" + patientCode + "'" + " AND wpds.del='1'";
            List<String> signDiseaseList = jdbcTemplate.queryForList(areaSql,String.class);
            Set<String> stringSet =new HashSet<>(signDiseaseList);
//            stringSet.addAll(new HashSet<>(signDiseaseList));
            //已签约的疾病状态改成1
            stringList.stream().forEach(item->{
                item.put("status",stringSet.contains( item.get("disease_code"))?1:0) ;
            });
            objectMap.put("teamDisease", stringList);
            mapList.add(objectMap);
        }
        jsonObject.put("teamAndDoctors", mapList);
        //康复情况标签
        String labelSql = "SELECT wspl.label_code,wspl.label_name from  wlyy.wlyy_sign_patient_label wspl WHERE wspl.label_type='8' AND status='1'";
        List<Map<String, Object>> signPatientLabelList = jdbcTemplate.queryForList(labelSql);
        jsonObject.put("signPatientLabels", signPatientLabelList);
        return jsonObject;
    }
    /**
     * 病人的家签信息、专科开通信息
     * @param doctorCode 医生code
     * @param patientCode 病人id
     * @param signStatus 签约状态,待审核:0;未签约:-1
     */
    public JSONObject doctorForSpecialistInfoNew(String signStatus,String doctorCode, String patientCode)  throws Exception{
        JSONObject jsonObject = new JSONObject();
        SpecialistPatientRelationDO specialistPatientRelationDO = new SpecialistPatientRelationDO();
        //待审核
        if ("0".equals(signStatus)) {
            specialistPatientRelationDO = selectByDoctorAndPatient(doctorCode, patientCode);
        }
        jsonObject.put("specialistPatientRelationId", null == specialistPatientRelationDO ? null : specialistPatientRelationDO.getId());
        jsonObject.put("signCertificate", null == specialistPatientRelationDO ? null : specialistPatientRelationDO.getSignCertificate());
        //1、获取居民基础信息
        String preSql = "SELECT p.name as name, p.photo as photo,p.idcard as idcard,p.mobile as mobile,p.medicare_number as medicareNumber,p.ssc as ssc," +
                " CASE  WHEN wd.name is null THEN '无' ELSE wd.name END as doctorName,CASE  WHEN wd.hospital_name is NULL THEN '无' ELSE wd.hospital_name END as hospitalName,CASE  WHEN wd.mobile is NULL THEN '无' ELSE wd.mobile END as doctorMobole ";
        String patientSql = " from " + basedb + ".wlyy_patient p LEFT JOIN " + basedb + ".wlyy_sign_family wsf " +
                " ON p.code=wsf.patient AND wsf.type='2' AND wsf.status='1' " +
                " LEFT JOIN " + basedb + ".wlyy_doctor wd ON wsf.doctor =wd.code WHERE p.code='" + patientCode + "'";
        //一个居民 生效的家签信息只会有一条
        Map<String, Object> map = jdbcTemplate.queryForMap(preSql + patientSql);
        map.put("age", IdCardUtil.getAgeForIdcard(map.get("idcard")+""));
        String sexCode= IdCardUtil.getSexForIdcard_new(map.get("idcard")+"");
        String sexName="";
        if("1".equals(sexCode)){
            sexName="男";
        }else if("2".equals(sexCode)){
            sexName="女";
        }else{
            sexName="未知";
        }
        map.put("sex",sexName);
        jsonObject.put("patientInfo", map);
        //2、获取医生信息(所属医院、科室、姓名)
        String doctorSql = "SELECT wd.hospital_name as hospitalName,wd.dept_name as deptName,wd.name as name FROM " + basedb + ".wlyy_doctor wd WHERE wd.code='" + doctorCode + "'";;
        if("0".equals(signStatus)){
            doctorSql="SELECT wd.hospital_name as hospitalName,wd.dept_name as deptName,wd.name as name FROM " + basedb + ".wlyy_doctor wd WHERE wd.code='" + specialistPatientRelationDO.getDoctor() + "'";
        }
        Map<String,Object> result =jdbcTemplate.queryForMap(doctorSql);
        if ("0".equals(signStatus) && !(doctorCode.equals(specialistPatientRelationDO.getDoctor()))) {
            result.put("buttonShowFlag", false);
        } else {
            result.put("buttonShowFlag",true);
        }
        jsonObject.put("doctorInfo", result);
        //3、获取该医生所属团队及团队成员信息
        String teamSql = "SELECT at.name teamName, tm.team_id , tm.doctor_code, wd.NAME as doctorName  FROM " + basedb + ".wlyy_doctor wd LEFT JOIN  " + basedb + ".wlyy_admin_team_member tm ON wd. CODE = tm.doctor_code, " + basedb + ".wlyy_admin_team at " +
                "WHERE tm.team_id IN ( SELECT watm.team_id teamId FROM  " + basedb + ".wlyy_admin_team_member watm WHERE watm.doctor_code ='" + doctorCode + "'" + " AND watm.available = '1' ) AND tm.available='1' AND `at`.id=tm.team_id";
        List<Map<String, Object>> teamList = jdbcTemplate.queryForList(teamSql);
        Map<Integer, List<Map<String, Object>>> m = teamList.stream().collect(Collectors.groupingBy(tem -> ((Integer) tem.get("team_id")).intValue(), Collectors.toList()));
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Integer i : m.keySet()) {
            Map<String, Object> objectMap = new HashMap<>();
            if ("0".equals(signStatus) && i.equals(specialistPatientRelationDO.getTeamCode())) {
                objectMap.put("checkFlag", true);
            } else {
                objectMap.put("checkFlag", false);
            }
            objectMap.put("teamId", i);
            objectMap.put("teamName", m.get(i).get(0).get("teamName"));
            objectMap.put("teamDoctors", m.get(i));
            //获取专科团队疾病标签
            String disSql = "SELECT wtdr.disease_code, wtdr.disease_name from  wlyy.wlyy_team_disease_relation wtdr WHERE wtdr.team_code ='" + i + "'" +"  AND wtdr.del='1'";
            //new BeanPropertyRowMapper(
            List<Map<String, Object>>  stringList = jdbcTemplate.queryForList(disSql);
            String areaSql = "SELECT wpds.disease FROM wlyy.wlyy_patient_disease_server wpds WHERE wpds.patient='" + patientCode + "'" + " AND wpds.del='1'";
            List<String> signDiseaseList = jdbcTemplate.queryForList(areaSql,String.class);
            Set<String> stringSet =new HashSet<>(signDiseaseList);
            List<String> speciaSignDiseaseList = new ArrayList<>();
            if("0".equals(signStatus) ){
                String speciaSignSql = "SELECT wpds.disease FROM wlyy.wlyy_patient_disease_server wpds WHERE wpds.patient='" + patientCode + "'" + " AND wpds.del='1' and wpds.specialist_relation_code='" + specialistPatientRelationDO.getId() + "'";
                speciaSignDiseaseList = jdbcTemplate.queryForList(speciaSignSql,String.class);
            }
            Set<String> speciaSignSet =new HashSet<>(speciaSignDiseaseList);
            //已签约的疾病状态改成1
            stringList.stream().forEach(item->{
                int status=0;
                if(stringSet.contains( item.get("disease_code"))){
                    //已签约过的疾病
                    status=1;
                }
                if(null!=speciaSignSet&& speciaSignSet.contains(item.get("disease_code"))){
                    //本次专病签约的疾病
                    status=2;
                }
                item.put("status",status) ;
            });
            objectMap.put("teamDisease", stringList);
            mapList.add(objectMap);
        }
        jsonObject.put("teamAndDoctors", mapList);
        //康复情况标签
        String labelSql = "SELECT wspl.label_code,wspl.label_name from  wlyy.wlyy_sign_patient_label wspl WHERE wspl.label_type='8' AND status='1'";
        List<Map<String, Object>> signPatientLabelList = jdbcTemplate.queryForList(labelSql);
        List<String> patientLabelList = new ArrayList<>();
        if("0".equals(signStatus) ){
            //居民的康复情况
            String patientLabelSql = "SELECT wspl.label from  wlyy.wlyy_sign_patient_label_info wspl WHERE wspl.patient='"+patientCode+"' and  wspl.label_type='8' AND status='1'";
            patientLabelList = jdbcTemplate.queryForList(patientLabelSql,String.class);
        }
        Set<String> patientLabelSet =new HashSet<>(patientLabelList);
        signPatientLabelList.stream().forEach(item->{
            item.put("status",patientLabelSet.contains(item.get("label_code").toString())?1:0) ;
        });
        jsonObject.put("signPatientLabels", signPatientLabelList);
        return jsonObject;
    }
    /**
     * 专科医生发起签约
     * @param specialistPatientRelationDO
     * @return
     * @throws Exception
     */
    public ObjEnvelop<SpecialistPatientRelationDO> createPatientInSpeciaRelation(SpecialistPatientRelationDO specialistPatientRelationDO) throws Exception {
        if(StringUtils.isNotEmpty(specialistPatientRelationDO.getId())){
            //获取专科相关的信息
            Map<String,Object> m=  getMessageByRelationId(specialistPatientRelationDO.getId());
            if(null!=m){
                updateMessageByRelationId(specialistPatientRelationDO.getId());
            }
        }
        specialistPatientRelationDO.setSignStatus("1");
        specialistPatientRelationDO.setSignDate(new Date());
        specialistPatientRelationDO.setCreateTime(new Date());
        specialistPatientRelationDO.setUpdateTime(new Date());
        specialistPatientRelationDO.setCreateUser(specialistPatientRelationDO.getDoctor());
        specialistPatientRelationDO.setCreateUserName(specialistPatientRelationDO.getDoctorName());
        specialistPatientRelationDO.setStatus("1");//计管师分配状态
        specialistPatientRelationDO.setSignYear(String.valueOf(DateUtil.getNowYear()));
        specialistPatientRelationDO.setSignDate(new Date());
        specialistPatientRelationDO = specialistPatientRelationDao.save(specialistPatientRelationDO);
        //签约成功之后,将签约关系保存在redis中
        String key = "specialist_patient_relation:" + specialistPatientRelationDO.getPatient() +"_"+ ":text";
        redisTemplate.opsForValue().set(key,"true");
        return ObjEnvelop.getSuccess("success", specialistPatientRelationDO);
    }
    public Integer updateRedisFindPatientTeamList(){
        List<SpecialistPatientRelationDO> specialistPatientRelationDOList=specialistPatientRelationDao.findAllBySignStatus("1");
        List<SpecialistPatientRelationDO> unique = specialistPatientRelationDOList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SpecialistPatientRelationDO::getPatient))), ArrayList::new)
        );
        unique.stream().forEach(item->{
            //签约成功之后,将签约关系保存在redis中
            String key = "specialist_patient_relation:" + item.getPatient() +"_"+ ":text";
            redisTemplate.opsForValue().set(key,"true");
        });
        return null==unique?0:unique.size();
    }
    /**
     * 根据共管医生和居民code查询专科签约信息
     *
     * @param patient
     * @param doctor
     * @return
     */
    public List<SpecialistPatientRelationDO> selectByAssistant(String patient, String doctor){
        String sql = "select *" +
                " from wlyy_specialist_patient_relation r where r.health_assistant = '"+doctor+"' and r.patient = '"+patient+"' ";
        sql = TransforSqlUtl.specialistPatientRelationAll(sql);
        List<SpecialistPatientRelationDO> relationDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SpecialistPatientRelationDO.class));
        return relationDOS;
    }
    /**
     * 专科-通过手机号码精确搜索注册居民
     * @param keywords
     */
    public MixEnvelop searchPatientInSpecialistNew(String doctorCode, String keywords, Integer page, Integer pageSize) throws Exception{
        String sql1 = " select count(1) as num ";
        String sql2 = " select p.name as name,p.idcard,p.code,p.photo";
        String whereSql ="";
        if(!StringUtils.isEmpty(keywords)){
            whereSql+=" and  p.mobile ='"+keywords+"'";
        }
        //根据手机号码精确查找居民
        String centerSql =" from "+basedb+".wlyy_patient p /*LEFT JOIN wlyy_specialist.wlyy_specialist_patient_relation r ON p.code=r.patient */where  p.openid IS NOT NULL "+whereSql;
        String signSql ="SELECT r.patient,r.sign_status  FROM  wlyy_specialist.wlyy_specialist_patient_relation r WHERE (r.sign_status = '1' or r.sign_status = '0') " +
                " AND doctor in (SELECT m.doctor_code FROM  "+basedb+".wlyy_admin_team_member m where m.team_id in " +
                " (SELECT dt.id FROM  "+basedb+".wlyy_admin_team dt LEFT JOIN  "+basedb+".wlyy_admin_team_member watm ON dt.id=watm.team_id " +
                " WHERE dt.available='1' AND watm.available='1' AND watm.doctor_code='"+doctorCode+"') AND  m.available='1')";
        List<Map<String,Object>> map1=jdbcTemplate.queryForList(signSql);
        String sqlCount=sql1+centerSql;
        String sql=sql2+centerSql+" LIMIT "+(page-1)*pageSize+","+pageSize;
        List<Map<String,Object>> map = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> countMap = jdbcTemplate.queryForList(sqlCount);
        //根据居民查找专科签约状态
        //已签约专科,获取签约信息
        Map<String,String> patientMap = new HashMap<>();
        if(null!=map1){
            map1.stream().forEach(temp->{
                patientMap.put(temp.get("patient").toString(),temp.get("sign_status").toString()) ;
            });
        }
        //未签约,获取居民信息,及专科医生信息
        List<Map<String,Object>> resultList = new ArrayList<>();
        Map m = null;
        Integer age = null;
        String sex = null;
        String sexName="";
        for(Map<String,Object> one:map){
            m = new HashMap();
            age = IdCardUtil.getAgeForIdcard(one.get("idcard")+"");
            sex = IdCardUtil.getSexForIdcard_new(one.get("idcard")+"");
            String patientCode=null==one.get("code")?"":one.get("code").toString();
            m.put("name",one.get("name"));
            m.put("age",age);
            m.put("sex",sex);
            //1已签约,0待审核,-1未签约或已取消或已拒绝
            if(patientMap.containsKey(patientCode)&&"1".equals(patientMap.get(patientCode))){
                m.put("sign_status", 1);
            }else if(patientMap.containsKey(patientCode)&&"0".equals(patientMap.get(patientCode))){
                m.put("sign_status", 0);
            }else {
                m.put("sign_status", -1);
            }
            if("1".equals(sex)){
                sexName="男";
            }else if("2".equals(sex)){
                sexName="女";
            }else{
                sexName="未知";
            }
            m.put("sexName",sexName);
            m.put("patientCode",one.get("code"));
            m.put("photo",one.get("photo"));
            resultList.add(m);
        }
        return MixEnvelop.getSuccessListWithPage(SpecialistMapping.api_success,resultList,page,pageSize,countMap.size()>0?Long.valueOf(countMap.get(0).get("num")+""):0);
    }
    /**
     * 根据医生和居民code查询居民与该医生所在团队的待审核专科签约信息
     *
     * @param patient
     * @param doctor
     * @return
     */
    public SpecialistPatientRelationDO selectByDoctorAndPatient(String doctor, String patient){
        String sql = "select * from wlyy_specialist.wlyy_specialist_patient_relation r where r.doctor in ( " +
                " SELECT m.doctor_code  FROM wlyy.wlyy_admin_team_member m " +
                " WHERE  m.team_id IN ( SELECT dt.id  FROM  wlyy.wlyy_admin_team dt LEFT JOIN wlyy.wlyy_admin_team_member watm ON dt.id = watm.team_id   WHERE " +
                " dt.available = '1' AND watm.available = '1'  AND watm.doctor_code = '"+doctor+"') AND m.available = '1'  ) and r.patient = '"+patient+"' and r.sign_status=0";
        sql  = TransforSqlUtl.specialistPatientRelationAll2(sql);
        List<SpecialistPatientRelationDO> relationDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SpecialistPatientRelationDO.class));
        SpecialistPatientRelationDO specialistPatientRelationDO=null!=relationDOS&&relationDOS.size()>0?relationDOS.get(0):new SpecialistPatientRelationDO();
        return specialistPatientRelationDO;
    }
    /**
     * 根据签约关系id获取消息
     * @param relationId
     * @return
     */
    public Map<String,Object> getMessageByRelationId(String relationId){
        String sql = "select w.* from wlyy.wlyy_message w where w.type='16' and  w.relation_code='" + relationId + "' ";
       List<Map<String,Object>> res= jdbcTemplate.queryForList(sql);
       if(null!=res&&res.size()>0){
           return res.get(0);
       }
       return null;
    }
    /**
     * 更新消息
     * @param relationId
     * @return
     */
    public void updateMessageByRelationId(String relationId){
        String sql = "update wlyy.wlyy_message set has_read=0 ,over=0  where relation_code='" + relationId + "' ";
        jdbcTemplate.execute(sql);
    }
    public Envelop updatePatientSignSpecialistInfo(String patient, String doctor, String doctorName) {
        specialistPatientRelationDao.updateSpecialistByPatient(patient, doctor, doctorName);
        return Envelop.getSuccess("更新成功!");
    }
    public JSONObject transferPatients(String teamCode,String toTeamCode,String doctorCode,String toDoctorCode,String patients){
        String[] patient = patients.split(",");
        boolean flag=false;//同团队时 teamCode==toTeamCode
        if (!teamCode.equals(toTeamCode)){//跨团队
            flag=true;
        }
        String sql =" select name from wlyy.wlyy_doctor where code='"+toDoctorCode+"'";
        String toDoctorName = jdbcTemplate.queryForObject(sql,String.class);
//        toDoctorName = AesEncryptUtils.decrypt(toDoctorName);
        sql =" select name from wlyy.wlyy_doctor where code='"+doctorCode+"'";
        String doctorName = jdbcTemplate.queryForObject(sql,String.class);
//        doctorName = AesEncryptUtils.decrypt(doctorName);
        JSONObject result = new JSONObject();
        JSONArray planObject = new JSONArray();
        JSONArray planDetailObject = new JSONArray();
        JSONArray specialistPatientRelation = new JSONArray();
        JSONArray rehabilitationOperateRecords = new JSONArray();
        for (String patientCode:patient){
            sql ="select name from wlyy.wlyy_patient where code='"+patientCode+"' ";
            String patientName = jdbcTemplate.queryForObject(sql,String.class);
            Long admin_team_code = 0L;
            //判断是否签约,如果签约 新增家签团队id
            try{
                String sqltmp = "SELECT a.admin_team_code  from wlyy.wlyy_sign_family a WHERE patient = '"+patientCode+"' and `status`>0 and expenses_status =1 order by id desc limit 1 ";
                List<Map<String,Object>> list =  jdbcTemplate.queryForList(sqltmp);
                if(list!=null&&list.size()>0){
                    admin_team_code = Long.valueOf(list.get(0).get("admin_team_code")+"");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
//            patientName = AesEncryptUtils.decrypt(patientName);
            List<PatientRehabilitationPlanDO> planList  = patientRehabilitationPlanDao.findByPatientAndCreateUserAndTeamCode(patientCode,doctorCode,Integer.parseInt(teamCode));{
                for (PatientRehabilitationPlanDO plan:planList){
                    plan.setCreateUser(toDoctorCode);
                    plan.setCreateUserName(toDoctorName);
                    plan.setUpdateUser(doctorCode);
                    plan.setUpdateUserName(doctorName);
                    plan.setUpdateTime(new Date());
                    if (flag){
                        plan.setTeamCode(Integer.parseInt(toTeamCode));
                    }
                    if(admin_team_code>0){
                        plan.setAdminTeamCode(admin_team_code);
                    }
                    patientRehabilitationPlanDao.save(plan);
                    planObject.add(plan.getId());
                    PatientRehabilitationPlanLogDO planLogDO = new PatientRehabilitationPlanLogDO();
                    planLogDO.setId(UUID.randomUUID().toString().replace("-",""));
                    planLogDO.setPlanId(plan.getId());
                    planLogDO.setCreateTime(new Date());
                    planLogDO.setCreateUser(doctorCode);
                    planLogDO.setCreateUserName(doctorName);
                    patientRehabilitationPlanLogDao.save(planLogDO);
                    List<RehabilitationDetailDO> planDetails  = rehabilitationDetailDao.findByPlanIdAndTypeAndDoctorAndStatusNot(plan.getId(),2,doctorCode,1);//未完成的任务
                    for (RehabilitationDetailDO planDetail:planDetails){
                        planDetail.setCreateUser(toDoctorCode);
                        planDetail.setCreateUserName(toDoctorName);
                        planDetail.setDoctor(toDoctorCode);
                        planDetail.setDoctorName(toDoctorName);
                        planDetail.setUpdateTime(new Date());
                        planDetail.setUpdateUser(doctorCode);
                        planDetail.setUpdateUserName(doctorName);
                        rehabilitationDetailDao.save(planDetail);
                        planDetailObject.add(planDetail.getId());
                        List<RehabilitationOperateRecordsDO> operateList = rehabilitationOperateRecordsDao.findByRehabilitationDetailIdAndDoctorCodeAndStatusNot(planDetail.getId(),doctorCode,1);
                        for (RehabilitationOperateRecordsDO operateRecordsDO:operateList){
                            operateRecordsDO.setDoctorCode(toDoctorCode);
                            operateRecordsDO.setDoctorName(toDoctorName);
                            operateRecordsDO.setUpdateTime(new Date());
                            operateRecordsDO.setUpdateUser(doctorCode);
                            operateRecordsDO.setUpdateUserName(doctorName);
                            rehabilitationOperateRecordsDao.save(operateRecordsDO);
                            rehabilitationOperateRecords.add(operateRecordsDO.getId());
                        }
                    }
                }
            }
            if (flag){
                SpecialistPatientRelationDO relations = specialistPatientRelationDao.findByTeamCodeAndPatient(Integer.parseInt(toTeamCode),patientCode);
                SpecialistPatientRelationDO relationDoBefore = specialistPatientRelationDao.findByTeamCodeAndPatient(Integer.parseInt(teamCode),patientCode);
                if (relations==null){//跨团队时  患者未与目标团队签约
                    SpecialistPatientRelationDO relationDO = new SpecialistPatientRelationDO();
                    relationDO.setId(UUID.randomUUID().toString().replace("-",""));
                    relationDO.setDoctorName(toDoctorCode);
                    relationDO.setDoctorName(toDoctorName);
                    relationDO.setPatient(patientCode);
                    relationDO.setPatientName(patientName);
                    relationDO.setTeamCode(Integer.parseInt(toTeamCode));
                    relationDO.setSignStatus("1");
                    relationDO.setStatus("1");
                    relationDO.setSignYear(DateUtil.getSignYear()+"");
                    relationDO.setSignDate(new Date());
                    relationDO.setCreateTime(new Date());
                    relationDO.setCreateUser(toDoctorCode);
                    relationDO.setCreateUserName(toDoctorName);
                    relationDO.setUpdateTime(new Date());
                    if (StringUtils.isNotBlank(relationDoBefore.getDiseaseCode())){
                        relationDO.setDiseaseCode(relationDoBefore.getDiseaseCode());
                    }
                    if (relationDoBefore.getDiseaseCode()!=null){
                        relationDO.setIsManage(relationDoBefore.getIsManage());
                    }
                    if (StringUtils.isNotBlank(relationDoBefore.getManageUser())){
                        relationDO.setManageUser(relationDoBefore.getManageUser());
                    }
                    if (StringUtils.isNotBlank(relationDoBefore.getManageTime().toString())){
                        relationDO.setManageTime(relationDoBefore.getManageTime());
                    }
                    if (StringUtils.isNotBlank(relationDoBefore.getRemindTime())){
                        relationDO.setRemindTime(relationDoBefore.getRemindTime());
                    }
                    specialistPatientRelationDao.save(relationDO);
                    specialistPatientRelation.add(relationDO.getId());
                    sql = "UPDATE wlyy.wlyy_patient_disease_server set specialist_relation_code='"+relationDO.getId()+"' \n" +
                            "where specialist_relation_code='"+relationDoBefore.getId()+"'";
                    jdbcTemplate.execute(sql);
                }
                else{
                    relations.setCreateUser(toDoctorCode);
                    relations.setCreateUserName(toDoctorName);
                    relations.setDoctor(toDoctorCode);
                    relations.setDoctorName(toDoctorName);
                    relations.setUpdateTime(new Date());
                    relations.setUpdateUser(doctorCode);
                    relations.setUpdateUserName(doctorName);
                    specialistPatientRelationDao.save(relations);
                    specialistPatientRelation.add(relations.getId());
                    sql = "UPDATE wlyy.wlyy_patient_disease_server set specialist_relation_code='"+relations.getId()+"' \n" +
                            "where specialist_relation_code='"+relationDoBefore.getId()+"'";
                    jdbcTemplate.execute(sql);
                }
            }
            else{//
                List<SpecialistPatientRelationDO> relations = specialistPatientRelationDao.findListByTeamCodeAndPatientAndDoctor(Integer.parseInt(teamCode),patientCode,doctorCode);
                for (SpecialistPatientRelationDO relation:relations){
                    relation.setCreateUser(toDoctorCode);
                    relation.setCreateUserName(toDoctorName);
                    relation.setDoctor(toDoctorCode);
                    relation.setDoctorName(toDoctorName);
                    relation.setUpdateTime(new Date());
                    relation.setUpdateUser(doctorCode);
                    relation.setUpdateUserName(doctorName);
                    specialistPatientRelationDao.save(relation);
                    specialistPatientRelation.add(relation.getId());
                }
            }
        }
        result.put("planList",planObject);
        result.put("planDetailList",planDetailObject);
        result.put("relationList",specialistPatientRelation);
        result.put("rehabilitationOperateRecords",rehabilitationOperateRecords);
        return  result;
    }
}

+ 64 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistServiceItemOperateLogService.java

@ -0,0 +1,64 @@
package com.yihu.jw.hospital.module.specialist.service;
import com.yihu.jw.entity.specialist.SpecialistServiceItemOperateLogDO;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistServiceItemOperateLogDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.health.bank.HealthBankMapping;
import com.yihu.jw.util.common.ISqlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
 * @author wangzhinan
 * @create 2018-08-17 8:48
 * @desc 服务项目操作记录
 **/
@Service
@Transactional
public class SpecialistServiceItemOperateLogService {
    @Autowired
    private SpecialistServiceItemOperateLogDao specialistServiceItemOperateLogDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     *
     * @param specialistServiceItemOperateLogDO
     * @return
     */
    public MixEnvelop<Boolean,Boolean> insert(SpecialistServiceItemOperateLogDO specialistServiceItemOperateLogDO){
        MixEnvelop<Boolean,Boolean> envelop = new MixEnvelop<>();
        specialistServiceItemOperateLogDao.save(specialistServiceItemOperateLogDO);
        envelop.setObj(true);
        return envelop;
    }
    /**
     *  查询操作记录
     *
     * @param specialistServiceItemOperateLogDO
     * @param page
     * @param pageSize
     * @return
     */
    public MixEnvelop<SpecialistServiceItemOperateLogDO, SpecialistServiceItemOperateLogDO> select(SpecialistServiceItemOperateLogDO specialistServiceItemOperateLogDO, Integer page, Integer pageSize){
        MixEnvelop<SpecialistServiceItemOperateLogDO, SpecialistServiceItemOperateLogDO> envelop = new MixEnvelop<>();
        String sql = ISqlUtils.getSql(specialistServiceItemOperateLogDO,page,pageSize,"*");
        List<SpecialistServiceItemOperateLogDO> specialistServiceItemOperateLogDOS = jdbcTemplate.query(sql,new BeanPropertyRowMapper(SpecialistServiceItemOperateLogDO.class));
        String sqlcount = ISqlUtils.getSql(specialistServiceItemOperateLogDO,0,0,"count");
        List<Map<String,Object>> rstotal = jdbcTemplate.queryForList(sqlcount);
        Long count = 0L;
        if(rstotal!=null&&rstotal.size()>0){
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccessListWithPage(HealthBankMapping.api_success,specialistServiceItemOperateLogDOS,page,pageSize,count);
    }
}

+ 219 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/specialist/service/SpecialistServiceItemService.java

@ -0,0 +1,219 @@
package com.yihu.jw.hospital.module.specialist.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.SpecialistEvaluateDO;
import com.yihu.jw.entity.specialist.SpecialistServiceItemDO;
import com.yihu.jw.entity.specialist.SpecialistServiceItemOperateLogDO;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistServiceItemDao;
import com.yihu.jw.hospital.module.specialist.dao.SpecialistServiceItemOperateLogDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.health.bank.HealthBankMapping;
import com.yihu.jw.util.common.ISqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
 * @author wangzhinan
 * @create 2018-08-17 8:48
 * @desc 服务项目
 **/
@Service
@Transactional
public class SpecialistServiceItemService {
    @Autowired
    private SpecialistServiceItemDao specialistServiceItemDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SpecialistServiceItemOperateLogDao specialistServiceItemOperateLogDao;
    /**
     * 添加服务项目
     *
     * @param specialistServiceItemDO
     * @return
     */
    public MixEnvelop<Boolean, Boolean> insert(SpecialistServiceItemDO specialistServiceItemDO) {
        MixEnvelop<Boolean, Boolean> envelop = new MixEnvelop<>();
        specialistServiceItemDO.setCreateTime(new Date());
        specialistServiceItemDO.setUpdateTime(new Date());
        specialistServiceItemDao.save(specialistServiceItemDO);
        envelop.setObj(true);
        return envelop;
    }
    /**
     * 按条件查询
     *
     * @param specialistServiceItemDO
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop<SpecialistServiceItemDO, SpecialistEvaluateDO> select(SpecialistServiceItemDO specialistServiceItemDO, Integer page, Integer size) {
        MixEnvelop<SpecialistServiceItemDO, SpecialistServiceItemDO> envelop = new MixEnvelop<>();
        String sql = ISqlUtils.getSql(specialistServiceItemDO, page, size, "*");
        List<SpecialistServiceItemDO> specialistServiceItemDOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper(SpecialistServiceItemDO.class));
        String sqlcount = new ISqlUtils().getSql(specialistServiceItemDO, 0, 0, "count");
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlcount);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = (Long) rstotal.get(0).get("total");
        }
        return MixEnvelop.getSuccessListWithPage(HealthBankMapping.api_success, specialistServiceItemDOS, page, size, count);
    }
    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    public MixEnvelop<Boolean, Boolean> batchDelete(List<String> ids) {
        MixEnvelop<Boolean, Boolean> envelop = new MixEnvelop<>();
        for (int i = 0; i < ids.size(); i++) {
            SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDao.findById(ids.get(i)).orElse(null);
            specialistServiceItemDO.setStatus(0);
            specialistServiceItemDO.setCreateTime(new Date());
            specialistServiceItemDO.setUpdateTime(new Date());
            specialistServiceItemDao.save(specialistServiceItemDO);
        }
        envelop.setObj(true);
        return envelop;
    }
    /**
     * 修改服务项目
     *
     * @param specialistServiceItemDO
     * @return
     */
    public MixEnvelop<Boolean, Boolean> update(SpecialistServiceItemDO specialistServiceItemDO) {
        MixEnvelop<Boolean, Boolean> envelop = new MixEnvelop<>();
        SpecialistServiceItemDO specialistServiceItemDO1 = specialistServiceItemDao.findById(specialistServiceItemDO.getId()).orElse(null);
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(specialistServiceItemDO1);
        String sql = ISqlUtils.getUpdateSql(specialistServiceItemDO);
        jdbcTemplate.update(sql);
        Class c = specialistServiceItemDO.getClass();
        Table table = (Table) c.getAnnotation(Table.class);
        String tableName = table.name();
        Field[] fArray = c.getDeclaredFields();
        JSONArray array = new JSONArray();
        for (Field f : fArray) {
            String getMethoName = "";
            JSONObject object = new JSONObject();
            boolean isCExist = f.isAnnotationPresent(Column.class);
            if (isCExist) {
                Column mc = f.getAnnotation(Column.class);
                String columeName = mc.name();
                String name = f.getName();
                Class a = f.getType();
                Object value = null;
                getMethoName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
                try {
                    Method m = c.getMethod(getMethoName);
                    value = (Object) m.invoke(specialistServiceItemDO);
                    if (value == null || "".equals(value)) {
                        continue;
                    } else if (value instanceof String || value instanceof Integer) {
                        value = "'" + value + "'";
                        object.put(name + "旧", jsonObject.getString(name));
                        object.put(name, value);
                        array.add(object);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        SpecialistServiceItemOperateLogDO specialistServiceItemOperateLogDO = new SpecialistServiceItemOperateLogDO();
        specialistServiceItemOperateLogDO.setSaasId("dev");
        specialistServiceItemOperateLogDO.setServiceItemId(specialistServiceItemDO.getId());
        specialistServiceItemOperateLogDO.setStatus(1);
        specialistServiceItemOperateLogDO.setOperateLog(array.toJSONString());
        specialistServiceItemOperateLogDO.setCreateTime(new Date());
        specialistServiceItemOperateLogDO.setUpdateTime(new Date());
        specialistServiceItemOperateLogDao.save(specialistServiceItemOperateLogDO);
        envelop.setObj(true);
        return envelop;
    }
    /**
     * 根据医院code获取服务项目
     *
     * @param hospital
     * @return
     */
    public MixEnvelop<SpecialistServiceItemDO, SpecialistServiceItemDO> selectByHospital(String hospital) {
        MixEnvelop<SpecialistServiceItemDO, SpecialistServiceItemDO> envelop = new MixEnvelop<>();
        String sql = "select * from wlyy_service_item where status = 1 AND imediate = 1 ";
        sql = TransforSqlUtl.wlyy_service_itemAll(sql);
        List<SpecialistServiceItemDO> specialistServiceItemDOS = jdbcTemplate.query(sql, new BeanPropertyRowMapper(SpecialistServiceItemDO.class));
        List<SpecialistServiceItemDO> specialistServiceItemDOList = new ArrayList<>();
        for (int i = 0; i < specialistServiceItemDOS.size(); i++) {
            SpecialistServiceItemDO specialistServiceItemDO = specialistServiceItemDOS.get(i);
            String sqlUtil = "";
            if (StringUtils.isNoneBlank(hospital)) {
                sqlUtil = " and hospital = '" + hospital + "'";
            }
            String sql1 = "select * from wlyy_hospital_service_item where 1=1 AND status = 1 AND service_item_id = '" + specialistServiceItemDO.getId() + "'" + sqlUtil;
            List<HospitalServiceItemDO> hospitalServiceItemDOS = jdbcTemplate.query(sql1, new BeanPropertyRowMapper(HospitalServiceItemDO.class));
            if (StringUtils.isNoneBlank(hospital)) {
                if (hospitalServiceItemDOS.size() == 0 || hospitalServiceItemDOS == null) {
                    specialistServiceItemDOList.add(specialistServiceItemDO);
                }
            } else {
                specialistServiceItemDOList.add(specialistServiceItemDO);
            }
        }
        envelop.setDetailModelList(specialistServiceItemDOList);
        return envelop;
    }
    /**
     * 导数据
     *
     * @param specialistServiceItemDOS
     * @return
     */
    public MixEnvelop<Boolean, Boolean> importData(List<SpecialistServiceItemDO> specialistServiceItemDOS) {
        MixEnvelop<Boolean, Boolean> envelop = new MixEnvelop<>();
        if (specialistServiceItemDOS != null && specialistServiceItemDOS.size() != 0) {
            for (SpecialistServiceItemDO specialistServiceItemDO : specialistServiceItemDOS) {
                List<SpecialistServiceItemDO> specialistServiceItemDOList = specialistServiceItemDao.findByTitle(specialistServiceItemDO.getTitle());
                if (specialistServiceItemDOList == null && specialistServiceItemDOList.size() == 0) {
                    continue;
                } else {
                    specialistServiceItemDO.setStatus(1);
                    specialistServiceItemDO.setId(UUID.randomUUID().toString());
                    specialistServiceItemDO.setCreateTime(new Date());
                    specialistServiceItemDO.setUpdateTime(new Date());
                    specialistServiceItemDao.save(specialistServiceItemDO);
                }
            }
        }
        envelop.setObj(true);
        return envelop;
    }
}

+ 1 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wechat/WechatPushLogDao.java

@ -1,4 +1,4 @@
package com.yihu.jw.hospital.module.wechat;
package com.yihu.jw.hospital.module.wx.dao;
import com.yihu.jw.entity.wechat.WechatPushLog;
@ -7,7 +7,6 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;

+ 1 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wechat/WechatTemplateConfigDao.java

@ -1,4 +1,4 @@
package com.yihu.jw.hospital.module.wechat;
package com.yihu.jw.hospital.module.wx.dao;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;

+ 1 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wechat/WxAccessTokenLogDao.java

@ -1,4 +1,4 @@
package com.yihu.jw.hospital.module.wechat;
package com.yihu.jw.hospital.module.wx.dao;
import com.yihu.jw.entity.wechat.WxAccessTokenLog;

+ 2 - 3
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/wx/service/AccessTokenService.java

@ -5,17 +5,16 @@
 *******************************************************************************/
package com.yihu.jw.hospital.module.wx.service;
import org.springside.modules.utils.*;
import com.yihu.jw.entity.base.wx.JsApiTicket;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.wechat.WxAccessTokenLog;
import com.yihu.jw.hospital.module.wechat.WxAccessTokenLogDao;
import com.yihu.jw.hospital.module.wx.dao.AccessTokenDao;
import com.yihu.jw.hospital.module.wx.dao.WxAccessTokenLogDao;
import com.yihu.jw.wechat.dao.JsapiTicketDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;
import java.util.Date;

+ 1 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/task/PushMsgTask.java

@ -5,11 +5,10 @@ import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.wechat.WechatPushLog;
import com.yihu.jw.entity.wechat.WechatTemplate;
import com.yihu.jw.entity.wechat.WechatTemplateData;
import com.yihu.jw.hospital.module.wechat.WechatPushLogDao;
import com.yihu.jw.hospital.module.wx.dao.WechatPushLogDao;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.hospital.utils.WeiXinOpenIdUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;

+ 7 - 0
svr/svr-visit-behind/src/main/resources/application.yml

@ -1431,6 +1431,7 @@ wechat:
  appSecret: fc96ec810e5078c0ca0f96a8fca4da95
  accId: gh_a09552a72c9b
# 20231012新增的
server:
  server_url: https://ehr.yihu.com/wlyy/
@ -1452,6 +1453,12 @@ pushMes:
neiwang:
  enable: true
  wlyy: http://172.26.0.110:22122/
basedb:
  name: base
base:
  url: http://172.17.110.212:10020/
# ====================================================
sms:
  clientId: EwC0iRSrcP