Forráskód Böngészése

康复计划代码提交

wangjun 3 éve
szülő
commit
83d91916bf
47 módosított fájl, 7216 hozzáadás és 320 törlés
  1. 12 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  2. 19 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/DoctorPatientRelationDao.java
  3. 10 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/PatientMedicalRecordsDao.java
  4. 193 0
      business/base-service/src/main/java/com/yihu/jw/rehabilitation/service/DoctorPatientRelationService.java
  5. 1 0
      business/base-service/src/mqConfig/mqdata/event1.json
  6. 1 0
      business/base-service/src/mqConfig/mqdata/event2.json
  7. 47 31
      business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java
  8. 206 124
      common/common-entity/src/main/java/com/yihu/jw/entity/base/doctor/BaseDoctorDO.java
  9. 55 0
      common/common-entity/src/main/java/com/yihu/jw/entity/hospital/message/SystemMessageDO.java
  10. 131 0
      common/common-entity/src/main/java/com/yihu/jw/entity/patient/PatientEvent.java
  11. 120 0
      common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/RehabilitationguidanceDO.java
  12. 141 0
      common/common-entity/src/main/java/com/yihu/jw/entity/rehabilitation/RehabilitationguidancePatientDO.java
  13. 406 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/DoctorPatientRelationDO.java
  14. 20 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/SpecialistPatientRelationDO.java
  15. 233 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientMedicalRecordsDO.java
  16. 9 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/PatientRehabilitationPlanDO.java
  17. 3 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/rehabilitation/RehabilitationRequestMapping.java
  18. 3 0
      gateway/ag-basic/src/main/resources/application.yml
  19. 9 0
      svr/svr-rehabilitation/pom.xml
  20. 14 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ObserverRequired.java
  21. 89 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ObserverRequiredAOP.java
  22. 22 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/aop/ServicesAuth.java
  23. 318 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanController.java
  24. 72 4
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitaionInfoController.java
  25. 571 2
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationManageController.java
  26. 213 10
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationPlanController.java
  27. 48 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/message/DoctorMessageController.java
  28. 18 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientEventDao.java
  29. 19 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/PatientMedicalRecordsRehabilitationDao.java
  30. 2 2
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationDetailDao.java
  31. 15 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationGuidanceDao.java
  32. 17 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationGuidancePatientDao.java
  33. 19 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationPlanTemplateDao.java
  34. 16 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationServiceItemDao.java
  35. 18 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/dao/RehabilitationTemplateDetailDao.java
  36. 315 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/PatientRecordService.java
  37. 221 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationGuidanceService.java
  38. 444 27
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationInfoService.java
  39. 1641 75
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationManageService.java
  40. 511 23
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanService.java
  41. 23 22
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/SpecialistEvaluateSevice.java
  42. 157 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ZsRehabilitationInfoService.java
  43. 285 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/message/RehabilitationMessageService.java
  44. 38 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/HtmlUtil.java
  45. 440 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/util/RHHttpClientUtil.java
  46. 47 0
      svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/vo/TemplateDetailVo.java
  47. 4 0
      svr/svr-rehabilitation/src/main/resources/application.yml

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

@ -30,4 +30,16 @@ public interface SystemMessageDao extends PagingAndSortingRepository<SystemMessa
    //获取资质申请审核有效的未结束已发送的消息
    //获取资质申请审核有效的未结束已发送的消息
    @Query("select a from SystemMessageDO a where a.type in ('401','408') and a.del='1' and a.over='1' and relationCode = ?1  ")
    @Query("select a from SystemMessageDO a where a.type in ('401','408') and a.del='1' and a.over='1' and relationCode = ?1  ")
    List<SystemMessageDO> findMessageByRelationCode(String relationCode);
    List<SystemMessageDO> findMessageByRelationCode(String relationCode);
    @Query("update SystemMessageDO a set a.isRead=0,a.over = '0' where a.id = ?1")
    @Modifying
    Integer setSpecialistById(String id);
    @Query("update SystemMessageDO a set a.isRead = 0 where a.id = ?1" )
    @Modifying
    Integer setSpecialistReadById(String id);
}
}

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

@ -0,0 +1,19 @@
package com.yihu.jw.rehabilitation;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.GuidanceMessageLogDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DoctorPatientRelationDao extends PagingAndSortingRepository<DoctorPatientRelationDO, String>, JpaSpecificationExecutor<DoctorPatientRelationDO> {
    @Query("from DoctorPatientRelationDO t where t.doctor =?1 and t.patient =?2")
    List<DoctorPatientRelationDO> findByDoctorAndPatient(String doctor,String patient);
    @Query("from DoctorPatientRelationDO t where t.doctor =?1 and t.patient =?2 and t.dischargeRecord = ?3")
    DoctorPatientRelationDO findByDoctorAndPatientAndCode(String doctor,String patient,String code);
}

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

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

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

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

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 1 - 0
business/base-service/src/mqConfig/mqdata/event1.json


A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 1 - 0
business/base-service/src/mqConfig/mqdata/event2.json


+ 47 - 31
business/im-service/src/main/java/com/yihu/jw/im/util/ImUtil.java

@ -22,7 +22,7 @@ import java.util.List;
public class ImUtil {
public class ImUtil {
	
	
	@Autowired
	@Autowired
	private HttpClientUtil HttpClientUtil;
	private HttpClientUtil httpClientUtil;
	
	
	@Value("${im.im_list_get}")
	@Value("${im.im_list_get}")
	private String im_host;
	private String im_host;
@ -87,7 +87,7 @@ public class ImUtil {
		params.put("sender_name", receiverId);
		params.put("sender_name", receiverId);
		params.put("content_type", contentType);
		params.put("content_type", contentType);
		params.put("content", content);
		params.put("content", content);
		String response = HttpClientUtil.postBody(imAddr, params);
		String response = httpClientUtil.postBody(imAddr, params);
		return response;
		return response;
	}
	}
	
	
@ -113,7 +113,7 @@ public class ImUtil {
		if (reply != null) {
		if (reply != null) {
			imAddr += ("&reply=" + reply);
			imAddr += ("&reply=" + reply);
		}
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
		return response;
	}
	}
	
	
@ -122,7 +122,7 @@ public class ImUtil {
		JSONObject params = new JSONObject();
		JSONObject params = new JSONObject();
		params.put("topic_id", topicId);
		params.put("topic_id", topicId);
		params.put("data", jsonValue);
		params.put("data", jsonValue);
		HttpClientUtil.putBody(imAddr, params);
		httpClientUtil.putBody(imAddr, params);
	}
	}
	
	
	/**
	/**
@ -150,7 +150,7 @@ public class ImUtil {
		if (reply != null) {
		if (reply != null) {
			imAddr += ("&reply=" + reply);
			imAddr += ("&reply=" + reply);
		}
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
		return response;
	}
	}
	
	
@ -175,7 +175,7 @@ public class ImUtil {
		if (reply != null) {
		if (reply != null) {
			imAddr += ("&reply=" + reply);
			imAddr += ("&reply=" + reply);
		}
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
		return response;
	}
	}
	
	
@ -210,7 +210,7 @@ public class ImUtil {
		if (endTime != null) {
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
			imAddr += ("&endTime=" + endTime);
		}
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
		return response;
	}
	}
	
	
@ -243,7 +243,7 @@ public class ImUtil {
		if (endTime != null) {
		if (endTime != null) {
			imAddr += ("&endTime=" + endTime);
			imAddr += ("&endTime=" + endTime);
		}
		}
		String response = HttpClientUtil.get(imAddr, "UTF-8");
		String response = httpClientUtil.get(imAddr, "UTF-8");
		return response;
		return response;
	}
	}
	
	
@ -374,7 +374,7 @@ public class ImUtil {
		if(!StringUtils.isEmpty(oldUserId)){
		if(!StringUtils.isEmpty(oldUserId)){
			params.put("old_user_id", oldUserId);
			params.put("old_user_id", oldUserId);
		}
		}
		return HttpClientUtil.postBody(imAddr, params);
		return httpClientUtil.postBody(imAddr, params);
	}
	}
	/**
	/**
@ -391,7 +391,7 @@ public class ImUtil {
		if(!StringUtils.isEmpty(oldUserId)){
		if(!StringUtils.isEmpty(oldUserId)){
			params.put("old_user_id", oldUserId);
			params.put("old_user_id", oldUserId);
		}
		}
		return HttpClientUtil.postBody(imAddr, params);
		return httpClientUtil.postBody(imAddr, params);
	}
	}
	
	
	/**
	/**
@ -408,7 +408,7 @@ public class ImUtil {
		params.put("session_type", sessionType );
		params.put("session_type", sessionType );
		params.put("message_id", msgId );
		params.put("message_id", msgId );
		params.put("content", content );
		params.put("content", content );
		return HttpClientUtil.postBody(imAddr, params);
		return httpClientUtil.postBody(imAddr, params);
	}
	}
	
	
	/**
	/**
@ -426,7 +426,7 @@ public class ImUtil {
		params.put("end_user", endUser);
		params.put("end_user", endUser);
		params.put("end_user_name", endUserName);
		params.put("end_user_name", endUserName);
		params.put("topic_id", topicId);
		params.put("topic_id", topicId);
		String ret = HttpClientUtil.postBody(imAddr, params);
		String ret = httpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		JSONObject obj = null;
		try {
		try {
			obj = JSON.parseObject(ret);
			obj = JSON.parseObject(ret);
@ -447,7 +447,7 @@ public class ImUtil {
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
		String imAddr = im_host + "api/v2/sessions/" + sessionId + "/participants/" + user;
		JSONObject params = new JSONObject();
		JSONObject params = new JSONObject();
		params.put("user", user + ":" + 0);
		params.put("user", user + ":" + 0);
		HttpClientUtil.putBody(imAddr, params);
		httpClientUtil.putBody(imAddr, params);
	}
	}
	
	
	/**
	/**
@ -466,7 +466,7 @@ public class ImUtil {
		params.put("messages", messages.toString());
		params.put("messages", messages.toString());
		params.put("session_id", sessionId);
		params.put("session_id", sessionId);
		params.put("session_type", sessionType);
		params.put("session_type", sessionType);
		String ret = HttpClientUtil.postBody(imAddr, params);
		String ret = httpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		JSONObject obj = null;
		try {
		try {
			obj = JSON.parseObject(ret);
			obj = JSON.parseObject(ret);
@ -483,7 +483,7 @@ public class ImUtil {
		Boolean re = false;
		Boolean re = false;
		String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
		String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
		JSONObject params = new JSONObject();
		JSONObject params = new JSONObject();
		String ret = HttpClientUtil.get(url, "UTF-8");
		String ret = httpClientUtil.get(url, "UTF-8");
		JSONObject obj = null;
		JSONObject obj = null;
		try {
		try {
			obj = JSON.parseObject(ret);
			obj = JSON.parseObject(ret);
@ -492,7 +492,7 @@ public class ImUtil {
				if (StringUtils.isNoneBlank(sessionStatus)){
				if (StringUtils.isNoneBlank(sessionStatus)){
					String sessionStatusUrl = im_host + "api/v2/sessions/"+sessionId+"/status?status=0&sessionId="+sessionId;
					String sessionStatusUrl = im_host + "api/v2/sessions/"+sessionId+"/status?status=0&sessionId="+sessionId;
					JSONObject object = new JSONObject();
					JSONObject object = new JSONObject();
					String rs = HttpClientUtil.postBody(sessionStatusUrl, object);
					String rs = httpClientUtil.postBody(sessionStatusUrl, object);
				}
				}
				re = true;
				re = true;
			}
			}
@ -507,12 +507,14 @@ public class ImUtil {
	 */
	 */
	public JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
	public JSONObject createSession(JSONObject participants, String sessionType, String sessionName, String sessionId) {
		String imAddr = im_host + "api/v2/sessions";
		String imAddr = im_host + "api/v2/sessions";
		System.out.println(imAddr);
		JSONObject params = new JSONObject();
		JSONObject params = new JSONObject();
		params.put("participants", participants.toString());
		params.put("participants", participants.toString());
		params.put("session_name", sessionName);
		params.put("session_name", sessionName);
		params.put("session_type", sessionType);
		params.put("session_type", sessionType);
		params.put("session_id", sessionId);
		params.put("session_id", sessionId);
		String ret = HttpClientUtil.postBody(imAddr, params);
		System.out.println(params.toString());
		String ret = httpClientUtil.postBody(imAddr, params);
		JSONObject obj = null;
		JSONObject obj = null;
		try {
		try {
			obj = JSON.parseObject(ret);
			obj = JSON.parseObject(ret);
@ -549,7 +551,7 @@ public class ImUtil {
				+ "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
				+ "api/v2/sessions/topic/" + topicId + "/messages?topic_id=" + topicId + "&end=" + startMsgId
				+ "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
				+ "&start=" + (endMsgId == null ? "" : endMsgId) + "&page=" + page + "&pagesize=" + pagesize + "&user=" + uid;
		try {
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			String ret = httpClientUtil.get(url, "UTF-8");
			JSONObject obj = JSON.parseObject(ret);
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException(obj.getString("message"));
				throw new RuntimeException(obj.getString("message"));
@ -565,7 +567,7 @@ public class ImUtil {
	public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
	public JSONArray getSessionMessage(String sessionId, String startMsgId, String endMsgId, int page, int pagesize, String uid) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
		String url = im_host + "api/v2/sessions/" + sessionId + "/messages?session_id=" + sessionId + "&user=" + uid + "&start_message_id=" + startMsgId + "&end_message_id=" + endMsgId + "&page=" + page + "&pagesize=" + pagesize;
		try {
		try {
			String ret = HttpClientUtil.get(url, "UTF-8");
			String ret = httpClientUtil.get(url, "UTF-8");
			JSONArray obj = JSON.parseArray(ret);
			JSONArray obj = JSON.parseArray(ret);
			return obj;
			return obj;
		} catch (Exception e) {
		} catch (Exception e) {
@ -588,7 +590,7 @@ public class ImUtil {
			params.put("user_id", userId);
			params.put("user_id", userId);
			params.put("old_user_id", oldUserId);
			params.put("old_user_id", oldUserId);
			params.put("session_id", sessionId);
			params.put("session_id", sessionId);
			String ret = HttpClientUtil.postBody(url, params);
			String ret = httpClientUtil.postBody(url, params);
			JSONObject obj = JSON.parseObject(ret);
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("人员更换失败!");
				throw new RuntimeException("人员更换失败!");
@ -609,7 +611,7 @@ public class ImUtil {
	 */
	 */
	public JSONObject deleteParticipants(String sessionId,String participants){
	public JSONObject deleteParticipants(String sessionId,String participants){
		String url  = im_host+"api/v2/sessions/"+sessionId+"/participants/"+participants;
		String url  = im_host+"api/v2/sessions/"+sessionId+"/participants/"+participants;
		String rs = HttpClientUtil.doDelete(url,null,null);
		String rs = httpClientUtil.doDelete(url,null,null);
		JSONObject obj = JSONObject.parseObject(rs);
		JSONObject obj = JSONObject.parseObject(rs);
		if (obj.getInteger("status")==-1){
		if (obj.getInteger("status")==-1){
			throw new RuntimeException("删除会话人员失败!");
			throw new RuntimeException("删除会话人员失败!");
@ -628,7 +630,7 @@ public class ImUtil {
	public JSONObject getTopic(String topicId) throws Exception {
	public JSONObject getTopic(String topicId) throws Exception {
		String url = im_host + "api/v2/sessions/topics/" + topicId + "?topic_id=" + topicId;
		String url = im_host + "api/v2/sessions/topics/" + topicId + "?topic_id=" + topicId;
		try {
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			JSONObject obj = JSON.parseObject(ret);
			JSONObject obj = JSON.parseObject(ret);
			if (obj.getInteger("status") == -1) {
			if (obj.getInteger("status") == -1) {
				throw new RuntimeException("获取议题失败!");
				throw new RuntimeException("获取议题失败!");
@ -650,7 +652,7 @@ public class ImUtil {
	public JSONArray getParticipants(String sessionId) {
	public JSONArray getParticipants(String sessionId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		try {
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			return JSON.parseArray(ret);
			return JSON.parseArray(ret);
		} catch (Exception e) {
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
@ -667,7 +669,7 @@ public class ImUtil {
	public JSONArray getSessions(String sessionId) {
	public JSONArray getSessions(String sessionId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		String url = im_host + "api/v2/sessions/" + sessionId + "/participants?session_id=" + sessionId;
		try {
		try {
			String ret = HttpClientUtil.get(url, "utf-8");
			String ret = httpClientUtil.get(url, "utf-8");
			return JSON.parseArray(ret);
			return JSON.parseArray(ret);
		} catch (Exception e) {
		} catch (Exception e) {
			throw new RuntimeException("获取议题失败!");
			throw new RuntimeException("获取议题失败!");
@ -677,7 +679,7 @@ public class ImUtil {
	public JSONObject cleanMessageToRedis(String sessionId){
	public JSONObject cleanMessageToRedis(String sessionId){
		String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
		String url = im_host + "api/v2/message/dataMessage?sessionId="+sessionId;
		try {
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			String ret = httpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
			return JSON.parseObject(ret);
		} catch (Exception e) {
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
			throw new RuntimeException("操作失败!");
@ -687,7 +689,7 @@ public class ImUtil {
	public JSONObject cleanMessageLastFetchTime(String sessionId,String userId){
	public JSONObject cleanMessageLastFetchTime(String sessionId,String userId){
		String url = im_host + "api/v2/message/cleanMessageLastFetchTimeToRedis?sessionId="+sessionId+"&userId="+userId;
		String url = im_host + "api/v2/message/cleanMessageLastFetchTimeToRedis?sessionId="+sessionId+"&userId="+userId;
		try {
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			String ret = httpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
			return JSON.parseObject(ret);
		} catch (Exception e) {
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
			throw new RuntimeException("操作失败!");
@ -704,7 +706,7 @@ public class ImUtil {
	public JSONObject getSingleSessionInfo(String sessionId,String userId){
	public JSONObject getSingleSessionInfo(String sessionId,String userId){
		String url = im_host + "api/v2/sessions/" + sessionId + "/session?user_id=" + userId;
		String url = im_host + "api/v2/sessions/" + sessionId + "/session?user_id=" + userId;
		try {
		try {
			String ret = HttpClientUtil.get(url,"utf-8");
			String ret = httpClientUtil.get(url,"utf-8");
			return JSON.parseObject(ret);
			return JSON.parseObject(ret);
		} catch (Exception e) {
		} catch (Exception e) {
			throw new RuntimeException("操作失败!");
			throw new RuntimeException("操作失败!");
@ -726,7 +728,7 @@ public class ImUtil {
		params.add(new BasicNameValuePair("to", to));
		params.add(new BasicNameValuePair("to", to));
		params.add(new BasicNameValuePair("contentType", contentType));
		params.add(new BasicNameValuePair("contentType", contentType));
		params.add(new BasicNameValuePair("content", content));
		params.add(new BasicNameValuePair("content", content));
		String response = HttpClientUtil.post(imAddr, params, "UTF-8");
		String response = httpClientUtil.post(imAddr, params, "UTF-8");
		return response;
		return response;
	}
	}
	
	
@ -759,7 +761,7 @@ public class ImUtil {
	 */
	 */
	public Integer sessionCountByType(String userid,Integer type,Integer status){
	public Integer sessionCountByType(String userid,Integer type,Integer status){
		String url = im_host + "api/v2/sessions/sessionCountByType?user_id="+userid+"&type="+type+"&status="+status;
		String url = im_host + "api/v2/sessions/sessionCountByType?user_id="+userid+"&type="+type+"&status="+status;
		String ret = HttpClientUtil.get(url,"utf-8");
		String ret = httpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
		JSONObject obj = JSON.parseObject(ret);
		if(obj.getInteger("status") ==200){
		if(obj.getInteger("status") ==200){
			return obj.getInteger("count");
			return obj.getInteger("count");
@ -776,7 +778,7 @@ public class ImUtil {
	 */
	 */
	public Integer SessionsUnreadMessageCount(String userid,String type){
	public Integer SessionsUnreadMessageCount(String userid,String type){
		String url = im_host + "api/v2/sessions/unread_message_count?user_id="+userid+"&type="+type;
		String url = im_host + "api/v2/sessions/unread_message_count?user_id="+userid+"&type="+type;
		String ret = HttpClientUtil.get(url,"utf-8");
		String ret = httpClientUtil.get(url,"utf-8");
		JSONObject obj = JSON.parseObject(ret);
		JSONObject obj = JSON.parseObject(ret);
//		if(obj.getInteger("count") ==200){
//		if(obj.getInteger("count") ==200){
		return obj.getInteger("count");
		return obj.getInteger("count");
@ -784,5 +786,19 @@ public class ImUtil {
//			return 0;
//			return 0;
//		}
//		}
	}
	}
	/**
	 * 获取会话未读消息数量
	 * @param sessionId
	 * @param userId
	 * @return
	 */
	public JSONObject getSessionUnreadMessageCount(String sessionId, String userId) {
		String url = im_host + "api/v2/sessions/" + sessionId + "/unread_message_count?user_id=" + userId;
		try {
			String ret = httpClientUtil.get(url, "utf-8");
			return  JSONObject.parseObject(ret);
		} catch (Exception e) {
			throw new RuntimeException("获取会话成员!sessionId =" + sessionId);
		}
	}
}
}

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

@ -6,177 +6,178 @@ import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;
import java.util.Date;
/**
/**
* 医生基本信息实体
*
* @author Administrator on  2018年09月05日
*
*/
 * 医生基本信息实体
 *
 * @author Administrator on  2018年09月05日
 *
 */
@Entity
@Entity
@Table(name = "base_doctor")
@Table(name = "base_doctor")
public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
    /**
    /**
	 * 密码
	 */
	private String password;
     * 密码
     */
    private String password;
    /**
    /**
	 * 
	 */
	private String salt;
     *
     */
    private String salt;
    /**
    /**
	 * 姓名
	 */
	private String name;
     * 姓名
     */
    private String name;
    /**
    /**
	 * 性别(1男,2女) 用国家标准字典
	 */
	private Integer sex;
     * 性别(1男,2女) 用国家标准字典
     */
    private Integer sex;
    /**
    /**
	 * 医生专长
	 */
	private String expertise;
     * 医生专长
     */
    private String expertise;
    /**
    /**
	 * 医生介绍
	 */
	private String introduce;
     * 医生介绍
     */
    private String introduce;
    /**
    /**
	 *  身份证
	 */
	private String idcard;
     *  身份证
     */
    private String idcard;
    /**
    /**
	 * 生日
	 */
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date birthday;
     * 生日
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date birthday;
    /**
    /**
	 * 头像http地址
	 */
	private String photo;
     * 头像http地址
     */
    private String photo;
    /**
    /**
	 * 手机号
	 */
	private String mobile;
     * 手机号
     */
    private String mobile;
    /**
    /**
	 * 医生二维码
	 */
	private String qrcode;
     * 医生二维码
     */
    private String qrcode;
    /**
    /**
	 * 省代码
	 */
	private String provinceCode;
     * 省代码
     */
    private String provinceCode;
    /**
    /**
	 * 省名称
	 */
	private String provinceName;
     * 省名称
     */
    private String provinceName;
    /**
    /**
	 * 市代码
	 */
	private String cityCode;
     * 市代码
     */
    private String cityCode;
    /**
    /**
	 * 市名称
	 */
	private String cityName;
     * 市名称
     */
    private String cityName;
    /**
    /**
	 * 区县代码
	 */
	private String townCode;
     * 区县代码
     */
    private String townCode;
    /**
    /**
	 * 区县名称
	 */
	private String townName;
     * 区县名称
     */
    private String townName;
    /**
    /**
	 * 街道代码
	 */
	private String streetCode;
     * 街道代码
     */
    private String streetCode;
    /**
    /**
	 * 街道名称
	 */
	private String streetName;
     * 街道名称
     */
    private String streetName;
    /**
    /**
	 * 资格是否认证通过,1是,0否
	 */
	private String iscertified;
     * 资格是否认证通过,1是,0否
     */
    private String iscertified;
    /**
    /**
	 * 是否是名医,1是,0否
	 */
	private Integer isFamous;
     * 是否是名医,1是,0否
     */
    private Integer isFamous;
    /**
    /**
	 * 是否提示设置密码  1 提示过 0未提示
	 */
	private String isPasswordPrompt;
     * 是否提示设置密码  1 提示过 0未提示
     */
    private String isPasswordPrompt;
    /**
    /**
	 * 名称拼音首字母
	 */
	private String spell;
     * 名称拼音首字母
     */
    private String spell;
    /**
    /**
	 * CA证书过期时间
	 */
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	private Date certifiedOvertime;
     * CA证书过期时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    private Date certifiedOvertime;
    /**
    /**
	 * CA证书编号
	 */
	private String certificateNum;
     * CA证书编号
     */
    private String certificateNum;
    /**
    /**
	 * 用户微信openid
	 */
	private String openid;
     * 用户微信openid
     */
    private String openid;
	/**
	 * 职称代码
	 */
	private String jobTitleCode;
    /**
     * 职称代码
     */
    private String jobTitleCode;
	/**
	 * 职称名称
	 */
	private String jobTitleName;
    /**
     * 职称名称
     */
    private String jobTitleName;
    /**
    /**
     * 号别字典
     * 号别字典
     */
     */
    private String chargeType;
    private String chargeType;
    /**
    /**
	 * 作废标识,1正常,0作废
	 */
	private String del;
     * 作废标识,1正常,0作废
     */
    private String del;
    /**
    /**
     * 是否锁定:0可用;1锁定
     * 是否锁定:0可用;1锁定
     */
     */
	private Integer locked;
    private Integer locked;
    /**
    /**
     * 账号是否可用,1为可用;0为不可用
     * 账号是否可用,1为可用;0为不可用
     */
     */
	private Integer enabled;
    private Integer enabled;
    /**
    /**
@ -280,6 +281,54 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
     * 家医咨询号别
     * 家医咨询号别
     */
     */
    private String jyzxChargeType;
    private String jyzxChargeType;
    private String visitTime;
    /**
     * 类型 1社区医生,2助老员, 3教师
     */
    private Integer level;
    private String doctorLat;//医生当前定位地址纬度
    private String doctorLon;//医生当前定位地址经度
    private String doctorLocateAddress;//医生定位地址
    private String levelName;
    private String isSign;
    private Date lastSignTime;
    @Column(name = "is_sign")
    public String getIsSign() {
        return isSign;
    }
    public void setIsSign(String isSign) {
        this.isSign = isSign;
    }
    @Column(name = "last_sign_time")
    public Date getLastSignTime() {
        return lastSignTime;
    }
    public void setLastSignTime(Date lastSignTime) {
        this.lastSignTime = lastSignTime;
    }
    @Transient
    public String getLevelName() {
        return levelName;
    }
    public void setLevelName(String levelName) {
        this.levelName = levelName;
    }
    @Column(name = "visit_time")
    public String getVisitTime() {
        return visitTime;
    }
    public void setVisitTime(String visitTime) {
        this.visitTime = visitTime;
    }
    @Column(name = "jyzx_charge_type")
    @Column(name = "jyzx_charge_type")
    public String getJyzxChargeType() {
    public String getJyzxChargeType() {
        return jyzxChargeType;
        return jyzxChargeType;
@ -324,7 +373,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.password = password;
        this.password = password;
    }
    }
	@Column(name = "salt")
    @Column(name = "salt")
    public String getSalt() {
    public String getSalt() {
        return salt;
        return salt;
    }
    }
@ -332,7 +381,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.salt = salt;
        this.salt = salt;
    }
    }
	@Column(name = "name")
    @Column(name = "name")
    public String getName() {
    public String getName() {
        return name;
        return name;
    }
    }
@ -340,7 +389,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.name = name;
        this.name = name;
    }
    }
	@Column(name = "sex")
    @Column(name = "sex")
    public Integer getSex() {
    public Integer getSex() {
        return sex;
        return sex;
    }
    }
@ -348,7 +397,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.sex = sex;
        this.sex = sex;
    }
    }
	@Column(name = "expertise")
    @Column(name = "expertise")
    public String getExpertise() {
    public String getExpertise() {
        return expertise;
        return expertise;
    }
    }
@ -356,7 +405,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.expertise = expertise;
        this.expertise = expertise;
    }
    }
	@Column(name = "introduce")
    @Column(name = "introduce")
    public String getIntroduce() {
    public String getIntroduce() {
        return introduce;
        return introduce;
    }
    }
@ -364,7 +413,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.introduce = introduce;
        this.introduce = introduce;
    }
    }
	@Column(name = "idcard")
    @Column(name = "idcard")
    public String getIdcard() {
    public String getIdcard() {
        return idcard;
        return idcard;
    }
    }
@ -372,7 +421,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.idcard = idcard;
        this.idcard = idcard;
    }
    }
	@Column(name = "birthday")
    @Column(name = "birthday")
    public Date getBirthday() {
    public Date getBirthday() {
        return birthday;
        return birthday;
    }
    }
@ -380,7 +429,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.birthday = birthday;
        this.birthday = birthday;
    }
    }
	@Column(name = "photo")
    @Column(name = "photo")
    public String getPhoto() {
    public String getPhoto() {
        return photo;
        return photo;
    }
    }
@ -388,7 +437,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.photo = photo;
        this.photo = photo;
    }
    }
	@Column(name = "mobile")
    @Column(name = "mobile")
    public String getMobile() {
    public String getMobile() {
        return mobile;
        return mobile;
    }
    }
@ -396,7 +445,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.mobile = mobile;
        this.mobile = mobile;
    }
    }
	@Column(name = "qrcode")
    @Column(name = "qrcode")
    public String getQrcode() {
    public String getQrcode() {
        return qrcode;
        return qrcode;
    }
    }
@ -404,7 +453,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.qrcode = qrcode;
        this.qrcode = qrcode;
    }
    }
	@Column(name = "province_code")
    @Column(name = "province_code")
    public String getProvinceCode() {
    public String getProvinceCode() {
        return provinceCode;
        return provinceCode;
    }
    }
@ -412,7 +461,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.provinceCode = provinceCode;
        this.provinceCode = provinceCode;
    }
    }
	@Column(name = "province_name")
    @Column(name = "province_name")
    public String getProvinceName() {
    public String getProvinceName() {
        return provinceName;
        return provinceName;
    }
    }
@ -420,7 +469,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.provinceName = provinceName;
        this.provinceName = provinceName;
    }
    }
	@Column(name = "city_code")
    @Column(name = "city_code")
    public String getCityCode() {
    public String getCityCode() {
        return cityCode;
        return cityCode;
    }
    }
@ -428,7 +477,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.cityCode = cityCode;
        this.cityCode = cityCode;
    }
    }
	@Column(name = "city_name")
    @Column(name = "city_name")
    public String getCityName() {
    public String getCityName() {
        return cityName;
        return cityName;
    }
    }
@ -436,7 +485,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.cityName = cityName;
        this.cityName = cityName;
    }
    }
	@Column(name = "town_code")
    @Column(name = "town_code")
    public String getTownCode() {
    public String getTownCode() {
        return townCode;
        return townCode;
    }
    }
@ -444,7 +493,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.townCode = townCode;
        this.townCode = townCode;
    }
    }
	@Column(name = "town_name")
    @Column(name = "town_name")
    public String getTownName() {
    public String getTownName() {
        return townName;
        return townName;
    }
    }
@ -452,7 +501,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.townName = townName;
        this.townName = townName;
    }
    }
	@Column(name = "street_code")
    @Column(name = "street_code")
    public String getStreetCode() {
    public String getStreetCode() {
        return streetCode;
        return streetCode;
    }
    }
@ -460,7 +509,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.streetCode = streetCode;
        this.streetCode = streetCode;
    }
    }
	@Column(name = "street_name")
    @Column(name = "street_name")
    public String getStreetName() {
    public String getStreetName() {
        return streetName;
        return streetName;
    }
    }
@ -468,7 +517,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.streetName = streetName;
        this.streetName = streetName;
    }
    }
	@Column(name = "iscertified")
    @Column(name = "iscertified")
    public String getIscertified() {
    public String getIscertified() {
        return iscertified;
        return iscertified;
    }
    }
@ -476,7 +525,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.iscertified = iscertified;
        this.iscertified = iscertified;
    }
    }
	@Column(name = "is_famous")
    @Column(name = "is_famous")
    public Integer getIsFamous() {
    public Integer getIsFamous() {
        return isFamous;
        return isFamous;
    }
    }
@ -484,7 +533,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.isFamous = isFamous;
        this.isFamous = isFamous;
    }
    }
	@Column(name = "is_password_prompt")
    @Column(name = "is_password_prompt")
    public String getIsPasswordPrompt() {
    public String getIsPasswordPrompt() {
        return isPasswordPrompt;
        return isPasswordPrompt;
    }
    }
@ -492,7 +541,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.isPasswordPrompt = isPasswordPrompt;
        this.isPasswordPrompt = isPasswordPrompt;
    }
    }
	@Column(name = "spell")
    @Column(name = "spell")
    public String getSpell() {
    public String getSpell() {
        return spell;
        return spell;
    }
    }
@ -500,7 +549,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.spell = spell;
        this.spell = spell;
    }
    }
	@Column(name = "certified_overtime")
    @Column(name = "certified_overtime")
    public Date getCertifiedOvertime() {
    public Date getCertifiedOvertime() {
        return certifiedOvertime;
        return certifiedOvertime;
    }
    }
@ -508,7 +557,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.certifiedOvertime = certifiedOvertime;
        this.certifiedOvertime = certifiedOvertime;
    }
    }
	@Column(name = "certificate_num")
    @Column(name = "certificate_num")
    public String getCertificateNum() {
    public String getCertificateNum() {
        return certificateNum;
        return certificateNum;
    }
    }
@ -516,7 +565,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.certificateNum = certificateNum;
        this.certificateNum = certificateNum;
    }
    }
	@Column(name = "openid")
    @Column(name = "openid")
    public String getOpenid() {
    public String getOpenid() {
        return openid;
        return openid;
    }
    }
@ -524,7 +573,7 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
        this.openid = openid;
        this.openid = openid;
    }
    }
	@Column(name = "del")
    @Column(name = "del")
    public String getDel() {
    public String getDel() {
        return del;
        return del;
    }
    }
@ -736,4 +785,37 @@ public class BaseDoctorDO extends UuidIdentityEntityWithOperator {
    public void setXtfzChargeType(String xtfzChargeType) {
    public void setXtfzChargeType(String xtfzChargeType) {
        this.xtfzChargeType = xtfzChargeType;
        this.xtfzChargeType = xtfzChargeType;
    }
    }
    @Column(name = "doctor_level")
    public Integer getLevel() {
        return level;
    }
    public void setLevel(Integer level) {
        this.level = level;
    }
    public String getDoctorLat() {
        return doctorLat;
    }
    public void setDoctorLat(String doctorLat) {
        this.doctorLat = doctorLat;
    }
    public String getDoctorLon() {
        return doctorLon;
    }
    public void setDoctorLon(String doctorLon) {
        this.doctorLon = doctorLon;
    }
    public String getDoctorLocateAddress() {
        return doctorLocateAddress;
    }
    public void setDoctorLocateAddress(String doctorLocateAddress) {
        this.doctorLocateAddress = doctorLocateAddress;
    }
}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -57,6 +57,9 @@ public class RehabilitationRequestMapping {
        public static final String updatePatientImgById = "/updatePatientImgById";
        public static final String updatePatientImgById = "/updatePatientImgById";
        public static final String findServicePackageItem = "/findServicePackageItem";
        public static final String findServicePackageItem = "/findServicePackageItem";
        public static final String findServiceItemInBase = "/findServiceItemInBase";
        public static final String findServiceItemInBase = "/findServiceItemInBase";
        public static final String findDoctorByTeams = "/findDoctorByTeams";
        public static final String findDoctorTeams = "/findDoctorTeams";
        public static final String findDoctorPatients = "/findDoctorPatients";
    }
    }
    public static class PatientRehabilitationManage {
    public static class PatientRehabilitationManage {

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

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

+ 9 - 0
svr/svr-rehabilitation/pom.xml

@ -113,6 +113,15 @@
			<artifactId>im-service</artifactId>
			<artifactId>im-service</artifactId>
			<version>2.0.0</version>
			<version>2.0.0</version>
		</dependency>
		</dependency>
		<dependency>
			<groupId>org.springside</groupId>
			<artifactId>springside-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springside</groupId>
			<artifactId>springside-core</artifactId>
			<version>4.2.3-GA</version>
		</dependency>
	</dependencies>
	</dependencies>
	<build>
	<build>

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

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

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

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

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

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

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 318 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/RehabilitationPlanController.java


+ 72 - 4
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitaionInfoController.java

@ -1,10 +1,13 @@
package com.yihu.rehabilitation.controller.doctor;
package com.yihu.rehabilitation.controller.doctor;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationAdviceDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.service.RehabilitationInfoService;
import com.yihu.rehabilitation.service.RehabilitationInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperation;
@ -14,6 +17,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.List;
@RestController
@RestController
@ -28,6 +32,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.createAdvice, method = RequestMethod.POST)
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.createAdvice, method = RequestMethod.POST)
    @ApiOperation("创建/编辑康复建议模板")
    @ApiOperation("创建/编辑康复建议模板")
    @ObserverRequired
    public Envelop createAdvice(@ApiParam(name = "doctorCode", value = "医生code", required = false)
    public Envelop createAdvice(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                               @RequestParam(value = "doctorCode", required = false) String doctorCode,
                               @RequestParam(value = "doctorCode", required = false) String doctorCode,
                                @ApiParam(name = "code", value = "模板code")
                                @ApiParam(name = "code", value = "模板code")
@ -51,6 +56,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.deleteAdvice, method = RequestMethod.POST)
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationInfo.deleteAdvice, method = RequestMethod.POST)
    @ApiOperation("删除康复建议模板")
    @ApiOperation("删除康复建议模板")
    @ObserverRequired
    public Envelop deleteAdvice(@ApiParam(name = "id", value = "模板id")
    public Envelop deleteAdvice(@ApiParam(name = "id", value = "模板id")
                               @RequestParam(value = "id", required = false) Long id) {
                               @RequestParam(value = "id", required = false) Long id) {
@ -73,7 +79,7 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
                doctorCode = getUID();
                doctorCode = getUID();
            }
            }
            List<RehabilitationAdviceDO> list = rehabilitationInfoService.getAdviceListByDoctor(doctorCode);
            List<RehabilitationAdviceDO> list = rehabilitationInfoService.getAdviceListByDoctor(doctorCode);
            return success("操作成功");
            return success("操作成功",list);
        } catch (Exception e) {
        } catch (Exception e) {
           e.printStackTrace();
           e.printStackTrace();
            return failed(e.getMessage());
            return failed(e.getMessage());
@ -84,15 +90,77 @@ public class DoctorRehabilitaionInfoController extends EnvelopRestEndpoint {
    @ApiOperation("发送微信模板提醒签约消息")
    @ApiOperation("发送微信模板提醒签约消息")
    public Envelop sendWxTemplate(@ApiParam(name = "patient", value = "居民code", required = false)
    public Envelop sendWxTemplate(@ApiParam(name = "patient", value = "居民code", required = false)
                                 @RequestParam(value = "patient", required = false)String patient,
                                 @RequestParam(value = "patient", required = false)String patient,
                                 @ApiParam(name = "patient", value = "居民code", required = false)
                                 @RequestParam(value = "patient", required = false)String wxId){
                                 @ApiParam(name = "wxId", value = "微信id", required = false)
                                 @RequestParam(value = "wxId", required = false)String wxId,
                                  @ApiParam(name = "scene", value = "模板code", required = false)
                                      @RequestParam(value = "scene", required = false)String scene){
        try {
        try {
            rehabilitationInfoService.sendSFWxTemplate(patient,wxId);
            rehabilitationInfoService.sendSFWxTemplate(patient,wxId,scene);
            return success("发送成功");
            return success("发送成功");
        } catch (Exception e) {
        } catch (Exception e) {
           e.printStackTrace();
           e.printStackTrace();
            return failed("发送失败");
            return failed("发送失败");
        }
        }
    }
    }
    @RequestMapping(value = "createMedicalRecords", method = RequestMethod.POST)
    @ApiOperation("添加编辑住院病历")
    @ObserverRequired
    public Envelop createMedicalRecords(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                       @RequestParam(value = "doctorCode", required = false) String doctorCode,
                                       @ApiParam(name = "patient", value = "居民code")
                                       @RequestParam String patient,
                                       @ApiParam(name = "patientName", value = "居民姓名")
                                       @RequestParam String patientName,
                                       @ApiParam(name = "jsonData", value = "住院病历相关数据")
                                       @RequestParam(value = "jsonData", required = true) String jsonData,
                                       @ApiParam(name = "id", value = "模板id,编辑时传入")
                                       @RequestParam(value = "id", required = false) String id) {
        try {
            if (StringUtils.isBlank(doctorCode)) {
                doctorCode = getUID();
            }
            System.out.println("111doctorid"+doctorCode);
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO = objectMapper.readValue(jsonData, PatientMedicalRecordsDO.class);
            System.out.println("实体转换完成");
            return success( "添加成功", rehabilitationInfoService.createMedicalRecords(doctorCode, patient, patientName, patientMedicalRecordsDO, id));
        } catch (Exception e) {
            e.printStackTrace();
            return failed(e.getMessage());
        }
    }
    @RequestMapping(value = "getRehabilitationPatientList", method = RequestMethod.GET)
    @ApiOperation("获取康复下转居民列表")
    public Envelop getRehabilitationPatientList(@ApiParam(name = "idcard", value = "身份证", required = false)
                                               @RequestParam(value = "idcard", required = false) String idcard,
                                               @ApiParam(name = "isTurnDown", value = "是否已下转 -2:未下转未家签,-1未下转 0未下转全部,;1已下转(未接收);2已下转(已接收);3已下转全部;03已下转全部+未下转全部", defaultValue = "0",required = false)
                                               @RequestParam(value = "isTurnDown", required = false,defaultValue = "3") String isTurnDown,
                                                @ApiParam(name = "doctor", value = "",required = false)
                                                    @RequestParam(value = "doctor", required = false,defaultValue = "3") String doctor) {
        try {
            JSONObject result = rehabilitationInfoService.getRehabilitationPatientList(idcard, doctor,isTurnDown);
            return success( "请求成功", result);
        } catch (Exception e) {
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "/getIcd10Info", method = RequestMethod.GET)
    @ApiOperation(value = "获取诊断结果")
    public Envelop getIcd10Info(@RequestParam(required = false)
                                @ApiParam(value = "诊断结果关键字", name = "nameKey") String nameKey,
                                @ApiParam(value = "页码", name = "page",defaultValue = "1",required = true)
                                @RequestParam(value = "page") Integer page,
                                @ApiParam(value = "每页数目", name = "pageSize",defaultValue = "15",required = true)
                                @RequestParam(value = "pageSize") Integer pageSize) {
        try {
            return success("操作成功!", rehabilitationInfoService.getIcd10Info(nameKey, page, pageSize).toString());
        } catch (Exception e) {
            return failed( "查询失败!");
        }
    }
}
}

+ 571 - 2
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationManageController.java

@ -1,6 +1,10 @@
package com.yihu.rehabilitation.controller.doctor;
package com.yihu.rehabilitation.controller.doctor;
import com.netflix.discovery.converters.Auto;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.rehabilitation.RehabilitationguidancePatientDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.Envelop;
@ -10,17 +14,22 @@ import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.service.RehabilitationGuidanceService;
import com.yihu.rehabilitation.service.RehabilitationManageService;
import com.yihu.rehabilitation.service.RehabilitationManageService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.service.message.RehabilitationMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
import java.util.*;
/**
/**
 * Created by 刘文彬 on 2018/8/30.
 * Created by 刘文彬 on 2018/8/30.
@ -40,6 +49,12 @@ public class DoctorRehabilitationManageController extends EnvelopRestEndpoint {
    private BasePatientDao basePatientDao;
    private BasePatientDao basePatientDao;
    @Autowired
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RehabilitationMessageService rehabilitationMessageService;
    @Autowired
    private RehabilitationGuidanceService rehabilitationGuidanceService;
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.findRehabilitationPlanList, method = RequestMethod.GET)
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.findRehabilitationPlanList, method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划列表")
    @ApiOperation("康复管理-康复计划列表")
@ -84,6 +99,7 @@ public class DoctorRehabilitationManageController extends EnvelopRestEndpoint {
            return rehabilitationManageService.findRehabilitationPlanDetailList(doctorCode,patientCode);
            return rehabilitationManageService.findRehabilitationPlanDetailList(doctorCode,patientCode);
        } catch (Exception e) {
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("请求失败");
            return ObjEnvelop.getError("请求失败");
        }
        }
    }
    }
@ -112,7 +128,59 @@ public class DoctorRehabilitationManageController extends EnvelopRestEndpoint {
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
        }
    }
    }
    @GetMapping("calendarPlanDetailBypatient")
    @ApiOperation("康复管理-康复计划按日历展示")
    public ObjEnvelop calendarPlanDetailBypatient(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                                      @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                                  @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                                      @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                                  @ApiParam(name = "patient", value = "患者code", required = true)
                                                      @RequestParam(value = "patient", required = true)String patient,
                                                  @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                                      @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                                  @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                                      @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                                  @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                                      @RequestParam(value = "status", required = false)Integer status,
                                                  @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                                      @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getUID();
            }
            return rehabilitationManageService.calendarPlanDetailByPatient(executeStartTime,executeEndTime,patient,searchTask,status,doctorCode,"1");
        } catch (Exception e) {
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "calendarPlanDetailListBypatient", method = RequestMethod.GET)
    @ApiOperation("康复管理--某患者的康复计划按列表展示")
    public ObjEnvelop calendarPlanDetailListBypatient(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                                  @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                                  @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                                  @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                                  @ApiParam(name = "patient", value = "患者code", required = true)
                                                  @RequestParam(value = "patient", required = true)String patient,
                                                  @ApiParam(name = "searchTask", value = "快速查找任务:(1电话/短信关怀,2康复咨询,3健康监测,4上门服务,5康复指导,6康复随访,7康复复诊)", required = false)
                                                  @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                                  @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                                  @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                                  @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                                  @RequestParam(value = "status", required = false)Integer status,
                                                  @ApiParam(name="taskExecutor",value = "任务执行人:0全部;1我的任务:2他人任务",required = false)
                                                  @RequestParam(value = "taskExecutor",required = false,defaultValue = "0")String taskExecutor){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getUID();
            }
            return rehabilitationManageService.calendarPlanDetailListByPatient(executeStartTime,executeEndTime,patient,searchTask,status,doctorCode,taskExecutor);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError( "请求失败");
        }
    }
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.calendarPlanDetailList, method = RequestMethod.GET)
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationManage.calendarPlanDetailList, method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划按列表展示")
    @ApiOperation("康复管理-康复计划按列表展示")
    public ObjEnvelop calendarPlanDetailList(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
    public ObjEnvelop calendarPlanDetailList(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
@ -412,4 +480,505 @@ public class DoctorRehabilitationManageController extends EnvelopRestEndpoint {
            return MixEnvelop.getError( e.getMessage());
            return MixEnvelop.getError( e.getMessage());
        }
        }
    }
    }
    @RequestMapping(value = "selectAllPlaneByPatient",method = RequestMethod.GET)
    @ApiOperation("获取居民所有康复计划")
    public Envelop getPatientAllRehabilitationPlan(@ApiParam(name = "patient",value = "居民Code", required = true)
                                                  @RequestParam(value = "patient",required = true)String patient){
        try {
            return success("获取成功",  rehabilitationManageService.getPatientAllRehabilitationPlan(patient));
        }catch (Exception e){
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectByGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据计划查询指导留言")
    public Envelop selectByGuidance(@ApiParam(name = "planId", value = "计划id", required = false)
                                   @RequestParam(value = "planId", required = true)String planId,
                                   @ApiParam(name = "itemCode", value = "服务项目code", required = true)
                                   @RequestParam(value = "itemCode", required = true)String itemCode){
        try {
            List<Map<String,Object>> mapList = rehabilitationManageService.selectByGuidance(planId,itemCode);
            return success("获取成功",  mapList);
        } catch (Exception e) {
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "manageAllPlanByPatient",method = RequestMethod.POST)
    @ApiOperation("一键确认管理居民所有的康复计划")
    public Envelop manageAllPlanByPatient(@ApiParam(name="patient",value = "患者code",required = true)
                                         @RequestParam(value = "patient",required = true)String patient){
        try {
            return  success("操作成功",rehabilitationManageService.manageAllPlanByPatient(patient,getUID()));
        }catch (Exception e){
            return failed( "请求失败");
        }
    }
    @PostMapping(value = "planDetailAfterCall")
    @ApiOperation(value = "康复管理-电话关怀拨打后生成记录对应怪坏记录")
    public MixEnvelop<RehabilitationOperateRecordsDO,RehabilitationOperateRecordsDO> planDetailAfterCall(
            @ApiParam(name = "planDetailId", value = "planDetailId", required = false)
            @RequestParam(value = "planDetailId", required = false)String planDetailId,
            @ApiParam(name = "doctorCode", value = "doctorCode", required = false)
            @RequestParam(value = "doctorCode", required = false)String doctorCode,
            @ApiParam(name = "doctorName", value = "doctorName", required = false)
            @RequestParam(value = "doctorName", required = false)String  doctorName){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("doctorCode",doctorCode);
        jsonObject.put("doctorName",doctorName);
        jsonObject.put("rehabilitationDetailId",planDetailId);
        try {
            return MixEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationManageService.planDetailAfterCall(jsonObject.toString()));
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "/dailyJobSendMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划每天8点,16点发送服务进展的job")
    @ObserverRequired
    public Envelop dailyJobSendMessage(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                      @RequestParam(value = "startTime", required = true)String startTime,
                                      @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                      @RequestParam(value = "endTime", required = true)String endTime,
                                      @ApiParam(name = "type", value = "8点:23,16点:22", required = true)
                                      @RequestParam(value = "type", required = true)Integer type){
        try {
            rehabilitationManageService.dailyJobSendMessage(startTime,endTime,type);
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "/tomorrowJobSendMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划每天15点发送明天服务定时提醒的job")
    @ObserverRequired
    public Envelop tomorrowJobSendMessage(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                         @RequestParam(value = "startTime", required = true)String startTime,
                                         @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                         @RequestParam(value = "endTime", required = true)String endTime,
                                         @ApiParam(name = "type", value = "15点:23", required = true)
                                         @RequestParam(value = "type", required = true)Integer type){
        try {
            rehabilitationManageService.tomorrowJobSendMessage(startTime,endTime,type);
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "/dailyByJobSendMessage", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划每15分钟服务进展提醒")
    @ObserverRequired
    public Envelop dailyByJobSendMessage(@ApiParam(name = "startTime", value = "开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                        @RequestParam(value = "startTime", required = true)String startTime,
                                        @ApiParam(name = "endTime", value = "结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = true)
                                        @RequestParam(value = "endTime", required = true)String endTime,
                                        @ApiParam(name = "type", value = "15分钟,22", required = true)
                                        @RequestParam(value = "type", required = true)Integer type){
        try {
            rehabilitationManageService.dailyByJobSendMessage(startTime,endTime,type);
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "/dailyJobReserve", method = RequestMethod.POST)
    @ApiOperation("康复管理-10天、7天、5天、当天(0)康复服务预约复诊通知")
    @ObserverRequired
    public Envelop dailyJobReserve(@ApiParam(name = "num", value = "10天、7天、5天、当天康复服务预约复诊通知", required = false)
                                  @RequestParam(value = "num", required = false)Integer num){
        try {
            if(num!=null){
                rehabilitationManageService.dailyJobReserve(num,20);
            }else{
                Integer[] days = {10,7,5,0};
                for(Integer one : days){
                    rehabilitationManageService.dailyJobReserve(one,20);
                }
            }
            return success( "发送成功");
        } catch (Exception e) {
            return failed( "发送失败");
        }
    }
    @RequestMapping(value = "selectByMedicalCode", method = RequestMethod.GET)
    @ApiOperation("获取医院病历")
    public Envelop selectByMedicalCode(@ApiParam(name = "medical", value = "住院code", required = true)
                                      @RequestParam(value = "medical", required = true)String medical){
        try {
            List<PatientMedicalRecordsDO> result = rehabilitationManageService.selectByMedicalCode(medical);
            try {
                String sql = "UPDATE `wlyy_patient_medical_records_rehabilitation` SET `doctor_read_status`='1' WHERE (`code`='"+medical+"') ";
                jdbcTemplate.update(sql);
            }catch (Exception e){
                e.printStackTrace();
            }
            return success("操作成功", result);
        } catch (Exception e) {
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "getPlanDetailForModifing",method = RequestMethod.GET)
    @ApiOperation(value = "根据planId、模板id获取计划列表")
    public Envelop getPlanDetailForModifing(@ApiParam(name = "planId",value = "康复计划id",required = true)
                                           @RequestParam(value = "planId",required = true) String planId,
                                           @ApiParam(name = "templateId",value = "模板Id,不传默认为系统模板",required = false)
                                           @RequestParam(value = "templateId",required = false) String templateId){
        try {
            return success("查询成功",rehabilitationManageService.getPlanDetailForModifing(planId, templateId));
        }catch (Exception e){
            return failed("查询失败");
        }
    }
    @RequestMapping(value = "selectPlanServerDoctor", method = RequestMethod.POST)
    @ApiOperation("康复管理-康复计划的服务医生")
    public Envelop selectPlanServerDoctor(@ApiParam(name = "planId", value = "康复计划ID")@RequestParam(value = "planId", required = true)String planId){
        try {
            String doctorCode = getUID();
            return success("查询成功",rehabilitationManageService.selectPlanServerDoctor(planId,doctorCode));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "查询失败");
        }
    }
    @RequestMapping(value = "selectBySpecialistDoctor", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取签约专科居民")
    public String selectBySpecialistDoctor(@ApiParam(name = "doctorCode", value = "医生code", required = false)
                                           @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                           @ApiParam(name = "doctorType", value = "医生类型(1专科2家医)", required = false)
                                           @RequestParam(value = "doctorType", required = false)String doctorType,
                                           @ApiParam(name = "patientInfo", value = "身份证或者姓名", required = false)
                                           @RequestParam(value = "patientInfo", required = false)String patientInfo,
                                           @ApiParam(name = "diseaseCode", value = "疾病类型code", required = false)
                                           @RequestParam(value = "diseaseCode", required = false)String diseaseCode,
                                           @ApiParam(name = "level", value = "1市2区3社区", required = false)
                                           @RequestParam(value = "level", required = false)String level,
                                           @ApiParam(name = "area", value = "区域", required = false)
                                           @RequestParam(value = "area", required = false)String area,
                                           @ApiParam(name = "page", value = "第几页,从1开始", required = true)
                                           @RequestParam(value = "page", required = false,defaultValue = "1")Integer page,
                                           @ApiParam(name = "pageSize", value = "每页分页大小", required = true)
                                           @RequestParam(value = "pageSize", required = false,defaultValue = "10")Integer pageSize,
                                           @ApiParam(name = "filterPlan", value = "是否过滤康复计划,1过滤,0或者放空不过滤", required = false)
                                           @RequestParam(value = "filterPlan", required = false)String filterPlan,
                                           @ApiParam(name = "turnDownState", value = "下转状态 0全部;1已下转;2已接受;3未下转", required = false)
                                           @RequestParam(value="turnDownState", required = false,defaultValue = "0")String turnDownState
    ) {
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getUID();
            }
            JSONObject result = rehabilitationManageService.selectBySpecialistDoctor1(level,area,doctorCode,diseaseCode,page,pageSize,doctorType,patientInfo,filterPlan,turnDownState);
            JSONArray showList = result.getJSONArray("showList");
            JSONObject turnDownStateObj = result.getJSONObject("turnDownState");
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "获取成功");
            json.put("data",showList);
            json.put("data2",turnDownStateObj);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败";
        }
    }
    @RequestMapping(value = "createSpecialDoctorQrCode", method = RequestMethod.POST)
    @ApiOperation("康复管理-生成康复下转专科医生二维码")
    @ObserverRequired
    public Envelop createSpecialDoctorQrCode(
            @ApiParam(name = "doctorCode", value = "医生code")@RequestParam(value = "doctorCode", required = true)String doctorCode,
            @ApiParam(name = "teamCode", value = "团队CODE")@RequestParam(value = "teamCode", required = true)String teamCode,
            @ApiParam(name = "teamName", value = "团队名称")@RequestParam(value = "teamName", required = true)String teamName
    ){
        try {
            return success("获取二维码成功!", rehabilitationManageService.createSpecialDoctorQrCode(doctorCode,teamCode,teamName));
        } catch (Exception e) {
            return failed( "请求二维码失败");
        }
    }
    @RequestMapping(value = "selectAllCompleteServiceItemsByPatient",method = RequestMethod.GET)
    @ApiOperation("康复计划主页动态")
    public Envelop selectAllCompleteServiceItemsByPatient(@ApiParam(name = "patient",value = "居民Code", required = true)
                                                         @RequestParam(value = "patient",required = true)String patient){
        try {
            return success("获取成功", rehabilitationManageService.selectAllCompleteServiceItemsByPatient(patient));
        }catch (Exception e){
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "calendarPlanDetailItems", method = RequestMethod.GET)
    @ApiOperation("康复管理-康复计划服务项目按列表展示")
    public Envelop calendarPlanDetailItems(@ApiParam(name = "executeStartTime", value = "日历开始时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                          @RequestParam(value = "executeStartTime", required = false)String executeStartTime,
                                          @ApiParam(name = "executeEndTime", value = "日历结束时间(格式:yyyy-MM-dd HH:mm:ss)", required = false)
                                          @RequestParam(value = "executeEndTime", required = false)String executeEndTime,
                                          @ApiParam(name = "planId", value = "计划id", required = true)
                                          @RequestParam(value = "planId", required = true)String planId,
                                          @ApiParam(name = "searchTask", value = "快速查找任务:(1、我的任务,2、健康教育,3、健康指导,4、随访,5、复诊)", required = false)
                                          @RequestParam(value = "searchTask", required = false)Integer searchTask,
                                          @ApiParam(name = "doctorCode", value = "医生code(专科医生、家庭医生)", required = false)
                                          @RequestParam(value = "doctorCode", required = false)String doctorCode,
                                          @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status){
        try {
            if(!StringUtils.isNotEmpty(doctorCode)){
                doctorCode = getUID();
            }
            List<Map<String,Object>> result = rehabilitationManageService.calendarPlanDetailItems(executeStartTime,executeEndTime,planId,searchTask,status,doctorCode);
            return success( "获取成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "confirmManage", method = RequestMethod.GET)
    @ApiOperation("康复管理-确认管理")
    public Envelop confirmManage(@ApiParam(name = "doctor", value = "签约医生code", required = true)
                                @RequestParam(value = "doctor", required = true) String signDoctor,
                                @ApiParam(name = "patient", value = "居民code", required = true)
                                @RequestParam(value = "patient", required = true) String patient,
                                @ApiParam(name = "specialist", value = "专医code", required = true)
                                @RequestParam(value = "specialist", required = true) String specialist,
                                @ApiParam(name = "relationId", value = "签约关系id", required = true)
                                @RequestParam(value = "relationId", required = false) String relationId,
                                @ApiParam(name = "planId", value = "计划id", required = true)
                                @RequestParam(value = "planId", required = false) String planId) {
        try {
            rehabilitationManageService.confirmManage(patient,signDoctor,specialist,relationId,planId);
            return success("请求成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectByPlanDetaiId", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取操作记录")
    public Envelop selectByPlanDetaiId(@ApiParam(name = "patient", value = "居民code", required = true)
                                      @RequestParam(value = "patient", required = false)String patient,
                                      @ApiParam(name = "planId", value = "计划id", required = true)
                                      @RequestParam(value = "planId", required = true)String planId,
                                      @ApiParam(name = "code", value = "服务项目code", required = true)
                                      @RequestParam(value = "code", required = true)String code,
                                      @ApiParam(name = "page", value = "", required = false)
                                      @RequestParam(value = "page", required = false)Integer page,
                                      @ApiParam(name = "pagesize", value = "", required = false)
                                      @RequestParam(value = "pagesize", required = false)Integer pagesize){
        try {
            return success("获取成功",  rehabilitationManageService.selectByPlanDetaiId(patient,planId,code,page,pagesize).toString());
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    /*@GetMapping(value = "selectRelationCode")
    @ResponseBody
    @ApiOperation("业务关联code")
    public Envelop selectRelationCode(@ApiParam(name = "relationCode", value = "业务关联code",required = true)
                                     @RequestParam String relationCode) {
        try {
            return success("请求成功!",wlyyDoorServiceOrderService.selectRelationCode(relationCode));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }*/
    @RequestMapping(value = "getServiceItemList", method = RequestMethod.GET)
    @ApiOperation("康复管理-获取服务项目列表")
    public Envelop getServiceItemList(@ApiParam(name = "name", value = "服务项目名称", required = false)
                                     @RequestParam(value = "name", required = false) String name) {
        try {
            return success( "请求成功!", rehabilitationManageService.getServiceItemList(name));
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @ApiOperation("获取居民最近的一次住院病历")//wlyy_patient_medical_records_rehabilitation
    @RequestMapping(value = "getNewRehabilitation", method = RequestMethod.GET)
    public Envelop getNewRehabilitation(
            @ApiParam(name = "patientCode", value = "居民code", required = true)
            @RequestParam(value = "patientCode", required = true)String patientCode){
        try {
            List<PatientMedicalRecordsDO> result = rehabilitationManageService.getNewRehabilitation(patientCode,getUID());
            return success("获取成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectPlanByPatient", method = RequestMethod.GET)
    @ApiOperation("康复管理-根据居民code查找康复计划")
    public Envelop calendarPlanDetailItems(@ApiParam(name = "patient", value = "居民code", required = false)
                                          @RequestParam(value = "patient", required = false)String patient,
                                          @ApiParam(name = "status", value = "任务状态(0未完成,1已完成,2已预约)", required = false)
                                          @RequestParam(value = "status", required = false)Integer status,
                                          @ApiParam(name = "planId", value = "计划id", required = false)
                                          @RequestParam(value = "planId", required = false)String planId){
        try {
            List<Map<String,Object>> result = rehabilitationManageService.selectPlanByPatient(patient,status,planId,getUID());
            return success("获取成功",  result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    /**
     *
     * @param patient 居民code
     * @param doctor 专科医生code
     * @param type 1康复指导2康复下转3复诊提醒4上门服务提醒5家签提醒
     * @param relationCode 业务关联code
     * @param planId 计划id
     * @return
     */
    @RequestMapping(value = "sendSpecialistWeixinMessage", method = RequestMethod.GET)
    @ApiOperation("康复管理-发送微信模板消息")
    @ObserverRequired
    public Envelop sendSpecialistWeixinMessage(@ApiParam(name = "patient", value = "居民code", required = true)
                                              @RequestParam(value = "patient", required = true) String patient,
                                              @ApiParam(name = "doctor", value = "医生code", required = true)
                                              @RequestParam(value = "doctor", required = true) String doctor,
                                              @ApiParam(name = "type", value = "发送类型", required = true)
                                              @RequestParam(value = "type", required = true) Integer type,
                                              @ApiParam(name = "relationCode", value = "业务code", required = false)
                                              @RequestParam(value = "relationCode", required = true) String relationCode,
                                              @ApiParam(name = "planId", value = "计划id", required = false)
                                              @RequestParam(value = "planId", required = true) String planId,
                                              @ApiParam(name = "reservationType", value = "复诊类型:1线上,2线下,3远程", required = false)
                                              @RequestParam(value = "reservationType", required = false) String reservationType) {
        try {
            rehabilitationMessageService.sendSpecialistWeixinMessage(patient,doctor,type,relationCode,planId,reservationType);
            return success("请求成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "selectType", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表标题")
    public Envelop selectType(@ApiParam(name="planId",value = "根据计划id取该计划对应疾病的指导",required = false)
                             @RequestParam(value = "planId",required = false)String planId) {
        try {
            return success("请求成功!",  rehabilitationGuidanceService.selectType(planId));
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "sendGuidance", method = RequestMethod.GET)
    @ApiOperation("康复管理-发送康复指导")
    public Envelop selectType(@ApiParam(name = "json", value = "康复指导json", required = true)
                             @RequestParam(value = "json", required = true) String json,
                             @ApiParam(name = "planId", value = "计划ID", required = true)
                             @RequestParam(value = "planId", required = true) String planId) {
        try {
            com.alibaba.fastjson.JSONArray array = com.alibaba.fastjson.JSONArray.parseArray(json);
            List<RehabilitationguidancePatientDO> rehabilitationguidancePatientDOS = new ArrayList<>();
            for (int i=0;i<array.size();i++){
                com.alibaba.fastjson.JSONObject object = array.getJSONObject(i);
                RehabilitationguidancePatientDO rehabilitationguidancePatientDO = objectMapper.readValue(object.toJSONString(),RehabilitationguidancePatientDO.class);
                rehabilitationguidancePatientDOS.add(rehabilitationguidancePatientDO);
            }
            return success( "请求成功!",  rehabilitationGuidanceService.sendGuidanceToPatient(rehabilitationguidancePatientDOS,planId));
        } catch (Exception e) {
           e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @RequestMapping(value = "selectGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public Envelop selectType(@ApiParam(name = "type", value = "康复指导类型", required = false)
                             @RequestParam(value = "type", required = false) Integer type,
                             @ApiParam(name = "id", value = "康复指导模板id", required = false)
                             @RequestParam(value = "id", required = false) String id,
                             @ApiParam(name = "title", value = "康复指导名称", required = false)
                             @RequestParam(value = "title", required = false) String title,
                             @ApiParam(name = "planId", value = "计划id", required = false)
                             @RequestParam(value = "planId", required = false) String planId,
                             @ApiParam(name = "page", value = "页码", required = false)
                             @RequestParam(value = "page", required = false, defaultValue ="1") Integer page,
                             @ApiParam(name = "pagesize", value = "每页大小", required = false)
                             @RequestParam(value = "pagesize", required = false,defaultValue = "15") Integer pagesize) {
        try {
            return success( "请求成功!", rehabilitationGuidanceService.select(title,type,id,planId,page,pagesize));
        } catch (Exception e) {
           e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "selectPatientGuidances", method = RequestMethod.GET)
    @ApiOperation("康复管理-查看指导列表")
    public Envelop selectPatientGuidances(@ApiParam(name = "patient", value = "居民code", required = false)
                                         @RequestParam(value = "patient", required = false) String patient,
                                         @ApiParam(name = "code", value = "康复指导模板code", required = false)
                                         @RequestParam(value = "code", required = false) String code,
                                         @ApiParam(name = "doctor", value = "医生code", required = false)
                                         @RequestParam(value = "doctor", required = false) String doctor,
                                         @ApiParam(name = "page", value = "页码", required = false)
                                         @RequestParam(value = "page", required = false) Integer page,
                                         @ApiParam(name = "pagesize", value = "每页大小", required = false)
                                         @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        try {
            return success( "请求成功!", rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,code,page,pagesize));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
}
}

+ 213 - 10
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/controller/doctor/DoctorRehabilitationPlanController.java

@ -4,14 +4,19 @@ import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.entity.util.AesEncryptUtils;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.service.DoctorPatientRelationService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.rehabilitation.RehabilitationRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.rehabilitation.aop.ObserverRequired;
import com.yihu.rehabilitation.service.PatientRecordService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.service.RehabilitationPlanService;
import com.yihu.rehabilitation.service.ZsRehabilitationInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiParam;
@ -19,10 +24,13 @@ import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.HashSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map;
import java.util.Set;
import java.util.Set;
@ -39,9 +47,19 @@ public class DoctorRehabilitationPlanController extends EnvelopRestEndpoint {
    private BaseDoctorDao baseDoctorDao;
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    @Autowired
    private BasePatientDao basePatientDao;
    private BasePatientDao basePatientDao;
    @Autowired
    private PatientRecordService patientRecordService;
    @Autowired
    private ZsRehabilitationInfoService zsRehabilitationInfoService;
    @Autowired
    private DoctorPatientRelationService doctorPatientRelationService;
    @Value("${demo.flag}")
    private Boolean demoFlag;
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.createRehabilitationPlan, method = RequestMethod.POST)
    @RequestMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.createRehabilitationPlan, method = RequestMethod.POST)
    @ApiOperation(value = "创建居民康复计划")
    @ApiOperation(value = "创建居民康复计划")
    @ObserverRequired
    public ObjEnvelop createRehabilitationPlan(@ApiParam(name = "doctor", value = "医生标识")
    public ObjEnvelop createRehabilitationPlan(@ApiParam(name = "doctor", value = "医生标识")
                                           @RequestParam(required = false)String doctor,
                                           @RequestParam(required = false)String doctor,
                                               @ApiParam(name = "json", value = "康复计划json")
                                               @ApiParam(name = "json", value = "康复计划json")
@ -204,20 +222,205 @@ public class DoctorRehabilitationPlanController extends EnvelopRestEndpoint {
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
        }
    }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findServiceItemInBase)
    @ApiOperation(value = "查询康复计划项目")
    public ObjEnvelop findServiceItemInBase(@ApiParam(name = "code", value = "项目", required = true)
                                             @RequestParam(value = "code")String code,
                                            @ApiParam(name = "name", value = "项目name", required = true)
                                            @RequestParam(value = "name")String name,
                                            @ApiParam(name = "teamCode", value = "团队code", required = true)
                                                @RequestParam(value = "teamCode")String teamCode){
        try {
            return ObjEnvelop.getSuccess("操作成功",rehabilitationPlanService.findServiceItemInBase( code, name, teamCode));
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findDoctorTeams)
    @ApiOperation(value = "查询医生团队")
    public ObjEnvelop findDoctorTeams(@ApiParam(name = "doctor", value = "医生id", required = false)
                                             @RequestParam(value = "doctor", required = false)String doctor){
        try {
            return ObjEnvelop.getSuccess("操作成功",rehabilitationPlanService.findDoctorTeams(doctor));
        }catch (Exception e){
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
        }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findDoctorByTeams)
    @ApiOperation(value = "根据团队查询医生列表")
    public ObjEnvelop findDoctorByTeams(@ApiParam(name = "teamCode", value = "团队id", required = false)
                                            @RequestParam(value = "teamCode", required = false)String teamCode){
        try {
            return ObjEnvelop.getSuccess("操作成功",rehabilitationPlanService.findDoctorByTeams( teamCode));
        }catch (Exception e){
        }catch (Exception e){
            e.printStackTrace();
            e.printStackTrace();
            return ObjEnvelop.getError(e.getMessage());
            return ObjEnvelop.getError(e.getMessage());
        }
        }
    }
    }
    @PostMapping(value = RehabilitationRequestMapping.DoctorRehabilitationPlan.findDoctorPatients)
    @ApiOperation(value = "根据团队查询医生列表")
    public MixEnvelop findDoctorPatients(@ApiParam(name = "doctor", value = "医生id", required = false)
                                        @RequestParam(value = "doctor", required = false)String doctor,
                                         @ApiParam(name = "patient", value = "患者id", required = false)
                                         @RequestParam(value = "patient", required = false)String patient,
                                         @ApiParam(name = "patientName", value = "患者姓名", required = false)
                                             @RequestParam(value = "patientName", required = false)String patientName,
                                         @ApiParam(name = "isDeal", value = "是否下转1是0否", required = false)
                                             @RequestParam(value = "isDeal", required = false)String isDeal,
                                         @ApiParam(name = "idcard", value = "是否下转1是0否", required = false)
                                             @RequestParam(value = "idcard", required = false)String idcard,
                                         @ApiParam(name = "page", value = "page", required = false)
                                             @RequestParam(value = "page", required = false)Integer page,
                                         @ApiParam(name = "pageSize", value = "pageSize", required = false)
                                             @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            return doctorPatientRelationService.findDoctorPatients(doctor,patient,patientName,isDeal,idcard,page,pageSize);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(e.getMessage());
        }
    }
    @RequestMapping(value = "getPatientByIdcardOrSsc", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("根据患者身份证或社保卡号进行搜索添加出院记录")
    public Envelop getPatientByIdcardOrSsc(@ApiParam(name = "patientInfo", value = "居民身份证或者社保卡", required = true)
                                          @RequestParam(value = "patientInfo")String patientInfo) {
        try {
            com.alibaba.fastjson.JSONObject object = doctorPatientRelationService.getPatientByIdcardOrSsc(patientInfo, getUID());
            if(object.getInteger("status") == 200) {
                return success("添加成功!", object.get("data"));
            }else {
                return failed( object.getString("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return failed("添加失败!");
        }
    }
    @RequestMapping(value = "/updateRehabilitationPlan", method = RequestMethod.POST)
    @ApiOperation(value = "编辑居民康复计划")
    public Envelop updateRehabilitationPlan(@ApiParam(name = "doctor", value = "医生标识")
                                           @RequestParam(required = false)String doctor,
                                           @ApiParam(name = "json", value = "康复计划json")
                                           @RequestParam(required = true) String json,
                                           @ApiParam(name = "updateStatus", value = "修改类型:0单个服务的修改(默认),1整个计划修改")
                                           @RequestParam(required = false,defaultValue = "0") String updateStatus){
        try {
            if(!StringUtils.isNotBlank(doctor)){
                doctor = getUID();
            }
            BaseDoctorDO d = baseDoctorDao.findById(doctor);
            JSONObject object = new JSONObject(json);
            JSONArray array = object.getJSONArray("detail");//获取服务内容
            Set<String> list = new HashSet<>();
            for(int i=0;i<array.length();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String hospitalServiceItemId = jsonObject.getString("hospitalServiceItemId");//服务id
                String frequencyCode = jsonObject.getString("frequencyCode");
                Long timeType = jsonObject.getLong("timeType");
                String executeTimes =jsonObject.getString("executeTimes");
                String str[] = executeTimes.split(",");
                for (int j=i+1;j<array.length();j++){
                    JSONObject jsonObject1 = array.getJSONObject(j);
                    String hospitalServiceItemId1 = jsonObject1.getString("hospitalServiceItemId");
                    String frequencyCode1 = jsonObject1.getString("frequencyCode");
                    Long timeType1 = jsonObject1.getLong("timeType");
                    String executeTimes1 =jsonObject1.getString("executeTimes");
                    if (hospitalServiceItemId.equalsIgnoreCase(hospitalServiceItemId1)&&frequencyCode.equalsIgnoreCase(frequencyCode1)&&timeType.equals(timeType1)){
                        for (int z=0;z<str.length;z++){
                            if (executeTimes1.contains(str[z])){//时间与之前项目时间相同
                                list.add(hospitalServiceItemId);
                            }
                        }
                    }
                }
            }
            if (list != null && list.size()!=0){
                return failed( "计划创建失败!您设置了重复项目时间,请修改后生成!");
            }
            return success("获取成功", rehabilitationPlanService.updateRehabilitationPlan(json,d,updateStatus));
        } catch (Exception e) {
            e.printStackTrace();
            return failed("请求失败");
        }
    }
    @RequestMapping(value = "getRehabilitationPlanLog",method = RequestMethod.GET)
    @ApiOperation(value = "获取康复计划修改记录")
    public Envelop getRehabilitationPlanLog(@ApiParam(name = "planId",value = "康复计划Id",required = true)
                                           @RequestParam(value = "planId",required = true) String planId){
        try {
            return success("获取成功",rehabilitationPlanService.getRehabilitationPlanLog(planId));
        }catch (Exception e){
            return failed("请求失败");
        }
    }
    /**
     * 查询居民信息
     *
     * @param patient 患者
     * @return
     */
    @GetMapping(value = "/patient")
    @ApiOperation("查询居民信息")
    public Envelop getPatient(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return failed( "居民不能为空");
            }
            JSONObject p = rehabilitationPlanService.getPatient(patient,getUID());
            return success( "查询成功",  p);
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "居民不能为空");
        }
    }
    @RequestMapping(value = "/findTemplateDetail", method = RequestMethod.GET)
    @ApiOperation(value = "获取康复服务套餐模板明细")
    public Envelop findTemplateDetail(@ApiParam(name = "templateId", value = "模板id")
                                     @RequestParam(required = true)String templateId){
        try {
            return success( "获取成功", rehabilitationPlanService.findTemplateDetailInfo(templateId));
        } catch (Exception e) {
            e.printStackTrace();
            return failed( "请求失败");
        }
    }
    @ApiOperation("获取门诊记录/住院记录(基卫+APP)")
    @RequestMapping(value = "/event", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Envelop getAllEvent(@ApiParam(name = "patient", value = "患者代码", defaultValue = "")
                              @RequestParam(value = "patient", required = false) String patient,
                              @ApiParam(name = "type", value = "类型", defaultValue = "")
                              @RequestParam(value = "type", required = false) String type,
                              @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                              @RequestParam(value = "page", required = true) String page,
                              @ApiParam(name = "pageSize", value = "每页几行", defaultValue = "10")
                              @RequestParam(value = "pageSize", required = true) String pageSize,
                              @ApiParam(name = "lastTime", value = "最后一条时间", defaultValue = "2010-10-10 00:00:00")
                              @RequestParam(value = "lastTime", required = false) String lastTime) {
        try {
            if(demoFlag){
                String res;
                switch (type){
                    case "1":
                    case "2":
                        res = patientRecordService.getJosnFileResullt("event"+type);
                        break;
                    default:
                        return success("获取成功");
                }
                return success(res);
            }else {
                List<Map<String, String>> result = patientRecordService.getAllEvent(patient, type, page, pageSize, lastTime);
                return success("获取就诊记录成功!", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().indexOf("卡号尚未在医疗机构注册过") > 0) {
                return failed("对不起,您的社保卡有变更,请改天再试");
            } else if (e.getMessage().startsWith("error")) {
                return failed( e.getMessage());
            } else {
                return failed("获取门/急诊数据失败!");
            }
        }
    }
}
}

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

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

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

@ -0,0 +1,18 @@
package com.yihu.rehabilitation.dao;
import com.yihu.jw.entity.patient.PatientEvent;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientEventDao extends PagingAndSortingRepository<PatientEvent, String>, JpaSpecificationExecutor<PatientEvent> {
      @Query("select a from PatientEvent a where a.patient = ?1 order by a.eventDate desc")
      List<PatientEvent> findByPatient(String patient) throws Exception;
      @Query("select a from PatientEvent a where a.patient = ?1 and a.eventType = ?2 order by a.eventDate desc")
      List<PatientEvent> findByPatientAndEventType(String patient, String type) throws Exception;
}

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

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

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

@ -30,8 +30,8 @@ public interface RehabilitationDetailDao extends PagingAndSortingRepository<Reha
    @Query("select d from RehabilitationDetailDO d where d.planId=?1 order by d.executeTime desc")
    @Query("select d from RehabilitationDetailDO d where d.planId=?1 order by d.executeTime desc")
    List<RehabilitationDetailDO> getAllRehabilitationDetail(String programId);
    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("select d from RehabilitationDetailDO d where d.planId=?1")
    List<RehabilitationDetailDO> findByPlanId(String planId);
    @Query(value ="select count(DISTINCT d.plan_id,d.hospital_service_item_id) from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.doctor=?1 and p.patient=?2  and d.status!=?3",nativeQuery = true)
    @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);
    Integer unfinishItemByDoctor(String doctor, String patient, Integer status);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 444 - 27
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationInfoService.java


+ 1641 - 75
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationManageService.java

@ -2,34 +2,38 @@ package com.yihu.rehabilitation.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
import com.yihu.jw.entity.specialist.SpecialistPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.GuidanceMessageLogDao;
import com.yihu.jw.rehabilitation.RehabilitationDetailAppointmentDao;
import com.yihu.jw.rehabilitation.RehabilitationOperateRecordsDao;
import com.yihu.jw.rehabilitation.SpecialistPatientRelationDao;
import com.yihu.jw.rehabilitation.*;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.rehabilitation.dao.FrequencyDao;
import com.yihu.rehabilitation.dao.PatientRehabilitationPlanDao;
import com.yihu.rehabilitation.dao.RehabilitationDetailDao;
import com.yihu.rehabilitation.dao.SignFamilyDao;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.rehabilitation.dao.*;
import com.yihu.rehabilitation.util.HtmlUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONArray;
@ -38,8 +42,11 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.*;
@ -51,8 +58,6 @@ import java.util.*;
@Transactional
@Transactional
public class RehabilitationManageService {
public class RehabilitationManageService {
    @Value("${basedb.name}")
    private String basedb;
    @Autowired
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private JdbcTemplate jdbcTemplate;
    @Autowired
    @Autowired
@ -79,7 +84,34 @@ public class RehabilitationManageService {
    private SpecialistEvaluateSevice specialistEvaluateSevice;
    private SpecialistEvaluateSevice specialistEvaluateSevice;
    @Autowired
    @Autowired
    private FrequencyDao frequencyDao;
    private FrequencyDao frequencyDao;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao medicalRecordsRehabilitationDao;
    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private DoctorPatientRelationDao doctorPatientRelationDao;
    @Autowired
    private FastDFSUtil fastDFSUtil;
    @Autowired
    private PatientMedicalRecordsRehabilitationDao patientMedicalRecordsDao;
    @Value("${im.data_base_name}")
    private String imDBName;
    @Value("${neiwang.enable}")
    private Boolean isneiwang;  //如果不是内网项目要转到到内网wlyy在上传
    @Autowired
    private ZsRehabilitationInfoService zsRehabilitationInfoService;
    @Autowired
    private PatientRecordService patientRecordService;
    @Autowired
    private RehabilitationInfoService rehabilitationInfoService;
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${demo.flag}")
    private Boolean demoFlag;
    /**
    /**
     * 预约协诊
     * 预约协诊
     * @param doctor
     * @param doctor
@ -163,6 +195,7 @@ public class RehabilitationManageService {
            count = rstotal.size();
            count = rstotal.size();
        }
        }
        sql += " ORDER BY p.create_time DESC LIMIT "+(page-1)*pageSize+","+pageSize;
        sql += " ORDER BY p.create_time DESC LIMIT "+(page-1)*pageSize+","+pageSize;
        System.out.println("sql==="+sql);
        List<Map<String,Object>> patientRehabilitationPlanDOList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> patientRehabilitationPlanDOList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> resultList = new ArrayList<>();
        List<Map<String,Object>> resultList = new ArrayList<>();
        BasePatientDO patient =null;
        BasePatientDO patient =null;
@ -194,7 +227,7 @@ public class RehabilitationManageService {
                resultMap.put("id",one.get("id"));
                resultMap.put("id",one.get("id"));
                resultMap.put("status",one.get("status"));//康复计划状态
                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";
                String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+one.get("patient")+"' and label_type=8";
                List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
                List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
                String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
                String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
                String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
                String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
@ -248,8 +281,8 @@ public class RehabilitationManageService {
     * @throws Exception
     * @throws Exception
     */
     */
    public ObjEnvelop findRehabilitationPlanDetailList(String currentDoctorCode,String patientCode) throws Exception{
    public ObjEnvelop findRehabilitationPlanDetailList(String currentDoctorCode,String patientCode) throws Exception{
        String sql = " select DISTINCT r.* from wlyy_specialist_patient_relation r join wlyy_patient_rehabilitation_plan p on r.patient=p.patient where r.sign_status ='1' and r.status in('0','1') and r.patient='"+patientCode+"' ";
        sql = TransforSqlUtl.specialistPatientRelationAll2(sql);
        String sql = " select DISTINCT r.* from wlyy_doctor_patient_relation r join wlyy_patient_rehabilitation_plan p on r.patient=p.patient where r.status in('0','1') and r.patient='"+patientCode+"' ";
        //sql = TransforSqlUtl.specialistPatientRelationAll2(sql);
        List<Map<String,Object>> specialistPatientRelationList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> specialistPatientRelationList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> resultList = new ArrayList<>();
        List<Map<String,Object>> resultList = new ArrayList<>();
        for(Map<String,Object> temp: specialistPatientRelationList){
        for(Map<String,Object> temp: specialistPatientRelationList){
@ -257,14 +290,14 @@ public class RehabilitationManageService {
            Map<String,Object> resultMap = new HashMap<>();
            Map<String,Object> resultMap = new HashMap<>();
            Integer isOperator = 0;
            Integer isOperator = 0;
            resultMap.put("patientCode",patientCode);//居民code
            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";
            String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+patientCode+"' and label_type=8";
            List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
            List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
            String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
            String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
            String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
            String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
            resultMap.put("healthyCondition",healthyCondition);
            resultMap.put("healthyCondition",healthyCondition);
            resultMap.put("healthyConditionType",healthyConditionType);
            resultMap.put("healthyConditionType",healthyConditionType);
            //专科医生
            //专科医生
            String specialistRelationSql = "select r.*,t.name as teamName,h.name as specialistHospitalName from wlyy_specialist_patient_relation r left join "+basedb+".wlyy_admin_team t on r.team_code=t.id left join "+basedb+".dm_hospital h on t.org_code=h.code where r.sign_status ='1' and r.status in('0','1') and r.patient='"+patientCode+"' and r.doctor='"+doctorCode+"'";
            String specialistRelationSql = "select r.*,t.name as teamName,h.name as specialistHospitalName from wlyy_doctor_patient_relation r left join base_team t on r.team_code=t.id left join base_org h on t.org_code=h.code where  r.status in('0','1') and r.patient='"+patientCode+"' and r.doctor='"+doctorCode+"'";
            specialistRelationSql = TransforSqlUtl.specialistPatientRelationAll2(specialistRelationSql);
            specialistRelationSql = TransforSqlUtl.specialistPatientRelationAll2(specialistRelationSql);
            List<Map<String,Object>> specialistRelationList = jdbcTemplate.queryForList(specialistRelationSql);
            List<Map<String,Object>> specialistRelationList = jdbcTemplate.queryForList(specialistRelationSql);
            Map<String,Object> specialistMap = specialistRelationList.get(0);
            Map<String,Object> specialistMap = specialistRelationList.get(0);
@ -275,14 +308,14 @@ public class RehabilitationManageService {
            Integer specialistFinishCount1 = rehabilitationDetailDao.findItemByDoctor(doctorCode,patientCode);
            Integer specialistFinishCount1 = rehabilitationDetailDao.findItemByDoctor(doctorCode,patientCode);
            Integer specialistServiceCount1 = rehabilitationDetailDao.completeServiceByDoctor(doctorCode,patientCode,1);
            Integer specialistServiceCount1 = rehabilitationDetailDao.completeServiceByDoctor(doctorCode,patientCode,1);
            Integer specialistUnfinishCount2 = rehabilitationDetailDao.unfinishItemByDoctor(specialistMap.get("health_assistant")+"",patientCode,1);
            /*Integer specialistUnfinishCount2 = rehabilitationDetailDao.unfinishItemByDoctor(specialistMap.get("health_assistant")+"",patientCode,1);
            Integer specialistFinishCount2 = rehabilitationDetailDao.findItemByDoctor(specialistMap.get("health_assistant")+"",patientCode);
            Integer specialistFinishCount2 = rehabilitationDetailDao.findItemByDoctor(specialistMap.get("health_assistant")+"",patientCode);
            Integer specialistServiceCount2 = rehabilitationDetailDao.completeServiceByDoctor(specialistMap.get("health_assistant")+"",patientCode,1);
            Integer specialistServiceCount2 = rehabilitationDetailDao.completeServiceByDoctor(specialistMap.get("health_assistant")+"",patientCode,1);*/
            resultMap.put("specialistFinishItemCount",specialistFinishCount1-specialistUnfinishCount1+specialistFinishCount2-specialistUnfinishCount2);//完成项目
            resultMap.put("specialistServiceRecordCount",specialistServiceCount1+specialistServiceCount2);//服务次数
            resultMap.put("specialistFinishItemCount",specialistFinishCount1-specialistUnfinishCount1);//完成项目
            resultMap.put("specialistServiceRecordCount",specialistServiceCount1);//服务次数
            //家庭医生(包括全科医生、健管师)
            //家庭医生(包括全科医生、健管师)
            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+"'";
            String signFamilySql = "SELECT f.*,t.name as teamName FROM wlyy_sign_family f LEFT JOIN wlyy_admin_team t on f.admin_team_code=t.id where f.status =1 and f.expenses_status='1' and f.patient='"+patientCode+"'";
            List<Map<String,Object>> signFamilyList = jdbcTemplate.queryForList(signFamilySql);
            List<Map<String,Object>> signFamilyList = jdbcTemplate.queryForList(signFamilySql);
            if(signFamilyList != null && signFamilyList.size() >0 ) {
            if(signFamilyList != null && signFamilyList.size() >0 ) {
                Map<String, Object> signFamilyMap = signFamilyList.get(0);
                Map<String, Object> signFamilyMap = signFamilyList.get(0);
@ -312,14 +345,14 @@ public class RehabilitationManageService {
                resultMap.put("sex", "1".equals(sex) ? "男" : ("2".equals(sex) ? "女" : "未知"));
                resultMap.put("sex", "1".equals(sex) ? "男" : ("2".equals(sex) ? "女" : "未知"));
                resultMap.put("patientName", signFamilyMap.get("patientName"));
                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")+"' ";
           /* //疾病类型
            String diseaseSql = " select s.* from wlyy_patient_disease_server s where s.del=1 and s.patient='"+patientCode+"' and s.specialist_relation_code='"+specialistMap.get("id")+"' ";
            List<Map<String,Object>> diseaseList = jdbcTemplate.queryForList(diseaseSql);
            List<Map<String,Object>> diseaseList = jdbcTemplate.queryForList(diseaseSql);
            List<String> disease = new ArrayList<>();
            List<String> disease = new ArrayList<>();
            for(Map<String,Object> one2:diseaseList){
            for(Map<String,Object> one2:diseaseList){
                disease.add(one2.get("disease_name")+"");
                disease.add(one2.get("disease_name")+"");
            }
            }
            resultMap.put("diseaseList",disease);
            resultMap.put("diseaseList",disease);*/
            //计划列表
            //计划列表
            List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatientAndCreateUser(patientCode,doctorCode);
            List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatientAndCreateUser(patientCode,doctorCode);
@ -373,7 +406,149 @@ public class RehabilitationManageService {
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultList);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultList);
    }
    }
    /**
     * 日历
     * @param searchTask 快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param status 任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode 登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailByPatient(String executeStartTime,String executeEndTime,String patient,Integer searchTask,Integer status,String doctorCode,String taskExecutor) throws Exception{
        List<Map<String,Object>> planList = getPatientAllRehabilitationPlan(patient);
        StringBuilder planCondition = new StringBuilder();
        planCondition .append("'"+planList.get(0).get("id").toString()+"'");
        for (int i=1;i<planList.size();i++){
            planCondition .append(",'"+planList.get(0).get("id").toString()+"'");
        }
        String sql = " select d.* from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  " +
                " where  d.plan_id in ("+planCondition+") " +
                "" ;
        if(StringUtils.isNotBlank(executeStartTime)){
            sql += " and d.execute_time>='"+executeStartTime+"' ";
        }
        if(StringUtils.isNotBlank(executeEndTime)){
            sql += " and d.execute_time<='"+executeEndTime+"' ";
        }
        if(searchTask!=null){
            if(searchTask==8){
                sql+=" and d.doctor='"+doctorCode+"' " ;
            }else {
                sql+=" and i.code="+searchTask+" " ;
            }
        }
        if(taskExecutor.equals("1")){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if(taskExecutor.equals("2")){//他人任务
            sql+="and d.doctor <>'"+doctorCode+"' ";
        }
        if(status!=null){
            sql+= " and d.status="+status;
        }
        sql += " ORDER BY d.execute_time ";
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
//        List<RehabilitationDetailDO> rehabilitationDetailList = rehabilitationDetailDao.findByPlanId(DateUtil.strToDate(executeStartTime),DateUtil.strToDate(executeEndTime),planId);
        Map<String,Map<String,Object>> map = new LinkedHashMap<>();
        for(Map<String,Object> one:rehabilitationDetailList){
            String executeTime = DateUtil.dateToStr((Date) one.get("execute_time"),DateUtil.YYYY_MM_DD);
            Map<String,Object> m = null;
            if(map.containsKey(executeTime)){
                m = map.get(executeTime);
                Map<String,Integer> family = null;
                Map<String,Integer> specialist = null;
                if(one.get("type")!=null){
                    if((Integer)one.get("type")==1){//家庭医生
                        if(m.containsKey("family")){
                            family = (Map<String,Integer>)m.get("family");
                        }else{
                            family = new HashMap<>();
                            family.put("all",0);
                            family.put("finish",0);
                        }
                        if((Integer)one.get("status")==1){
                            family.put("finish",family.get("finish")+1);
                        }
                        family.put("all",family.get("all")+1);
                        m.put("family",family);
                    }else if((Integer)one.get("type")==2){//专科医生
                        if(m.containsKey("specialist")){
                            specialist = (Map<String,Integer>)m.get("specialist");
                        }else{
                            specialist = new HashMap<>();
                            specialist.put("all",0);
                            specialist.put("finish",0);
                        }
                        if((Integer)one.get("status")==1){
                            specialist.put("finish",(specialist.get("finish"))+1);
                        }
                        specialist.put("all",(specialist.get("all"))+1);
                        m.put("specialist",specialist);
                    }
                }
            }else{
                m = new HashMap<>();
//                m.put("specialist",new HashMap<String,Object>());
                if(one.get("type")!=null){
                    if((Integer)one.get("type")==1){//家庭医生
                        Map<String,Integer> family = new HashMap<>();
                        family.put("all",0);
                        family.put("finish",0);
                        if((Integer)one.get("status")==1){
                            family.put("finish",family.get("finish")+1);
                        }
                        family.put("all",family.get("all")+1);
                        m.put("family",family);
                    }else if((Integer)one.get("type")==2){//专科医生
                        Map<String,Integer> specialist = new HashMap<>();
                        specialist.put("all",0);
                        specialist.put("finish",0);
                        if((Integer)one.get("status")==1){
                            specialist.put("finish",specialist.get("finish")+1);
                        }
                        specialist.put("all",specialist.get("all")+1);
                        m.put("specialist",specialist);
                    }
                }
            }
            //myTaskFlag,1:有自己任务,0:没有自己任务
            if(StringUtils.isNotEmpty(doctorCode)){
                if(m.containsKey("myTaskFlag")){
                    if((Integer)m.get("myTaskFlag")==0){
                        if(doctorCode.equals(one.get("doctor").toString())){
                            m.put("myTaskFlag",1);
                        }else{
                            m.put("myTaskFlag",0);
                        }
                    }
                }else{
                    if(doctorCode.equals(one.get("doctor").toString())){
                        m.put("myTaskFlag",1);
                    }else{
                        m.put("myTaskFlag",0);
                    }
                }
            }
            if(m.containsKey("planDetailIds")){
                m.put("planDetailIds",m.get("planDetailIds")+","+one.get("id"));
            }else{
                m.put("planDetailIds",one.get("id")+"");
            }
            map.put(executeTime,m);
        }
        /*List list = new ArrayList();
        for(String key : map.keySet()){
            Map<String,Object> result = map.get(key);
            result.put("executeTime", key);
            list.add(result);
        }*/
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
    }
    /**
    /**
     * 日历
     * 日历
     * @param planId 计划id
     * @param planId 计划id
@ -390,8 +565,9 @@ public class RehabilitationManageService {
            planCondition .append(",'"+planIdlist[i]+"'");
            planCondition .append(",'"+planIdlist[i]+"'");
        }
        }
        String sql = " select d.* from wlyy_rehabilitation_plan_detail d " +
        String sql = " select d.* from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN base_service_package_item i on i.id = d.hospital_service_item_id " +
                " where  d.plan_id in ("+planCondition+") and i.service_package_id='system' " ;
                " 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)){
        if(StringUtils.isNotBlank(executeStartTime)){
            sql += " and d.execute_time>='"+executeStartTime+"' ";
            sql += " and d.execute_time>='"+executeStartTime+"' ";
        }
        }
@ -415,7 +591,6 @@ public class RehabilitationManageService {
            sql+= " and d.status="+status;
            sql+= " and d.status="+status;
        }
        }
        sql += " ORDER BY d.execute_time ";
        sql += " ORDER BY d.execute_time ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
//        List<RehabilitationDetailDO> rehabilitationDetailList = rehabilitationDetailDao.findByPlanId(DateUtil.strToDate(executeStartTime),DateUtil.strToDate(executeEndTime),planId);
//        List<RehabilitationDetailDO> rehabilitationDetailList = rehabilitationDetailDao.findByPlanId(DateUtil.strToDate(executeStartTime),DateUtil.strToDate(executeEndTime),planId);
        Map<String,Map<String,Object>> map = new LinkedHashMap<>();
        Map<String,Map<String,Object>> map = new LinkedHashMap<>();
@ -536,8 +711,52 @@ public class RehabilitationManageService {
            planCondition .append(",'"+planIdlist[i]+"'");
            planCondition .append(",'"+planIdlist[i]+"'");
        }
        }
        String sql = " select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name from wlyy_rehabilitation_plan_detail d " +
        String sql = " select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN base_service_package_item i on i.id = d.hospital_service_item_id  " +
                " where  d.plan_id in ("+planCondition+" )AND  d.execute_time IS NOT NULL and i.service_package_id ='system'   and d.execute_time <>'' " ;
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id   " +
                " where  d.plan_id in ("+planCondition+" )AND  d.execute_time IS NOT NULL " +
                "   and d.execute_time <>'' " ;
        if(searchTask!=null){
            if(searchTask==8){//
                sql+="and d.doctor='"+doctorCode+"' ";
            }else {
                sql+=" and i.code="+searchTask+" " ;
            }/*else if(searchTask==5){
                sql+=" and i.reserve=1 " ;
            }*/
        }
        if("1".equals(taskExecutor)){ //我的任务
            sql+="and d.doctor='"+doctorCode+"' ";
        }
        if("2".equals(taskExecutor)){//他人任务
            sql+="and d.doctor <>'"+doctorCode+"' ";
        }
        if (StringUtils.isNoneBlank(executeEndTime)&&StringUtils.isNoneBlank(executeStartTime)){
            sql+="and d.execute_time>='"+executeStartTime+"' and d.execute_time<='"+executeEndTime+"' ";
        }
        if(status!=null){
            sql+= "and d.status="+status;
        }
        sql +="  order by d.execute_time desc ";
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationDetailList);
    }
    /**
     * 日历列表
     * @param searchTask 快速查找任务(1、我的任务,2、随访,3、复诊,4、健康教育)
     * @param status 任务状态(0未完成,1已完成,2已预约)
     * @param doctorCode 登陆医生
     * @param taskExecutor 任务执行者 0全部;1我的任务 2他人任务
     */
    public ObjEnvelop calendarPlanDetailListByPatient(String executeStartTime,String executeEndTime,String patient,Integer searchTask,Integer status,String doctorCode,String taskExecutor){
        List<Map<String,Object>> planList = getPatientAllRehabilitationPlan(patient);
        StringBuilder planCondition = new StringBuilder();
        planCondition .append("'"+planList.get(0).get("id").toString()+"'");
        for (int i=1;i<planList.size();i++){
            planCondition .append(",'"+planList.get(0).get("id").toString()+"'");
        }
        String sql = " select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id   " +
                " where  d.plan_id in ("+planCondition+" )AND  d.execute_time IS NOT NULL    and d.execute_time <>'' " ;
        if(searchTask!=null){
        if(searchTask!=null){
            if(searchTask==8){//
            if(searchTask==8){//
                sql+="and d.doctor='"+doctorCode+"' ";
                sql+="and d.doctor='"+doctorCode+"' ";
@ -564,7 +783,6 @@ public class RehabilitationManageService {
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> rehabilitationDetailList = jdbcTemplate.queryForList(sql);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationDetailList);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,rehabilitationDetailList);
    }
    }
    /**
    /**
     * 多个康复计划服务项目内容列表
     * 多个康复计划服务项目内容列表
     * @param planDetailIds
     * @param planDetailIds
@ -581,9 +799,9 @@ public class RehabilitationManageService {
        String sql = "select i.name,i.code,i.introduce,d.execute_time,d.hospital_name,d.id,d.status,d.type as detailType,d.expense,d.doctor as executeDoctor," +
        String sql = "select i.name,i.code,i.introduce,d.execute_time,d.hospital_name,d.id,d.status,d.type as detailType,d.expense,d.doctor as executeDoctor," +
                " d.doctor_name as executeDoctorName,p.patient ,p.id AS planId,p.create_user as createDoctor,p.create_user_name as createDoctorName, p.status as planStatus  " +
                " d.doctor_name as executeDoctorName,p.patient ,p.id AS planId,p.create_user as createDoctor,p.create_user_name as createDoctorName, p.status as planStatus  " +
                " from wlyy_rehabilitation_plan_detail d " +
                " from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN base_service_package_item i on i.id = d.hospital_service_item_id " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " where d.id in ("+planDetailResult+")   and i.service_package_id='system'  order BY d.execute_time ASC";
                " where d.id in ("+planDetailResult+")     order BY d.execute_time ASC";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName(sql);
        List<Map<String,Object>> serviceItemList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> serviceItemList = jdbcTemplate.queryForList(sql);
@ -684,19 +902,20 @@ public class RehabilitationManageService {
     *
     *
     */
     */
    public ObjEnvelop serviceItem(String planDetailId,String doctorCode,String recordId) throws Exception{
    public ObjEnvelop serviceItem(String planDetailId,String doctorCode,String recordId) throws Exception{
        String sql = "select h.name as title,h.introduce as content,h.code as itemType,d.id,d.execute_time,d.hospital_name,d.status,d.type,d.expense,d.doctor as executeDoctor, " +
        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," +
                " 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  "+
                " 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" +
                " ,a.appointment_time appointmentTime,a.appointment_doctor appointmentDoctor,a.appointment_doctor_name appointmentDoctorName,d.reservation_type reservationType" +
                " from wlyy_rehabilitation_plan_detail d " +
                " from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN base_service_package_item h on d.hospital_service_item_id = h.id "+
                " LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id = h.code "+
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
                " LEFT JOIN wlyy_plan_detail_appointment a on d.id=.a.rehabilitation_plan_detail_id " +
                " LEFT JOIN wlyy_plan_detail_appointment a on d.id=.a.rehabilitation_plan_detail_id " +
                " where d.id = '"+planDetailId+"' and  h.service_package_id='system'";
                " where d.id = '"+planDetailId+"'";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName2(sql);
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        sql = TransforSqlUtl.wlyy_plan_detail_appointmentAppDoctorName(sql);
        sql = TransforSqlUtl.wlyy_plan_detail_appointmentAppDoctorName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName(sql);
        sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailDoctorName(sql);
        System.out.println("sql===="+sql);
        List<Map<String,Object>> serviceItemList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> serviceItemList = jdbcTemplate.queryForList(sql);
        if (serviceItemList.size()==0){
        if (serviceItemList.size()==0){
            return ObjEnvelop.getSuccess(SpecialistMapping.api_success,new HashMap<>());
            return ObjEnvelop.getSuccess(SpecialistMapping.api_success,new HashMap<>());
@ -720,6 +939,12 @@ public class RehabilitationManageService {
//        if(!(one.get("specialistDoctor")+"").equals((one.get("create_user")+""))){
//        if(!(one.get("specialistDoctor")+"").equals((one.get("create_user")+""))){
//            executeDoctorList.add(one.get("create_user_name")+"");
//            executeDoctorList.add(one.get("create_user_name")+"");
//        }
//        }
        List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(one.get("executeDoctor").toString());
        if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
            resultMap.put("executeDoctorDept",baseDoctorHospitalDO.get(0).getDeptCode());
            resultMap.put("executeDoctorDeptName",baseDoctorHospitalDO.get(0).getDeptName());
        }
        executeDoctorList.add(one.get("executeDoctorName")+"");//
        executeDoctorList.add(one.get("executeDoctorName")+"");//
        resultMap.put("remark",one.get("remark"));//备注
        resultMap.put("remark",one.get("remark"));//备注
        resultMap.put("executeDoctorList",executeDoctorList);//执行医生名称列表
        resultMap.put("executeDoctorList",executeDoctorList);//执行医生名称列表
@ -1005,10 +1230,10 @@ public class RehabilitationManageService {
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> resultMap = new HashMap<>();
        //近期康复相关记录
        //近期康复相关记录
//        String currentTime = DateUtil.getStringDate();
//        String currentTime = DateUtil.getStringDate();
        String planDetailSql = " select d.*,h.name,h.code,s.complete_time from wlyy_rehabilitation_plan_detail d LEFT JOIN base_service_package_item h on d.hospital_service_item_id=h.id " +
        String planDetailSql = " select d.*,h.name,h.code,s.complete_time from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id=h.code " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id" +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id" +
                " left join wlyy_rehabilitation_operate_records s on s.rehabilitation_detail_id=d.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 h.service_package_id='system'  AND d.frequency_code <>'' ";
                " where d.status=1 and p.patient='"+patientCode+"' and d.frequency_code IS NOT NULL   AND d.frequency_code <>'' ";
        if(StringUtils.isNotEmpty(startTime)){
        if(StringUtils.isNotEmpty(startTime)){
            planDetailSql += "  and d.execute_Time>='"+startTime+"' ";
            planDetailSql += "  and d.execute_Time>='"+startTime+"' ";
        }
        }
@ -1045,8 +1270,8 @@ public class RehabilitationManageService {
            planDetailList.add(map);
            planDetailList.add(map);
        }
        }
        resultMap.put("planDetailList",planDetailList);//康复相关记录列表
        resultMap.put("planDetailList",planDetailList);//康复相关记录列表
        String planDetailCountSql = " select d.status as num from wlyy_rehabilitation_plan_detail d LEFT JOIN base_service_package_item h on d.hospital_service_item_id=h.id" +
                "  LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where p.patient='"+patientCode+"' and h.service_package_id='system' ";
        String planDetailCountSql = " select d.status as num from wlyy_rehabilitation_plan_detail d LEFT JOIN wlyy_rehabilitation_service_item h on d.hospital_service_item_id=h.code" +
                "  LEFT JOIN wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where p.patient='"+patientCode+"'  ";
        List<Map<String,Object>> planDetailList2 = jdbcTemplate.queryForList(planDetailCountSql);
        List<Map<String,Object>> planDetailList2 = jdbcTemplate.queryForList(planDetailCountSql);
        Integer planDetailFinish = 0;
        Integer planDetailFinish = 0;
        Integer planDetailUnfinish = 0;
        Integer planDetailUnfinish = 0;
@ -1103,12 +1328,12 @@ public class RehabilitationManageService {
            adminTeamCode = specialistPatientRelationDO.getTeamCode();
            adminTeamCode = specialistPatientRelationDO.getTeamCode();
            doctorName = specialistPatientRelationDO.getDoctorName();
            doctorName = specialistPatientRelationDO.getDoctorName();
        }else if(doctorType==2){
        }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+"'";
            String signFamilySql = " select f.* from wlyy_sign_family f where f.status=1 and f.expenses_status='1' and f.patient='"+patient+"'";
            List<Map<String,Object>> signFamily = jdbcTemplate.queryForList(signFamilySql);
            List<Map<String,Object>> signFamily = jdbcTemplate.queryForList(signFamilySql);
            adminTeamCode = (Integer)signFamily.get(0).get("admin_team_code");
            adminTeamCode = (Integer)signFamily.get(0).get("admin_team_code");
            doctorName = signFamily.get(0).get("doctor_name").toString();
            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;
        String adminTeamSql = " select t.* from base_team t where t.del='1' and t.id="+adminTeamCode;
        List<Map<String,Object>> adminTeam = jdbcTemplate.queryForList(adminTeamSql);
        List<Map<String,Object>> adminTeam = jdbcTemplate.queryForList(adminTeamSql);
        String adminTeamName = adminTeam.get(0).get("name").toString();
        String adminTeamName = adminTeam.get(0).get("name").toString();
        guidanceMessageLogDO.setAdminTeamCode(adminTeamCode);
        guidanceMessageLogDO.setAdminTeamCode(adminTeamCode);
@ -1233,7 +1458,7 @@ public class RehabilitationManageService {
     * @param endTime
     * @param endTime
     * @return
     * @return
     */
     */
    public ObjEnvelop dailyJob(String startTime,String endTime){
    public JSONArray dailyJob(String startTime,String endTime){
        String sql = "select d.doctor,p.patient,count(1) as num from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.status!=1 and p.status=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' GROUP BY d.doctor,p.patient";
        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<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
@ -1250,7 +1475,7 @@ public class RehabilitationManageService {
            }
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
        return new JSONArray(list);
    }
    }
    /**
    /**
@ -1260,7 +1485,7 @@ public class RehabilitationManageService {
     * @param endTime
     * @param endTime
     * @return
     * @return
     */
     */
    public ObjEnvelop tomorrowJob(String startTime,String endTime){
    public JSONArray tomorrowJob(String startTime,String endTime){
        String sql = "select d.doctor,p.patient,count(1) as num,p.id from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id where d.status!=1 and p.status=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' GROUP BY d.doctor,p.patient";
        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<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
@ -1277,7 +1502,7 @@ public class RehabilitationManageService {
            }
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
        return new JSONArray(list);
    }
    }
@ -1288,7 +1513,7 @@ public class RehabilitationManageService {
     * @param endTime
     * @param endTime
     * @return
     * @return
     */
     */
    public ObjEnvelop dailyByJob(String startTime,String endTime){
    public JSONArray dailyByJob(String startTime,String endTime){
        String sql = "select d.doctor,p.patient,h.service_item_name AS serviceItemName,d.time_type AS timeType from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id left join wlyy_hospital_service_item h ON h.id=d.hospital_service_item_id where d.status!=1 and p.status=1 and d.execute_time>='"+startTime+"' and d.execute_time<='"+endTime+"' GROUP BY d.doctor,p.patient,d.execute_time";
        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<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
@ -1305,7 +1530,7 @@ public class RehabilitationManageService {
            }
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
        return new JSONArray(list);
    }
    }
    /**
    /**
@ -1360,13 +1585,13 @@ public class RehabilitationManageService {
        }
        }
        //更新返回数据提供发送消息使用
        //更新返回数据提供发送消息使用
        String sql ="SELECT" +
        String sql ="SELECT" +
                " i.service_item_id," +
                " i.id as \"id\"," +
                " r.doctor_code," +
                " r.doctor_code," +
                " r.patient_code," +
                " r.patient_code," +
                " pd.hospital" +
                " pd.hospital" +
                " FROM" +
                " FROM" +
                " wlyy_rehabilitation_plan_detail pd" +
                " wlyy_rehabilitation_plan_detail pd" +
                " LEFT JOIN wlyy_hospital_service_item i ON pd.hospital_service_item_id = i.id" +
                " LEFT JOIN wlyy_rehabilitation_service_item i ON pd.hospital_service_item_id = i.id" +
                " LEFT JOIN wlyy_rehabilitation_operate_records r ON pd.id = r.rehabilitation_detail_id" +
                " LEFT JOIN wlyy_rehabilitation_operate_records r ON pd.id = r.rehabilitation_detail_id" +
                " WHERE" +
                " WHERE" +
                " pd.id = '"+planDeatilId+"'";
                " pd.id = '"+planDeatilId+"'";
@ -1374,18 +1599,22 @@ public class RehabilitationManageService {
        if (list!=null && list.size()>0){
        if (list!=null && list.size()>0){
            resultMap = list.get(0);
            resultMap = list.get(0);
        }
        }
        String itemSql ="SELECT evaluation,title FROM `wlyy_service_item` WHERE id='"+String.valueOf(resultMap.get("service_item_id"))+"'";
        String itemSql ="SELECT evaluation,title FROM `wlyy_service_item` WHERE id='"+String.valueOf(resultMap.get("id"))+"'";
        List<Map<String,Object>> itemList = jdbcTemplate.queryForList(itemSql);
        List<Map<String,Object>> itemList = jdbcTemplate.queryForList(itemSql);
        if (itemList!=null && itemList.size()>0){
        if (itemList!=null && itemList.size()>0){
            resultMap.put("evaluation",itemList.get(0).get("evaluation"));
            resultMap.put("evaluation",itemList.get(0).get("evaluation"));
            resultMap.put("title",itemList.get(0).get("title"));
            resultMap.put("title",itemList.get(0).get("title"));
        }
        }
        //保存wlyy_message
        //保存wlyy_message
        String hospotal = resultMap.get("hospital").toString();
        List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(resultMap.get("doctor_code").toString());
        String hospotal = "";
        String patient = resultMap.get("patient_code").toString();
        String patient = resultMap.get("patient_code").toString();
        String doctor = resultMap.get("doctor_code").toString();
        String doctor = resultMap.get("doctor_code").toString();
        Message message = new Message();
        message.setType(21);
        if (depts!=null&&depts.size()>0){
            hospotal=depts.get(0).getOrgCode();
        }
        SystemMessageDO message = new SystemMessageDO();
        message.setType("21");
        message.setSender(patient);
        message.setSender(patient);
        message.setReceiver(doctor);
        message.setReceiver(doctor);
        message.setRelationCode(planDeatilId);
        message.setRelationCode(planDeatilId);
@ -1462,7 +1691,7 @@ public class RehabilitationManageService {
        rehabilitationOperateRecordsDO.setPatientCode(patientRehabilitationPlanDO.getPatient());
        rehabilitationOperateRecordsDO.setPatientCode(patientRehabilitationPlanDO.getPatient());
        rehabilitationOperateRecordsDO.setPatientName(patientRehabilitationPlanDO.getName());
        rehabilitationOperateRecordsDO.setPatientName(patientRehabilitationPlanDO.getName());
        rehabilitationOperateRecordsDO.setDoctorCode(jsonObject.getString("doctorCode"));
        rehabilitationOperateRecordsDO.setDoctorCode(jsonObject.getString("doctorCode"));
        rehabilitationOperateRecordsDO.setDoctorName(jsonObject.getString("doctorName"));
        rehabilitationOperateRecordsDO.setDoctorName(rehabilitationDetailDO.getDoctorName());
        rehabilitationOperateRecordsDO.setRelationRecordType(5);
        rehabilitationOperateRecordsDO.setRelationRecordType(5);
        rehabilitationOperateRecordsDO.setCompleteTime(new Date());
        rehabilitationOperateRecordsDO.setCompleteTime(new Date());
        rehabilitationOperateRecordsDO.setCreateTime(new Date());
        rehabilitationOperateRecordsDO.setCreateTime(new Date());
@ -1502,7 +1731,6 @@ public class RehabilitationManageService {
    /**
    /**
     * 计划总进度
     * 计划总进度
     * @param planId
     * @return
     * @return
     */
     */
    public ObjEnvelop planSchedule(String planId,String patientCode){
    public ObjEnvelop planSchedule(String planId,String patientCode){
@ -1510,28 +1738,44 @@ public class RehabilitationManageService {
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);//计划总服务项目数
        Integer allCount = rehabilitationDetailDao.findAllByPlanId(planId);//计划总服务项目数
        Integer finishedCount = rehabilitationDetailDao.findByStatusAndPlanId(1,planId);
        Integer finishedCount = rehabilitationDetailDao.findByStatusAndPlanId(1,planId);
        PatientRehabilitationPlanDO p =patientRehabilitationPlanDao.findById(planId);
        PatientRehabilitationPlanDO p =patientRehabilitationPlanDao.findById(planId);
        SpecialistPatientRelationDO specialistPatientRelationDO;
        if (p.getTeamCode()!= null) {
             specialistPatientRelationDO = specialistPatientRelationDao.findByTeamCodeAndPatient(p.getTeamCode(),p.getPatient());
        }
        else {
             specialistPatientRelationDO = specialistPatientRelationDao.findByDoctorAndPatient(p.getCreateUser(),p.getPatient());
        List<DoctorPatientRelationDO> doctorPatientRelationDO= doctorPatientRelationDao.findByDoctorAndPatient(p.getCreateUser(),p.getPatient());
        List<RehabilitationDetailDO> details=rehabilitationDetailDao.findByPlanId(planId);
        String doctor="";
        String doctorName="";
        if (details!=null&&details.size()>0){
            doctor=details.get(0).getDoctor();
            doctorName=details.get(0).getDoctorName();
        }
        }
        resultMap.put("allCount",allCount);
        resultMap.put("allCount",allCount);
        resultMap.put("finishedCount",finishedCount);
        resultMap.put("finishedCount",finishedCount);
        resultMap.put("specialistPatientRelationDO",specialistPatientRelationDO);
        resultMap.put("specialistPatientRelationDO",doctorPatientRelationDO);
        if (p!=null){
        if (p!=null){
            resultMap.put("disease",p.getDisease());
            resultMap.put("disease",p.getDisease());
            resultMap.put("diseaseName",p.getDiseaseName());
            resultMap.put("diseaseName",p.getDiseaseName());
            resultMap.put("createUser",p.getCreateUser());
            resultMap.put("createUser",p.getCreateUser());
            resultMap.put("planTitle",p.getTitle());
            resultMap.put("planTitle",p.getTitle());
            resultMap.put("status", p.getStatus());
            resultMap.put("status", p.getStatus());
            resultMap.put("isVerify", p.getIsVerify());
            resultMap.put("patientImg", p.getPatientImg());
            resultMap.put("patientImg", p.getPatientImg());
            resultMap.put("adviceContent",p.getAdviceContent());
            resultMap.put("adviceContent",p.getAdviceContent());
            resultMap.put("createTimeDate",DateUtil.dateToStr(p.getCreateTime(),"yyyy-MM-dd"));
            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("createTime", DateUtil.dateToStr(p.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            resultMap.put("medicalRecordsCode",p.getMedicalRecordsCode());
            resultMap.put("medicalRecordsCode",p.getMedicalRecordsCode());
            List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(p.getCreateUser());
            if (baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
                resultMap.put("createUserName",p.getCreateUserName());
                resultMap.put("createUserDept",baseDoctorHospitalDO.get(0).getDeptCode());
                resultMap.put("createUserDeptName",baseDoctorHospitalDO.get(0).getDeptName());
            }
            List<BaseDoctorHospitalDO> baseDoctorHospitalDOTo = baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (baseDoctorHospitalDOTo!=null&&baseDoctorHospitalDOTo.size()>0){
                resultMap.put("doctorName",doctorName);
                resultMap.put("doctor",doctor);
                resultMap.put("doctorDept",baseDoctorHospitalDOTo.get(0).getDeptCode());
                resultMap.put("doctorDeptName",baseDoctorHospitalDOTo.get(0).getDeptName());
            }
            PatientMedicalRecordsDO patientMedicalRecordsDO = patientMedicalRecordsDao.findByCode(p.getMedicalRecordsCode());
            resultMap.put("patientMedicalRecordsDO",patientMedicalRecordsDO);
        }
        }
        BasePatientDO basePatientDO = basePatientDao.findById(patientCode);
        BasePatientDO basePatientDO = basePatientDao.findById(patientCode);
        Integer age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
        Integer age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard());
@ -1541,12 +1785,6 @@ public class RehabilitationManageService {
        resultMap.put("patientPhoto",basePatientDO.getPhoto());
        resultMap.put("patientPhoto",basePatientDO.getPhoto());
        resultMap.put("patientName",basePatientDO.getName());
        resultMap.put("patientName",basePatientDO.getName());
        resultMap.put("patientCode",basePatientDO.getId());
        resultMap.put("patientCode",basePatientDO.getId());
        String healthyConditionSql =" select  label_name,label from wlyy_sign_patient_label_info where status=1 and patient='"+basePatientDO.getId()+"' and label_type=8";
        List<Map<String,Object>> healthyConditionList = jdbcTemplate.queryForList(healthyConditionSql);
        String healthyCondition = healthyConditionList.size()>0?healthyConditionList.get(0).get("label_name")+"":"";
        String healthyConditionType = healthyConditionList.size()>0?healthyConditionList.get(0).get("label")+"":"";
        resultMap.put("healthyCondition",healthyCondition);
        resultMap.put("healthyConditionType",healthyConditionType);
        resultMap.put("idcard",basePatientDO.getIdcard());
        resultMap.put("idcard",basePatientDO.getIdcard());
//        resultMap.put("healthyCondition",healthyCondition);
//        resultMap.put("healthyCondition",healthyCondition);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,resultMap);
@ -1576,9 +1814,9 @@ public class RehabilitationManageService {
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,map);
    }
    }
    public ObjEnvelop dailyJobReserve(String startTime,String endTime){
    public JSONArray dailyJobReserve1(String startTime, String endTime){
        String sql = "select DISTINCT d.doctor,p.patient,d.hospital from wlyy_rehabilitation_plan_detail d left join wlyy_patient_rehabilitation_plan p on d.plan_id=p.id " +
        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_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 "+
                " 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 ";
                " 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<Object> list = rehabilitationDetailDao.dailyJob(startTime,endTime);
@ -1601,7 +1839,7 @@ public class RehabilitationManageService {
            }
            }
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
            one.put("planDetailIds",StringUtils.isNotEmpty(ids)?ids.substring(1):"");
        }
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,list);
        return new JSONArray(JSON.toJSONString(list));
    }
    }
    /**
    /**
@ -1658,11 +1896,11 @@ public class RehabilitationManageService {
                "  i.code as item_type " +
                "  i.code as item_type " +
                "  FROM" +
                "  FROM" +
                "  wlyy_rehabilitation_plan_detail d" +
                "  wlyy_rehabilitation_plan_detail d" +
                "  LEFT JOIN base_service_package_item i ON d.hospital_service_item_id = i.id  "+
                "  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" +
                "  LEFT JOIN wlyy_rehabilitation_operate_records r ON d.id = r.rehabilitation_detail_id" +
                "  WHERE" +
                "  WHERE" +
                "  r.`status` = 1" +
                "  r.`status` = 1" +
                " and i.service_package_id='system') a ON p.id = a.plan_id" +
                " ) a ON p.id = a.plan_id" +
                " WHERE" +
                " WHERE" +
                " p.id = '"+planId+"'";
                " p.id = '"+planId+"'";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
@ -1724,4 +1962,1332 @@ public class RehabilitationManageService {
    public String getCode() {
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    }
    public List<Map<String,Object>> getPatientAllRehabilitationPlan(String patient){
        String sql = "select p.team_code as teamCode,d.id as doctor,p.create_time as createTime,p.id,d.photo,p.title,d.idcard,YEAR (now()) - YEAR (substring(d.idcard, 7, 8)) AS age, d.sex,p.name,p.patient,p.disease_name,d.name as doctorName,p.advice_content as adviceContent,p.medical_records_code as medicalRecordsCode,p.create_time as create_time " +
                " FROM wlyy_patient_rehabilitation_plan p " +
                " LEFT JOIN base_doctor d ON d.id = p.create_user " +
                "WHERE p.patient='"+patient+"'";
        sql = sql +" union "+
                "SELECT p.team_code as teamCode,d.id AS doctor," +
                "p.create_time AS createTime," +
                "p.id," +
                "d.photo," +
                "p.title," +
                "d.idcard,YEAR (now())-YEAR (substring(d.idcard,7,8)) AS age," +
                "d.sex,p.name," +
                "p.patient," +
                "p.disease_name,"+
                "d.NAME AS doctorName," +
                "p.advice_content AS adviceContent," +
                "p.medical_records_code AS medicalRecordsCode," +
                "p.create_time AS create_time " +
                "FROM " +
                "wlyy_patient_rehabilitation_plan p " +
                "LEFT JOIN base_doctor d ON d.id=p.create_user" +
                " LEFT JOIN (" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code " +
                "FROM wlyy_doctor_patient_relation sr " +
                "JOIN wlyy_doctor_special_share se ON se.special_code=sr.id " +
                "WHERE sr.patient='"+patient+"') d " +
                "ON d.patient=p.patient WHERE " +
                "p.patient='"+patient+"' " +
                " "+
                "ORDER BY create_time DESC";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> result = new ArrayList<>();
        List<Map<String,Object>> hadManage = new ArrayList<>();
        for (Map<String,Object> mp:mapList){//获下转状态
            Date createTimeDate = DateUtil.strToDateLong(mp.get("createTime").toString());
            mp.put("createTimeDate",DateUtil.dateToStrShort(createTimeDate));
            String mpDoctor = mp.get("doctor").toString();
            String manageStatus;
            //获取最近完成服务
            sql = "select si.`code`,si.name,opr.complete_time update_time \n" +
                    "from wlyy_rehabilitation_plan_detail pd \n" +
                    "INNER  JOIN wlyy_rehabilitation_service_item si on si.`code` = pd.hospital_service_item_id \n" +
                    "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pd.id\n" +
                    "where plan_id='"+mp.get("id").toString()+"' and opr.`status` =1 ORDER BY opr.complete_time DESC ";
            List<Map<String,Object>> serverItems = jdbcTemplate.queryForList(sql);
            if(serverItems!=null&&serverItems.size()!=0){
                mp.put("completeServer",serverItems.get(0));
            }
            else{
                mp.put("completeServer","");
            }
            try {
                manageStatus = jdbcTemplate.queryForObject(sql,String.class);
            }catch (Exception e){
                manageStatus="0";
            }
            if (StringUtils.isBlank(manageStatus)||manageStatus.equals("0")){//已下转,即未接收
                mp.put("turnDownState",1);
                result.add(mp);
            }
            else{//已接受
                mp.put("turnDownState",2);
                hadManage.add(mp);
            }
        }
        result.addAll(hadManage);
        return  result;
    }
    public List<Map<String,Object>> selectByGuidance(String planId,String itemCode){
        String sql ="SELECT gm.* FROM wlyy_guidance_message_log gm LEFT JOIN wlyy_rehabilitation_plan_detail pd ON pd.id = gm.plan_detail_id " +
                "WHERE pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id = '"+itemCode+"' ORDER BY gm.create_time DESC ";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }
    @Transactional
    public String manageAllPlanByPatient(String patient,String doctor){
        String sql = "SELECT re.id,re.doctor,re.doctor_name as doctor_name,pl.id planId,pl.name as patientName,pl.create_user,pl.create_user_name specialDoctorName  \n" +
                "from  wlyy_patient_rehabilitation_plan pl \n" +
                "INNER JOIN  wlyy_doctor_patient_relation re\n" +
                "on pl.patient = re.patient \n" +
                "where   re.`status`>=0  \n" +
                "and  pl.patient ='"+patient+"' and (re.is_manage<>1 or re.is_manage is NULL) ";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planCreateName(sql);
        List<Map<String,Object>> planIds = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> planByCreate = jdbcTemplate.queryForList(sql+" GROUP BY pl.create_user");
        for (Map<String,Object> tmp:planIds){
            sql ="update wlyy_doctor_patient_relation set is_manage=1,manage_user ='"+doctor+"', manage_time ='"+DateUtil.getStringDate()+"' where id='"+tmp.get("id").toString()+"' ";
            jdbcTemplate.execute(sql);
        }
        BaseDoctorDO doctorObject = baseDoctorDao.findById(doctor);//家庭医生
        //接收患者时,给服务医生群组发送消息
        List<String> patientRelationDoctor = new ArrayList<>();
        for (Map<String,Object> tmp:planByCreate){
            try {
                if(!patientRelationDoctor.contains(tmp.get("doctor").toString())){
                    //guidanceService.sendSpecialistWeixinMessage(patient,tmp.get("doctor").toString(),2,null,null,null);
                    patientRelationDoctor.add(tmp.get("doctor").toString());
                }
                //患者服务医生群组发送Im消息
                com.alibaba.fastjson.JSONArray serverDoctorList =selectPlanServerDoctor(tmp.get("planId").toString(),doctor);
                int length = serverDoctorList.size();
                for (int i=0;i<length;i++){
                    JSONObject serverJson = serverDoctorList.getJSONObject(i);
                    if (serverJson.getString("type").equals("4")){
                        String sessionId = serverJson.getString("sessionId");
                        String message= tmp.get("specialDoctorName").toString()+"医生您好,我已确认接收管理患者"+tmp.get("patientName").toString()+",谢谢。";
                        imUtil.sendImMsg(doctor,doctorObject.getName(),sessionId,"1",message,"1","");
                    }
                }
                //发送模板消息
                /*if(messageService.getMessageNoticeSettingByMessageType(tmp.get("create_user").toString(),"1", MessageNoticeSetting.MessageTypeEnum.systemSwitch.getValue())) {
                    Doctor specialistDoctor = doctorDao.findByCode(tmp.get("create_user").toString());
                    if(StringUtils.isNoneBlank(specialistDoctor.getOpenid())){
                        Doctor SignDoctor = doctorDao.findByCode(doctor);
                        Patient p = patientDao.findByCode(patient);
                        //[医生姓名]医生您好,[医生姓名]医生已确认接收您的康复下转患者[患者姓名],请访问厦门i健康APP康复管理查看。
                        String first = specialistDoctor.getName() + "医生您好,"+SignDoctor.getName()+"医生已确认接收您的康复下转患者"
                                + p.getName() +",请访问厦门i健康APP康复管理查看。";
                        if (StringUtils.isNoneBlank(specialistDoctor.getOpenid())){
                            doctorAssistantUtil.sendWXTemplate(2,specialistDoctor.getOpenid(),first,"请及时处理","康复管理","已接收");
                        }
                    }
                }*/
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public com.alibaba.fastjson.JSONArray  selectPlanServerDoctor(String planId,String doctorCode) throws Exception{
        String sql ="SELECT t.patient,t.create_user FROM wlyy_patient_rehabilitation_plan t  where t.id='"+planId+"'";//专科
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        String patient = "";
        for (Map<String,Object> map:mapList){
            String doctor =map.get("create_user").toString();
            patient = map.get("patient").toString();
            JSONObject object = new JSONObject();
            BaseDoctorDO doctor1 = baseDoctorDao.findById(doctor);
            object.put("code",doctor1.getId());
            object.put("name",doctor1.getName());
            object.put("level",doctor1.getLevel());
            /*object.put("hospital",doctor1.getHospital());
            object.put("hospitalName",doctor1.getHospitalName());*/
            if (doctor1.getLevel()==1){
                object.put("levelName","专科医生");
            }else if (doctor1.getLevel()==2){
                object.put("levelName","全科医生");
            }
            object.put("photo",doctor1.getPhoto());
            object.put("idcard",doctor1.getIdcard());
            jsonArray.add(object);
        }
        /*SignFamily signFamily = signFamilyDao.findByPatient(patient);
        if (signFamily!=null){
            org.json.JSONObject object = new org.json.JSONObject();
            BaseDoctorDO doctor1 = baseDoctorDao.findById(signFamily.getDoctor());
            object.put("code",doctor1.getId());
            object.put("name",doctor1.getName());
            if (doctor.getLevel()==1){
                object.put("levelName","专科医生");
            }else if (doctor.getLevel()==2){
                object.put("levelName","全科医生");
            }
            object.put("photo",doctor.getPhoto());
            object.put("idcard",doctor.getIdcard());
            object.put("hospital",doctor.getHospital());
            object.put("hospitalName",doctor.getHospitalName());
            array.put(object);
            org.json.JSONObject object1 = new org.json.JSONObject();
            if (StringUtils.isNoneBlank(signFamily.getDoctorHealth())){
                BaseDoctorDO doctor1 = baseDoctorDao.findById(signFamily.getDoctorHealth());
                object1.put("code",doctor1.getId());
                object1.put("name",doctor1.getName());
                object1.put("level",3);
                object1.put("levelName","健管师");
                object1.put("photo",doctor1.getPhoto());
                object1.put("idcard",doctor1.getIdcard());
                object.put("hospital",doctor1.getHospital());
                object.put("hospitalName",doctor1.getHospitalName());
                array.put(object1);
            }
        }*/
        StringBuilder serverGroupSessionId =new StringBuilder();//群聊session_id
        StringBuilder serverGroupSessionName =new StringBuilder();//群聊名称
        JSONObject participants = new JSONObject();//群聊成员
        if (jsonArray!=null){
            for(int i=0;i<jsonArray.size();i++){//获取服务医生P2P 未读消息以及session_id。
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                serverGroupSessionId.append(jsonObject.getString("code")+"_");
                serverGroupSessionName.append(jsonObject.getString("name")+"、");
                participants.put(jsonObject.getString("code"),0);
                if(jsonObject.getString("code").equals(doctorCode)){//
                    jsonObject.put("unRead",0);
                    jsonObject.put("sessionId","");
                    jsonObject.put("type","");
                    jsonObject.put("business_type","");
                    continue;
                }
                //服务医生间的消息获取
                JSONObject participantsP2P = new JSONObject();
                participantsP2P.put(doctorCode,0);
                participantsP2P.put(jsonObject.getString("code"),0);
                //获取登录医生与其他服务医生的session_id
                //{"data":{"business_type":1,"name":"余研","id":"3438fdc6c1082c7b3c3e93dc27da244b59b694dc","type":"2","create_date":1603436112458},"status":200}
                JSONObject result = imUtil.createSession(participantsP2P,"2",jsonObject.getString("name"),null);
                jsonObject.put("sessionId",result.getJSONObject("data").getString("id"));
                jsonObject.put("type",result.getJSONObject("data").getString("type"));
                jsonObject.put("business_type",result.getJSONObject("data").getInteger("business_type"));
                //获取未读消息
                result  = imUtil.getSessionUnreadMessageCount(jsonObject.getString("sessionId"),doctorCode);
                jsonObject.put("unRead",result.getInteger("count"));
            }
        }
        //服务医生群聊数据获取
       JSONObject groupObject = new JSONObject();
        if(StringUtils.isNoneBlank(serverGroupSessionId)&&StringUtils.isNoneBlank(serverGroupSessionName)){
            serverGroupSessionId.append("server_group");
            serverGroupSessionName=serverGroupSessionName.deleteCharAt(serverGroupSessionName.length()-1);
            if(imUtil.sessionIsExist(serverGroupSessionId+"")){//会话存在
                JSONObject result  = imUtil.getSessionUnreadMessageCount(serverGroupSessionId+"",doctorCode);
                groupObject.put("unRead",result.getInteger("count"));
            }
            else{
                JSONObject result = imUtil.createSession(participants,"4",serverGroupSessionName+"",serverGroupSessionId+"");
                groupObject.put("unRead",0);
            }
            groupObject.put("name",serverGroupSessionName);
            groupObject.put("sessionId",serverGroupSessionId.toString());
            groupObject.put("business_type",1);
            groupObject.put("type","4");
        }
        jsonArray.add(groupObject);
        return  jsonArray;
    }
    /**
     * 每天8点,16点的job
     * @param startTime
     * @param endTime
     * @throws Exception
     */
    public void dailyJobSendMessage(String startTime,String endTime,Integer type) throws Exception{
        JSONArray jsonArray = dailyJob(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        Integer num = null;
        String planDetailIds = null;
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            num = (Integer)jsonObject.get("num");//需要今日需要执行的项目数
            planDetailIds = jsonObject.get("planDetailIds")+"";
            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
            message1.setType(type.toString());
            message1.setReceiver(doctor);
            message1.setRelationCode(planDetailIds);
//            specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
        }
    }
    /**
     * 每天15点的job
     * @param startTime
     * @param endTime
     * @throws Exception
     */
    public void tomorrowJobSendMessage(String startTime,String endTime,Integer type) throws Exception{
        JSONArray jsonArray =tomorrowJob(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        Integer num = null;
        String planDetailIds = null;
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            num = (Integer)jsonObject.get("num");//需要今日需要执行的项目数
            planDetailIds = jsonObject.get("planDetailIds")+"";
            String planId = jsonObject.get("id")+"";
            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
            message1.setType(type.toString());
            message1.setReceiver(doctor);
            message1.setRelationCode(planDetailIds);
            message1.setReason(planId);
//            specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
        }
    }
    /**
     * 每15分钟的job
     *
     * @param startTime
     * @param endTime
     * @param type
     * @throws Exception
     */
    public void dailyByJobSendMessage(String startTime,String endTime,Integer type) throws Exception{
        JSONArray jsonArray = dailyByJob(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        Integer num = null;
        String serviceItemName = null;
        String planDetailIds = null;
        Long timeType = null;
        String nowDate = DateUtil.getStringDate();
        String date9 = DateUtil.getStringDateShort()+" 09:00:00";//白天
        String date21 = DateUtil.getStringDateShort()+" 21:00:00";//白天
        String date9s = DateUtil.getNextDay(DateUtil.getNowDate(),1)+" 09:00:00";//晚上
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            /*num = (Integer)jsonObject.get("num");//需要今日需要执行的项目数*/
            planDetailIds = jsonObject.get("planDetailIds")+"";
            serviceItemName = jsonObject.getString("serviceItemName");
            timeType = jsonObject.getLong("timeType");
            if (timeType!=null){
                if (timeType==1  && nowDate.compareTo(date9)==1&&nowDate.compareTo(date21)==-1){
                    SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
                    message1.setType(type.toString());
                    message1.setReceiver(doctor);
                    message1.setRelationCode(planDetailIds);
                    message1.setData(serviceItemName);
//                    specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
                }else if (timeType==2 && nowDate.compareTo(date21)==1&&nowDate.compareTo(date9s)==-1){
                    SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
                    message1.setType(type.toString());
                    message1.setReceiver(doctor);
                    message1.setRelationCode(planDetailIds);
                    message1.setData(serviceItemName);
//                    specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
                }else if (timeType==0){
                    SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
                    message1.setType(type.toString());
                    message1.setReceiver(doctor);
                    message1.setRelationCode(planDetailIds);
                    message1.setData(serviceItemName);
//                    specialistEvaluateSevice.sendMessage(message1,null,patient,num,null);
                }
            }
        }
    }
    public void dailyJobReserve(Integer num,Integer type) throws Exception{
        Long time = num*24*60*60*1000L;
        String startTime = DateUtil.dateToStrShort(new Date(new Date().getTime()+time))+" "+"00:00:00";
        String endTime = DateUtil.dateToStrShort(new Date(new Date().getTime()+time))+" "+"23:59:59";
        JSONArray jsonArray=dailyJobReserve1(startTime,endTime);
        org.json.JSONObject jsonObject = null;
        String doctor = "";
        String patient ="";
        String hospital ="";
        String planDetailIds = null;
        for(int i=0;i<jsonArray.length();i++){
            jsonObject = jsonArray.getJSONObject(i);
            doctor = jsonObject.get("doctor")+"";//执行的医生(接收的医生)
            patient = jsonObject.get("patient")+"";//执行的居民
            hospital = jsonObject.get("hospital")+"";//医院
            planDetailIds = jsonObject.get("planDetailIds")+"";
            SystemMessageDO message1 = new SystemMessageDO();
//            message1.setSender(patient);
            message1.setType(type.toString());
            message1.setReceiver(doctor);
            message1.setRelationCode(planDetailIds);
//            specialistEvaluateSevice.sendMessage(message1,hospital,patient,num,null);
        }
    }
    public List<PatientMedicalRecordsDO> selectByMedicalCode(String code){
        String str[] = code.split(",");
        List<PatientMedicalRecordsDO> medicalRecordsDOS= new ArrayList<>();
        for (int i=0;i<str.length;i++){
            PatientMedicalRecordsDO medicalRecordsDO = medicalRecordsRehabilitationDao.findByCode(str[i]);
            medicalRecordsDOS.add(medicalRecordsDO);
        }
        return medicalRecordsDOS;
    }
    public List<Map<String,Object>> selectAllCompleteServiceItemsByPatient(String patient){
        List<Map<String,Object>> resutList = new ArrayList<>();
        String sql ="select A.id 'planId',pdl.id,pdl.frequency_code,A.patient,A.`name`,si.id 'code',si.`name` 'serviceName',opr.complete_time 'czrq' from  \n" +
                "(select p.team_code as teamCode,d.code as doctor,p.create_time as createTime,p.id,p.patient,p.name " +
                "from wlyy_patient_rehabilitation_plan p\n" +
                "LEFT JOIN base_doctor d ON d.id = p.create_user\n" +
                "WHERE p.patient='"+patient+"'\n" +
                "union\n" +
                "SELECT p.team_code as teamCode,d.CODE AS doctor,p.create_time AS createTime,p.id,p.patient,p.name " +
                "from \n" +
                " wlyy_patient_rehabilitation_plan p\n" +
                "LEFT JOIN base_doctor d ON d.id=p.create_user\n" +
                "LEFT JOIN (\n" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code \n" +
                "FROM wlyy_doctor_patient_relation sr \n" +
                "JOIN wlyy_doctor_special_share se ON se.special_code=sr.id \n" +
                "WHERE sr.patient='"+patient+"') d \n" +
                "ON d.patient=p.patient WHERE \n" +
                "p.patient='"+patient+"' \n" +
                "\n" +
                "ORDER BY createTime DESC)A \n" +
                "INNER  JOIN wlyy_rehabilitation_plan_detail pdl ON A.id = pdl.plan_id\n" +
                "INNER JOIN wlyy_rehabilitation_service_item si on pdl.hospital_service_item_id = si.id\n" +
                "INNER JOIN wlyy_rehabilitation_operate_records opr on opr.rehabilitation_detail_id = pdl.id\n" +
                "where pdl.hospital_service_item_id <>2 and  opr.`status`=1 order by opr.complete_time desc ";
        sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> planDetailList = jdbcTemplate.queryForList(sql);
        resutList.addAll(planDetailList);
        //康复咨询
        sql= "select ct.consult,ct.type,ct.patient,ct.name,ct.czrq,ct.symptoms,top.`status`,top.end_time,top.evaluate,top.evaluate_time,top.reply,top.reply_time, '2' as 'serviceId','康复咨询' as 'serviceName'\n" +
                "from wlyy_consult_team ct\n" +
                "INNER JOIN im_internet_hospital.topics top on top.id = ct.consult \n" +
                "where ct.patient='"+patient+"' and ct.type=18 and ct.del=1";
        List<Map<String,Object>> kangFuList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:kangFuList){
            if (map.get("status").toString().equals("0")&&map.get("reply").toString().equals("0")){
                map.put("serviceStatus","未回复");
            }
            if (map.get("status").toString().equals("0")&&map.get("reply").toString().equals("1")){
                map.put("serviceStatus","未结束");
            }
            if (map.get("status").toString().equals("10")){//&&map.get("evaluate").toString().equals("0")
                map.put("serviceStatus","已结束");
            }
//            if (map.get("status").toString().equals("10")&&map.get("evaluate").toString().equals("1")){
//                map.put("serviceStatus","已结束");
//            }
        }
        resutList.addAll(kangFuList);
        Collections.sort(resutList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Timestamp map1value = (Timestamp) o1.get("czrq");
                Timestamp  map2value = (Timestamp) o2.get("czrq");
                int sort = 1;
                if (map1value.getTime() - map2value.getTime() > 0) {
                    return sort == 1 ? -1 : 1;
                } else if (map1value.getTime() - map2value.getTime() < 0) {
                    return sort == 1 ? 1 : -1;
                } else {
                    return 0;
                }
            }
        });
        return resutList;
    }
    public JSONArray getPlanDetailForModifing(String planId,String templateId){
        String sql;
        JSONArray result = new JSONArray();
        if(StringUtils.isBlank(templateId)){
            sql ="select id from wlyy_rehabilitation_plan_template where title='系统模板'";
            templateId = jdbcTemplate.queryForObject(sql,String.class);
        }
        sql = "select d.hospital_service_item_id as code,i.`name`\n" +
                "from wlyy_rehabilitation_template_detail d LEFT JOIN wlyy_rehabilitation_service_item i\n" +
                "ON i.`code` = d.hospital_service_item_id\n" +
                "where d.template_id = '"+templateId+"'";
        List<Map<String,Object>> templateDetailList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:templateDetailList){
            sql ="select d.*,DATE_FORMAT(d.execute_time,'%Y/%m/%d %H:%i') as executeTime ,i.code,i.name \n" +
                    "from wlyy_rehabilitation_plan_detail d \n" +
                    "LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  \n" +
                    "where  d.plan_id ='"+planId+"' AND  d.execute_time IS NOT NULL  and d.execute_time <>''\n" +
                    "AND d.`status`<> 1\n" +
                    "and d.hospital_service_item_id ='"+map.get("code").toString()+"'\n" +
                    "ORDER BY hospital_service_item_id ASC,execute_time ASC;";
            sql = TransforSqlUtl.wlyy_rehabilitation_plan_detailAll2(sql);
            List<Map<String,Object>> planDetailList = jdbcTemplate.queryForList(sql);
            org.json.JSONObject temp = new org.json.JSONObject();
            temp.put("counts",planDetailList.size());
            temp.put("code",map.get("code").toString());
            temp.put("name",map.get("name").toString());
            temp.put("list",planDetailList);
            result.put(temp);
        }
        return result;
    }
    public org.json.JSONObject selectBySpecialistDoctor(String level, String area, String doctor, String disease, Integer page, Integer pageSize, String doctorType, String patientInfo, String filterPlan, String turnDownState){
        Integer turnDownStateTotal_0=0;//全部
        Integer turnDownStateTotal_1=0;//已下转
        Integer turnDownStateTotal_2=0;//已接受
        Integer turnDownStateTotal_3=0;//未下转
        org.json.JSONObject resultObj = new org.json.JSONObject();
        BaseDoctorDO doctorObj = baseDoctorDao.findById(doctor);
        List<Map<String, Object>> result = new ArrayList<>();
        String sql = "SELECT DISTINCT pr.id,p.`name`,plan.id as planId, p.`id` as code, p.idcard,p.photo, plan.disease,plan.disease_name,YEAR (now()) - YEAR (substring(p.idcard, 7, 8)) as age," +
                "p.sex,pr.doctor AS specialist,pr.doctor_name AS specialistName,pr.disease_code,pr.doctor_name ," +
                "pr.doctor, pr.health_doctor, pr.health_doctor_name, pr.is_manage,pr.manage_user,pr.manage_time FROM" +
                " base_doctor doc,`wlyy_doctor_patient_relation` pr" +
                " LEFT JOIN base_patient p ON p.`id` = pr.patient ";
        //关联居民计划表
        if("1".equals(filterPlan)){
            sql = sql + " INNER JOIN `wlyy_patient_rehabilitation_plan` plan on plan.patient = pr.patient ";
        }
        sql =sql+ " WHERE  doc.`id` = pr.doctor  ";
        String sqlCondition = "";
        if (doctorType.equalsIgnoreCase("1")){
            sqlCondition +=" AND pr.doctor = '"+doctor+"'";
        }else {
            sqlCondition +=" AND (pr.doctor = '"+doctor+"' or pr.health_doctor = '"+doctor+"') ";
        }
        if(StringUtils.isNoneBlank(patientInfo)){
            sqlCondition +=" AND (p.idcard like '%"+patientInfo+"%' OR p.`name`like '%"+patientInfo+"%') ";
        }
       /* if (level.equalsIgnoreCase("1")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.city='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("2")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.town='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("3")){
            sqlCondition +=" and sf.hospital = '"+area+"' ";
        }*/
        /*if (StringUtils.isNoneBlank(disease)){
            sqlCondition +=" and pr.id IN (SELECT pds.specialist_relation_code FROM wlyy_patient_disease_server pds WHERE  pds.del=1 and pds.disease ='"+disease+"')";
        }*/
        //LIMIT+(page-1)*pageSize+","+pageSize
        sqlCondition += " ORDER BY pr.create_time DESC  ";
        sql += sqlCondition;
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        System.out.println("mapList"+sql);
        for (Map<String,Object> map:mapList){
            BasePatientDO patientDo = basePatientDao.findById(map.get("code").toString());
            List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (depts!=null&&depts.size()>0){
                map.put("dept_code",depts.get(0).getDeptCode());
                map.put("dept_name",depts.get(0).getDeptName());
            }
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(patientDo.getIdcard(),patientDo.getBirthday());
            map.put("age",age);
            String specialistRelationCode = map.get("id").toString();
            String relationManageState = map.get("is_manage")==null?"0":map.get("is_manage").toString();//管理状态
            /*List<PatientDiseaseServer> diseaseServers = patientDiseaseServerDao.findBySpecialistRelationCodeAndDel(specialistRelationCode,"1");
            StringBuffer diseaseName = new StringBuffer();
            for (int i=0;i<diseaseServers.size();i++){
                diseaseName.append(diseaseServers.get(i).getDiseaseName()+",");
            }
            if(StringUtils.isNoneBlank(diseaseName)){
                diseaseName.deleteCharAt(diseaseName.length()-1);
            }
            map.put("disease_name",diseaseName);*/
            if(StringUtils.isBlank(relationManageState)||!relationManageState.equals("1")){//未进行管理
                map.put("turnDownState", 1);//已下转
                turnDownStateTotal_1+=1;
                turnDownStateTotal_0+=1;
                if(turnDownState.equals("1")||turnDownState.equals("0")){
                    result.add(map);
                }
            }
            else{
                map.put("turnDownState", 2);//已管理
                turnDownStateTotal_2+=1;
                turnDownStateTotal_0+=1;
                if(turnDownState.equals("2")||turnDownState.equals("0")){
                    result.add(map);
                }
            }
        }
        //家医端未下转(签约居民,但是还未下转的居民) 专科医生端未下转(与未下转列表同-去除未家签)
        if (doctorType.equalsIgnoreCase("1")){//专科
            sql = "select null as id,p.`name`,p.`id` as code,p.idcard,p.photo,YEAR (now()) - YEAR (substring(p.idcard, 7, 8)) AS age, p.sex,d.create_user AS specialist,d.create_user_name AS specialistName,\n" +
                    " d.doctor_name,d.doctor,d.health_doctor,d.health_doctor_name,null as is_manage,null as manage_user,null as manage_time \n" +
                    "from wlyy_doctor_patient_relation d,base_patient p ,base_doctor doc where doc.`id` = d.create_user AND d.create_user='"+doctor+"' ";
        }
        sqlCondition="";
        if(StringUtils.isNoneBlank(patientInfo)){
            sqlCondition +=" AND (p.idcard like '%"+patientInfo+"%' OR p.`name`like '%"+patientInfo+"%') ";
        }
       /* if (level.equalsIgnoreCase("1")){
            sqlCondition +=" and s.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.city='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("2")){
            sqlCondition +=" and s.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.town='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("3")){
            sqlCondition +=" and s.hospital = '"+area+"' ";
        }*/
        if (StringUtils.isNoneBlank(disease)){
            sqlCondition +=" AND d.patient in (select patient from wlyy_patient_disease_server pds where pds.del=1 and pds.disease ='"+disease+"') ";
        }
        sql  = sql + sqlCondition ;
        if (doctorType.equalsIgnoreCase("1")){//专科
            sql = sql+ " \n" +
                    " AND d.patient = p.id  \n" +
                    "AND d.patient NOT IN ( SELECT i.patient FROM wlyy_patient_rehabilitation_plan i, base_patient p \n" +
                    "WHERE i.create_user='"+doctor+"' AND i. STATUS != 0  AND p. id = i.patient    \n" +
                    "GROUP BY i.patient ORDER BY i.create_time DESC) GROUP BY d.patient ORDER BY d.create_time DESC ";
        }
        List<Map<String, Object>> mapList12 = jdbcTemplate.queryForList(sql);
        System.out.println("mapList2"+sql);
        for (Map<String, Object> map : mapList12) {
            List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (depts!=null&&depts.size()>0){
                map.put("dept_code",depts.get(0).getDeptCode());
                map.put("dept_name",depts.get(0).getDeptName());
            }
            BasePatientDO patientDo = basePatientDao.findById(map.get("code").toString());
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(patientDo.getIdcard(),patientDo.getBirthday());
            map.put("age",age);
            map.put("disease_name", "暂无");
            map.put("turnDownState",3);//未下
            turnDownStateTotal_3+=1;
            turnDownStateTotal_0+=1;
            if(turnDownState.equals("3")||turnDownState.equals("0")){
                result.add(map);
            }
        }
        org.json.JSONObject turnDownStateObj = new org.json.JSONObject();
        turnDownStateObj.put("stateAll",turnDownStateTotal_0);//全部
        turnDownStateObj.put("stateDown",turnDownStateTotal_1);//已下转
        turnDownStateObj.put("stateReceive",turnDownStateTotal_2);//已接受
        turnDownStateObj.put("stateNotDown",turnDownStateTotal_3);//未下转
        resultObj.put("showList",result);
        resultObj.put("turnDownState",turnDownStateObj);
        return resultObj;
    }
    /**
     * 康复管理-生成康复下转专科医生二维码
     * @param doctorCode
     * @param teamCode
     * @param teamName
     * @return
     * @throws Exception
     */
    public String createSpecialDoctorQrCode(String doctorCode,String teamCode,String teamName) throws Exception{
        Map<String, Object> param = new HashedMap();
        String fileUrl = "";
        String appId="";
        //生成二维码图片
        String contentJsonStr="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+""+"%2fwx%2fhtml%2fkfgl%2fhtml%2frecover_manage.html%3FdoctorCode%3D"+doctorCode+"%26teamCode%3D"+teamCode+"%26teamName%3D"+teamName+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        InputStream ipt = QrcodeUtil.createQrcode(contentJsonStr, 300, "png");
        if (isneiwang) {
            // 圖片列表
            List<String> tempPaths = new ArrayList<String>();
            try {
                ObjectNode imgNode = fastDFSUtil.upload(ipt, "png", "plan_service_qrcode" + System.currentTimeMillis());
                com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(imgNode.toString());
                tempPaths.add(json.getString("fid"));
                String urls = "";
                for (String image : tempPaths) {
                    if (urls.length() == 0) {
                        urls = image;
                    } else {
                        urls += "," + image;
                    }
                }
                fileUrl = "" + urls;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                //fileUrl = "" + CommonUtil.PrescriptionQRCodetoNeiWang(ipt);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println("服务码-----------1"+fileUrl);
        param.put("doctorCode", doctorCode);
        param.put("imageUrl",fileUrl);
        return fileUrl;
    }
    public org.json.JSONObject selectBySpecialistDoctor1(String level, String area, String doctor, String disease, Integer page, Integer pageSize, String doctorType, String patientInfo, String filterPlan, String turnDownState){
        Integer turnDownStateTotal_0=0;//全部
        Integer turnDownStateTotal_1=0;//已下转
        Integer turnDownStateTotal_2=0;//已接受
        Integer turnDownStateTotal_3=0;//未下转
        org.json.JSONObject resultObj = new org.json.JSONObject();
        List<Map<String, Object>> result = new ArrayList<>();
        String sql = "select DISTINCT t.id as \"id\"," +
                " p.name as \"name\"," +
                " p.id as \"code\"," +
                " p.idcard as \"idcard\"," +
                " p.photo as \"photo\"," +
                " p.sex as \"sex\"," +
                " t.disease as \"disease\"," +
                " t.disease_name as \"disease_name\"," +
                " YEAR (now()) - YEAR (substring(p.idcard, 7, 8)) as age," +
                " d.doctor as \"doctor\"," +
                " d.doctor_name as \"doctor_name\"," +
                " t.create_user as \"create_user\"," +
                " t.create_user_name as \"create_user_name\"," +
                " t.create_time as \"create_time\"," +
                " t.is_verify as \"is_verify\"" +
                " from wlyy_patient_rehabilitation_plan t left  join wlyy_rehabilitation_plan_detail d on t.id =d.plan_id" +
                " left join base_doctor doc on d.doctor=doc.id LEFT JOIN base_patient p ON p.`id` = t.patient" +
                " where 1=1 " ;
        if(StringUtils.isNoneBlank(patientInfo)){
            sql +=" AND (p.idcard like '%"+patientInfo+"%' OR p.`name`like '%"+patientInfo+"%') ";
        }
        if (doctorType.equalsIgnoreCase("1")){
            sql +=" AND d.doctor = '"+doctor+"'";
        }else {
            sql +=" AND (d.doctor = '"+doctor+"' or t.create_user = '"+doctor+"') ";
        }
       /* if (level.equalsIgnoreCase("1")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.city='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("2")){
            sqlCondition +=" and sf.hospital IN ( SELECT dh.`code` FROM `dm_hospital` dh where dh.town='"+area+"' and dh.del=1 )";
        }else if (level.equalsIgnoreCase("3")){
            sqlCondition +=" and sf.hospital = '"+area+"' ";
        }*/
        /*if (StringUtils.isNoneBlank(disease)){
            sqlCondition +=" and pr.id IN (SELECT pds.specialist_relation_code FROM wlyy_patient_disease_server pds WHERE  pds.del=1 and pds.disease ='"+disease+"')";
        }*/
        //LIMIT+(page-1)*pageSize+","+pageSize
        sql += " ORDER BY p.create_time DESC  ";
        List<Map<String,Object>> mapList = hibenateUtils.createSQLQuery(sql,page,pageSize);
        System.out.println("mapList"+sql);
        for (Map<String,Object> map:mapList){
            BasePatientDO patientDo = basePatientDao.findById(map.get("code").toString());
            List<BaseDoctorHospitalDO> depts= baseDoctorHospitalDao.findByDoctorCode(doctor);
            if (depts!=null&&depts.size()>0){
                map.put("dept_code",depts.get(0).getDeptCode());
                map.put("dept_name",depts.get(0).getDeptName());
            }
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(patientDo.getIdcard(),patientDo.getBirthday());
            map.put("age",age);
            String specialistRelationCode = map.get("id").toString();
            String relationManageState = map.get("is_verify")==null?"0":map.get("is_verify").toString();//管理状态
            /*List<PatientDiseaseServer> diseaseServers = patientDiseaseServerDao.findBySpecialistRelationCodeAndDel(specialistRelationCode,"1");
            StringBuffer diseaseName = new StringBuffer();
            for (int i=0;i<diseaseServers.size();i++){
                diseaseName.append(diseaseServers.get(i).getDiseaseName()+",");
            }
            if(StringUtils.isNoneBlank(diseaseName)){
                diseaseName.deleteCharAt(diseaseName.length()-1);
            }
            map.put("disease_name",diseaseName);*/
            if(StringUtils.isBlank(relationManageState)||!relationManageState.equals("1")){
                map.put("turnDownState", 1);//已确认
                turnDownStateTotal_1+=1;
                turnDownStateTotal_0+=1;
                if(turnDownState.equals("1")||turnDownState.equals("0")){
                    result.add(map);
                }
            }
            else{
                map.put("turnDownState", 2);//未确认
                turnDownStateTotal_2+=1;
                turnDownStateTotal_0+=1;
                result.add(map);
            }
        }
        org.json.JSONObject turnDownStateObj = new org.json.JSONObject();
        turnDownStateObj.put("stateAll",turnDownStateTotal_0);//全部
        turnDownStateObj.put("stateDown",turnDownStateTotal_1);//已下转
        turnDownStateObj.put("stateReceive",turnDownStateTotal_2);//已接受
        turnDownStateObj.put("stateNotDown",turnDownStateTotal_3);//未下转
        resultObj.put("showList",result);
        resultObj.put("turnDownState",turnDownStateObj);
        return resultObj;
    }
    public List<Map<String,Object>> calendarPlanDetailItems(String executeStartTime, String executeEndTime, String planId, Integer searchTask, Integer status, String doctorCode) throws Exception{
        String sqlCondition = "";
        if (searchTask!=null){
            if(searchTask==8){
                sqlCondition+="and d.doctor='"+doctorCode+"' ";
            }else {
                sqlCondition+=" and i.code="+searchTask+" " ;
            }
        }
        if(status!=null){
            sqlCondition  += "and d.status="+status;
        }//服务项目
        String sql = " select d.id,d.plan_id as planId,i.code,i.name,p.patient,d.frequency_code,DATE_FORMAT(d.create_time,'%Y-%m-%d %H:%i:%s') as createTime from wlyy_rehabilitation_plan_detail d " +
                " LEFT JOIN wlyy_patient_rehabilitation_plan p ON p.id=d.plan_id " +
                " LEFT JOIN wlyy_rehabilitation_service_item i on i.code = d.hospital_service_item_id  " +
                " where   d.plan_id='"+planId+"' "+sqlCondition+"  group by i.code";
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:mapList){
            String sql1 = "SELECT d.frequency_code,d.plan_id as planId ,d.id,DATE_FORMAT(d.create_time,'%Y-%m-%d %H:%i:%s') AS createTime " +
                    "FROM wlyy_rehabilitation_plan_detail d " +
                    "WHERE d.plan_id = '"+planId+"' and d.hospital_service_item_id='"+map.get("code")+"'ORDER BY d.create_time DESC";
            List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sql1);
            if (mapList1!=null&&mapList1.size()!=0){
                Map<String,Object> map1 = mapList1.get(0);
                map.put("frequency_code",map1.get("frequency_code"));
                map.put("planId",map1.get("planId"));
                map.put("id",map1.get("id"));
                map.put("createTime",map1.get("createTime"));
            }
        }
        for (Map<String,Object> map:mapList){
            if (!StringUtils.isNoneBlank(map.get("frequency_code").toString())){//
                String sqlCount = "SELECT ror.id,MAX(ror.complete_time) as date,count(*) as total FROM `wlyy_rehabilitation_operate_records` ror, " +
                        "wlyy_rehabilitation_plan_detail pd WHERE pd.id = ror.rehabilitation_detail_id " +
                        "AND pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id='"+map.get("code")+"' AND ror.`status`=1 ";
                List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sqlCount);
                int count = 0;
               /* if (map.get("code").toString().equalsIgnoreCase("6")){
                    String allPlanSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate,\n" +
                            "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName,\n" +
                            "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard,\n" +
                            "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode,\n" +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                            "and wf.patient_code = '"+map.get("patient")+"' order by wf.followup_plan_date desc";
                    List<Map<String , Object>> allPlanList = jdbcTemplate.queryForList(allPlanSql);
                    count = allPlanList.size();
                }*/
                /*if (map.get("code").toString().equalsIgnoreCase("7")){
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`, \n" +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime \n" +
                            "FROM wlyy_prescription pr LEFT JOIN wlyy_patient p ON pr.patient = p.`code` WHERE 1=1 AND pr.patient = '"+map.get("patient")+"' AND pr.status = 100 GROUP BY pr.`code`;";
                    List<Map<String , Object>> allPrescrList = jdbcTemplate.queryForList(allPrescrSql);
                    count = allPrescrList.size();
                }
                if (mapList1!=null && mapList1.size()!=0){
                    Map<String,Object> map1 = mapList1.get(0);
                    map.put("compeletTotal",new Integer(map1.get("total").toString()) + count );
                    map.put("firstDate",map1.get("date"));
                }*/
            }else {
                int codeCount = 0 ;
               /* if (map.get("code").toString().equalsIgnoreCase("6")){ //康复随访
                    //该居民的所有随访计划,需要同步展示到康复计划-康复随访内
                    String allPlanSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as followupDate,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate,\n" +
                            "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName,\n" +
                            "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard,\n" +
                            "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode,\n" +
                            "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                            "and wf.patient_code = '"+map.get("patient")+"' order by wf.followup_plan_date desc";
                    List<Map<String , Object>> allPlanList = jdbcTemplate.queryForList(allPlanSql);
                    codeCount = allPlanList.size();
                    map.put("allPlanList",allPlanList);
                }
                if (map.get("code").toString().equalsIgnoreCase("7")){ //康复复诊
                    //居民的处方续方,需要同步展示到康复计划-康复复诊内
                    String allPrescrSql = "SELECT p.`name`, TIMESTAMPDIFF(YEAR,p.birthday,SYSDATE()) age, p.sex, p.photo, pr.`status`, pr.`code`, \n" +
                            "LEFT(pr.create_time,19) AS createTime, pr.doctor, pr.min_drug_day AS minDrugDay, LEFT(pr.pres_create_time,19) AS presCreateTime \n" +
                            "FROM wlyy_prescription pr LEFT JOIN wlyy_patient p ON pr.patient = p.`code` WHERE 1=1 AND pr.patient = '"+map.get("patient")+"' AND pr.status = 100 GROUP BY pr.`code`;";
                    List<Map<String , Object>> allPrescrList = jdbcTemplate.queryForList(allPrescrSql);
                    codeCount = allPrescrList.size();
                    map.put("allPrescrList",allPrescrList);
                }*/
                String sqlCount="SELECT\n" +
                        "\tCOUNT(pd.id) AS total ,\n" +
                        "\tCOUNT(CASE WHEN pd.`status`=1 THEN 1 ELSE NULL END) AS compeletTotal\n" +
                        "FROM\n" +
                        "\t wlyy_rehabilitation_plan_detail pd\n" +
                        "WHERE\n" +
                        "\t pd.plan_id = '"+planId+"' " +
                        "AND pd.hospital_service_item_id='"+map.get("code")+"' and (pd.frequency_code IS NOT NULL AND pd.frequency_code<>'')\n";
                List<Map<String,Object>> mapList1 = jdbcTemplate.queryForList(sqlCount);
                if (mapList1!=null && mapList1.size()!=0){
                    Map<String,Object> map1 = mapList1.get(0);
                    map.put("total",new Integer(map1.get("total").toString()) + codeCount);
                    map.put("compeletTotal",new Integer(map1.get("compeletTotal").toString()) + codeCount);
                }
                String dateSql = "SELECT  MAX(CASE WHEN pd.`status`=1 THEN pd.execute_time ELSE NULL END) AS firstDate FROM wlyy_rehabilitation_plan_detail pd " +
                        "WHERE  pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id='"+map.get("code")+"'";
                List<Map<String,Object>> mapList2 = jdbcTemplate.queryForList(dateSql);
                if (mapList2!=null && mapList2.size()!=0){
                    Map<String,Object> map1 = mapList2.get(0);
                    map.put("firstDate",map1.get("firstDate"));
                    String condition = "";
                    if (map1.get("firstDate")!=null&&StringUtils.isNoneBlank(map1.get("firstDate").toString())){
                        condition = "and pd.execute_time >='"+map1.get("firstDate").toString()+"'";
                    }
                    String dateSql1 = "SELECT pd.execute_time as lastDate  FROM wlyy_rehabilitation_plan_detail pd " +
                            "WHERE  pd.plan_id = '"+planId+"' AND pd.hospital_service_item_id='"+map.get("code")+"' and pd.status=0  "+condition+" order by pd.execute_time ASC ";
                    List<Map<String,Object>> mapList3 = jdbcTemplate.queryForList(dateSql1);
                    if (mapList3!=null&&mapList3.size()!=0){
                        Map<String,Object> map2 = mapList3.get(0);
                        map.put("lastDate",map2.get("lastDate"));
                    }else {
                        map.put("lastDate",null);
                    }
                }
            }
            if (map.get("code").toString().equalsIgnoreCase("2"))
            {//康复咨询
                //总康复咨询数量
                String sqlTotal = "select count(*)\n" +
                        "from wlyy_consult a,wlyy_consult_team b where a.id = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18";
                Integer consultTotal = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
               /* String healthCount = "SELECT * FROM wlyy_patient_reservation WHERE incidental_msg_type = 0 AND source = 4 AND patient = '"+map.get("patient")+"' ORDER BY start_time DESC";
                List<Map<String , Object>> healthList = jdbcTemplate.queryForList(healthCount);
                map.put("healthList",healthList);
                map.put("total",consultTotal + healthList.size());*/
                //完成康复咨询数量
               /* sqlTotal = "select count(*)\n" +
                        "from wlyy_consult a,wlyy_consult_team b where a.code = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18 and b.`status`=1";
                consultTotal = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
                map.put("compeletTotal",consultTotal + healthList.size());*/
                //上次发起时间
                String sqlTemp ="select a.czrq\n" +
                        "from wlyy_consult a,wlyy_consult_team b where a.id = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18 order by a.czrq desc limit 1";
                List<Map<String,Object>> czrqMap = jdbcTemplate.queryForList(sqlTemp);
                if(czrqMap.size()!=0){
                    if(czrqMap.get(0).get("czrq")!=null){
                        map.put("lastDate",czrqMap.get(0).get("czrq").toString());
                    }
                }
                else{
                    map.put("lastDate",null);
                }
               /* //未回复康复咨询数量
                sqlTotal="SELECT count(*) FROM wlyy.wlyy_consult_team a WHERE a.type = 18\n" +
                        "AND EXISTS ( SELECT DISTINCT t.id consultId FROM "+imDBName+".topics t, "+imDBName+".participants p, "+imDBName+".doctors d, "+imDBName+".sessions s \n" +
                        "WHERE p.participant_id = d.id AND t.session_id = p.session_id AND t.session_id = s.id\n" +
                        "AND s.type =18  AND t.`reply` = 0  AND a.consult = t.id\n" +
                        "and a.id in( select b.id from wlyy_consult a,wlyy_consult_team b \n" +
                        "where a.code = b.consult and a.patient = '"+map.get("patient")+"' and a.del = '1' and a.type=18 )\n" +
                        ")";
                Integer noReplay = jdbcTemplate.queryForObject(sqlTotal,Integer.class);
                map.put("noReplay",noReplay);*/
            }
        }
        return mapList;
    }
    public PatientRehabilitationPlanDO confirmManage(String patient,String signDoctor,String specialist,String relationId,String planId) throws Exception {
        String sqlCondition;
        if (StringUtils.isNoneBlank(relationId)){
            sqlCondition=" and pr.id='"+relationId+"' ";
        }
        else{
            sqlCondition=" and pr.doctor = '"+specialist+ "'";
        }
        PatientRehabilitationPlanDO patientRehabilitationPlanDO = patientRehabilitationPlanDao.findById(planId);
        if (patientRehabilitationPlanDO!=null){
            patientRehabilitationPlanDO.setIsVerify("1");
            patientRehabilitationPlanDao.save(patientRehabilitationPlanDO);
            String specialistSql = "select pr.doctor,pr.patient from wlyy_doctor_patient_relation pr where pr.patient='"+patient+"' "+sqlCondition;
            List<Map<String,Object>> mapList = jdbcTemplate.queryForList(specialistSql);
            if (mapList!=null&&mapList.size()!=0){
                Map<String,Object> map = mapList.get(0);
                String doctor = (String)map.get("doctor");
                String patient1 = (String)map.get("patient");
                //guidanceService.sendSpecialistWeixinMessage(patient1,doctor,2,null,null,null);
            }
            //下转患者被家庭医生确认管理时,专科医生收到推送
            /*if(messageService.getMessageNoticeSettingByMessageType(specialist,"1", MessageNoticeSetting.MessageTypeEnum.systemSwitch.getValue())) {
                Doctor specialistDoctor = doctorDao.findByCode(specialist);
                if(StringUtils.isNoneBlank(specialistDoctor.getOpenid())){
                    Doctor doctor = doctorDao.findByCode(signDoctor);
                    Patient p = patientDao.findByCode(patient);
                    //[医生姓名]医生您好,[医生姓名]医生已确认接收您的康复下转患者[患者姓名],请访问厦门i健康APP康复管理查看。
                    String first = specialistDoctor.getName() + "医生您好,"+doctor.getName()+"医生已确认接收您的康复下转患者"
                            + p.getName() +",请访问厦门i健康APP康复管理查看。";
                    doctorAssistantUtil.sendWXTemplate(2,specialistDoctor.getOpenid(),first,"请及时处理","康复管理","已接收");
                }
            }*/
            //确认管理给管理医生群组发送消息
           /* if (StringUtils.isNoneBlank(planId)){
                try {
                    JSONArray serverDoctorList =selectPlanServerDoctor(planId,signDoctor);
                    int length = serverDoctorList.length();
                    BaseDoctorDO doctor = baseDoctorDao.findById(signDoctor);
                    Patient p = patientDao.findByCode(patient);
                    Doctor specialistDoctor = doctorDao.findByCode(specialist);
                    for (int i=0;i<length;i++){
                        org.json.JSONObject serverJson = serverDoctorList.getJSONObject(i);
                        if (serverJson.getString("type").equals("4")){
                            String sessionId = serverJson.getString("sessionId");
                            String message= specialistDoctor.getName()+"医生您好,我已确认接收管理患者"+p.getName()+",谢谢。";
                            ImUtill.sendImMsg(signDoctor,doctor.getName(),sessionId,"1",message,"1");
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }*/
        }
        return patientRehabilitationPlanDO;
    }
    public org.json.JSONObject selectByPlanDetaiId(String patient, String planId, String code, Integer page, Integer pagesize){
        org.json.JSONObject object = new org.json.JSONObject();
        String sql ="SELECT\n" +
                " DATE_FORMAT(r.complete_time,'%Y-%m-%d %H:%i:%s') AS completeTime," +
                " r.doctor_code AS doctorCode," +
                " r.doctor_name AS doctorName," +
                " r.`status`," +
                " r.id as recordId," +
                " si.`name`," +
                " si.`code`," +
                " pd.plan_id," +
                " pd.id," +
                " r.relation_code as relationCode," +
                " r.flag " +
                "FROM " +
                " wlyy_rehabilitation_operate_records r " +
                "LEFT JOIN wlyy_rehabilitation_plan_detail pd ON r.rehabilitation_detail_id = pd.id " +
                "LEFT JOIN wlyy_rehabilitation_service_item si ON si.code= pd.hospital_service_item_id " +
                "LEFT JOIN base_doctor d ON d.id = r.doctor_code " +
                "WHERE " +
                " pd.plan_id = '"+planId+"' " +
                " AND pd.hospital_service_item_id = '"+code+"' " +
                "ORDER BY " +
                " r.complete_time DESC " ;
        sql = TransforSqlUtl.wlyy_rehabilitation_operate_recordsDoctorName(sql);
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        String sqlCount ="SELECT\n" +
                "\tCOUNT(*) as total\n" +
                "FROM\n" +
                "\t wlyy_rehabilitation_operate_records r\n" +
                "LEFT JOIN wlyy_rehabilitation_plan_detail pd ON r.rehabilitation_detail_id = pd.id\n" +
                "LEFT JOIN wlyy_rehabilitation_service_item si ON si.code= pd.hospital_service_item_id\n" +
                "LEFT JOIN base_doctor d ON d.id = r.doctor_code\n" +
                "WHERE\n" +
                "\t pd.plan_id = '"+planId+"'\n" +
                "\t\tAND pd.hospital_service_item_id = '"+code+"'\n";
        List<Map<String,Object>> maps = jdbcTemplate.queryForList(sqlCount);
        /*String followupSql = "select  wf.id as id,wf.followup_no as followupNo,wf.followup_date as completeTime,wf.followup_plan_date as followupPlanDate,wf.followup_next_date as followupNextDate,\n" +
                "wf.followup_type as followupType,wf.followup_class as followupClass,wf.followup_manager_status as followupManagerStatus,wf.doctor_code as doctorCode,wf.doctor_name as doctorName,\n" +
                "wf.jwdoctor_code as jwdoctorCode,wf.org_code as orgCode,wf.org_name as orgName,wf.jworg_code as jworgCode,wf.patient_code as patientCode,wf.patient_name as patientName,wf.idcard,\n" +
                "wf.data_from as dataFrom,wf.status,wf.followup_content_phone as followupContentPhone,wf.creater,wf.sign_type as signType,wf.admin_team_code as adminTeamCode,wf.sign_code as signCode,\n" +
                "wf.prescription_code as prescriptionCode,wf.type from wlyy_followup wf where 1=1 and wf.status !=0\n" +
                "and wf.patient_code = '"+patient+"' ";
        List<Map<String,Object>> followupList = jdbcTemplate.queryForList(followupSql);
        mapList.addAll(followupList);*/
        Collections.sort(mapList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Timestamp map1value = (Timestamp) o1.get("completeTime");
                Timestamp map2value = (Timestamp) o2.get("completeTime");
                int sort = 1;
                if (map1value.getTime() - map2value.getTime() > 0) {
                    return sort == 1 ? -1 : 1;
                } else if (map1value.getTime() - map2value.getTime() < 0) {
                    return sort == 1 ? 1 : -1;
                } else {
                    return 0;
                }
            }
        });
        object.put("list",startPage(mapList,page,pagesize));
        object.put("total",new Integer(maps.get(0).get("total").toString()) );
        object.put("page",page);
        object.put("pagesize",pagesize);
        return  object;
    }
    /**
     * 开始分页
     * @param list
     * @param pageNum 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List startPage(List list, Integer pageNum,
                                 Integer pageSize) {
        if (pageNum == null){
            pageNum = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }
    /**
     * 获取康复服务项目列表
     * @return
     * @param name
     */
    public List<Map<String, Object>> getServiceItemList(String name) {
        String sql = "SELECT code,`name` FROM `wlyy_rehabilitation_service_item` ";
        if(StringUtils.isNotBlank(name)){
            sql += "where name like '%" + name + "%' ";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public List<PatientMedicalRecordsDO> getNewRehabilitation(String patient,String doctorCode) throws Exception {
        //智业中山同步病历
        String result = "";
        List<PatientMedicalRecordsDO> query = new ArrayList<>();
        BasePatientDO patient1 = basePatientDao.findById(patient);
        BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
        String orgCode="";
        List<BaseDoctorHospitalDO> baseDoctorHospitalDO = baseDoctorHospitalDao.findByDoctorCode(doctorCode);
        if(baseDoctorHospitalDO!=null&&baseDoctorHospitalDO.size()>0){
            orgCode=baseDoctorHospitalDO.get(0).getOrgCode();
        }
        if (demoFlag) {//demoFlag
            result = patientRecordService.getJosnFileResullt("event" + "2");
        } else {
            org.json.JSONObject jsonEvent = new org.json.JSONObject();
            List<Map<String, String>> resultMap = patientRecordService.getAllEvent_new(patient, "2", "1", "1", "2010-10-10 00:00:00",orgCode);
            jsonEvent.put("data", JSON.parseArray(JSON.toJSONString(resultMap)));
            result = jsonEvent.toString();
        }
        com.alibaba.fastjson.JSONObject rejson = com.alibaba.fastjson.JSONObject.parseObject(result);
        com.alibaba.fastjson.JSONArray temlist = rejson.getJSONArray("data");
        if (temlist.size() != 0) {//存在病历信息
            com.alibaba.fastjson.JSONObject tem = temlist.getJSONObject(0);
            /**
             * {
             "orgName": "厦门大学附属心血管病医院",
             "createTime": "2013-09-26 10:13:38",
             "patient": "386a35b8d17a47cbab6174ae7952b9b6",
             "orgCode": "182",
             "dataFrom": "1",
             "id": "9f35ff1f-f683-4f3c-a0a5-7ff8ef3df89e",
             "eventType": "2",
             "dianosis": "高血压2级",
             "eventDate": "2013-09-26 10:13:38"
             }
             */
            PatientMedicalRecordsDO pmr = new PatientMedicalRecordsDO();
            pmr.setHospitalName(tem.getString("orgName"));
            pmr.setHospital(tem.getString("orgCode"));
            if (demoFlag) {//测试获取为病历模板 hospitalcode获取为自己的code
                pmr.setHospital("ac02a9b87a3611e69f7c005056850d66");//
            }
//        pmr.setDischargeDiagnosis(re.getDiagnosis());
            pmr.setDischargeDiagnosisName(tem.getString("dianosis"));
//        pmr.setAdmittingDiagnosis(re.getDiagnosis());
            pmr.setJwpatient(tem.getString("patient"));
            pmr.setAdmittingDiagnosisName(tem.getString("dianosis"));
            pmr.setEvent(tem.getString("id"));
            pmr.setDataFrom(tem.getString("dataFrom"));
            pmr.setAdvice("出院继续观察");
            if (tem.getString("dataFrom").equals("4"))//3中山 4智业
            {
                try {
                    String html = rehabilitationInfoService.getEmrContentByRID(tem.getString("patient"),tem.getString("id"),tem.getString("orgCode"));
                    if (StringUtils.isNoneBlank(html)){
                        List<String> tmp = HtmlUtil.getTagContent(html,"xid=\"diagnosis.in\" diagpop=\"1\">" + "(.*?)</TD>");
                        String diagnosisIn =tmp.size()>0?tmp.get(0):"";
                        tmp = HtmlUtil.getTagContent(html,"xid=\"diagnosis.out\" diagpop=\"1\">" + "(.*?)</TD>");
                        String diagnosisOut =tmp.size()>0?tmp.get(0):"";
                        if (StringUtils.isNoneBlank(diagnosisIn)){//入院诊断
                            pmr.setAdmittingDiagnosisName(diagnosisIn);
                        }
                        if (StringUtils.isNoneBlank(diagnosisOut)){//出院诊断
                            pmr.setDischargeDiagnosisName(diagnosisOut);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (tem.getString("dataFrom").equals("3"))//3中山 4智业
            {
                try {
                    com.alibaba.fastjson.JSONObject zsResult = zsRehabilitationInfoService.zsHospitalRecordDetail(tem.getString("patient"),tem.getString("id"));
                    com.alibaba.fastjson.JSONObject zsResultData = zsResult.getJSONObject("data");
                    if (zsResult.getInteger("status")==200&&zsResultData!=null){
                        if(zsResultData.containsKey("入院诊断")&&StringUtils.isNoneBlank(zsResultData.getString("入院诊断"))){
                            pmr.setDischargeDiagnosisName(zsResultData.getString("入院诊断"));
                        }
                        if (zsResultData.containsKey("出院诊断")&&StringUtils.isNoneBlank(zsResultData.getString("出院诊断"))){
                            pmr.setAdmittingDiagnosisName(zsResultData.getString("出院诊断"));
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
//        pmr.setDiseaseCode(diseaseObj.getString("disease"));//疾病code
//        pmr.setDiseaseName(diseaseObj.getString("diseaseName"));//疾病名称
            String jsonData = JSON.toJSONString(pmr);
            //创建居民住院病历
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            PatientMedicalRecordsDO patientMedicalRecordsDO = objectMapper.readValue(jsonData, PatientMedicalRecordsDO.class);
            PatientMedicalRecordsDO patientMedicalRecordsDO1 = rehabilitationInfoService.createMedicalRecords(doctorCode, patient, patient1.getName(), patientMedicalRecordsDO, null);
            if (patientMedicalRecordsDO1 != null) { //创建病历成功
                query.add(patientMedicalRecordsDO1);
                return query;
            }
        }
        String sql = "SELECT pmrr.* FROM wlyy_patient_medical_records_rehabilitation pmrr WHERE pmrr.patient = '"+patient+"' and (data_from=3 or  data_from=4) GROUP BY id DESC LIMIT 0,1";//find_in_set('"+diseaseCode+"',disease)
        query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PatientMedicalRecordsDO.class));
        return query;
    }
    public List<Map<String,Object>> selectPlanByPatient(String patient, Integer status, String planId,String doctor){
        if (StringUtils.isNoneBlank(planId)){
            String planSql = "select p.patient " +
                    " FROM wlyy_patient_rehabilitation_plan p where p.id='"+planId+"' ";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(planSql);
            if (maps!=null&&maps.size()!=0){
                Map<String,Object> map = maps.get(0);
                patient = map.get("patient").toString();
            }
        }
        String sql = "select d.id as doctor,p.create_time as createTime,p.id,d.photo,p.title,d.idcard,YEAR (now()) - YEAR (substring(d.idcard, 7, 8)) AS age, d.sex,p.name,p.patient,d.name as doctorName,p.advice_content as adviceContent,p.medical_records_code as medicalRecordsCode,p.create_time as create_time " +
                " FROM wlyy_patient_rehabilitation_plan p " +
                " LEFT JOIN base_doctor d ON d.id = p.create_user " +
                "WHERE p.patient='"+patient+"'";
        if (status!=null){
            sql +=" and p.status ="+status;
        }
        if (StringUtils.isNoneBlank(doctor)){
            BaseDoctorDO doctor1 = baseDoctorDao.findById(doctor);
            if (doctor1!=null&&doctor1.getLevel()==1){
                sql +=" and p.create_user ='"+doctor+"'";
            }
        }
        /*sql+=" union ";
        sql+=" SELECT d.CODE AS doctor," +
                "p.create_time AS createTime," +
                "p.id," +
                "d.photo," +
                "p.title," +
                "d.idcard,YEAR (now())-YEAR (substring(d.idcard,7,8)) AS age," +
                "d.sex,p.name," +
                "p.patient," +
                "d.NAME AS doctorName," +
                "d.dept_name AS deptName," +
                "hospital_name AS hospitalName," +
                "p.advice_content AS adviceContent," +
                "p.medical_records_code AS medicalRecordsCode," +
                "p.create_time AS create_time " +
                "FROM " +
                "wlyy_patient_rehabilitation_plan p " +
                "LEFT JOIN base_doctor d ON d.id=p.create_user" +
                " LEFT JOIN (" +
                "SELECT sr.patient AS patient,sr.team_code AS team_code " +
                "FROM wlyy_doctor_patient_relation sr " +
                "JOIN wlyy_doctor_special_share se ON se.special_code=sr.id " +
                "WHERE se.doctor='"+doctor+"' " +
                "AND sr.patient='"+patient+"') d " +
                "ON d.patient=p.patient WHERE " +
                "p.patient='"+patient+"' " +
                "AND d.team_code=p.team_code ";
*/
        sql+=" ORDER BY create_time DESC ";
        //sql = TransforSqlUtl.wlyy_patient_rehabilitation_planName(sql);
        List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:mapList){
            List<BaseDoctorHospitalDO> depts=baseDoctorHospitalDao.findByDoctorCode(map.get("doctor").toString());
            if(depts!=null&&depts.size()>0){
                map.put("deptCode",depts.get(0).getDeptCode());
                map.put("deptName",depts.get(0).getDeptName());
                map.put("orgCode",depts.get(0).getOrgCode());
                map.put("orgName",depts.get(0).getOrgName());
            }
            String sqlSpecilist = "select * from wlyy_doctor_patient_relation where doctor = '"+map.get("doctor")+"' and patient ='"+patient+"' and status=1";
            List<Map<String,Object>> maps = jdbcTemplate.queryForList(sqlSpecilist);
            map.put("specialist",maps);
        }
        return mapList;
    }
}
}

+ 511 - 23
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/RehabilitationPlanService.java

@ -13,32 +13,37 @@ import com.yihu.jw.entity.base.team.BaseTeamMemberDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.door.SignFamily;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.hospital.doctor.Frequency;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.specialist.rehabilitation.PatientRehabilitationPlanDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationDetailDO;
import com.yihu.jw.entity.specialist.rehabilitation.RehabilitationOperateRecordsDO;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.HospitalServiceItemDO;
import com.yihu.jw.entity.specialist.RehabilitationServiceItemDO;
import com.yihu.jw.entity.specialist.rehabilitation.*;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.file_upload.FileUploadService;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.DoctorPatientRelationDao;
import com.yihu.jw.rehabilitation.RehabilitationOperateRecordsDao;
import com.yihu.jw.rehabilitation.RehabilitationOperateRecordsDao;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.specialist.PatientSignInfoVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.sign.dao.MessagesDao;
import com.yihu.jw.sign.dao.MessagesDao;
import com.yihu.jw.team.BaseDoctorTeamMemberDao;
import com.yihu.jw.team.BaseDoctorTeamMemberDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.common.QrcodeUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.rehabilitation.dao.FrequencyDao;
import com.yihu.rehabilitation.dao.PatientRehabilitationPlanDao;
import com.yihu.rehabilitation.dao.RehabilitationDetailDao;
import com.yihu.rehabilitation.dao.SignFamilyDao;
import com.yihu.rehabilitation.dao.*;
import com.yihu.rehabilitation.vo.TemplateDetailVo;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpResponse;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.network.HttpUtils;
import com.yihu.utils.security.MD5;
import com.yihu.utils.security.MD5;
@ -48,6 +53,8 @@ import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.jdbc.core.JdbcTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Service;
@ -57,6 +64,7 @@ import java.io.InputStream;
import java.text.ParseException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.*;
import java.util.stream.Collectors;
/**
/**
 * Created by humingfen on 2018/8/22.
 * Created by humingfen on 2018/8/22.
@ -72,7 +80,7 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
    @Autowired
    @Autowired
    private SignFamilyDao signFamilyDao;
    private SignFamilyDao signFamilyDao;
    @Autowired
    @Autowired
    private MessagesDao messageDao;
    private SystemMessageDao messageDao;
    @Autowired
    @Autowired
    private BasePatientDao patientDao;
    private BasePatientDao patientDao;
    @Autowired
    @Autowired
@ -115,6 +123,16 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    private BaseDoctorHospitalDao baseDoctorHospitalDao;
    @Autowired
    @Autowired
    private HibenateUtils hibenateUtils;
    private HibenateUtils hibenateUtils;
    @Autowired
    private DoctorPatientRelationDao doctorPatientRelationDao;
    @Autowired
    private RehabilitationPlanTemplateDao templateDao;
    @Autowired
    private RehabilitationTemplateDetailDao templateDetailDao;
    @Autowired
    private RehabilitationServiceItemDao serviceItemDao;
    @Autowired
    StringRedisTemplate redisTemplate;
    public Envelop updatePatientImgById(String planId, String patientImg) {
    public Envelop updatePatientImgById(String planId, String patientImg) {
        if(patientRehabilitationPlanDao.updatePatientImgById(planId,patientImg) > 0){
        if(patientRehabilitationPlanDao.updatePatientImgById(planId,patientImg) > 0){
@ -167,15 +185,15 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
    public String createRehabilitationPlan(String json, BaseDoctorDO doctor) throws Exception {
    public String createRehabilitationPlan(String json, BaseDoctorDO doctor) throws Exception {
        JSONObject object = new JSONObject(json);
        JSONObject object = new JSONObject(json);
        String patient = object.getString("patient");
        String patient = object.getString("patient");
        BasePatientDO patientDo  = null;
        if (!StringUtils.isNoneBlank(patient)){
        String relationId=object.getString("relationId");
        String teamCode=object.getString("teamCode");
        BasePatientDO patientDo  = patientDao.findById(patient);
        if (patientDo==null){
            BasePatientDO basePatientDO = new BasePatientDO();
            BasePatientDO basePatientDO = new BasePatientDO();
            basePatientDO.setName(object.getString("patientName"));
            basePatientDO.setName(object.getString("patientName"));
            basePatientDO.setIdcard(object.getString("idCard"));
            basePatientDO.setIdcard(object.getString("idCard"));
            basePatientDO.setMobile(object.getString("mobile"));
            basePatientDO.setMobile(object.getString("mobile"));
            patientDo = saveUnSignPatient(basePatientDO);
            patientDo = saveUnSignPatient(basePatientDO);
        }else {
            patientDo = patientDao.findById(patient);
        }
        }
        String patientName="";
        String patientName="";
        if(patientDo!=null){
        if(patientDo!=null){
@ -227,14 +245,16 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
        details = createRehabilitationDetail(details, planDO.getId(),doctor.getId(),doctor.getName());
        details = createRehabilitationDetail(details, planDO.getId(),doctor.getId(),doctor.getName());
        //康复计划创建完给执行者发送消息
        //康复计划创建完给执行者发送消息
        String planId = null;
        String planId = null;
        if (planDO!=null){
            planId=planDO.getId();
        }
        HashSet set = new HashSet();
        HashSet set = new HashSet();
        for ( RehabilitationDetailDO rehabilitationDetailDO : details) {
        for ( RehabilitationDetailDO rehabilitationDetailDO : details) {
            if (!set.contains(rehabilitationDetailDO.getDoctor())) {
            if (!set.contains(rehabilitationDetailDO.getDoctor())) {
                set.add(rehabilitationDetailDO.getDoctor());
                set.add(rehabilitationDetailDO.getDoctor());
                planId = rehabilitationDetailDO.getPlanId();
                Message message = new Message();
                SystemMessageDO message = new SystemMessageDO();
                message.setSender(doctor.getId());
                message.setSender(doctor.getId());
                message.setType(19);
                message.setType("19");
                message.setRelationCode(rehabilitationDetailDO.getPlanId());
                message.setRelationCode(rehabilitationDetailDO.getPlanId());
                message.setReceiver(rehabilitationDetailDO.getDoctor());
                message.setReceiver(rehabilitationDetailDO.getDoctor());
                message.setReason(doctor.getName());
                message.setReason(doctor.getName());
@ -243,6 +263,17 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
            }
            }
        }
        }
        DoctorPatientRelationDO doctorPatientRelationDO = doctorPatientRelationDao.findOne(relationId);
        if (null!=doctorPatientRelationDO){
            if (doctorPatientRelationDO.getIsManage()==null||doctorPatientRelationDO.getIsManage()==0){
                doctorPatientRelationDO.setDoctor(doctor.getId());
                doctorPatientRelationDO.setDoctorName(doctor.getName());
                doctorPatientRelationDO.setIsManage(0);
            }
            doctorPatientRelationDO.setTeamCode(teamCode);
            doctorPatientRelationDO.setIsdeal("1");
            doctorPatientRelationDao.save(doctorPatientRelationDO);
        }
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        SignFamily signFamily = signFamilyDao.findByPatient(patient);
        //推送消息到IM
        //推送消息到IM
@ -321,6 +352,7 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
    public PatientRehabilitationPlanDO createPatientRehabilitationPlan(PatientRehabilitationPlanDO planDO) {
    public PatientRehabilitationPlanDO createPatientRehabilitationPlan(PatientRehabilitationPlanDO planDO) {
        planDO.setCreateTime(new Date());
        planDO.setCreateTime(new Date());
        planDO.setStatus(1);
        planDO.setStatus(1);
        planDO.setIsVerify("0");
        planDO.setUpdateTime(new Date());
        planDO.setUpdateTime(new Date());
        return patientRehabilitationPlanDao.save(planDO);
        return patientRehabilitationPlanDao.save(planDO);
    }
    }
@ -592,7 +624,7 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
        HttpResponse response = HttpUtils.doPost(specialistUrl + "svr-specialist/updatePlanStatusById", param);
        HttpResponse response = HttpUtils.doPost(specialistUrl + "svr-specialist/updatePlanStatusById", param);
        JSONObject result = new JSONObject(response.getContent());
        JSONObject result = new JSONObject(response.getContent());
        if (result.getInt("status")==200 && status==0){
        if (result.getInt("status")==200 && status==0){
            List<Message> messageList = new ArrayList<>();
            List<SystemMessageDO> messageList = new ArrayList<>();
            Map<String,String> recieveMap = new HashMap<>();
            Map<String,String> recieveMap = new HashMap<>();
            JSONObject jsonObject =result.getJSONObject("obj");
            JSONObject jsonObject =result.getJSONObject("obj");
            String patientCode = jsonObject.getString("patient");
            String patientCode = jsonObject.getString("patient");
@ -618,7 +650,7 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
            for (Map.Entry<String,String> entry : recieveMap.entrySet()){
            for (Map.Entry<String,String> entry : recieveMap.entrySet()){
                //推送消息到IM
                //推送消息到IM
                //pushMsgTask.put(entry.getKey(),"20", "康复计划中止消息", "您的居民"+patientName+",已中止"+diseaseName+"康复计划,点击查看原因", "");
                //pushMsgTask.put(entry.getKey(),"20", "康复计划中止消息", "您的居民"+patientName+",已中止"+diseaseName+"康复计划,点击查看原因", "");
                Message message = initMessage(patientName,entry.getKey(),entry.getValue(),"system","system","康复计划-中止提醒","您的居民"+patientName+",已中止"+diseaseName+"康复计划,点击查看原因。",planId,29);
                SystemMessageDO message = initMessage(patientName,entry.getKey(),entry.getValue(),"system","system","康复计划-中止提醒","您的居民"+patientName+",已中止"+diseaseName+"康复计划,点击查看原因。",planId,29);
                messageList.add(message);
                messageList.add(message);
            }
            }
            messageDao.save(messageList);
            messageDao.save(messageList);
@ -651,12 +683,11 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
        }
        }
    }
    }
    private Message initMessage(String patientName,String doctor,String doctorName,String sender,String senderName,String title,String content,String relatioenCode,int type){
        Message message = new Message();
        message.setCzrq(new Date());
    private SystemMessageDO initMessage(String patientName, String doctor, String doctorName, String sender, String senderName, String title, String content, String relatioenCode, int type){
        SystemMessageDO message = new SystemMessageDO();
        message.setCreateTime(new Date());
        message.setCreateTime(new Date());
        message.setContent("您的服务居民"+patientName+",已中止康复计划,点击查看原因。");
        message.setContent("您的服务居民"+patientName+",已中止康复计划,点击查看原因。");
        message.setRead(1);//设置未读
        message.setIsRead("1");//设置未读
        message.setReceiver(doctor);//设置接受医生的code
        message.setReceiver(doctor);//设置接受医生的code
        message.setReceiverName(doctorName);
        message.setReceiverName(doctorName);
        message.setSender(sender);//设置发送的用户
        message.setSender(sender);//设置发送的用户
@ -664,7 +695,7 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
        message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
        message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
        message.setSenderPhoto("");
        message.setSenderPhoto("");
        message.setTitle(title);
        message.setTitle(title);
        message.setType(type);//康复计划中止消息提醒
        message.setType(String.valueOf(type));//康复计划中止消息提醒
        message.setReadonly(1);//是否只读消息
        message.setReadonly(1);//是否只读消息
        message.setRelationCode(relatioenCode);
        message.setRelationCode(relatioenCode);
        message.setOver("0");//未处理
        message.setOver("0");//未处理
@ -845,7 +876,7 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
        }
        }
        String packageSql = "select m.service_package_id as \"servicePackageId\"," +
        String packageSql = "select m.service_package_id as \"servicePackageId\"," +
                " n.name as \"name\"" +
                " n.name as \"name\"" +
                "from base_service_package_item m left join base_service_package_item n on" +
                "from base_service_package_item m left join base_service_package n on" +
                " m.service_package_id = n.id where 1=1 and m.service_package_id !='system' ";
                " m.service_package_id = n.id where 1=1 and m.service_package_id !='system' ";
        if(StringUtils.isNoneBlank(teamCode)){
        if(StringUtils.isNoneBlank(teamCode)){
@ -918,4 +949,461 @@ public class RehabilitationPlanService extends BaseJpaService<PatientRehabilitat
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        List<Map<String, Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
        return list;
    }
    }
    public  List<Map<String,Object>> findDoctorTeams(String doctor){
        String sql = "select a.id as \"id\", " +
                " a.org_code as \"orgCode\"," +
                " a.org_name as \"orgName\"," +
                " a.name as \"name\"," +
                " a.leader_code as \"leaderCode\"," +
                " a.team_num as \"teamNum\"," +
                " a.qrcode as \"qrcode\"," +
                " a.del as \"del\"," +
                " a.create_time as \"createTime\"" +
                " from base_team a left join base_team_member b " +
                " on a.id = b.team_code where a.del ='1' ";
        if (StringUtils.isNotBlank(doctor)){
            sql+=" and b.doctor_code ='"+doctor+"'";
        }else{
            return null;
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }
    public List<Map<String,Object>> findDoctorByTeams(String teamCode){
        String sql = "select b.id as \"id\"," +
                " t.id as \"doctorId\"," +
                " t.name as \"doctorName\"," +
                " b.team_code as \"teamcode\"," +
                " b.org_code as \"orgcode\"" +
                "from base_team_member b left join base_doctor t on b.doctor_code = t.id" +
                " where b.del =1 ";
        if (StringUtils.isNotBlank(teamCode)){
            sql+=" and b.team_code ='"+teamCode+"'";
        }else{
            return null;
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        return list;
    }
    public ObjEnvelop createRehabilitationTemplate(RehabilitationPlanTemplateDO templateDO) {
        templateDO.setCreateTime(new Date());
        templateDO.setDel(1);
        templateDO.setUpdateTime(new Date());
        templateDO = templateDao.save(templateDO);
        String templateId = templateDO.getId();
        String user = templateDO.getCreateUser();
        String userName = templateDO.getCreateUserName();
        //默认新增服务项
        String sql = "SELECT code from wlyy.system_dict WHERE `dict_name` = 'default_service_item_id'";
        List<String> list = jdbcTemplate.queryForList(sql,String.class);
        if(list!=null&&list.size()>0){
            list.stream().forEach(code->{
                RehabilitationTemplateDetailDO detailDO = new RehabilitationTemplateDetailDO();
                detailDO.setTemplateId(templateId);
                detailDO.setHospitalServiceItemId(code);
                detailDO.setCreateUser(user);
                detailDO.setCreateUserName(userName);
                detailDO.setCreateTime(new Date());
                detailDO.setUpdateTime(new Date());
                templateDetailDao.save(detailDO);
            });
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,templateDO.getId());
    }
    public ObjEnvelop createRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details) {
        for(RehabilitationTemplateDetailDO detail : details){
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            templateDetailDao.save(detail);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    public ObjEnvelop updateRehabilitationTemplateDetail(List<RehabilitationTemplateDetailDO> details) {
        String templateId = details.get(0).getTemplateId();
        if(templateId != null && templateId.length() > 0){
            templateDetailDao.deleteByTemplateId(templateId);
        }
        for(RehabilitationTemplateDetailDO detail : details){
            detail.setCreateTime(new Date());
            detail.setUpdateTime(new Date());
            templateDetailDao.save(detail);
        }
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    public MixEnvelop findRehabilitationPlanTemplate(Long adminTeamCode, String doctor, String patient) {
        List<RehabilitationPlanTemplateDO> list = templateDao.findByAdminTeamCode(adminTeamCode);
        return MixEnvelop.getSuccessList(SpecialistMapping.api_success, list);
    }
    /**
     * 根据模板id修改康复模板删除状态
     * @param id
     * @return
     */
    public ObjEnvelop deleteRehabilitationPlanTemplate(String id) {
        templateDao.updateDelById(id);
        return ObjEnvelop.getSuccess(SpecialistMapping.api_success,true);
    }
    /**
     * 根据模板id获取机构服务项目id,然后找出具体服务项目内容
     * @param templateId
     * @return
     */
    public ListEnvelop findTemplateDetailByTemplateId(String templateId) {
        List<TemplateDetailVo> resultList = new ArrayList<>();
        List<RehabilitationTemplateDetailDO>  list = templateDetailDao.findTemplateDetailByTemplateId(templateId);
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        Map<String, List<RehabilitationTemplateDetailDO>> map = list.stream().collect(Collectors.groupingBy(RehabilitationTemplateDetailDO::getHospitalServiceItemId));
        for (String code : map.keySet()){
            TemplateDetailVo detailVo = new TemplateDetailVo();
            detailVo.setCode(code);
            detailVo.setId(code);
            detailVo.setList(map.get(code));
            for (RehabilitationServiceItemDO item:itemDOList){
                if(code.equals(item.getCode())){
                    detailVo.setName(item.getName());
                    break;
                }
            }
            resultList.add(detailVo);
        }
        return ListEnvelop.getSuccess(SpecialistMapping.api_success,resultList);
    }
    public List<RehabilitationServiceItemDO> findSystemTemplateList(){
        List<RehabilitationServiceItemDO> itemDOList = serviceItemDao.findList();
        return itemDOList;
    }
    public List<RehabilitationDetailDO> createRehabilitationDetail(List<RehabilitationDetailDO> details, String planId) {
        for(RehabilitationDetailDO detail : details) {
            /*List<String> list = new ArrayList<>();
            list.add(detail.getHospitalServiceItemId());
            HospitalServiceItemDO hospitalServiceItemDO = hospitalServiceItemService.selectById(list).getDetailModelList().get(0);
            detail.setHospital(hospitalServiceItemDO.getHospital());
            detail.setHospitalName(hospitalServiceItemDO.getHospitalName());
            detail.setExpense(hospitalServiceItemDO.getExpense());*/
            detail.setPlanId(planId);
            detail.setCreateTime(new Date());
            detail.setStatus(0);
            detail.setUpdateTime(new Date());
        }
        return (List<RehabilitationDetailDO>)rehabilitationDetailDao.save(details);
    }
    public void deleteDetailByPlanIdAndHospitalServiceItemId(String planId, String hospitalServiceItemId, Date dateShort) {
        rehabilitationDetailDao.deleteDetailByPlanIdAndHospitalServiceItemId(planId, hospitalServiceItemId, dateShort);
    }
    public void deleteDetailByPlanId(String planId, Date dateShort) {
        rehabilitationDetailDao.deleteDetailByPlanId(planId, dateShort);
    }
    public List<RehabilitationDetailDO> updateRehabilitationPlan(String json, BaseDoctorDO doctor,String updateStatus) throws Exception {
        JSONObject object = new JSONObject(json);
        JSONArray array = object.getJSONArray("detail");
        for (int z=0;z<array.length();z++){
            JSONObject jsonObject = array.getJSONObject(z);
            Long timeType = jsonObject.getLong("timeType");
            Frequency frequency = frequencyDao.findByCode(jsonObject.getString("frequencyCode"));
            String executeTimes = jsonObject.getString("executeTimes");
            BaseDoctorDO doctor1 = doctorDao.findById(jsonObject.getString("doctor"));
            if(StringUtils.isNotBlank(executeTimes)) {
                List<String> list = new ArrayList<>();
                String[] executeTime = executeTimes.split(",");
                for (int i = 0; i < executeTime.length; i++) {
                    List<String> times = getFrequencyDate(frequency.getCode(), executeTime[i], frequency.getUnit(), frequency.getTime(), timeType);
                    for (int j = 0; j < times.size(); j++) {
                        if (list != null && list.size() != 0) {
                            if (!list.contains(times.get(j))) {
                                list.add(times.get(j));
                            }
                        } else {
                            list.add(times.get(j));
                        }
                    }
                }
                StringBuffer buffer = new StringBuffer();
                if (list != null && list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        buffer.append(list.get(i) + ",");
                    }
                    if (StringUtils.isNoneBlank(buffer)) {
                        buffer.deleteCharAt(buffer.length() - 1);
                    }
                }
                jsonObject.put("executeTime", buffer);
            }
            jsonObject.remove("executeTimes");
        }
        object.put("createUser", doctor.getId());
        object.put("createUserName", doctor.getName());
        String planId = object.getString("planId");
        String hospitalServiceItemId = object.getString("hospitalServiceItemId");
        //删除该服务项目今日之后未完成的计划
        if(StringUtils.isBlank(updateStatus)||updateStatus.equals("0")){//单个服务的修改
            deleteDetailByPlanIdAndHospitalServiceItemId(planId, hospitalServiceItemId, DateUtil.getDateShort(new Date()));
        }
        else{
           deleteDetailByPlanId(planId, DateUtil.getDateShort(new Date()));
        }
        JSONArray array1 = new JSONArray();
        for(Object planDetail : object.getJSONArray("detail")) {
            String expense="";
            JSONObject j = (JSONObject)planDetail;
            if (j.get("expense") instanceof Integer){
                expense= String.valueOf(j.getInt("expense"));
            }
            else{
                expense = j.getString("expense");
                if(expense.contains(".")){
                    int pointIndex = expense.indexOf(".");
                    expense = expense.substring(0,pointIndex);
                }
            }
            j.put("expense",expense);
            if(j.has("executeTime")) {
                String executeTime = j.get("executeTime").toString();
                String[] result = null;
                if (executeTime.contains(",")) {
                    result = executeTime.split(",");
                } else {
                    result = new String[1];
                    result[0] = executeTime;
                }
                int len = result.length;
                while (len > 0) {
                    len--;
                    JSONObject temp = new JSONObject(j.toString());
                    temp.put("executeTime", result[len]);
                    temp.put("createUser", object.get("createUser"));
                    temp.put("createUserName", object.get("createUserName"));
                    array1.put(temp);
                }
            }else {
                j.put("createUser", object.get("createUser"));
                j.put("createUserName", object.get("createUserName"));
                array1.put(j);
            }
        }
        String planDetails = array1.toString();
        ObjectMapper object1 = new ObjectMapper();
        object1.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm"));
        List<RehabilitationDetailDO> details = object1.readValue(planDetails, new TypeReference<List<RehabilitationDetailDO>>(){});
        details = createRehabilitationDetail(details, planId);
        String updateTime = DateUtil.dateToStr(details.get(0).getCreateTime(),"yyyy-MM-dd hh:mm:ss");
        //康复计划修改 日志添加
        String sql ="INSERT INTO wlyy_patient_rehabilitation_plan_log(id,plan_id,create_user,create_user_name,create_time) " +
                "VALUES('"+getCode()+"','"+planId+"','"+doctor.getId()+"','"+ doctor.getName()+"','"+updateTime+"')";
        jdbcTemplate.execute(sql);
        return details;
    }
    /**
     * 获取康复计划修改记录
     * @param planId
     * @return
     */
    public List<Map<String,Object>> getRehabilitationPlanLog(String planId){
        String sql ="select * from wlyy_patient_rehabilitation_plan_log where plan_id = '"+planId+"' ORDER BY create_time DESC";
        List<Map<String,Object>> planLogList = jdbcTemplate.queryForList(sql);
        return planLogList;
    }
    /**
     * 查询单个居民信息
     *
     * @param patient
     * @return
     * @throws Exception
     */
    public JSONObject getPatient(String patient,String doctor) throws Exception {
        JSONObject json = new JSONObject();
//        Patient p = patientDao.findByCode(patient);
        BasePatientDO p = patientDao.findById(patient);
        if (p == null) {
            throw new Exception("patient info can not find");
        }
        // 设置患者标识
        json.put("code", p.getId());
        // 设置患者姓名
        json.put("name", p.getName());
        // 设置患者手机号
        json.put("mobile", p.getMobile());
        // 设置患者微信openid
        json.put("openid", StringUtils.isNotEmpty(p.getOpenid()) ? p.getOpenid() : "");
        json.put("openidTime",DateUtil.dateToStr(p.getOpenidTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));
        // 设置患者联系电话
        json.put("phone", p.getPhone());
        // 设置患者头像
        json.put("photo", p.getPhoto());
        // 设置患者年龄
        json.put("age", IdCardUtil.getAgeByIdcardOrBirthday(p.getIdcard(),p.getBirthday()));
        // 设置患者性别
        json.put("sex", p.getSex());
        // 身份证号
        json.put("idcard", p.getIdcard());
        //1.4.2新增medicareNumber
        //json.put("medicareNumber", p.());
        // 设置患者居住省份
        json.put("provinceName", p.getProvinceName());
        json.put("cityName", p.getCityName());
        json.put("townName", p.getTownName());
        json.put("streetName", p.getStreetName());
        // 设置患者地址
        json.put("address", p.getAddress());
        // 社保号
        json.put("ssc", p.getSsc());
        //病情类型:0健康,1高血压,2糖尿病,(1,2)高血压+糖尿病
       /* json.put("disease",p.getDisease());
        // 病情:0绿标,1黄标,2红标,
        json.put("diseaseCondition",p.getDiseaseCondition());*/
        //预警状态
        json.put("standardStatus",p.getStandardStatus());
        //设备状态:0未绑定,1血糖仪,2血压仪,3血糖仪+血压仪
       /* json.put("deviceType",p.getDeviceType()==null?"":p.getDeviceType());
        //20190719 增加返回字段:档案状态(-2冻结 1未管理 2死亡3 正常4 高危)
        json.put("archiveStatus",p.getArchiveStatus() == null? "":p.getArchiveStatus().toString());
        // 专病类型,专病名称
        json.put("specialistDisease", p.getSpecialistDisease());
        json.put("specialistDiseaseName", p.getSpecialistDiseaseName());
*/
        if (json.has("expensesStatus") && (StringUtils.isEmpty(String.valueOf(json.get("expensesStatus"))) || String.valueOf(json.get("expensesStatus")).equals("0"))) {
            boolean epTime = false;
            try {
                epTime = redisTemplate.opsForSet().isMember("expenses:remind:set", p.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!epTime) {
                json.put("expensesRemindStatus", 0);
            } else {
                json.put("expensesRemindStatus", 1);
            }
        }
        boolean epTime = false;
        try {
            epTime = redisTemplate.opsForSet().isMember("wechat:focus:remind:set", p.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!epTime) {
            json.put("wechatFocusRemind", 0);
        } else {
            json.put("wechatFocusRemind", 1);
        }
        String timeKey = DateUtil.dateToStr(new Date(), "yyyyMMdd");
        String flag = redisTemplate.opsForValue().get("renew:" + timeKey + ":" + patient);
        if (StringUtils.isNotBlank(flag)) {
            json.put("isRemindRenew", "1");
        } else {
            json.put("isRemindRenew", "0");
        }
        //1.4.9  是否专科医生服务
        List<PatientSignInfoVO> patientSignInfoVOS =findPatientSignSpecialist(patient);
        if(patientSignInfoVOS!=null&&patientSignInfoVOS.size()>0){
            json.put("isSpecialist",1);
            json.put("specialistArray", patientSignInfoVOS);
        }else{
            json.put("isSpecialist",0);
        }
        //1.5.0 是否有康复计划
        List<PatientRehabilitationPlanDO> planList = planListByPatient(patient);
        if(planList!=null&&planList.size()>0){
            json.put("havePlan",1);
        }else{
            json.put("havePlan",0);
        }
        return json;
    }
    public List<PatientSignInfoVO> findPatientSignSpecialist(String patient){
        String sql = "SELECT " +
                " r.id AS relationCode, " +
                " r.patient, " +
                " r.team_code AS teamCode,r.patient_name as patientName" +
                // AesEncryptUtils.decryptMysql("r.patient_name","patientName") +
//                " r.patient_name AS patientName, " +
//                " d.name AS doctorName, " +
                ",d.name as doctorName"+
                // AesEncryptUtils.decryptMysql("d.name","doctorName") +
                " ,d.id AS doctor, " +
                " d.photo, " +
                " d.job_title_name AS job, " +
                " d.sex AS sex " +
                " FROM " +
                " wlyy_doctor_patient_relation r " +
                " JOIN base_doctor d ON r.doctor = d.id " +
                " WHERE  " +
                " r.patient ='"+patient+"' " +
                " AND r.`status`>=0 " ;
        //sql = TransforSqlUtl.wlyySpecialistPatientRelationReplay(sql,"r.patient_name");
        List<PatientSignInfoVO> patientSignInfoVOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(PatientSignInfoVO.class));
        return patientSignInfoVOs;
    }
    /**
     * 根据居民获取康复计划
     * @param patient
     * @return
     */
    public List<PatientRehabilitationPlanDO> planListByPatient(String patient){
        List<PatientRehabilitationPlanDO> list = patientRehabilitationPlanDao.findByPatients(patient);
        return list;
    }
    public JSONArray findTemplateDetailInfo(String templateId) throws Exception {
        Map<String, Object> param = new HashedMap();
        param.put("templateId", templateId);
        HttpResponse response = null;
        try {
            response = HttpUtils.doGet(specialistUrl + "svr-specialist/findTemplateDetailByTemplateId", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject rs = new JSONObject(response.getContent());
        if (rs.getInt("status") == 200) {
            JSONArray result = rs.getJSONArray("detailModelList");
            for (int i=0;i<result.length();i++){
                JSONObject obj = result.getJSONObject(i);
                JSONObject reobj = obj.getJSONArray("list").getJSONObject(0);
                if(!reobj.isNull("expense")){
                    Integer expense  = reobj.getInt("expense");
                    obj.put("expense",expense);
                }
                else{
                    obj.put("expense",0);
                }
            }
            return rs.getJSONArray("detailModelList");
        }
        throw new Exception("请求获取模板明细列表失败!");
    }
}
}

+ 23 - 22
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/SpecialistEvaluateSevice.java

@ -8,9 +8,11 @@ import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.patient.Message;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.rehabilitation.RehabilitationInformationDO;
import com.yihu.jw.entity.rehabilitation.RehabilitationInformationDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.sign.dao.MessagesDao;
import com.yihu.jw.sign.dao.MessagesDao;
@ -41,7 +43,7 @@ import java.util.UUID;
public class SpecialistEvaluateSevice {
public class SpecialistEvaluateSevice {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SpecialistEvaluateSevice.class);
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SpecialistEvaluateSevice.class);
    @Autowired
    @Autowired
    private MessagesDao messageDao;
    private SystemMessageDao messageDao;
    @Value("${specialist.url}")
    @Value("${specialist.url}")
    private String specialistUrl;
    private String specialistUrl;
@ -191,7 +193,7 @@ public class SpecialistEvaluateSevice {
     * 发送消息 type:19 受理提醒,20 待办工作提醒 21 服务进展提醒-已完成 22 服务进展提醒-未完成 23 服务进展提醒-待完成 24 收到协同任务 25 在线助手已接收 26 在线助手已退回 27 协同服务已完成
     * 发送消息 type:19 受理提醒,20 待办工作提醒 21 服务进展提醒-已完成 22 服务进展提醒-未完成 23 服务进展提醒-待完成 24 收到协同任务 25 在线助手已接收 26 在线助手已退回 27 协同服务已完成
     */
     */
    public JSONObject sendMessage(Message message, String hospitalCode, String patientCode, Integer num, JSONObject jsonObject){
    public JSONObject sendMessage(SystemMessageDO message, String hospitalCode, String patientCode, Integer num, JSONObject jsonObject){
        JSONObject object = new JSONObject();
        JSONObject object = new JSONObject();
        try {
        try {
            BaseOrgDO hospital = null;
            BaseOrgDO hospital = null;
@ -204,53 +206,53 @@ public class SpecialistEvaluateSevice {
            }
            }
//            Doctor sendDoctor = doctorDao.findByCode(message.getSender());
//            Doctor sendDoctor = doctorDao.findByCode(message.getSender());
            BaseDoctorDO receiverDoctor = doctorDao.findById(message.getReceiver());
            BaseDoctorDO receiverDoctor = doctorDao.findById(message.getReceiver());
            if (message.getType() == 19 ){
            if (  "19".equalsIgnoreCase(message.getType()) ){
                message.setOver("0");//未处理
                message.setOver("0");//未处理
                message.setType(19);
                message.setType("19");
                message.setTitle("康复计划-受理提醒");
                message.setTitle("康复计划-受理提醒");
                message.setContent("您的居民"+patient.getName()+"已出院,"+/*(hospital!=null?hospital.getName():"")*/message.getReason()+"为他制定了新康复计划,请查看");
                message.setContent("您的居民"+patient.getName()+"已出院,"+/*(hospital!=null?hospital.getName():"")*/message.getReason()+"为他制定了新康复计划,请查看");
            }else if (message.getType() == 20){
            }else if ("20".equalsIgnoreCase(message.getType()) ){
                message.setOver("1");//未处理
                message.setOver("1");//未处理
                message.setType(20);
                message.setType("20");
                message.setTitle("康复计划-待办工作提醒");
                message.setTitle("康复计划-待办工作提醒");
                if(num==0){
                if(num==0){
                    message.setContent("您的居民"+patient.getName()+"今天计划到"+(hospital!=null?hospital.getName():"")+"复诊,请查看");
                    message.setContent("您的居民"+patient.getName()+"今天计划到"+(hospital!=null?hospital.getName():"")+"复诊,请查看");
                }else{
                }else{
                    message.setContent("您的居民"+patient.getName()+num+"天后计划到"+(hospital!=null?hospital.getName():"")+"复诊,请查看");
                    message.setContent("您的居民"+patient.getName()+num+"天后计划到"+(hospital!=null?hospital.getName():"")+"复诊,请查看");
                }
                }
            }else if (message.getType() == 21){
            }else if ("21".equalsIgnoreCase(message.getType()) ){
                message.setOver("0");//未处理
                message.setOver("0");//未处理
                message.setType(21);
                message.setType("21");
                message.setTitle("康复计划-服务进展提醒");
                message.setTitle("康复计划-服务进展提醒");
                message.setContent("您的居民"+patient.getName()+"已完成康复计划今日项目,请查看");
                message.setContent("您的居民"+patient.getName()+"已完成康复计划今日项目,请查看");
            }else if (message.getType() == 22){
            }else if ("22".equalsIgnoreCase(message.getType())){
                message.setOver("1");//未处理
                message.setOver("1");//未处理
                message.setType(22);
                message.setType("22");
                message.setTitle("康复计划-服务进展提醒");
                message.setTitle("康复计划-服务进展提醒");
                message.setContent("服务时间提醒!您的居民"+patient.getName()+"该进行"+message.getData()+"了。");
                message.setContent("服务时间提醒!您的居民"+patient.getName()+"该进行"+message.getData()+"了。");
            }else if (message.getType() == 23){
            }else if ("23".equalsIgnoreCase(message.getType())){
                message.setOver("1");//未处理
                message.setOver("1");//未处理
                message.setType(23);
                message.setType("23");
                message.setTitle("康复计划-服务定时提醒");
                message.setTitle("康复计划-服务定时提醒");
                message.setContent("您的居民"+patient.getName()+"明天有"+num+"个康复项目需完成,您可以修改定时提醒!");
                message.setContent("您的居民"+patient.getName()+"明天有"+num+"个康复项目需完成,您可以修改定时提醒!");
            }else if (message.getType() == 24){
            }else if ("24".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setOver("1");
                message.setType(24);
                message.setType("24");
                message.setTitle("收到协同任务");
                message.setTitle("收到协同任务");
                message.setContent("您接收到“"+jsonObject.getString("type")+"”协同服务:"+jsonObject.getString("content").substring(0,19));
                message.setContent("您接收到“"+jsonObject.getString("type")+"”协同服务:"+jsonObject.getString("content").substring(0,19));
            }else if (message.getType() == 25){
            }else if ("25".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setOver("1");
                message.setType(25);
                message.setType("25");
                message.setTitle("在线助手已接收");
                message.setTitle("在线助手已接收");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手接收,负责人:"+jsonObject.getString("customerName")+",联系方式:"+jsonObject.getString("phone")+"。");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手接收,负责人:"+jsonObject.getString("customerName")+",联系方式:"+jsonObject.getString("phone")+"。");
            }else if (message.getType() == 26){
            }else if ("26".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setOver("1");
                message.setType(26);
                message.setType("26");
                message.setTitle("在线助手已退回");
                message.setTitle("在线助手已退回");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手退回。原因:"+jsonObject.getString("returnedRemark"));
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已被在线助手退回。原因:"+jsonObject.getString("returnedRemark"));
            }else if (message.getType() == 27){
            }else if ("27".equalsIgnoreCase(message.getType())){
                message.setOver("1");
                message.setOver("1");
                message.setType(27);
                message.setType("27");
                message.setTitle("协同服务已完成");
                message.setTitle("协同服务已完成");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已完成。");
                message.setContent("您发起的“"+jsonObject.getString("type")+"”协同服务,已完成。");
            }
            }
@ -262,8 +264,7 @@ public class SpecialistEvaluateSevice {
            message.setDel("1");
            message.setDel("1");
            message.setState(1);
            message.setState(1);
            message.setRead(1);
            message.setCzrq(new Date());
            message.setIsRead("1");
            message.setReceiverName(receiverDoctor.getName());
            message.setReceiverName(receiverDoctor.getName());
            message.setData(patientCode);
            message.setData(patientCode);
            message.setCreateTime(new Date());
            message.setCreateTime(new Date());

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 157 - 0
svr/svr-rehabilitation/src/main/java/com/yihu/rehabilitation/service/ZsRehabilitationInfoService.java


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

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

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

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

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

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

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

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

+ 4 - 0
svr/svr-rehabilitation/src/main/resources/application.yml

@ -245,6 +245,10 @@ express:
  sf_url: http://mrds-admin-ci.sit.sf-express.com:45478
  sf_url: http://mrds-admin-ci.sit.sf-express.com:45478
  sf_code: HD000001
  sf_code: HD000001
  sf_check_word: AAAABBBBCCCCDDDD
  sf_check_word: AAAABBBBCCCCDDDD
sign:
  check_upload: http://59.61.92.90:8072/wlyy_service
  check_upload_sign: http://59.61.92.90:8072/wlyy_sign
---
---
spring:
spring:
  profiles: jwprod
  profiles: jwprod