Browse Source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy/patient-co-management into dev

chenyongxing 7 years ago
parent
commit
633ab7f3c8
68 changed files with 5466 additions and 1534 deletions
  1. 5 3
      common/common-entity/src/main/java/com/yihu/device/entity/DevicePatientHealthIndex.java
  2. 4 1
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/dao/PatientHealthIndexDao.java
  3. 9 7
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/http/HttpClientUtil.java
  4. 4 2
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/http/HttpHelper.java
  5. 17 10
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/util/ImUtill.java
  6. 3 3
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/model/PatientHealthIndex.java
  7. 32 24
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java
  8. 10 20
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/task/PushMsgTask.java
  9. 4 4
      patient-co-service/wlyy_device/src/main/resources/application.yml
  10. 73 73
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/SignController.java
  11. 2 2
      patient-co-service/wlyy_service/src/main/webapp/prescription_consulting/js/prescription_consulting_info.js
  12. 1 1
      patient-co/patient-co-doctor-assistant/pom.xml
  13. 1 1
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java
  14. 4 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/common/account/DoctorService.java
  15. 366 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java
  16. 484 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java
  17. 564 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java
  18. 42 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java
  19. 48 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/data/DataController.java
  20. 65 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java
  21. 45 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java
  22. 88 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java
  23. 63 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java
  24. 49 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java
  25. 80 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/icd/Icd10Controller.java
  26. 350 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/im/imController.java
  27. 35 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java
  28. 399 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java
  29. 115 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java
  30. 61 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java
  31. 45 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java
  32. 108 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java
  33. 353 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java
  34. 326 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java
  35. 61 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java
  36. 65 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java
  37. 1 1
      patient-co/patient-co-doctor-assistant/src/main/resources/wechat/weixin_menu_jimei.txt
  38. 90 90
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/activemq/StartListener.java
  39. 70 70
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  40. 93 93
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java
  41. 49 49
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java
  42. 1 1
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java
  43. 59 59
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  44. 93 93
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java
  45. 49 49
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java
  46. 8 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java
  47. 2 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientDao.java
  48. 74 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java
  49. 8 33
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java
  50. 40 10
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionInfoService.java
  51. 9 7
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java
  52. 4 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/DoctorService.java
  53. 4 18
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java
  54. 13 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/DateUtil.java
  55. 201 201
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ElasticsearchUtil.java
  56. 2 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ImUtill.java
  57. 2 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java
  58. 4 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java
  59. 6 7
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java
  60. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/scheme/DoctroSchemeController.java
  61. 8 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java
  62. 4 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java
  63. 7 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java
  64. 213 213
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcEduArticleController.java
  65. 314 314
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/service/GcEduArticleService.java
  66. 1 0
      patient-co/patient-co-wlyy/src/main/resources/application-devtest.yml
  67. 54 55
      patient-co/patient-co-wlyy/src/main/resources/application-local.yml
  68. 1 1
      patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu_jimei.txt

+ 5 - 3
common/common-entity/src/main/java/com/yihu/device/entity/DevicePatientHealthIndex.java

@ -51,7 +51,7 @@ public class DevicePatientHealthIndex extends IdEntity {
	//设备编号
	private String deviceSn;
	private Short status;//状态:0为标准,1为异常
	private Integer status;//状态:0为标准,1为异常
	public String getUser() {
		return user;
@ -188,11 +188,13 @@ public class DevicePatientHealthIndex extends IdEntity {
		this.deviceSn = deviceSn;
	}
	public Short getStatus() {
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Short status) {
	public void setStatus(Integer status) {
		this.status = status;
	}
}

+ 4 - 1
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/dao/PatientHealthIndexDao.java

@ -53,5 +53,8 @@ public interface PatientHealthIndexDao
	List<PatientHealthIndex> findByType(String patient, String deviceSn, String value1, Integer type, Date recordDate);
	@Query("select a from PatientHealthIndex a where a.user = ?1 and a.type =?2  order by recordDate desc ")
    List<PatientHealthIndex> findByPatientAndType(String patientCode, String diseaseType, Pageable pageable);
    List<PatientHealthIndex> findByPatientAndType(String patientCode, int type, Pageable pageable);
	@Query("select count(a) from PatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1'")
	int getCountByTimeAndStatus(Date start, Date end,int status);
}

+ 9 - 7
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/http/HttpClientUtil.java

@ -18,6 +18,7 @@ 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.util.StringUtils;
import org.springframework.web.client.RestTemplate;
@ -29,10 +30,11 @@ import java.util.Map;
/**
 * Created by hzp on 2016/8/9.
 */
@Component
public class HttpClientUtil {
    /**************************** 私有方法 *****************************************/
    private static CloseableHttpClient getCloseableHttpClient(SSLConnectionSocketFactory ssl) {
    private CloseableHttpClient getCloseableHttpClient(SSLConnectionSocketFactory ssl) {
        if(ssl == null)
        {
            return HttpClients.createDefault();
@ -45,7 +47,7 @@ public class HttpClientUtil {
        }
    }
    private static void close(CloseableHttpClient httpClient, CloseableHttpResponse response) {
    private void close(CloseableHttpClient httpClient, CloseableHttpResponse response) {
        try {
            if (httpClient != null) {
                httpClient.close();
@ -62,7 +64,7 @@ public class HttpClientUtil {
        }
    }
    private static HttpRequestBase getRequest(String method,String url,Map<String,Object> params,Map<String,Object> header) throws Exception
    private HttpRequestBase getRequest(String method,String url,Map<String,Object> params,Map<String,Object> header) throws Exception
    {
        List<BasicNameValuePair> jsonParams = new ArrayList<>();
        //配置参数
@ -101,7 +103,7 @@ public class HttpClientUtil {
    /**
     * get请求
     */
    public static HttpResponse request(String method,String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password) {
    public HttpResponse request(String method,String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password) {
        HttpResponse re = new HttpResponse();
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = getCloseableHttpClient(ssl);
@ -142,7 +144,7 @@ public class HttpClientUtil {
     * @param chatSet 编码格式
     * @return
     */
    public static String get(String url, String chatSet) {
    public String get(String url, String chatSet) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
@ -175,7 +177,7 @@ public class HttpClientUtil {
        return null;
    }
    public static String postBody(String url,JSONObject 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");
@ -186,7 +188,7 @@ public class HttpClientUtil {
        return ret;
    }
    public static void putBody(String url,JSONObject params){
    public void putBody(String url,JSONObject params){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");

+ 4 - 2
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/http/HttpHelper.java

@ -3,7 +3,7 @@ package com.yihu.hos.device.common.http;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.net.ssl.SSLContext;
@ -23,6 +23,8 @@ public class HttpHelper {
    private String httpsUser;
    private String httpsUserPassword;
    @Autowired
    private HttpClientUtil HttpClientUtil;
    private SSLConnectionSocketFactory  getDefaultSSL()
    {
@ -148,7 +150,7 @@ public class HttpHelper {
        }
    }
    public static HttpResponse delete(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password)
    public HttpResponse delete(String url,Map<String,Object> params,Map<String,Object> header,SSLConnectionSocketFactory ssl,String user,String password)
    {
        return HttpClientUtil.request("DELETE",url,params,header,ssl,user,password);

+ 17 - 10
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/util/ImUtill.java

@ -2,11 +2,18 @@ package com.yihu.hos.device.common.util;
import com.yihu.hos.device.common.http.HttpClientUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * Created by 卓 on 2017/1/13.
 */
@Component
public class ImUtill {
    @Autowired
    private HttpClientUtil HttpClientUtil;
    /**
     * 发送消息给IM
     *
@ -14,7 +21,7 @@ public class ImUtill {
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public static String sendImMsg(String baseUrl,String from,String fromName, String sessionId, String contentType, String content,String businessType) {
    public String sendImMsg(String baseUrl,String from,String fromName, String sessionId, String contentType, String content,String businessType) {
        String imAddr = baseUrl + "/api/v2/sessions/"+sessionId+"/messages";
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
@ -35,7 +42,7 @@ public class ImUtill {
     * @param contentType 1文字 2图片消息
     * @param content     内容
     */
    public static String sendTopicIM(String baseUrl,String from,String fromName, String topicId, String contentType, String content) {
    public String sendTopicIM(String baseUrl,String from,String fromName, String topicId, String contentType, String content) {
        String url = baseUrl+ ("api/v2/sessions/topic/"+topicId+"/messages");
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
@ -55,7 +62,7 @@ public class ImUtill {
     * @param endUserName 结束人名字
     * @param sessionId 会话ID
     */
    public static JSONObject endTopics(String baseUrl,String sessionId,String endUser, String endUserName,String topicId) {
    public JSONObject endTopics(String baseUrl,String sessionId,String endUser, String endUserName,String topicId) {
        String imAddr = baseUrl + "api/v2/sessions/"+sessionId+"/topics/"+topicId+"/ended";
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
@ -78,7 +85,7 @@ public class ImUtill {
     * @param user 结束人名字
     * @param sessionId 会话ID
     */
    public static void updateTopicUser(String baseUrl,String sessionId,String user) {
    public void updateTopicUser(String baseUrl,String sessionId,String user) {
        String imAddr = baseUrl + "api/v2/sessions/"+sessionId+"/participants/"+user;
        JSONObject params = new JSONObject();
        params.put("user", user+":"+0);
@ -92,7 +99,7 @@ public class ImUtill {
     * @param topicName  议题名称
     * @param participants 成员
     */
    public static JSONObject createTopics(String baseUrl,String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
    public JSONObject createTopics(String baseUrl,String sessionId, String topicId, String topicName, JSONObject participants, JSONObject messages, String sessionType) {
        String imAddr = baseUrl + "api/v2/sessions/"+topicId+"/topics";
        JSONObject params = new JSONObject();
        params.put("topic_id", topicId);
@ -115,7 +122,7 @@ public class ImUtill {
     * 创建会话(system)
     *
     */
    public static JSONObject createSession(String baseUrl,JSONObject participants,String sessionType,String sessionName,String sessionId) {
    public JSONObject createSession(String baseUrl,JSONObject participants,String sessionType,String sessionName,String sessionId) {
        String imAddr = baseUrl + "api/v2/sessions";
        JSONObject params = new JSONObject();
        params.put("participants", participants.toString());
@ -141,7 +148,7 @@ public class ImUtill {
     * @param images
     * @return
     */
    public static JSONObject getCreateTopicMessage(String senderId,String senderName,String title,String description,String images){
    public JSONObject getCreateTopicMessage(String senderId,String senderName,String title,String description,String images){
        JSONObject messages = new JSONObject();
        messages.put("description",description);
        messages.put("title",title);
@ -151,7 +158,7 @@ public class ImUtill {
        return messages;
    }
    public static JSONObject getTopicMessage(String baseUrl,String topicId,String startMsgId,String endMsgId,int page,int pagesize,String uid){
    public JSONObject getTopicMessage(String baseUrl,String topicId,String startMsgId,String endMsgId,int page,int pagesize,String uid){
        String url = baseUrl
                + "api/v2/sessions/topic/"+topicId+"/messages?topic_id="+topicId+"&end="+startMsgId
                +"&start="+(endMsgId==null?"":endMsgId)+"&page="+page+"&pagesize="+pagesize+"&user="+uid;
@ -176,7 +183,7 @@ public class ImUtill {
     * @param sessionId
     * @return
     */
    public static JSONObject deleteMucUser(String baseUrl,String userId,String oldUserId,String sessionId) throws  Exception{
    public JSONObject deleteMucUser(String baseUrl,String userId,String oldUserId,String sessionId) throws  Exception{
        String url = baseUrl
                + "api/v2/sessions/"+sessionId+"/participant/update";
        try{
@ -202,7 +209,7 @@ public class ImUtill {
     * @param topicId
     * @return
     */
    public static JSONObject getTopic(String baseUrl,String topicId) throws  Exception{
    public JSONObject getTopic(String baseUrl,String topicId) throws  Exception{
        String url =baseUrl
                + "api/v2/sessions/topics/"+topicId+"?topic_id="+topicId;
        try{

+ 3 - 3
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/model/PatientHealthIndex.java

@ -48,7 +48,7 @@ public class PatientHealthIndex extends IdEntity {
	//设备编号
	private String deviceSn;
	private int status;//状态:0为标准,1为异常
	private Integer status;//状态:0为标准,1为异常
	public String getUser() {
		return user;
@ -185,11 +185,11 @@ public class PatientHealthIndex extends IdEntity {
		this.deviceSn = deviceSn;
	}
	public int getStatus() {
	public Integer getStatus() {
		return status;
	}
	public void setStatus(int status) {
	public void setStatus(Integer status) {
		this.status = status;
	}
}

+ 32 - 24
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java

@ -19,7 +19,6 @@ import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -58,6 +57,8 @@ public class DeviceService {
    @Autowired
    private HttpHelper httpHelper;
    @Autowired
    private HttpClientUtil HttpClientUtil;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private JdbcTemplate jdbcTemplate;
@ -65,6 +66,8 @@ public class DeviceService {
    private  PatientBloodSuggerDao patientBloodSuggerDao;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private PushMsgTask pushMsgTask;
    private ObjectMapper objectMapper = new ObjectMapper();
    private Integer aStart;
@ -164,16 +167,16 @@ public class DeviceService {
        return "1";//"空腹血糖"
    }
 /*   private Boolean isInArea(String time, String[] timeArea) {
        String date = DateUtil.getDateFromDateTime(time);
        Long beginTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + timeArea[0] + ":00"));
        Long endTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + timeArea[1] + ":00"));
        if (beginTime > 0 && endTime < 0) {
            return true;
        } else {
            return false;
        }
    }*/
    /*   private Boolean isInArea(String time, String[] timeArea) {
           String date = DateUtil.getDateFromDateTime(time);
           Long beginTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + timeArea[0] + ":00"));
           Long endTime = DateUtil.compareDateTime(DateUtil.toTimestamp(time), DateUtil.toTimestamp(date + " " + timeArea[1] + ":00"));
           if (beginTime > 0 && endTime < 0) {
               return true;
           } else {
               return false;
           }
       }*/
// 判断时间是否在对应时间段
    private Boolean isInArea(String time,String begin,String end) {
        String date = DateUtil.getDateFromDateTime(time);
@ -397,7 +400,6 @@ public class DeviceService {
                //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----START
                String patientCode = result.getUser();
                //患者信息
                Patient patient = patientDao.findByCode(patientCode);
@ -408,37 +410,42 @@ public class DeviceService {
                Sort sort = new Sort(Sort.Direction.DESC, "recordDate");
                // 分页信息
                Pageable pageRequest = new PageRequest(0, 5, sort);
                Pageable pageable = new PageRequest(1, 5);
                List<PatientHealthIndex> bloodPressurepatientHealthIndices = new ArrayList<>();
                List<PatientHealthIndex> bloodSuggurpatientHealthIndices = new ArrayList<>();
                if( 1 == patient.getDisease()){
                    bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"2",pageable);
                    bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,2,pageable);
                } else if( 2 == patient.getDisease()){
                    bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"1",pageable);
                    bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,1,pageable);
                } else {
                    bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"2",pageable);
                    bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,"1",pageable);
                    bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,2,pageable);
                    bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndType(patientCode,1,pageable);
                }
                for (PatientHealthIndex patientHealthIndex : bloodPressurepatientHealthIndices) {
                    if(1 == patientHealthIndex.getStatus()){
                    if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                        bloodPressureBbnormalCount++;
                    }
                }
                for (PatientHealthIndex patientHealthIndex : bloodSuggurpatientHealthIndices) {
                    if(1 == patientHealthIndex.getStatus()){
                    if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                        bloodSuggurBbnormalCount++;
                    }
                }
                //连续5次异常,修改用户为预警状态
                if( (5 == bloodPressureBbnormalCount || 5 == bloodSuggurBbnormalCount) && 0 == patient.getStandardStatus()){
                //连续3次异常,修改用户为预警状态
                if( (bloodPressureBbnormalCount >=3 || bloodSuggurBbnormalCount >=3) && 0 == patient.getStandardStatus()){
                    patient.setStandardStatus(1);
                }else{
                    Date end = new Date();
                    Date start = DateUtil.setDateTime(end,-7);
                    //计算血糖或者血压一周内的异常记录数量
                    int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start,end,1);
                    if(errorCount >= 5){//超过5次,记为预警状态
                        patient.setStandardStatus(1);
                    }
                }
                //连续5次正常,修改用户为非预警状态
@ -446,6 +453,7 @@ public class DeviceService {
                    patient.setStandardStatus(0);
                }
                patientDao.save(patient);
                //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----END
            }
        } catch (Exception e) {
@ -775,7 +783,7 @@ public class DeviceService {
        // 批量保存消息
        messageDao.save(messages);
        // 推送消息给医生
        PushMsgTask.getInstance().put(array);
        pushMsgTask.put(array);
    }
    /**

+ 10 - 20
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/task/PushMsgTask.java

@ -1,39 +1,28 @@
package com.yihu.hos.device.task;
import com.yihu.hos.device.common.configuration.SystemConfig;
import com.yihu.hos.device.common.util.ImUtill;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.LinkedBlockingQueue;
@Component
public class PushMsgTask {
	public static String url="";
	private static Logger logger = LoggerFactory.getLogger(PushMsgTask.class);
	// 最大容量为50的数组堵塞队列
	private static LinkedBlockingQueue<JSONObject> queue = new LinkedBlockingQueue<JSONObject>();
	private static PushMsgTask instance;
	private static Object lock = new Object();
	@Value("${systemConfig.socket_server}")
	private String socket_server;
	@Autowired
	private SystemConfig systemConfig;
	public static PushMsgTask getInstance() {
		synchronized (lock) {
			if (instance == null) {
				instance = new PushMsgTask();
				instance.run();
			}
		}
		return instance;
	}
	private ImUtill ImUtill;
	/**
	 * 添加一条推送消息
@ -75,6 +64,7 @@ public class PushMsgTask {
		}
	}
	@PostConstruct
	private void run() {
		new Thread(new ConsumerTask()).start();
	}
@ -116,7 +106,7 @@ public class PushMsgTask {
	 * @param msg 消息内容
	 * @param data 消息数据
	 */
	public static boolean pushMessage(String receiver, String msgType, String title, String msg, String data) {
	public boolean pushMessage(String receiver, String msgType, String title, String msg, String data) {
		try {
//			String url = "http://127.0.0.1:3000/api/v1/chats/sm";
//			HttpHelper httpHelper=new HttpHelper();
@ -135,8 +125,8 @@ public class PushMsgTask {
//			} else {
//				throw new Exception("接口调用错误!"+response.getBody());
//			}
			String url = "http://127.0.0.1:3000/";
			String url = socket_server +"/";
			org.json.JSONObject participants = new org.json.JSONObject();
			participants.put("system",0);
			participants.put(receiver,0);

+ 4 - 4
patient-co-service/wlyy_device/src/main/resources/application.yml

@ -52,8 +52,8 @@ spring:
  profiles: test
  datasource:
    url: jdbc:mysql://172.19.103.85:3306/device?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: ssgg
    password: ssgg
    username: linzhou
    password: linzhou
    driverClassName: com.mysql.jdbc.Driver
    maxTotal: 500
    maxIdle: 30
@ -77,7 +77,7 @@ healthStandard:
systemConfig:
  msg_push_server: http://127.0.0.1:3000/system/sendmsg.im
  jw_server: http://172.19.103.88:8011/wlyy_service-1.0-SNAPSHOT
  socket_server: http://192.168.131.102:3008
  socket_server: http://172.19.103.88:3000
---
spring:
  profiles: production
@ -107,5 +107,5 @@ healthStandard:
  ssy_max: 140
systemConfig:
  msg_push_server: http://127.0.0.1:3000/system/sendmsg.im
  jw_server: http://59.61.92.90:8087/wlyy_service
  jw_server: http://59.61.92.90:8072/wlyy_service
  socket_server: http://27.155.101.77:3000

+ 73 - 73
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/SignController.java

@ -23,84 +23,84 @@ import java.util.Map;
@Api(description = "基卫签约服务接口")
public class SignController {
	@Autowired
	ZysoftService zysoftService;
    @Autowired
    ZysoftService zysoftService;
	@Autowired
	private SignZYService signZYService;
    @Autowired
    private SignZYService signZYService;
	/******************************* 签约接口 ********************************************************/
    /******************************* 签约接口 ********************************************************/
	@RequestMapping(value = "CheckSignFamily",method = RequestMethod.POST)
	@ApiOperation("查询是否已签约")
	public Result checkSignFamily(
			@ApiParam(name="idcard",value="患者身份证",defaultValue = "350821201112240026")
			@RequestParam(value="idcard",required = true) String idcard){
		try {
			Map<String,String> response = signZYService.checkSignFamily(idcard);
			return Result.success("查询签约成功!",response);
		} catch (Exception ex) {
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
    @RequestMapping(value = "CheckSignFamily",method = RequestMethod.POST)
    @ApiOperation("查询是否已签约")
    public Result checkSignFamily(
            @ApiParam(name="idcard",value="患者身份证",defaultValue = "350821201112240026")
            @RequestParam(value="idcard",required = true) String idcard){
        try {
            Map<String,String> response = signZYService.checkSignFamily(idcard);
            return Result.success("查询签约成功!",response);
        } catch (Exception ex) {
            if(ex instanceof ApiException)
            {
                ApiException apiEx = (ApiException) ex;
                return Result.error(apiEx.errorCode(),ex.getMessage());
            }
            else{
                return Result.error(ex.getMessage());
            }
        }
    }
	@RequestMapping(value = "getSickFamilyDoctorSignLimit",method = RequestMethod.POST)
	@ApiOperation("查询家庭医生签约人数上限接口")
	public Result getSickFamilyDoctorSignLimit(
			@ApiParam(name="jwTeamCode",value="智业行政团队code",defaultValue = "44")
			@RequestParam(value="jwTeamCode",required = true) String jwTeamCode){
		try {
			String response = signZYService.getSickFamilyDoctorSignLimit(jwTeamCode);
			return Result.success("查询签约成功!",response);
		} catch (Exception ex) {
			ex.printStackTrace();
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
    @RequestMapping(value = "getSickFamilyDoctorSignLimit",method = RequestMethod.POST)
    @ApiOperation("查询家庭医生签约人数上限接口")
    public Result getSickFamilyDoctorSignLimit(
            @ApiParam(name="jwTeamCode",value="智业行政团队code",defaultValue = "44")
            @RequestParam(value="jwTeamCode",required = true) String jwTeamCode){
        try {
            String response = signZYService.getSickFamilyDoctorSignLimit(jwTeamCode);
            return Result.success("查询签约成功!",response);
        } catch (Exception ex) {
            ex.printStackTrace();
            if(ex instanceof ApiException)
            {
                ApiException apiEx = (ApiException) ex;
                return Result.error(apiEx.errorCode(),ex.getMessage());
            }
            else{
                return Result.error(ex.getMessage());
            }
        }
    }
	@RequestMapping(value = "getSickFamilyDoctorSpecialistControl",method = RequestMethod.POST)
	@ApiOperation("查询家签慢病患者定标情况接口")
	public Result getSickFamilyDoctorSpecialistControl(
			@ApiParam(name="TIME_START",value="修改的开始时间",defaultValue = "2017-6-6 00:00:00")
			@RequestParam(value="TIME_START",required = false) String TIME_START,
			@ApiParam(name="TIME_END",value="修改的开始时间",defaultValue = "2017-6-7 23:59:59")
			@RequestParam(value="TIME_END",required = false) String TIME_END,
			@ApiParam(name="IDENTITY_CARD_NO",value="身份证号",defaultValue = "360502194503120013")
			@RequestParam(value="IDENTITY_CARD_NO",required = false) String IDENTITY_CARD_NO){
		try {
			String response = "";
			if(StringUtils.isBlank(IDENTITY_CARD_NO)){
				response = signZYService.getSickFamilyDoctorSpecialistControl(TIME_START,TIME_END);
			}else{
				response = signZYService.getSickFamilyDoctorSpecialistControlByIdcard(IDENTITY_CARD_NO);
			}
			return Result.success("查询成功!",response);
		} catch (Exception ex) {
			ex.printStackTrace();
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	}
    @RequestMapping(value = "getSickFamilyDoctorSpecialistControl",method = RequestMethod.POST)
    @ApiOperation("查询家签慢病患者定标情况接口")
    public Result getSickFamilyDoctorSpecialistControl(
            @ApiParam(name="TIME_START",value="修改的开始时间",defaultValue = "2017-6-6 00:00:00")
            @RequestParam(value="TIME_START",required = false) String TIME_START,
            @ApiParam(name="TIME_END",value="修改的开始时间",defaultValue = "2017-6-7 23:59:59")
            @RequestParam(value="TIME_END",required = false) String TIME_END,
            @ApiParam(name="IDENTITY_CARD_NO",value="身份证号",defaultValue = "360502194503120013")
            @RequestParam(value="IDENTITY_CARD_NO",required = false) String IDENTITY_CARD_NO){
        try {
            String response = "";
            if(StringUtils.isBlank(IDENTITY_CARD_NO)){
                response = signZYService.getSickFamilyDoctorSpecialistControl(TIME_START,TIME_END);
            }else{
                response = signZYService.getSickFamilyDoctorSpecialistControlByIdcard(IDENTITY_CARD_NO);
            }
            return Result.success("查询成功!",response);
        } catch (Exception ex) {
            ex.printStackTrace();
            if(ex instanceof ApiException)
            {
                ApiException apiEx = (ApiException) ex;
                return Result.error(apiEx.errorCode(),ex.getMessage());
            }
            else{
                return Result.error(ex.getMessage());
            }
        }
    }

+ 2 - 2
patient-co-service/wlyy_service/src/main/webapp/prescription_consulting/js/prescription_consulting_info.js

@ -5,8 +5,8 @@ var request = GetRequest(),
    page = 1,
    prepend =  false; 
//var server = "http://192.168.131.24:8081/";//本地
//var server = "http://172.19.103.88:8011/wlyy_service";//测试
var server = "http://10.95.22.10:8011/wlyy_service";//正式
//var server = "http://172.19.103.88:8011/wlyy_service/";//测试
var server = "http://10.95.22.10:8011/wlyy_service/";//正式
$(function(){
    dialroll = iscrollAssist.newVerScrollForPull($('.pull-iscroll-wrap'), pulldownAction, null);

+ 1 - 1
patient-co/patient-co-doctor-assistant/pom.xml

@ -438,7 +438,7 @@
        </dependency>
    </dependencies>
    <build>
        <finalName>wlyy</finalName>
        <finalName>assistant</finalName>
        <plugins>
            <!--打成war包需要的配置-->

+ 1 - 1
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java

@ -340,7 +340,7 @@ public class DoctorSchemeService {
                    patientSchemeListObj.setSchemecode(schemecode);
                    patientSchemeListObj.setDoctorcode(doctorcode);
                    Short _type = new Short(type);
                    patientSchemeListObj.setType(_type);
                    patientSchemeListObj.setType(Integer.parseInt(type));
                    patientSchemeListObj.setCreateTime(DateUtil.getNowTimestamp());
                    patientSchemeListDao.save(patientSchemeListObj);
                }

+ 4 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/common/account/DoctorService.java

@ -158,4 +158,8 @@ public class DoctorService extends TokenService {
        return doctorList;
    }
    public void save(Doctor doctor){
        doctorDao.save(doctor);
    }
}

+ 366 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java

@ -0,0 +1,366 @@
package com.yihu.wlyy.web.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImageCompress;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.fastdfs.FastDFSUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
@RequestMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "文件上传")
public class FileUploadController extends BaseController {
    @ApiParam
    FastDFSUtil fastDFSUtil;
    @Autowired
    private CommonUtil CommonUtil;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    /**
     * 患者头像上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "patientPhoto", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
    @ResponseBody
    public String patientPhoto(HttpServletRequest request, HttpServletResponse response, String photo) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            String firstPhoto = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                firstPhoto = photo.substring(0, photo.lastIndexOf(".")) + "_small." + fileExt;
                File uploadFile = new File(SystemConf.getInstance().getTempPath() + File.separator + firstPhoto);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", String.join(",", firstPhoto));
            System.out.println("图片上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "上传失败");
        }
    }
    /**
     * 图片上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "image", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
    @ResponseBody
    public String image(HttpServletRequest request, HttpServletResponse response) {
        // 圖片列表
        List<File> images = new ArrayList<File>();
        List<String> tempPaths = new ArrayList<String>();
        // 文件保存的临时路径
        String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // 创建文件夹
            File file = new File(tempPath + datePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File uploadFile = new File(tempPath + datePath + newFileName);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 生成缩略图
                ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
                // 添加到上传成功数组中
                images.add(uploadFile);
                tempPaths.add(datePath + newFileName);
            }
            String urls = "";
            for (String image : tempPaths) {
                if (urls.length() == 0) {
                    urls = image;
                } else {
                    urls += "," + image;
                }
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("图片上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            try {
                // 清除垃圾图片
                for (File file : images) {
                    FileUtils.forceDelete(file);
                }
            } catch (Exception e2) {
                error(e2);
            }
            return error(-1, "上传失败");
        }
    }
    /**
     * 聊天附件上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "chat", method = RequestMethod.POST)
    @ResponseBody
    public String chatFile(HttpServletRequest request, HttpServletResponse response) {
        List<String> tempPaths = new ArrayList<String>();
        try {
            String fastUrl = fastdfs_file_url;
            String type  = request.getParameter("type");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                if("3".equals(type)){
                    String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
                    String map3Path = tempPath.substring(0,tempPath.lastIndexOf("."));
                    CommonUtil.changeToMp3(tempPath,map3Path);
                    File tempFile = new File(tempPath);
                    File mp3File = new File(map3Path);
                    ObjectNode objectNode = fastDFSUtil.upload(new FileInputStream(mp3File),"mp3","");
                    //1.3.7 去掉前缀,返回相对路径
//                    tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(objectNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    if(tempFile!=null){
                        tempFile.delete();
                    }
                    if(mp3File!=null){
                        mp3File.delete();
                    }
                }else if("4".equals(type)){
                    String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
                    String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
                    File tempFile = new File(tempPath);
                    File pngFile = new File(pngPath);
                    long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
                    if(times<1000){
                        JSONObject json = new JSONObject();
                        json.put("status", -1);
                        json.put("success",true);
                        json.put("msg", "视频录制时间太短!");
                        json.put("times", times);
                        return json.toString();
                    }
                    ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
                    //1.3.7 去掉前缀,返回相对路径
//                    tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
//                    tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(imgNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(videoNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(times+"");
                    if(tempFile!=null){
                        tempFile.delete();
                    }
                    if(pngFile!=null){
                        pngFile.delete();
                    }
                } else{
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    ObjectNode objectNode = fastDFSUtil.upload(mf.getInputStream() ,fileExt,"");
                    //1.3.7 去掉前缀,返回相对路径
//                  tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(objectNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                }
            }
            String urls = String.join(",", tempPaths);
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("success",true);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("附件上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "上传失败");
        }
    }
    /**
     * 语音上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "voice", method = RequestMethod.POST)
    @ResponseBody
    public String voice(HttpServletRequest request, HttpServletResponse response) {
        // 圖片列表
        List<File> voices = new ArrayList<File>();
        List<String> tempPaths = new ArrayList<String>();
        // 文件保存的临时路径
        String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // 创建文件夹
            File file = new File(tempPath + datePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File uploadFile = new File(tempPath + datePath + newFileName);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 添加到上传成功数组中
                voices.add(uploadFile);
                tempPaths.add(datePath + newFileName);
            }
            String urls = "";
            for (String voice : tempPaths) {
                if (urls.length() == 0) {
                    urls = voice;
                } else {
                    urls += "," + voice;
                }
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("语音上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            try {
                // 清除垃圾图片
                for (File file : voices) {
                    FileUtils.forceDelete(file);
                }
            } catch (Exception e2) {
                error(e2);
            }
            return error(-1, "上传失败");
        }
    }
    /**
     * 语音上传
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "test", method = RequestMethod.POST)
    @ResponseBody
    public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<String> tempPaths = new ArrayList<String>();
        String fastUrl = fastdfs_file_url;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();
            String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
            String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
            File tempFile = new File(tempPath);
            File pngFile = new File(pngPath);
            long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
            ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
            tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
                    + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
            tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
                    + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
            tempPaths.add(times+"");
            if(tempFile!=null){
                tempFile.delete();
            }
            if(pngFile!=null){
                pngFile.delete();
            }
        }
        String urls = String.join(",", tempPaths);
        return urls;
    }
}

+ 484 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java

@ -0,0 +1,484 @@
package com.yihu.wlyy.web.common.account;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.login.LoginLog;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.repository.security.TokenDao;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.common.account.RoleService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.service.common.login.LoginLogService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.util.SystemData;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.patchca.color.SingleColorFactory;
import org.patchca.filter.predefined.*;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
//import io.swagger.annotations.Api;
/**
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者、医生及管理员登录")
public class LoginController extends BaseController {
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SMSService smsService;
    @Autowired
    public TokenDao tokenDao;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoginLogService loginLogService;
    /**
     * 公钥生成并返回接口
     *
     * @return
     */
    @RequestMapping(value = "public_key", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String publicKey() {
        try {
            String modulus = RSAUtils.getInstance(smsService).getModulus();
            String exponent = RSAUtils.getInstance(smsService).getExponent();
            if (StringUtils.isEmpty(modulus) || StringUtils.isEmpty(exponent)) {
                return error(-1, "公钥获取失败!");
            } else {
                JSONObject json = new JSONObject();
                json.put("modulus", modulus);
                json.put("exponent", exponent);
                return write(200, "公钥获取成功!", "data", json);
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "公钥获取失败!");
        }
    }
    /**
     * 医生登录接口
     *
     * @param mobile   手机号
     * @param captcha  短信验证码
     * @param platform // 1患者端,2医生端app,3微信公众号wechat,4 IM医生端pc, PC端取药系统,5医生助手公众号
     * @param password 密码
     * @return
     */
    @RequestMapping(value = "doctor", method = RequestMethod.POST)
    @ResponseBody
    public String doctor(@ApiParam(required = false, name = "mobile", value = "手机号") @RequestParam(required = false, value = "mobile") String mobile,
                         @ApiParam(required = false, name = "captcha", value = "短信验证码") @RequestParam(required = false) String captcha,
                         @ApiParam(required = false, name = "platform", value = "医生端pc,取药系统 或者对外系统") @RequestParam(required = false) Integer platform,
                         @ApiParam(required = false, name = "password", value = "密码") @RequestParam(required = false) String password,
                         @ApiParam(required = false, name = "password", value = "openid") @RequestParam(required = false) String openid) {
        String errorMessage;
        LoginLog loginLog = new LoginLog();
        loginLog.setCreateTime(new Date());
        loginLog.setPhone(mobile);
        loginLog.setType("2");
        loginLog.setUserType("2");
        loginLog.setAppVersion(super.getAppVersion());
        try {
            if (StringUtils.isEmpty(getIMEI())) {
                errorMessage = "获取手机IMEI码失败!";
                loginLog.setErrorMessage(errorMessage);
                loginLogService.saveLog(loginLog);
                return error(-1, errorMessage);
            }
            if (platform == null) {
                platform = 2;//默认为医生app端
            }
            //身份证登录
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(password)) {
                password = RSAUtils.getInstance(doctorService).decryptString(password);
                password = StringUtils.reverse(password);
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                loginLog.setLoginType("2");
                if (doctor == null) {
                    errorMessage = "该号码未注册!";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
                loginLog.setUserCode(doctor.getCode());
                String loginPassword = MD5.GetMD5Code(password + doctor.getSalt());
                if (loginPassword.equals(doctor.getPassword())) {
                    Token token = tokenService.findDoctorToken(doctor.getCode());
                    if (token != null && platform == 4 && getIMEI().equals(token.getImei())) {
                        //pc版本要做单点登陆 所以如果platform =4 并且 token存在直接返回之前的token
                    }else {
                        // 用户校验通过,生成token
                        token = tokenService.newToken(doctor.getCode(), getIMEI(), platform);
                    }
                    loginLog.setTokenId(token.getId());
                    loginLog.setType("1");
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", doctor.getId());
                    map.put("uid", doctor.getCode());
                    map.put("token", token.getToken());
                    map.put("name", doctor.getName());
                    map.put("hospital", doctor.getHospital());
                    map.put("photo", doctor.getPhoto());
                    // 设置医生类型:1专科医生,2全科医生,3健康管理师
                    map.put("doctorType", doctor.getLevel());
                    //获取医生角色和区域权限
                    List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(doctor.getCode());
                    map.put("userRole", roleMap);
                    if ("10" .equals(doctor.getLevel()) && roleMap.size() == 0) {
                        errorMessage = "该用户没有管理员权限";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    loginLogService.saveLog(loginLog);
                    if(StringUtils.isNotBlank(openid)){
                        doctor.setOpenid(openid);
                        doctorService.save(doctor);
                    }
                    return write(200, "登录成功", "data", map);
                } else {
                    errorMessage = "密码错误,登录失败";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
            }
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(captcha)) {
                // 对验证码进行校验
                int res = smsService.check(mobile, 5, captcha);
                switch (res) {
                    case -2: {
                        errorMessage = "验证码已过期!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case -1: {
                        errorMessage = "请输入正确的验证码!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case 0: {
                        errorMessage = "验证码无效!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                }
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                loginLog.setLoginType("1");
                if (doctor == null) {
                    errorMessage = "该手机号未注册,请确认!";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else {
                    loginLog.setUserCode(doctor.getCode());
                    // 用户校验通过,生成token
                    Token token = tokenService.findDoctorToken(doctor.getCode());
                    if (token != null && platform == 4 && getIMEI().equals(token.getImei())) {
                        //pc版本要做单点登陆 所以如果platform =4 并且 token存在直接返回之前的token
                    } else {
                        // 用户校验通过,生成token
                        token = tokenService.newToken(doctor.getCode(), getIMEI(), platform);
                    }
                    loginLog.setTokenId(token.getId());
                    loginLog.setType("1");
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", doctor.getId());
                    map.put("uid", doctor.getCode());
                    map.put("token", token.getToken());
                    map.put("name", doctor.getName());
                    map.put("hospital", doctor.getHospital());
                    map.put("photo", doctor.getPhoto());
                    // 设置医生类型:1专科医生,2全科医生,3健康管理师
                    map.put("doctorType", doctor.getLevel());
                    //获取医生角色和区域权限
                    List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(doctor.getCode());
                    map.put("userRole", roleMap);
                    if ("10" .equals(doctor.getLevel()) && roleMap.size() == 0) {
                        errorMessage = "改用户没有管理员权限";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    loginLogService.saveLog(loginLog);
                    return write(200, "登录成功", "data", map);
                }
            }
            errorMessage = "登录信息不完整,请重新输入!";
            loginLog.setErrorMessage(errorMessage);
            loginLogService.saveLog(loginLog);
            return error(-1, errorMessage);
        } catch (Exception e) {
            loginLog.setErrorMessage(e.getMessage());
            loginLogService.saveLog(loginLog);
            error(e);
            return error(-1, "系统异常,登录失败");
        }
    }
    /**
     * 忘记密码
     *
     * @param type    1患者端,2医生端
     * @param idcard  患者身份证号
     * @param mobile  手机号
     * @param captcha 手机验证码
     * @param newpwd  新密码
     * @return
     */
    @RequestMapping(value = "forgetpwd", method = RequestMethod.POST)
    @ResponseBody
    public String forgetpwd(int type,
                            @RequestParam(required = false) String idcard,
                            @RequestParam(required = false) String mobile,
                            @RequestParam(required = false) String captchaToken,
                            @RequestParam(required = false) String captcha,
                            @RequestParam(required = false) String patient,
                            String newpwd) {
        try {
            //String ct = request.getSession().getAttribute("captchaToken").toString();
//            if (StringUtils.isEmpty(captchaToken)) {
//                return error(-1, "图形验证码不允许为空!");
//            }
//            if (!StringUtils.equalsIgnoreCase(captchaToken, ct)) {
//                return error(-1, "图形验证码错误!");
//            }
//            idcard = RSAUtils.getInstance(doctorService).decryptString(idcard);
//            idcard = URLDecoder.decode(idcard, "UTF-8");
//            idcard = StringUtils.reverse(idcard);
//            newpwd = RSAUtils.getInstance(doctorService).decryptString(newpwd);
//            newpwd = URLDecoder.decode(newpwd, "UTF-8");
//            newpwd = StringUtils.reverse(newpwd);
            // 对验证码进行校验
            if (type == 2) {
                // 医生端
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                String password = RSAUtils.getInstance(doctorService).decryptString(newpwd);
                password = StringUtils.reverse(password);
                password = MD5.GetMD5Code(password + doctor.getSalt());
                doctor.setPassword(password);
                doctorService.updateDoctorPwd(doctor);
                return success("操作成功!");
            } else {
                // 患者端
                Patient patientTemp = patientService.findByIdcard(idcard);
                if (patientTemp == null) {
                    return error(-1, "操作失败:此用户未注册");
                } else {
                    String password = RSAUtils.getInstance(doctorService).decryptString(newpwd);
                    password = StringUtils.reverse(password);
                    password = MD5.GetMD5Code(password + patientTemp.getSalt());
                    patientTemp.setPassword(password);
                    patientService.updatePatientPwd(patientTemp);
                    return success("操作成功!");
                }
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "系统异常,操作失败");
        }
    }
    /**
     * 退出登录
     *
     * @param type 1患者,2医生,3微信公众号
     * @return
     */
    @RequestMapping(value = "exit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String logout(int type) {
        try {
            tokenService.delToken(type, getUID());
            return success("已成功退出!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    @RequestMapping(value = "/third/login", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String thirdLogin(
            @RequestParam(value = "id") int id,
            @RequestParam(value = "uid") String uid,
            @RequestParam(value = "imei") String imei,
            @RequestParam(value = "token") String tokenStr,
            @RequestParam(value = "platform") int platform) {
        try {
            if (StringUtils.isEmpty(tokenStr) || StringUtils.isEmpty(imei) || StringUtils.isEmpty(uid)) {
                // response.getWriter().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!"));
                return error(-1, "系统异常,操作失败");
            }
            Token token = SystemData.doctorTokens.get(uid);
            if (token == null) {
                token = tokenDao.findByToken(tokenStr);
                if (token != null) {
                    // 加入缓存
                    SystemData.doctorTokens.put(uid, token);
                }
            }
            if (token == null || token.getPlatform() != 2) {
                // 未登录
                return error(-1, "系统异常,操作失败");
            } else {
                if (token.getTimeout().getTime() < new Date().getTime()) {
                    // 登录超时
                    return error(-1, "系统异常,操作失败");
                } else if (!StringUtils.equals(uid, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
                    // 别处登录
                    return error(-1, "系统异常,操作失败");
                } else {
                    // 一天只更新一次
                    if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
                        // 今天未更新,则更新缓存
                        token.setCzrq(new Date());
                        // 更新内存
                        SystemData.doctorTokens.put(uid, token);
                        // 更新数据库
                        tokenDao.save(token);
                    }
                }
            }
            return success("登陆成功");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "系统异常,操作失败");
        }
    }
    /**
     * 验证码地址
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "pcrimg", method = {RequestMethod.POST, RequestMethod.GET})
    public void crimg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
        cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
        Random random = new Random();
        switch (random.nextInt(5)) {
            case 0:
                cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
                break;
            case 1:
                cs.setFilterFactory(new MarbleRippleFilterFactory());
                break;
            case 2:
                cs.setFilterFactory(new DoubleRippleFilterFactory());
                break;
            case 3:
                cs.setFilterFactory(new WobbleRippleFilterFactory());
                break;
            case 4:
                cs.setFilterFactory(new DiffuseRippleFilterFactory());
                break;
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            session = request.getSession();
        }
        setResponseHeaders(response);
        String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
        session.setAttribute("captchaToken", token);
    }
    protected void setResponseHeaders(HttpServletResponse response) {
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        long time = System.currentTimeMillis();
        response.setDateHeader("Last-Modified", time);
        response.setDateHeader("Date", time);
        response.setDateHeader("Expires", time);
    }
    /**
     * 患者,医生注册-验证手机号
     *
     * @param mobile 登录手机号
     * @return
     */
    @RequestMapping(value = "checkmobile", method = RequestMethod.POST)
    @ResponseBody
    public String checkmobile(@RequestParam(required = true, value = "mobile", defaultValue = "0") String mobile,
                              @RequestParam(required = true, value = "type", defaultValue = "0") int type) {
        try {
            if (type == 0) {//患者端
                List<Patient> temp = patientService.findByMobile(mobile);
                if (temp != null && temp.size() > 0) {
                    // 设置身份证号
                    return write(200, "手机号码已经被注册!");
                }
                return error(-1, "该手机号未被注册!");
            } else if (type == 1) {
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                if (doctor != null) {
                    return write(200, "手机号码已经被注册!");
                }
                return error(-1, "该手机号未被注册!");
            } else {
                return error(1, "错误的请求类型!");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "手机号验证失败");
        }
    }
}

+ 564 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java

@ -0,0 +1,564 @@
package com.yihu.wlyy.web.common.account;
import com.yihu.wlyy.entity.login.LoginLog;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SocialSecurityInfo;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.service.app.family.FamilyMemberService;
import com.yihu.wlyy.service.app.family.FamilyService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.service.common.login.LoginLogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.IdcardValidator;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.web.WeixinBaseController;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import com.yihu.wlyy.wechat.util.WeiXinTagUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.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;
import java.net.URLDecoder;
import java.util.*;
/**
 * @author calvin
 */
@Controller
@RequestMapping(value = "/weixin", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "微信端用户注册")
public class WechatController extends WeixinBaseController {
    @Autowired
    private PatientService patientService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SMSService smsService;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private FamilyService familyService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private FamilyMemberService familyMemberService;
    @Autowired
    WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    AccessTokenService accessTokenService;
    @Autowired
    HttpUtil HttpUtil;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinTagUtil weiXinTagUtil;
    /**
     * 获取验证码发送的手机号码
     *
     * @param idCard
     * @return
     */
    @RequestMapping(value = "getMobile", method = RequestMethod.POST)
    @ResponseBody
    public String getPatientInfoByIdCard(@RequestParam(value = "idCard", required = true) String idCard) {
        Patient temp = patientService.findByIdcard(idCard);
        getAccessToken();
        if (temp == null) {
            return error(-1, "用户未注册");
        } else {
            if (StringUtils.isBlank(temp.getMobile())) {
                return error(-2, "用户未绑定手机号");
            } else {
                JSONObject object = new JSONObject();
                object.put("mobile", temp.getMobile());
                return write(200, "获取成功", "data", object);
            }
        }
    }
    /**
     * 注册信息验证
     *
     * @param name   姓名
     * @param idcard 身份证号
     * @param ssc    社保卡号
     * @param mobile 手机号
     * @return
     */
    @RequestMapping(value = "/check_regist_info", method = RequestMethod.POST)
    @ResponseBody
    public String checkRegistInfo(String name, String idcard, String ssc, String mobile) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空");
            }
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号不允许为空");
            }
            //if (patientService.findByMobile(mobile) != null) {
            //    return error(-1, "该手机号已被注册");
            //}
            // 解密身份证号
            idcard = RSAUtils.getInstance(patientService).decryptString(idcard);
            idcard = URLDecoder.decode(idcard, "UTF-8");
            idcard = StringUtils.reverse(idcard);
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致,请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0 && ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                    return error(-1, "身份证号与医保卡号不一致,请检查后重新输入");
                }
            } else {
                return error(-1, "对不起,暂不支持16年6月份之后办理的医保卡注册");
            }
            Patient patient = patientDao.findByIdcard(idcard);
            if (patient != null) {
                if (!StringUtils.isEmpty(patient.getMobile())) {
                    return error(-2, "该身份证已被注册");
                }
            }
            return write(200, "验证成功");
        } catch (Exception e) {
            return error(-1, "验证失败");
        }
    }
    /**
     * 患者注册
     *
     * @param idcard  身份證號
     * @param mobile  登录手机号
     * @param captcha 手机验证码
     * @return
     */
    @RequestMapping(value = "regist", method = RequestMethod.POST)
    @ResponseBody
    public String regist(@RequestParam(value = "name", required = true) String name,
                         @RequestParam(value = "idcard", required = true) String idcard,
                         @RequestParam(value = "ssc", required = true) String ssc,
                         @RequestParam(value = "mobile", required = true) String mobile,
                         @RequestParam(value = "captcha", required = true) String captcha,
                         @RequestParam(value = "openid", required = true) String openid,
                         @RequestParam(value = "password", required = true) String password) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空!");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空!");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空!");
            }
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号不允许为空!");
            }
            //if (patientService.findByMobile(mobile) != null) {
            //    return error(-1, "该手机号已被注册!");
            //}
            // 对验证码进行校验
            int res = smsService.check(mobile, 1, captcha);
            switch (res) {
                case -2:
                    return error(-1, "验证码已过期!");
                case -1:
                    return error(-1, "请输入正确的验证码!");
                case 0:
                    return error(-1, "验证码无效!");
            }
            // 未绑定openid,查询是否绑定其他账号
//			if (patientService.countByOpenid(openid) > 0) {
//				return error(-1, "该微信号已绑定其他手机号!");
//			}
            // 解密身份证号
            idcard = RSAUtils.getInstance(patientService).decryptString(idcard);
            idcard = URLDecoder.decode(idcard, "UTF-8");
            idcard = StringUtils.reverse(idcard);
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号!");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号!");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致<br/>请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0) {
                    if (ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                        return error(-1, "身份证号与医保卡号不一致,请检查后重新输入");
                    } else {
                        ssc = socialSecurityInfo.getCardno();//统一只存英文字母开头的医保卡
                    }
                }
            } else {
                return error(-1, "对不起,暂不支持16年6月份之后办理的医保卡注册");
            }
            Patient patient = patientDao.findByIdcard(idcard);
            if (patient == null) {
                patient = new Patient();
            } else {
                if (!StringUtils.isEmpty(patient.getMobile())) {
                    return error(-2, "该身份证已被注册!");
                }
            }
            patient.setName(name);
            patient.setIdcard(idcard);
            patient.setMobile(mobile);
            //增加密码
            String salt = UUID.randomUUID().toString().replace("-", "");
            patient.setSalt(salt);
            password = RSAUtils.getInstance(patientService).decryptString(password);
            password = StringUtils.reverse(password);
            patient.setPassword(MD5.GetMD5Code(password + salt));
            patient.setSsc(ssc);
            if (!org.springframework.util.StringUtils.isEmpty(openid)) {
                patient.setOpenid(openid);
                patient.setOpenidTime(new Date());
            }
            JSONObject json = patientService.register(idcard, ssc, name, mobile, MD5.GetMD5Code(password + salt)
                    , salt, openid, 3);
            if (json != null) {
                try {
                    Patient p = patientDao.findByIdcard(idcard);
                    BusinessLogs.info(BusinessLogs.BusinessType.register, p.getCode(), p.getCode(), new JSONObject(p));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 注册成功
                return write(200, "注册成功!", "data", json);
            } else {
                // 注册失败
                return error(-1, "注册失败!");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "注册失败!");
        }
    }
    /**
     * 患者微信登录接口
     *
     * @param captcha  短信号
     * @param mobile   电话号码
     * @param password 登录密码
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public String login(
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) String captcha,
            @RequestParam(required = false) String password,
            String openid) {
        System.out.println("login openid : " + openid);
        String errorMessage;
        LoginLog loginLog = new LoginLog();
        loginLog.setCreateTime(new Date());
        loginLog.setPhone(mobile);
        loginLog.setType("2");
        loginLog.setUserType("1");
        try {
            //账号登录 mobile可能是电话号也可能是身份证
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(password)) {
                Patient p = patientService.findByIdcard(mobile);
                if (p == null) {
                    List<Patient> patients = patientService.findByMobile(mobile);
                    if (patients.size() > 1) {
                        return error(-1, "此手机号码存在多个用户,请用身份证进行登录!");
                    } else if (patients.size() == 1) {
                        p = patients.get(0);
                    }
                }
                loginLog.setLoginType("2");
                if (p == null) {
                    if (mobile.length() == 11) {
                        errorMessage = "该手机号暂未注册账号,请确认后重新输入!";
                    } else {
                        errorMessage = "该身份证号暂未注册账号,请确认后重新输入!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (p.getStatus() == 0) {
                    if (mobile.length() == 11) {
                        errorMessage = "该手机号已被禁止使用!";
                    } else {
                        errorMessage = "该身份证号已被禁止使用!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (p.getStatus() == 2) {
                    errorMessage = "该账号正在审核中,请确认审核通过后再登录,“如有疑问,拨打400-6677-400转2人工客服”";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (StringUtils.isEmpty(openid)) {
                    errorMessage = "无效的OpenID!";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
                loginLog.setUserCode(p.getCode());
                //解密
                password = RSAUtils.getInstance(patientService).decryptString(password);
                password = StringUtils.reverse(password);
                //生成MD5
                String loginPassword = MD5.GetMD5Code(password + p.getSalt());
                //判断d登录密码是否正确
                if (loginPassword.equals(p.getPassword())) {
                    // 绑定用户手机号和openid
                    if (!StringUtils.equals(p.getOpenid(), openid) && !"undefined".equals(openid)) {//undefined不更新数据库
                        //patient.setOpenid(openid);
                        patientService.updatePatient(p, openid);
                    }
                    // 用户校验通过,生成token
                    Token token = tokenService.newTxToken(p.getCode(), openid);
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    map.put("id", p.getId());
                    map.put("uid", p.getCode());
                    map.put("name", p.getName());
                    map.put("token", token.getToken());
                    map.put("photo", p.getPhoto());
                    if (StringUtils.isNoneEmpty(openid)) {
                        //发送微信模板
                        familyService.sendWXMessage(p);
                    }
                    loginLog.setLoginType("1");
                    loginLogService.saveLog(loginLog);
                    //判断是否打过标签
                   //if (!(Patient.isWchatTage.yes.getValue() == p.getIsWxtag())) {
                    //给患者打微信标签
                    weiXinTagUtil.addTagWithOpenid(openid, p.getCode(), p.getName());
                    //}
                    return write(200, "登录成功", "data", map);
                } else {
                    errorMessage = "密码错误,登录失败";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
            }
            //短信登录
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(captcha)) {
                List<Patient> patients = patientService.findByMobile(mobile);
                if (patients.size() > 1) {
                    return error(-1, "此手机存在多个用户,请用身份证和密码登录!");
                }
                // 对验证码进行校验
                int res = smsService.check(mobile, 4, captcha);
                switch (res) {
                    case -2: {
                        errorMessage = "验证码已过期!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case -1: {
                        errorMessage = "请输入正确的验证码!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case 0: {
                        errorMessage = "验证码无效!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                }
                loginLog.setLoginType("1");
                if (patients == null || patients.size() == 0) {
                    if (mobile.length() == 11) {
                        errorMessage = "该手机号暂未注册账号,请确认后重新输入!";
                    } else {
                        errorMessage = "该身份证号暂未注册账号,请确认后重新输入!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else {
                    Patient p = null;
                    if (patients.size() == 1) {
                        p = patients.get(0);
                    }
                    if (p.getStatus() == 0) {
                        if (mobile.length() == 11) {
                            errorMessage = "该手机号已被禁止使用!";
                        } else {
                            errorMessage = "该身份证号已被禁止使用!";
                        }
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    } else if (p.getStatus() == 2) {
                        errorMessage = "该账号正在审核中,请确认审核通过后再登录,“如有疑问,拨打400-6677-400转2人工客服”";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    } else if (StringUtils.isEmpty(openid)) {
                        errorMessage = "无效的OpenID!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    loginLog.setUserCode(p.getCode());
                    // 绑定用户手机号和openid
                    if (!StringUtils.equals(p.getOpenid(), openid) && !"undefined".equals(openid)) {//undefined不更新数据库
                        //patient.setOpenid(openid);
                        patientService.updatePatient(p, openid);
                    }
                    // 用户校验通过,生成token
                    Token token = tokenService.newTxToken(p.getCode(), openid);
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    map.put("id", p.getId());
                    map.put("uid", p.getCode());
                    map.put("name", p.getName());
                    map.put("token", token.getToken());
                    map.put("photo", p.getPhoto());
                    if (StringUtils.isNoneEmpty(openid)) {
                        //发送微信模板
                        familyService.sendWXMessage(p);
                    }
                    loginLog.setType("1");
                    loginLogService.saveLog(loginLog);
                    //判断是否打过标签
                    //if (!(Patient.isWchatTage.yes.getValue() == p.getIsWxtag())) {
                        //给患者打微信标签
                        weiXinTagUtil.addTagWithOpenid(openid, p.getCode(), p.getName());
                    //}
                    return write(200, "登录成功", "data", map);
                }
            }
            return error(-1, "登录失败");
        } catch (Exception e) {
            errorMessage = "系统异常,登录失败";
            loginLog.setErrorMessage(errorMessage);
            loginLogService.saveLog(loginLog);
            error(e);
            return error(-1, "系统异常,登录失败");
        }
    }
    /**
     * 获取签名signature
     *
     * @param pageUrl 需要签名的页面全地址(?后的也需要除了#后的不需要)
     * @return
     */
    @RequestMapping(value = "getSign", method = RequestMethod.POST)
    @ResponseBody
    public String getSign(String pageUrl) {
        try {
            String ticket = getJsapi_ticketByToken();
            if (ticket != null) {
                String noncestr = UUID.randomUUID().toString();
                long timestamp = System.currentTimeMillis() / 1000;
                String url = pageUrl;
                String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
                // sha1加密
                String signature = SHA1(str);
                Map<Object, Object> map = new HashMap<Object, Object>();
                map.put("noncestr", noncestr);
                map.put("timestamp", timestamp);
                map.put("signature", signature);
                return write(200, "获取签名成功", "data", map);
            } else
                return error(-1, "获取签名失败");
        } catch (Exception e) {
            error(e);
        }
        return error(-1, "获取签名失败");
    }
    /**
     * 获取微信openid
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "getOpenidByCode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getOpenidByCode(String code) {
        try {
            String openid = super.getOpenidByCode(code);
            if (!StringUtils.isEmpty(openid)) {
                return write(200, "获取openid成功!", "openid", openid);
            } else {
                return error(-1, "获取openid失败!");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "获取openid失败!");
        }
    }
}

+ 42 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java

@ -0,0 +1,42 @@
package com.yihu.wlyy.web.common.area;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.service.common.area.AreaService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by lyr-pc on 2016/11/22.
 */
@RestController
@RequestMapping(value = "/area")
@Api(description = "城市、城镇管理")
public class AreaController extends BaseController {
    @Autowired
    AreaService areaService;
    /**
     * 查询城市下的城镇
     *
     * @param city 城市
     * @return
     */
    @RequestMapping(value = "/{city}/towns", method = RequestMethod.GET)
    public String getCityTowns(@PathVariable String city) {
        try {
            List<Town> towns = areaService.getCityTowns(city);
            return write(200, "查询成功", "data", towns == null ? new ArrayList<Town>() : towns);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 48 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/data/DataController.java

@ -0,0 +1,48 @@
package com.yihu.wlyy.web.common.data;
import com.yihu.wlyy.entity.dict.Disease;
import com.yihu.wlyy.service.common.data.DataService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
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.ResponseBody;
import java.util.List;
@RequestMapping(value = "/common/data", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Controller
@Api(description = "疾病与社区")
public class DataController extends BaseController {
	@Autowired
	private DataService dataService;
	@RequestMapping(value = "diseases",method = RequestMethod.POST)
	@ResponseBody
	public String diseases() {
		try {
			JSONArray array = new JSONArray();
			List<Disease> list = dataService.findAllDisease();
			for (Disease temp : list) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				json.put("code", temp.getCode());
				json.put("name", temp.getName());
				array.put(json);
			}
			return write(200, "获取疾病成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "获取疾病失败!");
		}
	}
}

+ 65 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.web.common.device;
import com.yihu.wlyy.entity.device.Device;
import com.yihu.wlyy.entity.device.DeviceCategory;
import com.yihu.wlyy.service.app.device.DeviceService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/common/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "设备管理")
public class DeviceController extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @ApiOperation("获取设备分类")
    @RequestMapping(value = "DeviceCategory", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String getDeviceCategory() {
        try {
            List<DeviceCategory> list = deviceService.findAllCategory();
            return write(200, "获取设备分类成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "获取设备分类失败!");
        }
    }
    @ApiOperation("获取设备列表")
    @RequestMapping(value = "DeviceList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceList(@ApiParam(name = "category_code", value = "设备类型代码", defaultValue = "1")
                                @RequestParam(value = "category_code", required = true) String categoryCode) {
        try {
            List<Device> list = deviceService.findDeviceByCategory(categoryCode);
            return write(200, "获取设备列表成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "获取设备列表失败!");
        }
    }
    @ApiOperation("获取设备信息")
    @RequestMapping(value = "DeviceInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceInfo(@ApiParam(name = "id", value = "设备ID", defaultValue = "19")
                                @RequestParam(value = "id", required = true) String id) {
        try {
            Device device = deviceService.findById(id);
            return write(200, "查询成功", "data", device);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}

+ 45 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java

@ -0,0 +1,45 @@
package com.yihu.wlyy.web.common.district;
import com.yihu.wlyy.service.common.district.DistrictService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
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.ResponseBody;
import java.util.List;
/**
 * 省市区三级地址控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "省市区三级地址")
public class DistrictController extends BaseController {
	@Autowired
	private DistrictService districtService;
	/**
	 * 省市一二三级查询接口
	 * @param type 1一级目录,2二级目录,3三级目录,4街道目录
	 * @param code 省或市标识
	 * @return
	 */
	@RequestMapping(value = "district",method = RequestMethod.POST)
	@ResponseBody
	public String district(int type, String code) {
		try {
			List<?> list = districtService.findByType(type, code);
			return write(200, "查询成功!", "list", list);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
}

+ 88 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java

@ -0,0 +1,88 @@
package com.yihu.wlyy.web.common.health;
import com.yihu.wlyy.entity.education.FoodComp;
import com.yihu.wlyy.service.app.health.FoodCompService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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;
import java.util.List;
/**
 * 患者端:食物热量查询
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/common/health/food", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-食物热量查询")
public class FoodCompController extends BaseController {
    @Autowired
    private FoodCompService foodCompService;
    /**
     * 查询食物热量列表
     *
     * @param pid 父id
     * @return 列表
     */
    @ApiOperation("查询食物热量列表")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ResponseBody
    public String list(@RequestParam("pid") long pid) {
        try {
            List<FoodComp> foodComps = foodCompService.getByPid(pid);
            return write(200, "查询成功", "list", foodComps);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 查询食物热量查询
     *
     * @param name 查询名称
     * @return 列表
     */
    @ApiOperation("查询食物热量查询")
    @RequestMapping(value = "search", method = RequestMethod.POST)
    @ResponseBody
    public String list(@RequestParam("name") String name) {
        try {
            List<FoodComp> foodComps = foodCompService.getByName(name);
            return write(200, "查询成功", "list", foodComps);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 查询食物热量详情
     *
     * @param id 查询名称
     * @return 列表
     */
    @ApiOperation("查询食物热量详情")
    @RequestMapping(value = "detail", method = RequestMethod.POST)
    @ResponseBody
    public String list(@RequestParam("id") Long id) {
        try {
            FoodComp foodComp = foodCompService.getById(id);
            return write(200, "查询成功", "list", foodComp);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
}

+ 63 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java

@ -0,0 +1,63 @@
package com.yihu.wlyy.web.common.health;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by Reece on 2017/2/13.
 */
@Controller
@RequestMapping(value = "/common")
@Api(description = "获取福州健康教育文章并保存")
public class HealthEduArticlesController extends BaseController{
    @Autowired
    private HealthEduArticleService healthEduArticleService;
    @RequestMapping(value = "getHealthEduArticles",method = RequestMethod.GET)
    @ResponseBody
    public String getHealthEduArticles(
            @RequestParam(value = "医院名称") String hospitalName,
            @RequestParam(value = "开始时间") String startTime,
            @RequestParam(value = "截至时间") String endTime,
            @RequestParam(value = "文章来源 0 医生自创 1健康之路 2 39健康网") String MessageFrom,
            @RequestParam(value = "获取文章数量默认10",defaultValue = "10") String pageSize,
            @RequestParam(value = "展示页数,从0开始",defaultValue = "0") String pageNumber
    ){
        try {
            Map<String,String> params = new HashMap<>();
            params.put("hospitalName",hospitalName);
            params.put("startTime",startTime);
            params.put("endTime",endTime);
            params.put("MessageFrom",MessageFrom);
            params.put("pageSize",pageSize);
            params.put("pageNumber",pageNumber);
//      timestamp必须与服务器时间相差在5分钟以内,否则调用将失败
            String timestamp = Long.toString(System.currentTimeMillis());
            params.put("timestamp",timestamp);
//          获取福州健康教育文章
            String result = healthEduArticleService.getHealthEduArticles(params);
//          保存福州健康教育文章
            int rows = healthEduArticleService.saveHealthEduArticles(result);
            if(rows>0){
                return write(200, "数据导入成功");
            }
            return write(-1, "数据导入失败!");
        }catch (Exception e){
            return error(-1, "数据导入失败!");
        }
    }
}

+ 49 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java

@ -0,0 +1,49 @@
package com.yihu.wlyy.web.common.hospital;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by lyr-pc on 2016/11/22.
 */
@RestController
@RequestMapping(value = "/hospitals")
@Api(description = "医院管理")
public class HospitalCommonController extends BaseController {
    @Autowired
    HospitalService hospitalService;
    @RequestMapping(value = "/{town}/community_hospitals",method = RequestMethod.GET)
    @ApiOperation(value = "查询城镇下社区")
    public String getTownHospitals(@PathVariable String town) {
        try {
            List<Hospital> hospitals = hospitalService.getHositalByTownCode(town);
            return write(200, "查询成功", "data", hospitals == null ? new ArrayList<Hospital>() : hospitals);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/getHospitalsNot00",method = RequestMethod.GET)
    @ApiOperation(value = "查询健管师所属的社区下的服务站")
    public String getHospitalsNot00() {
        try {
            List<Hospital> hospitals = hospitalService.getHospitalsNot00(getUID());
            return write(200, "查询成功", "data", hospitals == null ? new ArrayList<Hospital>() : hospitals);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 80 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/icd/Icd10Controller.java

@ -0,0 +1,80 @@
package com.yihu.wlyy.web.common.icd;
import com.yihu.wlyy.service.system.Icd10DictServcie;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by chenweida on 2017/8/9.
 */
@RestController
@RequestMapping("/idc10/")
@Api(description = "icd10和健康问题接口管理")
public class Icd10Controller extends BaseController {
    @Autowired
    private Icd10DictServcie icd10DictServcie;
    @ApiOperation("根据icd10字典的code找到name")
    @RequestMapping(value = "/getIdc10NameByCode", method = RequestMethod.GET)
    public String getTopic(
            @ApiParam(required = true, name = "code", value = "icd10字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getIcd10Name(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("根据icd10的code找到健康问题字典")
    @RequestMapping(value = "/getIcd10ByHealthProCode", method = RequestMethod.GET)
    public String getIcd10ByHealthProCode(
            @ApiParam(required = true, name = "code", value = "icd10字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getIcd10ByHealthProblemCode(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("根据健康问题字典的code找到name")
    @RequestMapping(value = "/getHealthProNameByCode", method = RequestMethod.GET)
    public String getHealthProNameByCode(
            @ApiParam(required = true, name = "code", value = "健康问题字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getHealthProblemName(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("根据健康问题字典的code找到icd10字典")
    @RequestMapping(value = "/getHealthProByIcd10Code", method = RequestMethod.GET)
    public String getHealthProByIcd10Code(
            @ApiParam(required = true, name = "code", value = "健康问题字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getHealthProblemsByIcd10Code(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("初始化全部数据到redis")
    @RequestMapping(value = "/init2Redis", method = RequestMethod.POST)
    public String init2Redis() {
        try {
            icd10DictServcie.cacheDict();
            return write(200, "查询成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
}

+ 350 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/im/imController.java

@ -0,0 +1,350 @@
package com.yihu.wlyy.web.common.im;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.util.ImUtill;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping(value = "im_new", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "IM-即时消息")
public class imController extends BaseController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ImUtill ImUtill;
    /**
     * 获取单个咨询
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "/getTopic",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String getTopic(String consult) {
        try {
            return success(ImUtill.getTopic(consult).get("data").toString());
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    /**
     * 获取当前团队的咨询列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamList", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam int adminTeamCode,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = ImUtill.getTeamConsultByStatus(doctor,adminTeamCode, status, reply, page, pagesize);
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }
                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型:1三师咨询,2家庭医生咨询,3图文咨询,4公共咨询,5病友圈
                map.put("type", con.getType());
                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getList", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @ApiParam(name = "type", value = "咨询类型") @RequestParam(required = false) Integer type,
            @ApiParam(name = "patientName", value = "居民姓名") @RequestParam(required = false) String patientName,
            @ApiParam(name = "startTime", value = "开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = null;
            if(type==null){
                consult = ImUtill.getConsultByStatus(doctor, status, reply, page, pagesize);
            }else {
                consult = ImUtill.getConsultByStatusAndType(doctor, status, reply,type,patientName,startTime,endTime, page, pagesize);
            }
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }
                map.put("id", id);
                map.put("status", status);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型:1三师咨询,2家庭医生咨询,3图文咨询,4公共咨询,5病友圈
                map.put("type", con.getType());
                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getListCount", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultCountByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @ApiParam(name = "type", value = "咨询类型") @RequestParam(required = true) Integer type,
            @ApiParam(name = "patientName", value = "居民姓名") @RequestParam(required = false) String patientName,
            @ApiParam(name = "startTime", value = "开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = null;
            consult = ImUtill.getConsultCountByStatusAndType(doctor, status, reply,type,patientName,startTime,endTime);
            JSONObject json = new JSONObject(consult);
            return write(200, "查询成功", "total", json.getInt("count"));
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取团队统计数据
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamData", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamData(@RequestParam int adminTeamCode) {
        try {
            String uid = getUID();
            List<Map<String, Object>> doctors = getMemberByDoctor(uid);
            JSONObject json = new JSONObject();
            List list = new ArrayList();
            int countUnReply = 0;
            int countReply = 0;
            int countConsult = 0;
//        团队下的医生统计数量
            for (Map<String, Object> doc : doctors) {
                Map map = new HashMap();
                String doctor = doc.get("code").toString();
                map.put("photo", doc.get("photo") == null ? "" : doc.get("photo").toString());
                map.put("name", doc.get("name").toString());
                map.put("sex", doc.get("sex").toString());
                map.put("doctor", doctor);
                map.put("type", doc.get("level") == null ? "" : doc.get("level").toString());
//                未回复
                String totalUnReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 0);
                int unReply = Integer.parseInt(totalUnReply);
                map.put("totalUnReply", unReply);
//                已回复
                String totalReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 1);
                String totalReply1 = ImUtill.getConsultData(doctor,adminTeamCode, 10, null);
                int reply = Integer.parseInt(totalReply) + Integer.parseInt(totalReply1);
                map.put("totalReply", reply);
//                总咨询量
                String totalConsult = ImUtill.getConsultData(doctor, adminTeamCode,null, null);
                int consult = Integer.parseInt(totalConsult);
                map.put("totalConsult", consult);
                countUnReply += unReply;
                countReply += reply;
                countConsult += consult;
                list.add(map);
            }
            json.put("totalUnReply", countUnReply);
            json.put("totalReply", countReply);
            json.put("totalConsult", countConsult);
            json.put("doctors", list);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取团队医生下居民的咨询
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/getConsultByPatient", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByPatient(@RequestParam String patient) {
        try {
//            1.调im接口
//            2.判断团队长和当前咨询居民是否存在签约关系
            String doctor = getUID();
            int count = signFamilyDao.findByPatientAndDoctor(patient, doctor);
            boolean flag = (count == 0) ? false : true;
            return write(200, "查询成功", "data", flag);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 提醒医生相关信息
     *
     * @param doctor  提醒的医生
     * @param content 提醒的内容
     * @return
     */
    @RequestMapping(value = "/message/remain", method = RequestMethod.POST)
    @ResponseBody
    public String reaminDoctor(String doctor, String content) {
        try {
            JSONObject participants = new JSONObject();
            participants.put(doctor, 0);
            participants.put(getUID(), 0);
            Doctor d = doctorDao.findByCode(getUID());
            //创建医生会话讨论组
            JSONObject sessionObj = ImUtill.createSession(participants, ImUtill.SESSION_TYPE_P2P, d.getName() + "发来消息提醒", "");
            if (sessionObj.getInt("status") == -1) {
                throw new RuntimeException(sessionObj.getString("message"));
            }
            JSONObject session = sessionObj.getJSONObject("data");
            ImUtill.sendImMsg(getUID(), d.getName(), session.getString("id"), "1", content, "REMAIN");
            return success("提醒成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    public List getMemberByDoctor(String doctor) {
        String sql = "SELECT d.photo,d.`name`,d.sex,d.`code`,d.level " +
                " from wlyy_admin_team t,wlyy_admin_team_member m,wlyy_doctor d " +
                " where t.id = m.team_id and m.doctor_code = d.`code` and t.available = 1 and m.available=1 " +
                " and t.leader_code = ? ";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql, doctor);
        return doctors;
    }
}

+ 35 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java

@ -0,0 +1,35 @@
package com.yihu.wlyy.web.common.messages;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
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.ResponseBody;
@Controller
@RequestMapping(value = "/im/common/message", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-消息")
public class ImMessageController extends BaseController {
    @Autowired
    private MessageService messageService;
    @RequestMapping(value = "messages",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @ApiOperation("查询医生未读消息和最后消息")
    public String messages() {
        try {
            JSONObject json = messageService.findDoctorAllMessage(getUID());
            return write(200, "获取消息总数成功!", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
}

+ 399 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java

@ -0,0 +1,399 @@
package com.yihu.wlyy.web.common.qrcode;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.service.common.QrcodeService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
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.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * Created by lyr on 2016/08/10.
 */
@Controller
@RequestMapping(value = "/qrcode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "二维码")
public class QrCodeController extends WeixinBaseController {
    @Autowired
    private QrcodeService qrcodeService;
    @Autowired
    private DoctorService doctorService;
    @RequestMapping(value = "/doctors",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeDoctorQrcodes(String hospital) {
        try {
            if (qrcodeService.makeDoctorQrCode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成某个医生的二维码
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeDoctorQrcode(String doctor) {
        try {
            if (qrcodeService.makeDoctorQrcode(doctor, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成社区二维码
     *
     * @param hospital
     * @return
     */
    @RequestMapping(value = "/hospital",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeHospitalQrcode(String hospital) {
        try {
            if (qrcodeService.makeHospitalQrcode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成区二维码
     *
     * @param town
     * @return
     */
    @RequestMapping(value = "/town",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeTownQrcode(String town) {
        try {
            if (qrcodeService.makeTownQrcode(town, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 下载某个社区的二维码
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/hospital_img",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadSqQrcode(String hospital, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + hospital + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeHospitalQrcode(hospital, getAccessToken());
            } else {
                flag = true;
            }
            if (flag = true) {
                response.setCharacterEncoding("utf-8");
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + hospital + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
        }
    }
    /**
     * 下载某个区的二维码
     *
     * @param town
     * @param response
     */
    @RequestMapping(value = "/town_img",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadTownQrcode(String town, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + town + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeTownQrcode(town, getAccessToken());
            } else {
                flag = true;
            }
            if (flag = true) {
                response.setCharacterEncoding("utf-8");
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + town + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/download",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadQrcode(String doctor, HttpServletResponse response) {
        try {
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());
                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + doc.getQrcode());
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/doctor_img",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadQrcodeImage(String doctor, HttpServletResponse response) {
        try {
            System.out.println("------------------doctor:" + doctor);
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());
                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + doc.getQrcode());
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载所有医生的二维码图片
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/download/doctors",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadQrcodes(String hospital, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadDoctorQrCodes(hospital, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=doctors_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载某个区的社区的二维码图片
     *
     * @param area
     * @param response
     */
    @RequestMapping(value = "/download/hospitals",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadSqQrcodes(String area, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadHospitalQrCodes(area, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=hospitals_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载某个城市的区的二维码图片 t
     *
     * @param city
     * @param response
     */
    @RequestMapping(value = "/download/towns",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadTownQrcodes(String city, HttpServletResponse response) {
        try {
            File file = qrcodeService.downLoadTownQrcodes(city, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=towns_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
}

+ 115 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java

@ -0,0 +1,115 @@
package com.yihu.wlyy.web.common.sms;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.NetworkUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.List;
@Controller
@RequestMapping(value = "/common")
@Api(description = "短信")
public class SMSController extends BaseController {
	@Autowired
	public SMSService smsService;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private DoctorDao doctorDao;
	/**
	 * 发送短信验证码接口
	 * @param mobile 手机号
	 * @param type 消息类型:1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录 .6患者签约验证 7用户变更手机号验证 8用户新手机号验证 9绑定手机号
	 *             10 家庭成员添加验证
	 * @return
	 */
	@RequestMapping(value = "captcha", method = RequestMethod.POST)
	@ResponseBody
	public String send(String mobile, int type, @RequestParam(required = false) String captchaToken) {
		try {
			if (type > 10 || type < 1) {
				return error(-1, "无效的请求!");
			}
			if (StringUtils.isEmpty(mobile)) {
				return error(-1, "手机号码不允许为空!");
			}
			if (type == 4) {
				// 登录时校验用户是否存在
				List<Patient> patients = patientDao.findByMobile(mobile);
				if (patients == null||patients.size()==0) {
					return error(-1, "该手机号未注册!");
				}
			} else if (type == 5) {
				// 登录时校验用户是否存在
				Doctor doctor = doctorDao.findByMobile(mobile);
				if (doctor == null) {
					return error(-1, "该手机号未注册!");
				}
			}
			if (StringUtils.isNotEmpty(captchaToken)) {
				String ct = request.getSession().getAttribute("captchaToken").toString();
				if (!StringUtils.equalsIgnoreCase(captchaToken, ct)) {
					return error(-1, "图形验证码错误!");
				}
			}
			// 获取ip地址
			String ip = NetworkUtil.getIpAddress(request);
			if (StringUtils.isEmpty(ip)) {
				return error(-1, "无效的ip请求!");
			}
//			String res = smsService.send(mobile, ip, type, getUID());
			String res = smsService.send(mobile, ip, type, getRepUID());
			if (StringUtils.equals(res, "ok")) {
				return write(200, "验证码短信已发送!");
			} else {
				return error(-1, res);
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "短信发送失败!");
		}
	}
	/**
	 * 验证手机验证码
	 * @param type 消息类型:1微信端注册,2微信端找回密码,3医生端找回密码
	 * @param mobile
	 * @param captcha
	 * @return
	 */
	@RequestMapping(value = "check_captcha", method = RequestMethod.POST)
	@ResponseBody
	public String checkCaptcha(int type, String mobile, String captcha) {
		try {
			// 对验证码进行校验
			int res = smsService.check(mobile, type, captcha);
			switch (res) {
			case -2:
				return error(-1, "验证码已过期!");
			case -1:
				return error(-1, "验证码错误!");
			case 0:
				return error(-1, "验证码无效!");
			}
			return success("有效验证码!");
		} catch (Exception e) {
			error(e);
			return error(-1, "验证码检查失败!");
		}
	}
}

+ 61 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java

@ -0,0 +1,61 @@
package com.yihu.wlyy.web.common.system;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.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;
import java.util.List;
/**
 * Created by Administrator on 2016/8/13.
 */
@Controller
@RequestMapping(value = "/common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "系统字典")
public class SystemDictController extends BaseController {
    @Autowired
    private SystemDictService systemDictService;
    @ApiOperation("根據dictname查找字典数据")
    @RequestMapping(value = "/getDictByDictName", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getDictByDictName(
            @ApiParam(name="name",value="字典名",defaultValue = "")@RequestParam(value="name",required = true) String name){
        try {
            List<SystemDict> list=systemDictService.getDictByDictName(name);
            JSONArray ja=new JSONArray();
            for (SystemDict systemDict:list){
                JSONObject jo=new JSONObject();
                jo.put("code",systemDict.getCode());
                jo.put("value",systemDict.getValue());
                ja.put(jo);
            }
            return write(200,"查询成功","list",ja);
        } catch (Exception e) {
            error(e);
            return error(-1, "验证码检查失败!");
        }
    }
//    @RequestMapping(value = "/test",method = RequestMethod.GET)
//    @ApiOperation("测试方法")
//    @ResponseBody
//    public Index index(
//            @ApiParam(name="name",required = false,value = "参数") @RequestParam(required = false,name = "name") String name
//    ) {
//        return new Index();
//    }
}

+ 45 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java

@ -0,0 +1,45 @@
package com.yihu.wlyy.web.common.url;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by lyr-pc on 2017/1/17.
 */
@RestController
@RequestMapping(value = "/common/cud_url")
@Api("增删改路径查询")
public class CudUrlController extends BaseController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 查询增删改路径
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation(value = "查询增删改路径")
    public String getCudUrl() {
        try {
            String sql = "select * from wlyy_cud_url";
            List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
            return write(200,"查询成功","data",result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
}

+ 108 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java

@ -0,0 +1,108 @@
package com.yihu.wlyy.web.common.util;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 患者端验证码生成控制器。验证码生成后保存到Redis中,并将Redis的Key与图片路径返回。
 * 客户端获取图片,并由用户输入后,与redis的key一块返回,用于验证是否出错。
 *
 * @author Sand
 * @created 2016/09/28
 */
@Api(description = "验证码")
@RestController
@RequestMapping(value = "/patient/captcha", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CaptchaController extends BaseController {
    private Map<String, String> captchaCache = new ConcurrentHashMap<>();
    private DefaultKaptcha captchaProducer = new DefaultKaptcha();
    public CaptchaController() {
        Properties properties = new Properties();
        properties.put("kaptcha.textproducer.font.color", "blue");
        properties.put("kaptcha.textproducer.font.size", "45");
        properties.put("kaptcha.textproducer.char.length", "4");
        properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        captchaProducer.setConfig(config);
    }
    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation("生成验证码,用于第一次请求")
    public String createCaptcha(){
        try{
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    @RequestMapping(value = "/{legacy_key}", method = RequestMethod.POST)
    @ApiOperation("刷新验证码,需提供第一次生成验证码返回的key")
    public String refreshCaptcha(@PathVariable("legacy_key") String legacyKey){
        try{
            cleanCaptcha(legacyKey);
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    @RequestMapping(value = "/{key}", method = RequestMethod.GET)
    @ApiOperation("校验证码,提供key及用户输入的验证码")
    public String verifyCaptcha(@PathVariable("key") String key,
                                @RequestParam("text") String text){
        try{
            boolean pass = false;
            String captcha = captchaCache.get(key);
            if (captcha != null && captcha.equals(text.toLowerCase())){
                pass = true;
                cleanCaptcha(key);
            }
            return write(200, "ok", "pass", pass);
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    private String generateCaptcha() throws IOException {
        String captchaText = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        String base64Img = new BASE64Encoder().encode(outputStream.toByteArray());
        String key = "captcha:" + UUID.randomUUID().toString() + ":text";
        Map<String, String> data = new HashMap<>();
        data.put("key", key);
        data.put("image", base64Img);
        data.put("format", "png");
        captchaCache.put(key, captchaText.toLowerCase());
        return write(200, "ok", "data", data);
    }
    private void cleanCaptcha(String key){
        captchaCache.remove(key);
    }
}

+ 353 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java

@ -0,0 +1,353 @@
package com.yihu.wlyy.web.common.util;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.interceptors.DoctorInterceptor;
import com.yihu.wlyy.interceptors.GateWayInterceptor;
import com.yihu.wlyy.interceptors.PatientInterceptor;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.statistics.StatisticsService;
import com.yihu.wlyy.service.common.util.ManageUtilService;
import com.yihu.wlyy.service.common.util.SignTeamAndGroupRunnable;
import com.yihu.wlyy.util.SpringUtil;
import com.yihu.wlyy.util.SystemData;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by lyr on 2016/09/13.
 */
@RestController
@RequestMapping(value = "/manage_util", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "管理工具及后台任务控制")
public class ManagerUtilController extends BaseController {
    @Autowired
    PatientDiseaseService diseaseService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    DoctorWorkTimeService workTimeService;
    @Autowired
    StatisticsService statisticsService;
    @Autowired
    ManageUtilService manageUtilService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    ConsultTeamDoctorDao consultTeamDoctorDao;
    /*********************************************患者疾病相关******************************************/
    /**
     * 更新到redis
     *
     * @return
     */
    @RequestMapping(value = "/disease/to_redis", method = RequestMethod.POST)
    public String updateToRedid() {
        try {
            diseaseService.updateToRedis();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新到疾病表
     *
     * @return
     */
    @RequestMapping(value = "/disease/to_disease", method = RequestMethod.POST)
    public String updateToDisease() {
        try {
            diseaseService.updateToDisease();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 查询患者redis疾病
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/disease/patient", method = RequestMethod.POST)
    public String getDiseaseFromRedis(String patient) {
        try {
            return write(200, "查询成功", "data", redisTemplate.opsForValue().get("disease:" + patient));
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /***********************************************名医咨询相关****************************************/
    /**
     * 名医咨询剩余次数手动更新
     *
     * @return
     */
    @RequestMapping(value = "/famous_doctor/times_update", method = RequestMethod.POST)
    public String famousConsultTimeUpdate() {
        try {
            workTimeService.consultTimesRemain(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /*********************************************统计相关*******************************************/
    /**
     * 更新人口数据到redis
     *
     * @return
     */
    @RequestMapping(value = "/people_num_to_redis", method = RequestMethod.POST)
    public String peopleNumToRedis(String year) {
        try {
            statisticsService.peopleNumToRedis(year);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team", method = RequestMethod.POST)
    public String signSetGroupAndTeam() {
        try {
            manageUtilService.signPatientSetGroup();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team_page", method = RequestMethod.POST)
    public String signSetGroupAndTeamPage(int page) {
        try {
            manageUtilService.setSignTeamAndGroupByPage(page);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team_id", method = RequestMethod.POST)
    public String signSetGroupAndTeamId(Long id) {
        try {
            manageUtilService.setSignTeamAndGroupById(id);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_error_page_id", method = RequestMethod.POST)
    public String getErrorPage(int type) {
        try {
            if (type == 1) {
                return write(200, "查询成功", "data", ManageUtilService.page);
            } else if (type == 2) {
                return write(200, "查询成功", "data", ManageUtilService.errorPages);
            } else {
                return write(200, "查询成功", "data", ManageUtilService.errorSigns);
            }
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_team_group_thread", method = RequestMethod.POST)
    public String getErrorPage(long start, long end) {
        try {
            new Thread(SpringUtil.getBean(SignTeamAndGroupRunnable.class)
                    .setEnd(end).setStart(start)).start();
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 健康教育数据清洗
     *
     * @return
     */
    @RequestMapping(value = "/tranform_edu_article", method = RequestMethod.POST)
    public String tranformEduArticle() {
        try {
            manageUtilService.transformEduArticle();
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 产检提醒
     * 每天早上六点
     *
     * @return
     */
//    @RequestMapping(value = "/start_prenatal_inspector_job")
//    @ResponseBody
//    public String startPrenatalInspectorJob() {
//        try {
//            if (!quartzHelper.isExistJob("prenatal_inspector_job")) {
//                quartzHelper.addJob(PrenatalInspectorJob.class, "0 0 6 * * ?", "prenatal_inspector_job", new HashMap<String, Object>());
//                return write(200, "启动成功");
//            } else {
//                return write(200, "任务已存在");
//            }
//        } catch (Exception e) {
//            return error(-1, "启动失败");
//        }
//    }
    //---------------------------获取在线人数相关 start---------------------------------
    @RequestMapping(value = "/online_num", method = RequestMethod.GET)
    @ApiOperation("获取在线人数")
    public String online_num() {
        try {
            JSONObject jo = new JSONObject();
            jo.put("doctor_online", SystemData.doctorTokens.size());
            jo.put("pc_online", SystemData.doctorPCTokens.size());
            jo.put("patient_online", SystemData.patientTokens.size());
            return write(200, "启动成功","data",jo);
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    //---------------------------获取在线人数相关 end---------------------------------
    //----------------------------权限相关 start---------------------------------
    @RequestMapping(value = "/closeAll", method = RequestMethod.POST)
    @ApiOperation("关闭全部拦截")
    public String closeAll() {
        try {
            String close = "0";
            DoctorInterceptor.status = close;
            PatientInterceptor.status = close;
            GateWayInterceptor.status = close;
            return write(200, "关闭成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/openAll", method = RequestMethod.POST)
    @ApiOperation("开启全部拦截")
    public String openAll() {
        try {
            String open = "1";
            DoctorInterceptor.status = open;
            PatientInterceptor.status = open;
            GateWayInterceptor.status = open;
            return write(200, "开启成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/closeByType", method = RequestMethod.POST)
    @ApiOperation("根据类型关闭拦截")
    public String closeByType(
            @ApiParam(name = "type", value = "1 患者端 2医生端 3对外", required = true) @RequestParam(value = "type", required = true) String type) {
        try {
            String close = "0";
            switch (type) {
                case "1": {
                    DoctorInterceptor.status = close;
                    break;
                }
                case "2": {
                    PatientInterceptor.status = close;
                    break;
                }
                case "3": {
                    GateWayInterceptor.status = close;
                    break;
                }
            }
            return write(200, "关闭成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/openByTYpe", method = RequestMethod.POST)
    @ApiOperation("根据类型开启拦截")
    public String openByTYpe(
            @ApiParam(name = "type", value = "1 患者端 2医生端 3对外", required = true) @RequestParam(value = "type", required = true) String type) {
        try {
            String open = "1";
            switch (type) {
                case "1": {
                    DoctorInterceptor.status = open;
                    break;
                }
                case "2": {
                    PatientInterceptor.status = open;
                    break;
                }
                case "3": {
                    GateWayInterceptor.status = open;
                    break;
                }
            }
            return write(200, "开启成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    //----------------------------权限相关 end---------------------------------
}

+ 326 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java

@ -0,0 +1,326 @@
package com.yihu.wlyy.web.common.util;
import com.yihu.wlyy.service.third.guahao.GuahaoXMService;
import com.yihu.wlyy.service.third.jw.JwSmjkService;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by lyr on 2016/9/29.
 */
@RestController
@RequestMapping(value = "/wlyy_service")
@Api(description = "卫计委签约接口调试")
public class WlyySerivceController extends BaseController{
    @Autowired
    private GuahaoXMService guahaoXM;
    @Autowired
    private JwSmjkService jwSmjkService;
    @Autowired
    private HttpUtil HttpUtil;
    //基卫服务地址
    @Value("${sign.check_upload}")
    private String jwUrl;
    /**
     * 检查是否签约
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/third/sign/CheckSignFamily",method = RequestMethod.POST)
    @ApiOperation("检查是否签约")
    public String checkSignFamily(@RequestParam("idcard") String idcard){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/CheckSignFamily?idcard=" + idcard, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 上传签约数据
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/third/sign/UploadSignFamily",method = RequestMethod.POST)
    @ApiOperation("上传签约数据")
    public String uploadSignFamily(@RequestParam("code")String code){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/UploadSignFamily?code=" + code, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 初次采集签约接口
     *
     * @param start_time
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadAllSignFamily",method = RequestMethod.POST)
    @ApiOperation("初次采集签约接口")
    public String loadAllSignFamily(@RequestParam("start_time")String start_time){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadAllSignFamily?start_time=" + start_time, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 单条采集签约接口
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadSignFamily",method = RequestMethod.POST)
    @ApiOperation("单条采集签约接口")
    public String loadSingleSignFamily(@RequestParam("idcard")String idcard){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadSignFamily?idcard=" + idcard, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 时间范围采集签约接口
     *
     * @param start_time
     * @param end_time
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadSignFamilyBatch",method = RequestMethod.POST)
    @ApiOperation("时间范围采集签约接口")
    public String loadSignFamilyBatch(@RequestParam("start_time")String start_time,@RequestParam("end_time")String end_time){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadSignFamilyBatch?start_time=" + start_time + "&end_time=" + end_time, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 补上传签约接口
     *
     * @return
     */
    @RequestMapping(value = "/third/sign/ReUploadSignFamily",method = RequestMethod.POST)
    public String reuploadSignFamily(){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/ReUploadSignFamily", "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 补更新签约接口
     *
     * @return
     */
    @RequestMapping(value = "/third/sign/ReUpdateSignFamily",method = RequestMethod.POST)
    public String reupdateSignFamily(){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/ReUpdateSignFamily", "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 转诊预约医生特殊号源获取
     * @param OrgCode 医院编号
     * @param DeptCode 科室编号
     * @param DocCode 医生编号
     * @return
     */
    @RequestMapping(value = "/third/smjk/RegDeptSpeDoctorSectionList",method = RequestMethod.POST)
    @ApiOperation("转诊预约获取特殊号源接口")
    public String getSpeDoctorSectionList(@RequestParam("OrgCode") String OrgCode,
                                          @RequestParam("DeptCode") String DeptCode,
                                          @RequestParam("DocCode") String DocCode){
        try{
            List<Map<String,Object>> list = guahaoXM.GetDoctorArrangeTenDay(OrgCode,DeptCode,DocCode);
            return write(200, "获取医生排班成功!", "data", list);
           /* *//*****modify by linz 暂时把号源转换成普通号源****//*
            List<Map<String,Object>> list =  guahaoXM.GetDoctorArrange(OrgCode,DeptCode,DocCode);
            for(Map map :list){
                String date = (String)map.get("date");
                map.put("date",date.replaceAll("-","/"));
            }
            return write(200, "获取医生排班成功!", "data", list);*/
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"医生排班时间获取失败");
        }
    }
    /**
     * 获取转诊预约医生列表
     * @param city
     * @param hospitalId
     * @param hosDeptId
     * @param filter
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/third/smjk/RegDeptSpeDoctorList",method = RequestMethod.POST)
    @ApiOperation("获取转诊预约医生列表")
    @ResponseBody
    public String getRegDeptSpeDoctorList(
            @ApiParam(name = "city", value = "城市编码", defaultValue = "350200")@RequestParam(value = "city", required = true) String city,
            @ApiParam(name="hospitalId",value="医院编码",defaultValue = "350211A1001") @RequestParam(name="hospitalId",required = true) String hospitalId,
            @ApiParam(name="hosDeptId",value="科室编码",defaultValue = "1040610") @RequestParam(name="hosDeptId",required = true) String hosDeptId,
            @ApiParam(name = "filter", value = "过滤条件", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "pageIndex", value = "第几页", defaultValue = "")
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @ApiParam(name = "pageSize", value = "每页记录数", defaultValue = "")
            @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            //10天排班的医生列表
            //String list  = jwSmjkService.getRegDeptSpeDoctorList(orgCode,deptCode);
            //7天排班的医生列表
            String list = jwSmjkService.GetDoctorList(hospitalId,hosDeptId);
            return list;
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1,"获取转诊预约医生列表列表失败");
        }
    }
    /**
     * 转诊预约医生号源转换
     * @param xml
     * @return
     */
    private List<Map<String,Object>>  parseXmlForSpe(String xml) {
            List<Map<String,Object>> re = new ArrayList<>();
            Document document = null;
            try{
                 document = DocumentHelper.parseText(xml);
             }catch (Exception e){
                throw new RuntimeException("解析数据失败!");
            }
            Element root = document.getRootElement();
            List<?> child = root.elements();//取出root的子集合
            for (Object o : child) {
                List<?> dataList = ((Element) o).elements();
                for(Object dataElement:dataList) {
                    Element e = (Element) dataElement;
                    // 日期
                    String date = e.attributeValue("date");
                    // a或者p
                    String time = e.attributeValue("time");
                    // 限号
                    String max = e.attributeValue("max");
                    // 已使用的号
                    String used = e.attributeValue("used");
                    // 1正常、2满号、3已过期
                    String status = e.attributeValue("status");
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", date);
                    map.put("time", time);
                    map.put("max", max);
                    map.put("used", used);
                    map.put("status", status);
                    // 排班信息
                    List<?> sections = e.elements();
                    List<Map<String, String>> arrangeList = new ArrayList<>();
                    for (Object s : sections) {
                        Element section = (Element) s;
                        // 限号
                        String s_max = section.attributeValue("max");
                        // 已使用的号
                        String s_used = section.attributeValue("used");
                        // 一次专家坐诊时间段的开始时间
                        String start_time = section.attributeValue("start_time");
                        // 结束时间
                        String end_time = section.attributeValue("end_time");
                        Map<String, String> item = new HashMap<>();
                        item.put("max", s_max);
                        item.put("used", s_used);
                        item.put("startTime", start_time);
                        item.put("endTime", end_time);
                        arrangeList.add(item);
                    }
                    map.put("sections", arrangeList);
                    re.add(map);
                }
            }
            return  re;
        }
}

+ 61 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java

@ -0,0 +1,61 @@
package com.yihu.wlyy.web.common.verified;
import com.yihu.wlyy.service.third.verified.VerifiedService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
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.*;
@Controller
@RequestMapping(value = "/verified", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "实名认证")
public class VerifiedController extends BaseController {
	@Autowired
	private VerifiedService verifiedService;
	/**
	 * 人脸识别
	 */
	@RequestMapping(value = "face", method = RequestMethod.POST)
	@ResponseBody
	public String face(
			@ApiParam(name="idcard",value="身份证号码",defaultValue = "350628198802200051")
			@RequestParam(value="idcard",required = true) String idcard,
			@ApiParam(name="username",value="姓名",defaultValue = "黄展鹏")
			@RequestParam(value="username",required = true) String username,
			@ApiParam(name="picData",value="图片Base64转化后的输入流",defaultValue = "")
			@RequestBody String picData) throws Exception {
		try {
			/*// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
			String imgFile = "D:/1.jpg";// 待处理的图片
			InputStream in = null;
			byte[] data = null;
			// 读取图片字节数组
			try {
				in = new FileInputStream(imgFile);
				data = new byte[in.available()];
				in.read(data);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			picData = encoder.encode(data);*/
			verifiedService.faceVerified(idcard,username,picData);
			return write(200, "人脸识别成功!");
		} catch (Exception e) {
			return error(-1, e.getMessage());
		}
	}
}

+ 65 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.web.common.version;
import com.yihu.wlyy.entity.Versions;
import com.yihu.wlyy.service.app.version.VersionsService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.json.JSONObject;
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.ResponseBody;
/**
 * 版本号控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/version", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "版本")
public class VersionController extends BaseController {
	@Autowired
	private VersionsService versionsService;
	/**
	 * 校验APP版本号
	 * @param code 版本类型编码
	 * @param version 当前版本号
	 * @return
	 */
	@RequestMapping(value = "app",method = RequestMethod.POST)
	@ResponseBody
	public String appVersion(String code, double version) {
		try {
			Versions temp = versionsService.findVersionByCode(code);
			if (temp == null) {
				return error(-1, "无效的APP类型失败!");
			}
			if (version > 0) {
				if (temp.getVersionInt() > version) {
					// 有新的版本号
					return write(200, "发现新版本!", "url", temp.getUrl());
				} else {
					// 已是最新版本
					return write(200, "已是最新版本!");
				}
			} else {
				JSONObject json = new JSONObject();
				json.put("version_int", temp.getVersionInt());
				json.put("version_str", temp.getVersionStr());
				json.put("url", temp.getUrl());
				json.put("info", temp.getInfo());
				json.put("size", temp.getSize());
				return write(200, "读取版本号成功!", "data", json);
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "版本号校验失败!");
		}
	}
}

+ 1 - 1
patient-co/patient-co-doctor-assistant/src/main/resources/wechat/weixin_menu_jimei.txt

@ -61,7 +61,7 @@
	  "sub_button":[
		{
		   "type":"view",
		   "name":"签约特色服务",
		   "name":"集美家签特色",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fdist%2fhtml%2fexclusive-service.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
		{

+ 90 - 90
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/activemq/StartListener.java

@ -1,90 +1,90 @@
package com.yihu.wlyy.activemq;
import com.yihu.wlyy.util.SpringUtil;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.jms.MessageListener;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by chenweida on 2017/9/9.
 */
@Component
public class StartListener {
    private static Map<String, DefaultMessageListenerContainer> holder = new HashMap<String, DefaultMessageListenerContainer>();
    private Logger logger = LoggerFactory.getLogger(StartListener.class);
    @Value("${activemq.queue.healtHarticleQueue}")
    private String healtHarticleQueue;
    @Value("${activemq.consumers.count}")
    private Integer count;
    @Autowired
    private HealthArtListener healthArtListener;
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;
    @PostConstruct
    public void startListener() {
        startHealthArticQueueListener();
    }
    /**
     * 启动健康教育消费
     */
    private void startHealthArticQueueListener() {
        try {
            //启动监听
            startReceiverByQueueName(healthArtListener, healtHarticleQueue);
            logger.info("start HealthArtListener success");
        } catch (Exception e) {
            logger.error("start HealthArtListener error");
        }
    }
    /**
     * 启动
     *
     * @param receiver
     * @param queueName
     */
    private void startReceiverByQueueName(MessageListener receiver, String queueName) {
        if (holder.get(queueName) != null) {
            return;
        }
        ActiveMQQueue destination = new ActiveMQQueue(queueName);
        DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
        // 监听容器属性的配置
        listenerContainer.setConnectionFactory(cachingConnectionFactory);
        // 设置目的地
        listenerContainer.setDestination(destination);
        // 设置监听器
        listenerContainer.setMessageListener(receiver);
        // 设置消费者集群数
        int consumers = count;
        listenerContainer.setConcurrentConsumers(2);
        listenerContainer.setMaxConcurrentConsumers(consumers);
        // 设置监听队列还是主题 默认是队列
        listenerContainer.setPubSubNoLocal(false);
        // listenerContainer.setAcceptMessagesWhileStopping(true);
        // 设置应答模式 默认是4
        listenerContainer.setSessionAcknowledgeMode(ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
        // 设置是否启动事物 默认不开启
        listenerContainer.setSessionTransacted(false);
        // 将监听容器保存在holder中
        holder.put(queueName, listenerContainer);
        listenerContainer.initialize();
        // 启动监听
        listenerContainer.start();
    }
}
//package com.yihu.wlyy.activemq;
//
//import com.yihu.wlyy.util.SpringUtil;
//import org.apache.activemq.ActiveMQSession;
//import org.apache.activemq.command.ActiveMQQueue;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.jms.connection.CachingConnectionFactory;
//import org.springframework.jms.listener.DefaultMessageListenerContainer;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import javax.jms.MessageListener;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by chenweida on 2017/9/9.
// */
//@Component
//public class StartListener {
//    private static Map<String, DefaultMessageListenerContainer> holder = new HashMap<String, DefaultMessageListenerContainer>();
//    private Logger logger = LoggerFactory.getLogger(StartListener.class);
//
//    @Value("${activemq.queue.healtHarticleQueue}")
//    private String healtHarticleQueue;
//    @Value("${activemq.consumers.count}")
//    private Integer count;
//    @Autowired
//    private HealthArtListener healthArtListener;
//    @Autowired
//    private CachingConnectionFactory cachingConnectionFactory;
//
//    @PostConstruct
//    public void startListener() {
//        startHealthArticQueueListener();
//    }
//
//    /**
//     * 启动健康教育消费
//     */
//    private void startHealthArticQueueListener() {
//        try {
//            //启动监听
//            startReceiverByQueueName(healthArtListener, healtHarticleQueue);
//            logger.info("start HealthArtListener success");
//        } catch (Exception e) {
//            logger.error("start HealthArtListener error");
//        }
//    }
//
//    /**
//     * 启动
//     *
//     * @param receiver
//     * @param queueName
//     */
//    private void startReceiverByQueueName(MessageListener receiver, String queueName) {
//        if (holder.get(queueName) != null) {
//            return;
//        }
//        ActiveMQQueue destination = new ActiveMQQueue(queueName);
//
//        DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer();
//        // 监听容器属性的配置
//        listenerContainer.setConnectionFactory(cachingConnectionFactory);
//        // 设置目的地
//        listenerContainer.setDestination(destination);
//        // 设置监听器
//        listenerContainer.setMessageListener(receiver);
//        // 设置消费者集群数
//        int consumers = count;
//        listenerContainer.setConcurrentConsumers(2);
//        listenerContainer.setMaxConcurrentConsumers(consumers);
//        // 设置监听队列还是主题 默认是队列
//        listenerContainer.setPubSubNoLocal(false);
//        // listenerContainer.setAcceptMessagesWhileStopping(true);
//        // 设置应答模式 默认是4
//        listenerContainer.setSessionAcknowledgeMode(ActiveMQSession.INDIVIDUAL_ACKNOWLEDGE);
//        // 设置是否启动事物 默认不开启
//        listenerContainer.setSessionTransacted(false);
//        // 将监听容器保存在holder中
//        holder.put(queueName, listenerContainer);
//        listenerContainer.initialize();
//        // 启动监听
//        listenerContainer.start();
//    }
//}

+ 70 - 70
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java

@ -1,70 +1,70 @@
package com.yihu.wlyy.config;
import com.yihu.wlyy.activemq.HealthArtListener;
import com.yihu.wlyy.util.SpringUtil;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import javax.annotation.PostConstruct;
import javax.jms.MessageListener;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by chenweida on 2017/9/9.
 * 生产者配置
 */
@EnableJms
@Configuration
public class ActiveMQConfig {
   @Value("${activemq.username}")
    private String username;
    @Value("${activemq.password}")
    private String password;
    @Value("${activemq.url}")
    private String url;
    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
        //设置异步发送
        activeMQConnectionFactory.setUseAsyncSend(true);
        return activeMQConnectionFactory;
    }
    /**
     * 缓存session链接
     *
     * @return
     */
    @Bean
    @Primary
    public CachingConnectionFactory CachingConnectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
        //Session缓存数量,这里属性也可以直接在这里配置
        cachingConnectionFactory.setSessionCacheSize(100);
        return cachingConnectionFactory;
    }
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory(CachingConnectionFactory());
        return jmsTemplate;
    }
}
//package com.yihu.wlyy.config;
//
//import com.yihu.wlyy.activemq.HealthArtListener;
//import com.yihu.wlyy.util.SpringUtil;
//import org.apache.activemq.ActiveMQConnectionFactory;
//import org.apache.activemq.ActiveMQSession;
//import org.apache.activemq.command.ActiveMQQueue;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Primary;
//import org.springframework.jms.annotation.EnableJms;
//import org.springframework.jms.connection.CachingConnectionFactory;
//import org.springframework.jms.core.JmsTemplate;
//import org.springframework.jms.listener.DefaultMessageListenerContainer;
//
//import javax.annotation.PostConstruct;
//import javax.jms.MessageListener;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by chenweida on 2017/9/9.
// * 生产者配置
// */
//@EnableJms
//@Configuration
//public class ActiveMQConfig {
//   @Value("${activemq.username}")
//    private String username;
//    @Value("${activemq.password}")
//    private String password;
//    @Value("${activemq.url}")
//    private String url;
//
//    @Bean
//    public ActiveMQConnectionFactory activeMQConnectionFactory() {
//        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
//        //设置异步发送
//        activeMQConnectionFactory.setUseAsyncSend(true);
//        return activeMQConnectionFactory;
//    }
//
//    /**
//     * 缓存session链接
//     *
//     * @return
//     */
//    @Bean
//    @Primary
//    public CachingConnectionFactory CachingConnectionFactory() {
//        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
//        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
//        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
//        //Session缓存数量,这里属性也可以直接在这里配置
//        cachingConnectionFactory.setSessionCacheSize(100);
//        return cachingConnectionFactory;
//    }
//
//    @Bean
//    public JmsTemplate jmsTemplate() {
//        JmsTemplate jmsTemplate = new JmsTemplate();
//        jmsTemplate.setConnectionFactory(CachingConnectionFactory());
//
//        return jmsTemplate;
//    }
//
//}

+ 93 - 93
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java

@ -1,93 +1,93 @@
package com.yihu.wlyy.config.es;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
/**
 * Created by chenweida on 2017/6/5.
 */
@Component
public class ElasticFactory {
    private static JestClientFactory factory = null;
    @Value("${es.host}")
    private String esHost;
    @Value("${es.port}")
    private String port;
    @Value("${es.tPort}")
    private String tPort;
    @Value("${es.clusterName}")
    private String clusterName;
//-----------------------------------jestClient----------------------------------------
    /**
     * @param "http://localhost:9200"
     * @return
     */
    @PostConstruct
    public JestClient getJestClient() {
        synchronized (ElasticFactory.class) {
            if (factory == null) {
                //初始化链接
                init();
            }
        }
        return factory.getObject();
    }
    /**
     * 初始化链接
     */
    public synchronized void init() {
        // Construct a new Jest client according to configuration via factory
        factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://" + esHost + ":" + port)
                .multiThreaded(true)
                .maxTotalConnection(50)// 最大链接
                .maxConnectionIdleTime(120, TimeUnit.SECONDS)//链接等待时间
                .connTimeout(30000)
                .discoveryEnabled(true)
                .readTimeout(30000)//30秒
                .build());//得到链接
    }
    //-----------------------------------TransportClient----------------------------------------
    private Client transportClient;
    public Client getTransportClient() {
        try {
            initTranClient();
            return transportClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private synchronized void initTranClient() throws UnknownHostException {
        if (transportClient == null) {
            Settings settings = Settings.settingsBuilder()
                    .put("client.transport.sniff", true)//开启嗅探功能
                    .put("cluster.name", StringUtils.isEmpty(clusterName) ? "jkzl" : clusterName)//默认集群名字是jkzl
                    .build();
            transportClient = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHost), Integer.valueOf(tPort)));
        }
    }
}
//package com.yihu.wlyy.config.es;
//
//import io.searchbox.client.JestClient;
//import io.searchbox.client.JestClientFactory;
//import io.searchbox.client.config.HttpClientConfig;
//import org.elasticsearch.client.Client;
//import org.elasticsearch.client.transport.TransportClient;
//import org.elasticsearch.common.settings.Settings;
//import org.elasticsearch.common.transport.InetSocketTransportAddress;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//
//import javax.annotation.PostConstruct;
//import java.net.InetAddress;
//import java.net.UnknownHostException;
//import java.util.concurrent.TimeUnit;
//
///**
// * Created by chenweida on 2017/6/5.
// */
//@Component
//public class ElasticFactory {
//    private static JestClientFactory factory = null;
//
//    @Value("${es.host}")
//    private String esHost;
//    @Value("${es.port}")
//    private String port;
//    @Value("${es.tPort}")
//    private String tPort;
//    @Value("${es.clusterName}")
//    private String clusterName;
////-----------------------------------jestClient----------------------------------------
//
//    /**
//     * @param "http://localhost:9200"
//     * @return
//     */
//    @PostConstruct
//    public JestClient getJestClient() {
//        synchronized (ElasticFactory.class) {
//            if (factory == null) {
//                //初始化链接
//                init();
//            }
//        }
//        return factory.getObject();
//    }
//
//    /**
//     * 初始化链接
//     */
//    public synchronized void init() {
//
//        // Construct a new Jest client according to configuration via factory
//        factory = new JestClientFactory();
//        factory.setHttpClientConfig(new HttpClientConfig
//                .Builder("http://" + esHost + ":" + port)
//                .multiThreaded(true)
//                .maxTotalConnection(50)// 最大链接
//                .maxConnectionIdleTime(120, TimeUnit.SECONDS)//链接等待时间
//                .connTimeout(30000)
//                .discoveryEnabled(true)
//                .readTimeout(30000)//30秒
//                .build());//得到链接
//    }
//
//    //-----------------------------------TransportClient----------------------------------------
//    private Client transportClient;
//
//    public Client getTransportClient() {
//        try {
//            initTranClient();
//            return transportClient;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    private synchronized void initTranClient() throws UnknownHostException {
//        if (transportClient == null) {
//            Settings settings = Settings.settingsBuilder()
//                    .put("client.transport.sniff", true)//开启嗅探功能
//                    .put("cluster.name", StringUtils.isEmpty(clusterName) ? "jkzl" : clusterName)//默认集群名字是jkzl
//                    .build();
//
//            transportClient = TransportClient.builder().settings(settings).build()
//                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHost), Integer.valueOf(tPort)));
//        }
//    }
//}

+ 49 - 49
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java

@ -1,49 +1,49 @@
package com.yihu.wlyy.config.es;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElastricSearchSave {
    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
    @Autowired
    private ElasticFactory elasticFactory;
    public Boolean save(List  sms,String esIndex,String esType) {
        try {
            //得到链接
            JestClient jestClient = elasticFactory.getJestClient();
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (Object obj : sms) {
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
            }
            BulkResult br = jestClient.execute(bulk.build());
            logger.info("save data count:" + sms.size());
            logger.info("save flag:" + br.isSucceeded());
            return br.isSucceeded();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" save error :" + e.getMessage());
        }
        return null;
    }
}
//package com.yihu.wlyy.config.es;
//
//import io.searchbox.client.JestClient;
//import io.searchbox.core.Bulk;
//import io.searchbox.core.BulkResult;
//import io.searchbox.core.Index;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Scope;
//import org.springframework.stereotype.Component;
//
//import java.util.List;
//
//;
//
///**
// * Created by chenweida on 2017/6/2.
// */
//@Component
//@Scope("prototype")
//public class ElastricSearchSave {
//
//    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
//    @Autowired
//    private ElasticFactory elasticFactory;
//
//    public Boolean save(List  sms,String esIndex,String esType) {
//        try {
//            //得到链接
//            JestClient jestClient = elasticFactory.getJestClient();
//
//            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
//            for (Object obj : sms) {
//                Index index = new Index.Builder(obj).build();
//                bulk.addAction(index);
//            }
//            BulkResult br = jestClient.execute(bulk.build());
//            logger.info("save data count:" + sms.size());
//            logger.info("save flag:" + br.isSucceeded());
//            return br.isSucceeded();
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(" save error :" + e.getMessage());
//        }
//        return null;
//    }
//
//}

+ 1 - 1
patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java

@ -149,7 +149,7 @@ public class PatientService extends TokenService {
        }
        //如果之前患者的openId为空并且openID有值更新时间 如果opentime是空也设置时间
        if ((!org.springframework.util.StringUtils.isEmpty(openid) && org.springframework.util.StringUtils.isEmpty(patient.getOpenid())) ||
            patient.getOpenidTime() == null) {
                patient.getOpenidTime() == null) {
            patient.setOpenidTime(new Date());
        }
        //System.out.println("========openid=======");

+ 59 - 59
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java

@ -1,59 +1,59 @@
package com.yihu.wlyy.config;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
/**
 * Created by chenweida on 2017/9/9.
 * 生产者配置
 */
@EnableJms
@Configuration
@Profile({"dev", "devtest", "prod", "test"})
public class ActiveMQConfig {
    @Value("${activemq.username}")
    private String username;
    @Value("${activemq.password}")
    private String password;
    @Value("${activemq.url}")
    private String url;
    @Bean
    public ActiveMQConnectionFactory activeMQConnectionFactory() {
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
        //设置异步发送
        activeMQConnectionFactory.setUseAsyncSend(true);
        return activeMQConnectionFactory;
    }
    /**
     * 缓存session链接
     *
     * @return
     */
    @Bean
    @Primary
    public CachingConnectionFactory CachingConnectionFactory() {
        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
        //Session缓存数量,这里属性也可以直接在这里配置
        cachingConnectionFactory.setSessionCacheSize(100);
        return cachingConnectionFactory;
    }
    @Bean
    public JmsTemplate jmsTemplate() {
        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setConnectionFactory( CachingConnectionFactory());
        return jmsTemplate;
    }
}
//package com.yihu.wlyy.config;
//
//import org.apache.activemq.ActiveMQConnectionFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Primary;
//import org.springframework.context.annotation.Profile;
//import org.springframework.jms.annotation.EnableJms;
//import org.springframework.jms.connection.CachingConnectionFactory;
//import org.springframework.jms.core.JmsTemplate;
//
///**
// * Created by chenweida on 2017/9/9.
// * 生产者配置
// */
//@EnableJms
//@Configuration
//@Profile({"dev", "devtest", "prod", "test"})
//public class ActiveMQConfig {
//    @Value("${activemq.username}")
//    private String username;
//    @Value("${activemq.password}")
//    private String password;
//    @Value("${activemq.url}")
//    private String url;
//
//    @Bean
//    public ActiveMQConnectionFactory activeMQConnectionFactory() {
//        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, url);
//        //设置异步发送
//        activeMQConnectionFactory.setUseAsyncSend(true);
//        return activeMQConnectionFactory;
//    }
//
//    /**
//     * 缓存session链接
//     *
//     * @return
//     */
//    @Bean
//    @Primary
//    public CachingConnectionFactory CachingConnectionFactory() {
//        CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
//        //目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory
//        cachingConnectionFactory.setTargetConnectionFactory(activeMQConnectionFactory());
//        //Session缓存数量,这里属性也可以直接在这里配置
//        cachingConnectionFactory.setSessionCacheSize(100);
//        return cachingConnectionFactory;
//    }
//
//    @Bean
//    public JmsTemplate jmsTemplate() {
//        JmsTemplate jmsTemplate = new JmsTemplate();
//        jmsTemplate.setConnectionFactory( CachingConnectionFactory());
//
//        return jmsTemplate;
//    }
//}

+ 93 - 93
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java

@ -1,93 +1,93 @@
package com.yihu.wlyy.config.es;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
/**
 * Created by chenweida on 2017/6/5.
 */
@Component
public class ElasticFactory {
    private static JestClientFactory factory = null;
    @Value("${es.host}")
    private String esHost;
    @Value("${es.port}")
    private String port;
    @Value("${es.tPort}")
    private String tPort;
    @Value("${es.clusterName}")
    private String clusterName;
//-----------------------------------jestClient----------------------------------------
    /**
     * @param "http://localhost:9200"
     * @return
     */
    @PostConstruct
    public JestClient getJestClient() {
        synchronized (ElasticFactory.class) {
            if (factory == null) {
                //初始化链接
                init();
            }
        }
        return factory.getObject();
    }
    /**
     * 初始化链接
     */
    public synchronized void init() {
        // Construct a new Jest client according to configuration via factory
        factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://" + esHost + ":" + port)
                .multiThreaded(true)
                .maxTotalConnection(50)// 最大链接
                .maxConnectionIdleTime(120, TimeUnit.SECONDS)//链接等待时间
                .connTimeout(30000)
                .discoveryEnabled(true)
                .readTimeout(30000)//30秒
                .build());//得到链接
    }
    //-----------------------------------TransportClient----------------------------------------
    private Client transportClient;
    public Client getTransportClient() {
        try {
            initTranClient();
            return transportClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private synchronized void initTranClient() throws UnknownHostException {
        if (transportClient == null) {
            Settings settings = Settings.settingsBuilder()
                    .put("client.transport.sniff", true)//开启嗅探功能
                    .put("cluster.name", StringUtils.isEmpty(clusterName) ? "jkzl" : clusterName)//默认集群名字是jkzl
                    .build();
            transportClient = TransportClient.builder().settings(settings).build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHost), Integer.valueOf(tPort)));
        }
    }
}
//package com.yihu.wlyy.config.es;
//
//import io.searchbox.client.JestClient;
//import io.searchbox.client.JestClientFactory;
//import io.searchbox.client.config.HttpClientConfig;
//import org.elasticsearch.client.Client;
//import org.elasticsearch.client.transport.TransportClient;
//import org.elasticsearch.common.settings.Settings;
//import org.elasticsearch.common.transport.InetSocketTransportAddress;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//
//import javax.annotation.PostConstruct;
//import java.net.InetAddress;
//import java.net.UnknownHostException;
//import java.util.concurrent.TimeUnit;
//
///**
// * Created by chenweida on 2017/6/5.
// */
//@Component
//public class ElasticFactory {
//    private static JestClientFactory factory = null;
//
//    @Value("${es.host}")
//    private String esHost;
//    @Value("${es.port}")
//    private String port;
//    @Value("${es.tPort}")
//    private String tPort;
//    @Value("${es.clusterName}")
//    private String clusterName;
////-----------------------------------jestClient----------------------------------------
//
//    /**
//     * @param "http://localhost:9200"
//     * @return
//     */
//    @PostConstruct
//    public JestClient getJestClient() {
//        synchronized (ElasticFactory.class) {
//            if (factory == null) {
//                //初始化链接
//                init();
//            }
//        }
//        return factory.getObject();
//    }
//
//    /**
//     * 初始化链接
//     */
//    public synchronized void init() {
//
//        // Construct a new Jest client according to configuration via factory
//        factory = new JestClientFactory();
//        factory.setHttpClientConfig(new HttpClientConfig
//                .Builder("http://" + esHost + ":" + port)
//                .multiThreaded(true)
//                .maxTotalConnection(50)// 最大链接
//                .maxConnectionIdleTime(120, TimeUnit.SECONDS)//链接等待时间
//                .connTimeout(30000)
//                .discoveryEnabled(true)
//                .readTimeout(30000)//30秒
//                .build());//得到链接
//    }
//
//    //-----------------------------------TransportClient----------------------------------------
//    private Client transportClient;
//
//    public Client getTransportClient() {
//        try {
//            initTranClient();
//            return transportClient;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    private synchronized void initTranClient() throws UnknownHostException {
//        if (transportClient == null) {
//            Settings settings = Settings.settingsBuilder()
//                    .put("client.transport.sniff", true)//开启嗅探功能
//                    .put("cluster.name", StringUtils.isEmpty(clusterName) ? "jkzl" : clusterName)//默认集群名字是jkzl
//                    .build();
//
//            transportClient = TransportClient.builder().settings(settings).build()
//                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(esHost), Integer.valueOf(tPort)));
//        }
//    }
//}

+ 49 - 49
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java

@ -1,49 +1,49 @@
package com.yihu.wlyy.config.es;
import io.searchbox.client.JestClient;
import io.searchbox.core.Bulk;
import io.searchbox.core.BulkResult;
import io.searchbox.core.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.List;
;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElastricSearchSave {
    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
    @Autowired
    private ElasticFactory elasticFactory;
    public Boolean save(List  sms,String esIndex,String esType) {
        try {
            //得到链接
            JestClient jestClient = elasticFactory.getJestClient();
            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
            for (Object obj : sms) {
                Index index = new Index.Builder(obj).build();
                bulk.addAction(index);
            }
            BulkResult br = jestClient.execute(bulk.build());
            logger.info("save data count:" + sms.size());
            logger.info("save flag:" + br.isSucceeded());
            return br.isSucceeded();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" save error :" + e.getMessage());
        }
        return null;
    }
}
//package com.yihu.wlyy.config.es;
//
//import io.searchbox.client.JestClient;
//import io.searchbox.core.Bulk;
//import io.searchbox.core.BulkResult;
//import io.searchbox.core.Index;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Scope;
//import org.springframework.stereotype.Component;
//
//import java.util.List;
//
//;
//
///**
// * Created by chenweida on 2017/6/2.
// */
//@Component
//@Scope("prototype")
//public class ElastricSearchSave {
//
//    private Logger logger = LoggerFactory.getLogger(ElastricSearchSave.class);
//    @Autowired
//    private ElasticFactory elasticFactory;
//
//    public Boolean save(List  sms,String esIndex,String esType) {
//        try {
//            //得到链接
//            JestClient jestClient = elasticFactory.getJestClient();
//
//            Bulk.Builder bulk = new Bulk.Builder().defaultIndex(esIndex).defaultType(esType);
//            for (Object obj : sms) {
//                Index index = new Index.Builder(obj).build();
//                bulk.addAction(index);
//            }
//            BulkResult br = jestClient.execute(bulk.build());
//            logger.info("save data count:" + sms.size());
//            logger.info("save flag:" + br.isSucceeded());
//            return br.isSucceeded();
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(" save error :" + e.getMessage());
//        }
//        return null;
//    }
//
//}

+ 8 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java

@ -98,6 +98,12 @@ public interface DevicePatientHealthIndexDao
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from device.wlyy_patient_health_index a where a.user = ?1 and a.record_date >= ?2 and a.record_date <= ?3 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?4 ,?5",nativeQuery = true)
	List<String> findDateList(String patient,Date start ,Date end,int currentSize,int pageSize);
	@Query(value= " select * from device.wlyy_patient_health_index where type in (?1) and record_date BETWEEN ?2 AND ?3  AND user in (select p.code from wlyy_patient p INNER JOIN wlyy_sign_family s on s.patient = p.code and s.status > 0 AND s.admin_team_code = ?4 and p.disease >0)",nativeQuery = true)
	List<DevicePatientHealthIndex> findByTeamcodeAndRecordDate(String type ,Date start, Date end,String teamcode);
	@Query(value= " select * from device.wlyy_patient_health_index where type in (?1) and record_date BETWEEN ?2 AND ?3  AND user in (select p.code from wlyy.wlyy_patient p INNER JOIN wlyy.wlyy_sign_family s on s.patient = p.code and s.status > 0 AND s.admin_team_code = ?4 and p.disease >0 and (s.doctor = ?5 or s.doctor_health =?5))",nativeQuery = true)
	List<DevicePatientHealthIndex> findByTeamcodeAndRecordDate(String type ,Date start, Date end,String teamcode,String doctorcode);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type =?2  order by recordDate desc ")
	List<DevicePatientHealthIndex> findByPatientAndTypeByPage(String patientCode, int type, Pageable pageable);
	@Query("select count(a) from DevicePatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1'")
	int getCountByTimeAndStatus(Date start, Date end,int status);
}

+ 2 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientDao.java

@ -65,6 +65,6 @@ public interface PatientDao extends PagingAndSortingRepository<Patient, Long> {
    @Query("select distinct p.openid from Patient p where p.openid is not null and p.openid <> '' ")
    List<String> findOpenids();
    @Query(value=" select p.* from wlyy_patient p INNER JOIN wlyy_sign_family s on s.patient = p.code WHERE s.status > 0  and p.disease >0 and p.status>0 and s.admin_team_code = ?1",nativeQuery = true)
    List<Patient> findAllSignPatientTeamcode(String teamcode);
    @Query(value=" select p.* from wlyy_patient p LEFT JOIN wlyy_sign_family s on s.patient = p.code WHERE s.status > 0  and p.disease >0 and p.status>0 and s.admin_team_code = ?1 and (s.doctor = ?2 or s.doctor_health =?2)",nativeQuery = true)
    List<Patient> findAllSignPatientTeamcode(String teamcode, String  doctorcode);
}

+ 74 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java

@ -29,6 +29,7 @@ import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
@ -118,7 +119,7 @@ public class PatientHealthIndexService extends BaseService {
            }
        }
        else{
           throw new Exception("Result not exit!");
            throw new Exception("Result not exit!");
        }
    }
@ -599,10 +600,15 @@ public class PatientHealthIndexService extends BaseService {
            if (index % 2 == 0) {
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                    //体征异常,更新体征数据状态
                    data.setStatus(1);
                    patientHealthIndexDao.save(data);
                }
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueAfter, minValueAfter)) {
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                    data.setStatus(1);
                    patientHealthIndexDao.save(data);
                }
            }
        }
@ -633,6 +639,8 @@ public class PatientHealthIndexService extends BaseService {
            // 收缩压/舒张压校验
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY) || !checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                msgContent = patient.getName() + "血压异常(舒张压 " + value2 + "mmHg、收缩压 " + value1 + "mmHg)";
                data.setStatus(1);
                patientHealthIndexDao.save(data);
            }
        }
@ -783,6 +791,69 @@ public class PatientHealthIndexService extends BaseService {
        return obj;
    }
    /**
     * 判断居民的体征预警状态
     * @param obj
     */
    public void handlePatientStandarStatus(DevicePatientHealthIndex obj){
        //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----START
        String patientCode = obj.getUser();
        //患者信息
        Patient patient = patientDao.findByCode(patientCode);
        int bloodPressureBbnormalCount = 0;//血压异常次数
        int bloodSuggurBbnormalCount = 0;//血糖异常次数
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "recordDate");
        // 分页信息
        Pageable pageRequest = new PageRequest(0, 5, sort);
        Pageable pageable = new PageRequest(1, 5);
        List<DevicePatientHealthIndex> bloodPressurepatientHealthIndices = new ArrayList<>();
        List<DevicePatientHealthIndex> bloodSuggurpatientHealthIndices = new ArrayList<>();
        if( 1 == patient.getDisease()){
            bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,2,pageable);
        } else if( 2 == patient.getDisease()){
            bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,1,pageable);
        } else {
            bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,2,pageable);
            bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,1,pageable);
        }
        for (DevicePatientHealthIndex patientHealthIndex : bloodPressurepatientHealthIndices) {
            if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                bloodPressureBbnormalCount++;
            }
        }
        for (DevicePatientHealthIndex patientHealthIndex : bloodSuggurpatientHealthIndices) {
            if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                bloodSuggurBbnormalCount++;
            }
        }
        //连续3次异常,修改用户为预警状态
        if( (bloodPressureBbnormalCount >=3 || bloodSuggurBbnormalCount >=3) && 0 == patient.getStandardStatus()){
            patient.setStandardStatus(1);
        }else{
            Date end = new Date();
            Date start = DateUtil.setDateTime(end,-7);
            //计算血糖或者血压一周内的异常记录数量
            int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start,end,1);
            if(errorCount >= 5){//超过5次,记为预警状态
                patient.setStandardStatus(1);
            }
        }
        //连续5次正常,修改用户为非预警状态
        if((0 == bloodPressureBbnormalCount && 0 == bloodSuggurBbnormalCount) && 1 == patient.getStandardStatus()){
            patient.setStandardStatus(0);
        }
        patientDao.save(patient);
        //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----END
    }
    /**
     * 按录入时间和患者标识查询健康记录
@ -871,7 +942,7 @@ public class PatientHealthIndexService extends BaseService {
        }
        sql = sql +conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by sort_date desc ,record_date desc limit "+0+" ,"+1000+" ";
                " order by record_date desc ,sort_date desc limit "+0+" ,"+1000+" ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:list){
            JSONObject json = new JSONObject();
@ -972,7 +1043,7 @@ public class PatientHealthIndexService extends BaseService {
                    " and record_date <= '"+end+"' " +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by sort_date desc ,record_date desc limit "+pageRequest.getOffset()+" ,"+pageRequest.getPageSize()+" ";
                    " order by record_date desc ,sort_date desc limit "+pageRequest.getOffset()+" ,"+pageRequest.getPageSize()+" ";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            for (Map<String,Object> map:list){
                JSONObject json = new JSONObject();

+ 8 - 33
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java

@ -3883,11 +3883,11 @@ public class SignPatientLabelInfoService extends BaseService {
                                //判断微信绑定情况
                                re = openid1.compareTo(openid2);
                            }else{
                                re = disease2 - disease1;
                                re = disease1 - disease2;
                            }
                        }else{
                            re = diseaseCondition2 - diseaseCondition1;
                            re = diseaseCondition1 - diseaseCondition2;
                        }
@ -4064,7 +4064,7 @@ public class SignPatientLabelInfoService extends BaseService {
                                                           String labelCode, String labelType, long teamCode,
                                                           String exLabelCode,
                                                           String exLabelType,
                                                           int page, int pagesize, String diseaseCondition) throws Exception {
                                                           int page, int pagesize) throws Exception {
        Doctor doc = doctorDao.findByCode(doctor);
        Map<String,Object> patientDeviceTypeMap = new HashMap<>();//用于存储患者设备绑定情况
@ -4098,8 +4098,7 @@ public class SignPatientLabelInfoService extends BaseService {
                "    AND t2.status = 1 " +
                (StringUtils.isNotEmpty(labelCode) ? " AND t2.label = ? " : "") +
                (StringUtils.isNotEmpty(labelType) ? " AND t2.label_type = ? " : "") +
                (teamCode > 0 ? (" AND admin_team_code = " + teamCode) : "")+
                (StringUtils.isNotEmpty(diseaseCondition) ? " AND t3.disease_condition in (?) " : "");
                (teamCode > 0 ? (" AND admin_team_code = " + teamCode) : "");
        sql = sql + " AND t3.disease > 0 AND t3.status > 0 ";
        if (matcher.find()) {
@ -4122,40 +4121,15 @@ public class SignPatientLabelInfoService extends BaseService {
            }
        }
        if(StringUtils.isNotEmpty(diseaseCondition)){
            Object[] argsnew = new Object[args.length+1];
            for (int i = 0; i < argsnew.length; i++) {
                if(i == (argsnew.length-1)){
                    argsnew[i] = diseaseCondition;
                }else{
                    argsnew[i] = args[i];
                }
            }
            sql = sql + " order by t3.standard_status,t3.disease_condition,t3.disease,t3.openid desc limit " + page + "," + pagesize;
            signList = jdbcTemplate.queryForList(sql, argsnew);
        }else{
            sql = sql + " order by t3.standard_status,t3.disease_condition,t3.disease,t3.openid desc limit " + page + "," + pagesize;
            signList = jdbcTemplate.queryForList(sql, args);
        }
        sql = sql + " order by t3.standard_status,t3.disease_condition,t3.disease,t3.openid desc limit " + page + "," + pagesize;
        signList = jdbcTemplate.queryForList(sql, args);
//        //查询患者设备绑定情况
//        String _pdsql = "select user,sum(category_code) deviceType FROM wlyy_patient_device GROUP BY user";
//        List<Map<String,Object>> patientCodeDeviceTypes =  jdbcTemplate.queryForList(_pdsql);
//
//        if(!patientCodeDeviceTypes.isEmpty()){
//            for (Map<String,Object> patientCodeDeviceType : patientCodeDeviceTypes) {
//                String user = String.valueOf(patientCodeDeviceType.get("user"));
//                String sum = String.valueOf(patientCodeDeviceType.get("deviceType"));
//                patientDeviceTypeMap.put(user,sum);
//            }
//        }
        if (signList != null && signList.size() > 0) {
            for (Map<String, Object> sign : signList) {
                Patient p = patientDao.findByCode(sign.get("patient") == null ? "" : sign.get("patient").toString());
                System.out.println("1111");
                if (p == null) {
                    continue;
@ -4232,6 +4206,7 @@ public class SignPatientLabelInfoService extends BaseService {
                json.put("code", p.getCode());
                // 设置患者姓名
                json.put("name", p.getName());
                System.out.println(p.getName());
                // 设置患者手机号
                json.put("mobile", p.getMobile());
                // 设置患者微信openid

+ 40 - 10
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionInfoService.java

@ -1085,8 +1085,12 @@ public class PrescriptionInfoService extends BaseService {
            param.add(endDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(hospital)) {
            pre_sql.append(" AND e.hospital_code = ? ");
            param.add(hospital);
            if("other".equals(hospital)){
                pre_sql.append(" AND (e.patient_hospital_code IS NULL OR e.patient_hospital_code ='') ");
            }else{
                pre_sql.append(" AND e.patient_hospital_code = ? ");
                param.add(hospital);
            }
        }
        if (StringUtils.isNotBlank(state)) {
            pre_sql.append(" AND pr.status = ? ");
@ -1126,8 +1130,12 @@ public class PrescriptionInfoService extends BaseService {
            param.add(endDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(hospital)) {
            pre_sql.append(" AND e.hospital_code = ? ");
            param.add(hospital);
            if("other".equals(hospital)){
                pre_sql.append(" AND (e.patient_hospital_code IS NULL OR e.patient_hospital_code ='')");
            }else{
                pre_sql.append(" AND e.patient_hospital_code = ? ");
                param.add(hospital);
            }
        }
        if (StringUtils.isNotBlank(state)) {
            pre_sql.append(" AND pr.status = ? ");
@ -1174,8 +1182,22 @@ public class PrescriptionInfoService extends BaseService {
        //
        Doctor d = doctorDao.findByCode(doctor);
        if (d != null && StringUtils.isNotBlank(d.getHospital())) {
            String h = d.getHospital().substring(0, 8);
            String sql = "SELECT h.`code`,h.`name` FROM dm_hospital h WHERE h.`code` LIKE '%" + h + "%' ";
            //String h = d.getHospital().substring(0, 8);
            // String sql = "SELECT h.`code`,h.`name` FROM dm_hospital h WHERE h.`code` LIKE '%" + h + "%' ";
            String sql = " SELECT " +
                    " e.patient_hospital_name AS name, " +
                    " e.patient_hospital_code AS code " +
                    " FROM " +
                    " wlyy_prescription_expressage e " +
                    " WHERE " +
                    " ( " +
                    "  e.accept_code = '"+doctor+"' " +
                    "  OR e.expressage_code = '"+doctor+"' " +
                    " ) " +
                    " AND e.patient_hospital_code IS NOT NULL " +
                    " AND e.patient_hospital_code <> '' " +
                    " GROUP BY " +
                    " e.patient_hospital_code ";
            List<Map<String, Object>> hs = jdbcTemplate.queryForList(sql);
            rs.put("hospitals", hs);
        } else {
@ -1367,8 +1389,12 @@ public class PrescriptionInfoService extends BaseService {
            param.add(endDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(hospital)) {
            pre_sql.append(" AND e.patient_hospital_code = ? ");
            param.add(hospital);
            if("other".equals(hospital)){
                pre_sql.append(" AND (e.patient_hospital_code IS NULL OR e.patient_hospital_code ='')");
            }else{
                pre_sql.append(" AND e.patient_hospital_code = ? ");
                param.add(hospital);
            }
        }
        if (StringUtils.isNotBlank(state)) {
            pre_sql.append(" AND pr.status = ? ");
@ -1409,8 +1435,12 @@ public class PrescriptionInfoService extends BaseService {
            param.add(endDate + " 23:59:59");
        }
        if (StringUtils.isNotBlank(hospital)) {
            pre_sql.append(" AND e.patient_hospital_code = ? ");
            param.add(hospital);
            if("other".equals(hospital)){
                pre_sql.append(" AND (e.patient_hospital_code IS NULL OR e.patient_hospital_code ='')");
            }else{
                pre_sql.append(" AND e.patient_hospital_code = ? ");
                param.add(hospital);
            }
        }
        if (StringUtils.isNotBlank(state)) {
            pre_sql.append(" AND pr.status = ? ");

+ 9 - 7
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java

@ -71,9 +71,9 @@ public class DoctorSchemeService {
     * @date 2017/9/13 16:23
     * @return
     */
    public List<String> getPatientsByDiseaseConditionDiseaseDeviceType(String teamCode, Integer disease, String diseaseCondition, Integer deviceType) throws Exception{
    public List<String> getPatientsByDiseaseConditionDiseaseDeviceType(String teamCode, Integer disease, String diseaseCondition, Integer deviceType,String doctorcode) throws Exception{
        String sql = "select p.code from wlyy_patient p ";
        String sql = "select DISTINCT p.code from wlyy_patient p ";
        if(-1 != deviceType){
            sql = sql + " LEFT JOIN wlyy_patient_device dev on dev.user = p.code ";
@ -99,6 +99,8 @@ public class DoctorSchemeService {
        }
        sql = sql + " and (sf.doctor = "+doctorcode+" or sf.doctor_health ="+doctorcode+")";
        sql = sql + " and p.status > 0 and p.disease > 0 ";
        List<String> result = jdbcTemplate.queryForList(sql,new Object[]{},String.class);
@ -383,9 +385,9 @@ public class DoctorSchemeService {
     * @param enddate
     * @return
     */
    public JSONObject getSlowDiseaseTeaminfos(String teamCode, int getcolor, int getstands, int gethealthindex, String startdate, String enddate) throws Exception{
    public JSONObject getSlowDiseaseTeaminfos(String teamCode, int getcolor, int getstands, int gethealthindex, String startdate, String enddate,String doctorcode) throws Exception{
        List<Patient> patients = patientDao.findAllSignPatientTeamcode(teamCode);
        List<Patient> patients = patientDao.findAllSignPatientTeamcode(teamCode,doctorcode);
        JSONObject result = new JSONObject();
        JSONObject green = new JSONObject();//绿标
@ -478,7 +480,7 @@ public class DoctorSchemeService {
            Date end = DateUtil.strToDate(enddate);
            List<DevicePatientHealthIndex> devicePatientHealthIndices = devicePatientHealthIndexDao.findByTeamcodeAndRecordDate("1,2",start,end,teamCode);
            List<DevicePatientHealthIndex> devicePatientHealthIndices = devicePatientHealthIndexDao.findByTeamcodeAndRecordDate("1,2",start,end,teamCode,doctorcode);
            int sugar = 0;
            int sugar_unusual = 0;
@ -490,14 +492,14 @@ public class DoctorSchemeService {
                for (DevicePatientHealthIndex devicePatientHealthIndex : devicePatientHealthIndices) {
                    if( 1 == devicePatientHealthIndex.getType()){
                        sugar++;
                        if( 1 == devicePatientHealthIndex.getStatus()){
                        if( devicePatientHealthIndex.getStatus() !=null && 0 == devicePatientHealthIndex.getStatus()){
                            sugar_unusual++;
                        }
                    }
                    if( 2 == devicePatientHealthIndex.getType()){
                        pressure++;
                        if( 1 == devicePatientHealthIndex.getStatus()){
                        if(devicePatientHealthIndex.getStatus() !=null && 0 == devicePatientHealthIndex.getStatus()){
                            pressure_unusual++;
                        }
                    }

+ 4 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/DoctorService.java

@ -158,4 +158,8 @@ public class DoctorService extends TokenService {
        return doctorList;
    }
    public void save(Doctor doctor){
        doctorDao.save(doctor);
    }
}

+ 4 - 18
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java

@ -833,10 +833,6 @@ public class PatientService extends TokenService {
                ") c ON d. CODE = c.serverType " +
                "WHERE " +
                " d.`year` = '" + DateUtil.getSignYear() + "' " ;
        if(isSlowDisease){
            //获取预警分组数量
//            totalGSql = totalGSql +"  AND d. CODE in (4,5)  ";
        }
        totalGSql = totalGSql +
                "ORDER BY " +
@ -862,13 +858,8 @@ public class PatientService extends TokenService {
                "    wlyy_sign_family f ,wlyy_patient p " +
                "   WHERE " +
                "   f.patient = p.code ";
        if(isSlowDisease){
            //获取预警分组数量
            fousGSql = fousGSql +"   AND p.standard_status = 1  ";
        }else{
            //获取微信关注量分组数量
            fousGSql = fousGSql +"   AND p.openid IS NOT NULL AND p.openid <>'' " ;
        }
        //获取微信关注量分组数量
        fousGSql = fousGSql +"   AND p.openid IS NOT NULL AND p.openid <>'' " ;
        if(StringUtils.isNotBlank(diseaseCondition)){
            fousGSql = fousGSql +"   AND p.disease_condition = "+diseaseCondition;
@ -889,11 +880,6 @@ public class PatientService extends TokenService {
                "WHERE " +
                " d.`year` = '" + DateUtil.getSignYear() + "' " ;
        if(isSlowDisease){
            //获取预警分组数量
//            fousGSql = fousGSql +"  AND d. CODE in (4,5)  ";
        }
        fousGSql = fousGSql +
                "ORDER BY " +
                " d.sort ASC";
@ -1012,8 +998,8 @@ public class PatientService extends TokenService {
        patientDao.save(patient);
    }
    public List<Patient> findAllSignPatientTeamcode(String teamcode) {
    public List<Patient> findAllSignPatientTeamcode(String teamcode,String doctorcode) {
        return patientDao.findAllSignPatientTeamcode(teamcode);
        return patientDao.findAllSignPatientTeamcode(teamcode,doctorcode);
    }
}

+ 13 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/DateUtil.java

@ -870,4 +870,17 @@ public class DateUtil {
		Timestamp nousedate = new Timestamp(date.getTime());
		return nousedate;
	}
	/**
	 *  日期加减天数
	 * @param date 时间
	 * @param days 天数�?
	 * @return
	 */
	public static java.util.Date setDateTime(java.util.Date date,int days){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DATE, cal.get(Calendar.DATE) +(days));
		return  cal.getTime();
	}
}

+ 201 - 201
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ElasticsearchUtil.java

@ -1,201 +1,201 @@
package com.yihu.wlyy.util;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.parser.SQLExprParser;
import com.yihu.wlyy.config.es.ElasticFactory;
import org.elasticsearch.action.search.SearchResponse;
import org.nlpcn.es4sql.domain.Select;
import org.nlpcn.es4sql.jdbc.ObjectResult;
import org.nlpcn.es4sql.jdbc.ObjectResultsExtractor;
import org.nlpcn.es4sql.parse.ElasticSqlExprParser;
import org.nlpcn.es4sql.parse.SqlParser;
import org.nlpcn.es4sql.query.AggregationQueryAction;
import org.nlpcn.es4sql.query.DefaultQueryAction;
import org.nlpcn.es4sql.query.SqlElasticSearchRequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by chenweida on 2017/7/17.
 * SELECT town,townName,sum(result1) result1 FROM wlyy_quota_test
 * where quotaCode='1'
 * group by town,townName , date_histogram(field='quotaDate','interval'='week')
 */
@Component
public class ElasticsearchUtil {
    private Logger logger = LoggerFactory.getLogger(ElasticsearchUtil.class);
    @Autowired
    private ElasticFactory elasticFactory;
    public List excute(String sql, Class clazz, String esType, String esIndex) {
        List saveModels = new ArrayList<>();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getAggregations(), true);
            List<String> heads = temp.getHeaders();
            temp.getLines().stream().forEach(one -> {
                Object saveModel = null;
                try {
                    saveModel = clazz.newInstance();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
                for (int i = 0; i < one.size(); i++) {
                    try {
                        String key = null;
                        Object value = one.get(i);
                        if (heads.get(i).contains("date_histogram")) {
                            key = "setQuotaDate";
                            value = DateUtil.strToDate(String.valueOf(value), "yyyy-MM-dd HH:mm:ss");
                        } else {
                            key = "set" + UpFirstStr(heads.get(i));
                        }
                        if (value instanceof String) {
                            clazz.getMethod(key, String.class).invoke(saveModel, value);
                        } else if (value instanceof Integer) {
                            clazz.getMethod(key, Integer.class).invoke(saveModel, value);
                        } else if (value instanceof Double) {
                            clazz.getMethod(key, Integer.class).invoke(saveModel, ((Double) value).intValue());
                        } else if (value instanceof java.util.Date) {
                            clazz.getMethod(key, java.util.Date.class).invoke(saveModel, value);
                        }
                    } catch (Exception e) {
                        logger.warn(e.getMessage());
                    }
                }
                saveModels.add(saveModel);
            });
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return saveModels;
    }
    public Long excuteForLong(String sql, String esType, String esIndex) {
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getAggregations(), true);
            Long Longvalue = ((Double) temp.getLines().get(0).get(1)).longValue();
            return Longvalue;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return 0L;
    }
    /**
     * 首字母大写
     *
     * @param str
     * @return
     */
    private String UpFirstStr(String str) {
        return str.replaceFirst(str.substring(0, 1), str.substring(0, 1).toUpperCase());
    }
    public Object excuteOneObject(String sql, Class clazz, String esType, String esIndex) {
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
            Select select = null;
            select = new SqlParser().parseSelect(queryExpr);
            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
            AggregationQueryAction action = null;
            DefaultQueryAction queryAction = null;
            SqlElasticSearchRequestBuilder requestBuilder = null;
            if (select.isAgg) {
                //包含计算的的排序分组的
                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = action.explain();
            } else {
                //封装成自己的Select对象
                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getHits(), true);
            List<String> heads = temp.getHeaders();
            Object saveModel = clazz.newInstance();
            try {
                for (int i = 0; i < temp.getLines().get(0).size(); i++) {
                    String key = null;
                    Object value = temp.getLines().get(0).get(i);
                    if (heads.get(i).contains("createTime")) {
                        key = "setCreateTime";
                        value = DateUtil.strToDate(String.valueOf(value).replace("+0800","").replace("T"," "), "yyyy-MM-dd HH:mm:ss");
                    } else {
                        key = "set" + UpFirstStr(heads.get(i));
                    }
                    if (value instanceof String) {
                        clazz.getMethod(key, String.class).invoke(saveModel, value);
                    } else if (value instanceof Integer) {
                        clazz.getMethod(key, Integer.class).invoke(saveModel, value);
                    } else if (value instanceof Double) {
                        clazz.getMethod(key, Integer.class).invoke(saveModel, ((Double) value).intValue());
                    } else if (value instanceof java.util.Date) {
                        clazz.getMethod(key, java.util.Date.class).invoke(saveModel, value);
                    }
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
            }
            return saveModel;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
}
//package com.yihu.wlyy.util;
//
//import com.alibaba.druid.sql.ast.SQLExpr;
//import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
//import com.alibaba.druid.sql.parser.SQLExprParser;
//import com.yihu.wlyy.config.es.ElasticFactory;
//import org.elasticsearch.action.search.SearchResponse;
//import org.nlpcn.es4sql.domain.Select;
//import org.nlpcn.es4sql.jdbc.ObjectResult;
//import org.nlpcn.es4sql.jdbc.ObjectResultsExtractor;
//import org.nlpcn.es4sql.parse.ElasticSqlExprParser;
//import org.nlpcn.es4sql.parse.SqlParser;
//import org.nlpcn.es4sql.query.AggregationQueryAction;
//import org.nlpcn.es4sql.query.DefaultQueryAction;
//import org.nlpcn.es4sql.query.SqlElasticSearchRequestBuilder;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by chenweida on 2017/7/17.
// * SELECT town,townName,sum(result1) result1 FROM wlyy_quota_test
// * where quotaCode='1'
// * group by town,townName , date_histogram(field='quotaDate','interval'='week')
// */
//@Component
//public class ElasticsearchUtil {
//
//    private Logger logger = LoggerFactory.getLogger(ElasticsearchUtil.class);
//
//    @Autowired
//    private ElasticFactory elasticFactory;
//
//    public List excute(String sql, Class clazz, String esType, String esIndex) {
//        List saveModels = new ArrayList<>();
//        try {
//            SQLExprParser parser = new ElasticSqlExprParser(sql);
//            SQLExpr expr = parser.expr();
//            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
//
//            Select select = null;
//            select = new SqlParser().parseSelect(queryExpr);
//
//            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
//            AggregationQueryAction action = null;
//            DefaultQueryAction queryAction = null;
//            SqlElasticSearchRequestBuilder requestBuilder = null;
//            if (select.isAgg) {
//                //包含计算的的排序分组的
//                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
//                requestBuilder = action.explain();
//            } else {
//                //封装成自己的Select对象
//                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
//                requestBuilder = queryAction.explain();
//            }
//            SearchResponse response = (SearchResponse) requestBuilder.get();
//            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getAggregations(), true);
//            List<String> heads = temp.getHeaders();
//            temp.getLines().stream().forEach(one -> {
//                Object saveModel = null;
//                try {
//                    saveModel = clazz.newInstance();
//                } catch (Exception e) {
//                    logger.error(e.getMessage());
//                }
//                for (int i = 0; i < one.size(); i++) {
//                    try {
//                        String key = null;
//                        Object value = one.get(i);
//                        if (heads.get(i).contains("date_histogram")) {
//                            key = "setQuotaDate";
//                            value = DateUtil.strToDate(String.valueOf(value), "yyyy-MM-dd HH:mm:ss");
//                        } else {
//                            key = "set" + UpFirstStr(heads.get(i));
//                        }
//
//                        if (value instanceof String) {
//                            clazz.getMethod(key, String.class).invoke(saveModel, value);
//                        } else if (value instanceof Integer) {
//                            clazz.getMethod(key, Integer.class).invoke(saveModel, value);
//                        } else if (value instanceof Double) {
//                            clazz.getMethod(key, Integer.class).invoke(saveModel, ((Double) value).intValue());
//                        } else if (value instanceof java.util.Date) {
//                            clazz.getMethod(key, java.util.Date.class).invoke(saveModel, value);
//                        }
//                    } catch (Exception e) {
//                        logger.warn(e.getMessage());
//                    }
//                }
//                saveModels.add(saveModel);
//            });
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//        }
//        return saveModels;
//    }
//
//    public Long excuteForLong(String sql, String esType, String esIndex) {
//        try {
//            SQLExprParser parser = new ElasticSqlExprParser(sql);
//            SQLExpr expr = parser.expr();
//            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
//
//            Select select = null;
//            select = new SqlParser().parseSelect(queryExpr);
//
//            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
//            AggregationQueryAction action = null;
//            DefaultQueryAction queryAction = null;
//            SqlElasticSearchRequestBuilder requestBuilder = null;
//            if (select.isAgg) {
//                //包含计算的的排序分组的
//                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
//                requestBuilder = action.explain();
//            } else {
//                //封装成自己的Select对象
//                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
//                requestBuilder = queryAction.explain();
//            }
//            SearchResponse response = (SearchResponse) requestBuilder.get();
//            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getAggregations(), true);
//            Long Longvalue = ((Double) temp.getLines().get(0).get(1)).longValue();
//            return Longvalue;
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//        }
//        return 0L;
//    }
//
//    /**
//     * 首字母大写
//     *
//     * @param str
//     * @return
//     */
//    private String UpFirstStr(String str) {
//        return str.replaceFirst(str.substring(0, 1), str.substring(0, 1).toUpperCase());
//    }
//
//    public Object excuteOneObject(String sql, Class clazz, String esType, String esIndex) {
//        try {
//            SQLExprParser parser = new ElasticSqlExprParser(sql);
//            SQLExpr expr = parser.expr();
//            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
//
//            Select select = null;
//            select = new SqlParser().parseSelect(queryExpr);
//
//            //通过抽象语法树,封装成自定义的Select,包含了select、from、where group、limit等
//            AggregationQueryAction action = null;
//            DefaultQueryAction queryAction = null;
//            SqlElasticSearchRequestBuilder requestBuilder = null;
//            if (select.isAgg) {
//                //包含计算的的排序分组的
//                action = new AggregationQueryAction(elasticFactory.getTransportClient(), select);
//                requestBuilder = action.explain();
//            } else {
//                //封装成自己的Select对象
//                queryAction = new DefaultQueryAction(elasticFactory.getTransportClient(), select);
//                requestBuilder = queryAction.explain();
//            }
//            SearchResponse response = (SearchResponse) requestBuilder.get();
//            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(response.getHits(), true);
//            List<String> heads = temp.getHeaders();
//            Object saveModel = clazz.newInstance();
//            try {
//                for (int i = 0; i < temp.getLines().get(0).size(); i++) {
//                    String key = null;
//                    Object value = temp.getLines().get(0).get(i);
//                    if (heads.get(i).contains("createTime")) {
//                        key = "setCreateTime";
//                        value = DateUtil.strToDate(String.valueOf(value).replace("+0800","").replace("T"," "), "yyyy-MM-dd HH:mm:ss");
//                    } else {
//                        key = "set" + UpFirstStr(heads.get(i));
//                    }
//
//                    if (value instanceof String) {
//                        clazz.getMethod(key, String.class).invoke(saveModel, value);
//                    } else if (value instanceof Integer) {
//                        clazz.getMethod(key, Integer.class).invoke(saveModel, value);
//                    } else if (value instanceof Double) {
//                        clazz.getMethod(key, Integer.class).invoke(saveModel, ((Double) value).intValue());
//                    } else if (value instanceof java.util.Date) {
//                        clazz.getMethod(key, java.util.Date.class).invoke(saveModel, value);
//                    }
//                }
//            } catch (Exception e) {
//                logger.warn(e.getMessage());
//            }
//            return saveModel;
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//        }
//        return null;
//    }
//}

+ 2 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ImUtill.java

@ -330,10 +330,9 @@ public class ImUtill {
     */
    public Boolean sessionIsExist(String sessionId) {
        Boolean re = false;
        String imAddr = im_host + "api/v2/sessions/isExist";
        String url = im_host + "api/v2/sessions/isExist?session_id="+sessionId;
        JSONObject params = new JSONObject();
        params.put("session_id", sessionId);
        String ret = HttpClientUtil.postBody(imAddr, params);
        String ret = HttpClientUtil.get(url, "UTF-8");
        JSONObject obj = null;
        try {
            obj = new JSONObject(ret);

+ 2 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java

@ -99,7 +99,7 @@ public class LoginController extends BaseController {
     * 医生登录接口
     *
     * @param mobile   手机号
     * @param captcha  短信验证码
     * @param captcha  短信验证码t
     * @param platform // 1患者端,2医生端app,3微信公众号wechat,4 IM医生端pc, PC端取药系统,5医生助手公众号
     * @param password 密码
     * @return
@ -175,6 +175,7 @@ public class LoginController extends BaseController {
                    if(StringUtils.isNotBlank(openid)){
                        doctor.setOpenid(openid);
                        doctorService.save(doctor);
                    }
                    return write(200, "登录成功", "data", map);

+ 4 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java

@ -33,6 +33,7 @@ public class DoctorHealthController extends BaseController {
	@Autowired
	private PatientHealthIndexService healthIndexService;
	@Autowired
	private PatientService patientService;
@ -289,6 +290,7 @@ public class DoctorHealthController extends BaseController {
			}
			return write(200, "查询成功", "data", map);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
@ -378,7 +380,7 @@ public class DoctorHealthController extends BaseController {
		}
	}
	@RequestMapping(value = "savastandbyteamcode",method = RequestMethod.GET)
	@RequestMapping(value = "savastandbyteamcode",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("医生保存团队下所有居民的预警方案")
	public String doctorSaveStandardByTeamCode(
@ -391,7 +393,7 @@ public class DoctorHealthController extends BaseController {
				return error(-1, "保存失败!");
			}
			List<Patient> patients = patientService.findAllSignPatientTeamcode(teamcode);
			List<Patient> patients = patientService.findAllSignPatientTeamcode(teamcode,getUID());
			if(!patients.isEmpty()){

+ 6 - 7
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java

@ -784,8 +784,7 @@ public class SignPatientLabelInfoController extends BaseController {
                                             @RequestParam(required = false) String exLabelCode,
                                             @RequestParam(required = false) String exLabelType,
                                             @RequestParam(required = true) int page,
                                             @RequestParam(required = true) int pagesize,
                                             @RequestParam(required = true) String diseaseCondition) {
                                             @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(filter)) {
                return error(-1, "搜索字段不能为空");
@ -805,8 +804,8 @@ public class SignPatientLabelInfoController extends BaseController {
            page = page - 1;
            JSONArray result = labelInfoService.searchSlowDiseasePatientByNameOrLabel(getUID(), filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize,diseaseCondition);
//            JSONArray result = labelInfoService.searchPatientByNameOrLabel("xy201703150222", filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize,diseaseCondition);
            JSONArray result = labelInfoService.searchSlowDiseasePatientByNameOrLabel(getUID(), filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);
//            JSONArray result = labelInfoService.searchSlowDiseasePatientByNameOrLabel("xy201703150222", filter, labelCode, labelType, teamCode, exLabelCode, exLabelType, page, pagesize);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
@ -843,10 +842,10 @@ public class SignPatientLabelInfoController extends BaseController {
            @ApiParam(name="getcolor", value="是否获取颜色标签") @RequestParam(value = "getcolor",required = true,defaultValue = "1")  int getcolor,
            @ApiParam(name="getstands", value="是否获取预警人数数据") @RequestParam(value = "getstands",required = true,defaultValue = "1")  int getstands,
            @ApiParam(name="gethealthindex", value="是否获取体征数据") @RequestParam(value = "gethealthindex",required = true,defaultValue = "1")  int gethealthindex,
            @ApiParam(name="startdate", value="体征数据开始时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "startdate",required = false,defaultValue = "")  String startdate,
            @ApiParam(name="enddate", value="体征数据结束时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "enddate",required = false,defaultValue = "")  String enddate){
            @ApiParam(name="startdate", value="体征数据开始时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "startdate",required = false,defaultValue = "2017-9-10 00:00:00")  String startdate,
            @ApiParam(name="enddate", value="体征数据结束时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "enddate",required = false,defaultValue = "2017-9-16 23:59:59")  String enddate){
        try {
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode,getcolor,getstands,gethealthindex,startdate,enddate);
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode,getcolor,getstands,gethealthindex,startdate,enddate,getUID());
            return write(200, "查询成功", "data", result);
        }catch (Exception e){
            //日志文件中记录异常信息

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/scheme/DoctroSchemeController.java

@ -40,7 +40,7 @@ public class DoctroSchemeController extends BaseController {
            ){
        try {
            List<String> result = doctorSchemeService.getPatientsByDiseaseConditionDiseaseDeviceType(teamCode,disease,diseaseCondition,deviceType);
            List<String> result = doctorSchemeService.getPatientsByDiseaseConditionDiseaseDeviceType(teamCode,disease,diseaseCondition,deviceType,getUID());
            return write(200, "查询成功", "data", result);
        }catch (Exception e){

+ 8 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java

@ -352,7 +352,10 @@ public class ConsultController extends WeixinBaseController {
            System.out.println("guidance2="+guidance);
            // 保存到数据库
            int res = consultTeamService.addTeamConsult(consult, getRepUID(),getUID());
            int res = 0;
            synchronized (getRepUID().intern()){//新增同步方法。设备保存写在service层但是不生效,写在controller层才生效
                res = consultTeamService.addTeamConsult(consult, getRepUID(),getUID());
            }
            if (res == -1) {
                return error(-1, "家庭签约信息不存在或已过期,无法进行家庭医生咨询!");
            } else if (res == -2) {
@ -989,7 +992,10 @@ public class ConsultController extends WeixinBaseController {
            consult.setAdminTeamId(adminTeamId);
            // 保存到数据库
//            int res = consultTeamService.addPrescriptionConsult(jwCode, "b02f132bfbfc45d287bcde18ad342522","b02f132bfbfc45d287bcde18ad342522",doctor,consult,reason,type);
            int res = consultTeamService.addPrescriptionConsult(jwCode, getRepUID(),getUID(),doctor,consult,reason,type);
            int res = 0;
            synchronized (jwCode.intern()){
                res = consultTeamService.addPrescriptionConsult(jwCode, getRepUID(),getUID(),doctor,consult,reason,type);
            }
            if (res == -1) {
                return error(-1, "该处方存在未审核的续方,无法进行续方咨询!");
            } if (res == -2) {

+ 4 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java

@ -7,7 +7,6 @@ import com.yihu.wlyy.repository.deviece.PatientHealthTimeDao;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.util.HttpClientUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -161,8 +160,10 @@ public class PatientDeviceController extends BaseController {
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
            }
            patientDeviceService.saveDevice(device);
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                patientDeviceService.saveDevice(device);
            }
            return success("设备保存成功!");
        } catch (Exception ex) {

+ 7 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java

@ -283,6 +283,7 @@ public class PatientHealthController extends BaseController {
            }
            return write(200, "查询成功", "data", map);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
@ -394,13 +395,19 @@ public class PatientHealthController extends BaseController {
//                patient = getUID();
            }
            DevicePatientHealthIndex obj = healthIndexService.addPatientHealthIndex(data, type, patient, null);
            //血糖和血压需要校验
            if (type.equals("1") || type.equals("2")) {
                healthIndexService.verifyHealthIndex(obj.getId());
            }
            //判断居民的体征预警状态
            healthIndexService.handlePatientStandarStatus(obj);
            return success("新增患者指标成功!");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

+ 213 - 213
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcEduArticleController.java

@ -1,213 +1,213 @@
package com.yihu.wlyy.web.third.gateway.controller.doctor;
import com.yihu.es.entity.HealthEduArticlePatient;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImUtill;
import com.yihu.wlyy.web.WeixinBaseController;
import com.yihu.wlyy.web.third.gateway.service.GcEduArticleService;
import com.yihu.wlyy.web.third.gateway.vo.HealthEduArticlePatientModel;
import com.yihu.wlyy.web.third.gateway.vo.base.BaseResultModel;
import com.yihu.wlyy.web.third.gateway.vo.base.ResultPageListModel;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
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.http.MediaType;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
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;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.*;
/**
 * Created by chenweida on 2017/8/30.
 */
@Controller
@RequestMapping(value = "/wlyygc/doctor/edu/article", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Api(description = "医生文章相关服务")
public class GcEduArticleController extends WeixinBaseController {
    private Logger logger = LoggerFactory.getLogger(GcEduArticleController.class);
    @Autowired
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private PatientService patientService;
    @Autowired
    private ConsultService consultService;
    @Autowired
    private GcEduArticleService gcEduArticleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Value("${activemq.queue.healtHarticleQueue}")
    private String channelName;
    /**
     * @param doctorCode
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping(value = "logs", method = RequestMethod.GET)
    @ApiOperation("查询医生给患者推送记录 ")
    public ResultPageListModel<HealthEduArticlePatientModel> getPatientHealthLogs(
            @ApiParam(name = "articleType", value = "文章类别", required = false) @RequestParam(value = "articleType", required = false) String articleType,
            @ApiParam(name = "level1Type", value = "一级分类", required = false) @RequestParam(value = "level1Type", required = false) String level1Type,
            @ApiParam(name = "level2Type", value = "二级分类", required = false) @RequestParam(value = "level2Type", required = false) String level2Type,
            @ApiParam(name = "level", value = "等级", required = false) @RequestParam(value = "level", required = false) String level,
            @ApiParam(name = "doctorCode", value = "医生code,为空从useragent取", required = false) @RequestParam(value = "doctorCode", required = false) String doctorCode,
            @ApiParam(name = "patientCode", value = "接收人code", required = false) @RequestParam(value = "patientCode", required = false) String patientCode,
            @ApiParam(name = "articleTitle", value = "文章标题", required = false) @RequestParam(value = "articleTitle", required = false) String articleTitle,
            @ApiParam(name = "startTime", value = "开始时间yyyy-Mm-dd", required = false) @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间yyyy-Mm-dd", required = false) @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "page", value = "当前页 起始1", required = true) @RequestParam(value = "page", required = true) Integer page,
            @ApiParam(name = "pagesize", value = "每页显示条数", required = true) @RequestParam(value = "pagesize", required = true) Integer pagesize) {
        try {
            if (org.springframework.util.StringUtils.isEmpty(doctorCode)) {
                doctorCode = getUID();
            }
            //最大1000
            if (pagesize > 1000) {
                pagesize = 1000;
            }
            List<HealthEduArticlePatientModel> eduArticlePatients = gcEduArticleService.getPatientHealthLogs(doctorCode, articleType, level1Type, level2Type, level, articleTitle, startTime, endTime, page, pagesize);
            Long count = gcEduArticleService.getPatientHealthLogsCount(getUID(), articleType, level1Type, level2Type, level, articleTitle, startTime, endTime);
            return new ResultPageListModel(
                    page,
                    pagesize,
                    count.intValue()
                    , eduArticlePatients);
        } catch (Exception e) {
            return new ResultPageListModel(BaseResultModel.statusEm.find_error.getCode(), BaseResultModel.statusEm.find_error.getMessage() + "," + e.getMessage());
        }
    }
    /**
     * * 参考原来的教育文章推送
     * http://172.19.103.88:9092/wlyy//doctor/health/edu/send?code=2e6467b5bb2f4b81b598633624d7f98e&patient=e911d1b756cd4680ab241ab76a463282&teamCode=1&attachedContent=
     *
     * @return
     */
    @RequestMapping(value = "send", method = RequestMethod.POST)
    @ApiOperation("文章推送")
    public BaseResultModel send(
            @ApiParam(name = "sendType", value = "发送类型 1医生发送 2卫纪委发送", required = true) @RequestParam(value = "sendType", required = true) Integer sendType,
            @ApiParam(name = "sendCode", value = "发送人code", required = true) @RequestParam(value = "sendCode", required = true) String sendCode,
            @ApiParam(name = "sendName", value = "发送人名", required = true) @RequestParam(value = "sendName", required = true) String sendName,
            @ApiParam(name = "sendMessage", value = "发送人信息", required = false) @RequestParam(value = "sendMessage", required = false) String sendMessage,
            @ApiParam(name = "teamId", value = "发送人是医生的时候,医生所属的团队", required = false) @RequestParam(value = "teamId", required = false) Long teamId,
            @ApiParam(name = "labelCode", value = "所选群组,多个用逗号分隔", required = true) @RequestParam(value = "labelCode", required = false, defaultValue = "") String labelCode,
            @ApiParam(name = "labelType", value = "标签类型  1:服务类型(卫计委分组) 2:健康情况 3:疾病类型 4:团队标签(自定义标签)", required = false) @RequestParam(value = "labelType", required = false, defaultValue = "") String labelType,
            @ApiParam(name = "receiveCodes", value = "接收人code,多个逗号分割", required = false) @RequestParam(value = "receiveCodes", required = false, defaultValue = "") String receiveCodes,
            @ApiParam(name = "unReceiveCodes", value = "不接收人code,多个逗号分割(如果同时存在receiveCodes和unReceiveCodes,也不会发送)", required = false) @RequestParam(value = "unReceiveCodes", required = false, defaultValue = "") String unReceiveCodes,
            @ApiParam(name = "articleId", value = "文章ID", required = true) @RequestParam(value = "articleId", required = true) String articleId,
            @ApiParam(name = "articlePic", value = "文章封面", required = true) @RequestParam(value = "articlePic", required = true) String articlePic,
            @ApiParam(name = "articleTitle", value = "文章标题", required = true) @RequestParam(value = "articleTitle", required = true) String articleTitle,
            @ApiParam(name = "articleContent", value = "文章内容", required = true) @RequestParam(value = "articleContent", required = true) String articleContent,
            @ApiParam(name = "articleType", value = "文章类别", required = true) @RequestParam(value = "articleType", required = true) String articleType,
            @ApiParam(name = "level1Type", value = "一级分类", required = true) @RequestParam(value = "level1Type", required = true) String level1Type,
            @ApiParam(name = "level2Type", value = "二级分类", required = true) @RequestParam(value = "level2Type", required = true) String level2Type,
            @ApiParam(name = "level", value = "等级", required = true) @RequestParam(value = "level", required = true) String level,
            @ApiParam(name = "articleUrl", value = "宣教文章获取url", required = true) @RequestParam(value = "articleUrl", required = true) String articleUrl
    ) {
        try {
            String[] patients = receiveCodes.split(",");//接收人的code
            String[] unPatients = unReceiveCodes.split(",");//接收人的code
            Set<String> patientSet = new HashSet<>(); //放入set中可以去重复
            //得到需要发送的患者
            gcEduArticleService.initPatient(patientSet, patients, unPatients, labelType, labelCode, teamId);
            //获取保存发送记录
            List<com.yihu.es.entity.HealthEduArticlePatient> healthEduArticlePatients = gcEduArticleService.getSaveArticle(patientSet, sendCode, sendName, sendType, sendMessage, teamId, articleId, articlePic, articleTitle, articleContent, articleType, level1Type, level2Type, level,articleUrl);
            //推送微信模板消息和发送im消息
            new Thread(() -> {
                //发送任务到redis
                sender(healthEduArticlePatients);
            }).start();
            return new BaseResultModel();
        } catch (Exception e) {
            return new BaseResultModel(BaseResultModel.statusEm.opera_error.getCode(), BaseResultModel.statusEm.opera_error.getMessage() + ":" + e.getMessage());
        }
    }
    /**
     * 发送到redis
     *
     * @param healthEduArticlePatients
     */
    public void sender(List<HealthEduArticlePatient> healthEduArticlePatients) {
        //送到到队列
        healthEduArticlePatients.stream().forEach(one -> {
            jmsTemplate.send(channelName, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    TextMessage textMessage = session.createTextMessage();
                    textMessage.setText(net.sf.json.JSONObject.fromObject(one).toString());
                    return textMessage;
                }
            });
        });
    }
    @RequestMapping(value = "sendPatients", method = RequestMethod.POST)
    @ApiOperation("文章群推送")
    public BaseResultModel sendPatients(
            @ApiParam(name = "sendType", value = "发送类型 1医生发送 2卫纪委发送", required = false) @RequestParam(value = "sendType", required = false,defaultValue = "2") Integer sendType,
            @ApiParam(name = "labelUnitType", value = "标签类型  1:下属单位,多个用逗号分隔", required = false) @RequestParam(value = "labelUnitType", required = false, defaultValue = "") String labelUnitType,
            @ApiParam(name = "labelSexType", value = "标签类型  2:性别,多个用逗号分隔", required = false) @RequestParam(value = "labelSexType", required = false, defaultValue = "") String labelSexType,
            @ApiParam(name = "labelServeType", value = "标签类型  3:服务类型,多个用逗号分隔", required = false) @RequestParam(value = "labelServeType", required = false, defaultValue = "") String labelServeType,
            @ApiParam(name = "labelDiseaseType", value = "标签类型  4:疾病类型,多个用逗号分隔", required = false) @RequestParam(value = "labelDiseaseType", required = false, defaultValue = "") String labelDiseaseType,
            @ApiParam(name = "labelHealthType", value = "标签类型  5:健康情况,多个用逗号分隔", required = false) @RequestParam(value = "labelHealthType", required = false, defaultValue = "") String labelHealthType,
            @ApiParam(name = "articleId", value = "文章ID", required = true) @RequestParam(value = "articleId", required = true) String articleId,
            @ApiParam(name = "articlePic", value = "文章封面", required = true) @RequestParam(value = "articlePic", required = true) String articlePic,
            @ApiParam(name = "articleTitle", value = "文章标题", required = true) @RequestParam(value = "articleTitle", required = true) String articleTitle,
            @ApiParam(name = "articleContent", value = "文章内容", required = true) @RequestParam(value = "articleContent", required = true) String articleContent,
            @ApiParam(name = "articleType", value = "文章类别", required = true) @RequestParam(value = "articleType", required = true) String articleType,
            @ApiParam(name = "level1Type", value = "一级分类", required = true) @RequestParam(value = "level1Type", required = true) String level1Type,
            @ApiParam(name = "level2Type", value = "二级分类", required = true) @RequestParam(value = "level2Type", required = true) String level2Type,
            @ApiParam(name = "level", value = "等级", required = true) @RequestParam(value = "level", required = true) String level,
            @ApiParam(name = "articleUrl", value = "宣教文章获取的url", required = true) @RequestParam(value = "articleUrl", required = true) String articleUrl
    ){
        try {
            Set<String> patientSet = new HashSet<>(); //放入set中可以去重复
            //得到需要发送的患者
            gcEduArticleService.initPatient(patientSet,labelUnitType,labelSexType,labelServeType,labelDiseaseType,labelHealthType);
            //获取保存发送记录
            List<com.yihu.es.entity.HealthEduArticlePatient> healthEduArticlePatients = gcEduArticleService.getSaveArticle(patientSet, "", "", sendType, "", 0L, articleId, articlePic, articleTitle, articleContent, articleType, level1Type, level2Type, level,articleUrl);
            //推送微信模板消息和发送im消息
            new Thread(() -> {
                //发送任务到redis
                sender(healthEduArticlePatients);
            }).start();
            return new BaseResultModel();
        }catch (Exception e) {
            return new BaseResultModel(BaseResultModel.statusEm.opera_error.getCode(), BaseResultModel.statusEm.opera_error.getMessage() + ":" + e.getMessage());
        }
    }
}
//package com.yihu.wlyy.web.third.gateway.controller.doctor;
//
//import com.yihu.es.entity.HealthEduArticlePatient;
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.service.app.consult.ConsultService;
//import com.yihu.wlyy.service.common.account.PatientService;
//import com.yihu.wlyy.task.PushMsgTask;
//import com.yihu.wlyy.util.DateUtil;
//import com.yihu.wlyy.util.ImUtill;
//import com.yihu.wlyy.web.WeixinBaseController;
//import com.yihu.wlyy.web.third.gateway.service.GcEduArticleService;
//import com.yihu.wlyy.web.third.gateway.vo.HealthEduArticlePatientModel;
//import com.yihu.wlyy.web.third.gateway.vo.base.BaseResultModel;
//import com.yihu.wlyy.web.third.gateway.vo.base.ResultPageListModel;
//import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang3.StringUtils;
//import org.json.JSONArray;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//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.http.MediaType;
//import org.springframework.jms.core.JmsTemplate;
//import org.springframework.jms.core.MessageCreator;
//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;
//
//import javax.jms.JMSException;
//import javax.jms.Message;
//import javax.jms.Session;
//import javax.jms.TextMessage;
//import java.util.*;
//
///**
// * Created by chenweida on 2017/8/30.
// */
//@Controller
//@RequestMapping(value = "/wlyygc/doctor/edu/article", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//@ResponseBody
//@Api(description = "医生文章相关服务")
//public class GcEduArticleController extends WeixinBaseController {
//    private Logger logger = LoggerFactory.getLogger(GcEduArticleController.class);
//
//    @Autowired
//    private WeiXinOpenIdUtils weiXinOpenIdUtils;
//    @Autowired
//    private PushMsgTask pushMsgTask;
//    @Autowired
//    private PatientService patientService;
//    @Autowired
//    private ConsultService consultService;
//    @Autowired
//    private GcEduArticleService gcEduArticleService;
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//    @Autowired
//    private JmsTemplate jmsTemplate;
//    @Value("${activemq.queue.healtHarticleQueue}")
//    private String channelName;
//
//    /**
//     * @param doctorCode
//     * @param page
//     * @param pagesize
//     * @return
//     */
//    @RequestMapping(value = "logs", method = RequestMethod.GET)
//    @ApiOperation("查询医生给患者推送记录 ")
//    public ResultPageListModel<HealthEduArticlePatientModel> getPatientHealthLogs(
//            @ApiParam(name = "articleType", value = "文章类别", required = false) @RequestParam(value = "articleType", required = false) String articleType,
//            @ApiParam(name = "level1Type", value = "一级分类", required = false) @RequestParam(value = "level1Type", required = false) String level1Type,
//            @ApiParam(name = "level2Type", value = "二级分类", required = false) @RequestParam(value = "level2Type", required = false) String level2Type,
//            @ApiParam(name = "level", value = "等级", required = false) @RequestParam(value = "level", required = false) String level,
//            @ApiParam(name = "doctorCode", value = "医生code,为空从useragent取", required = false) @RequestParam(value = "doctorCode", required = false) String doctorCode,
//            @ApiParam(name = "patientCode", value = "接收人code", required = false) @RequestParam(value = "patientCode", required = false) String patientCode,
//            @ApiParam(name = "articleTitle", value = "文章标题", required = false) @RequestParam(value = "articleTitle", required = false) String articleTitle,
//            @ApiParam(name = "startTime", value = "开始时间yyyy-Mm-dd", required = false) @RequestParam(value = "startTime", required = false) String startTime,
//            @ApiParam(name = "endTime", value = "结束时间yyyy-Mm-dd", required = false) @RequestParam(value = "endTime", required = false) String endTime,
//            @ApiParam(name = "page", value = "当前页 起始1", required = true) @RequestParam(value = "page", required = true) Integer page,
//            @ApiParam(name = "pagesize", value = "每页显示条数", required = true) @RequestParam(value = "pagesize", required = true) Integer pagesize) {
//        try {
//            if (org.springframework.util.StringUtils.isEmpty(doctorCode)) {
//                doctorCode = getUID();
//            }
//            //最大1000
//            if (pagesize > 1000) {
//                pagesize = 1000;
//            }
//            List<HealthEduArticlePatientModel> eduArticlePatients = gcEduArticleService.getPatientHealthLogs(doctorCode, articleType, level1Type, level2Type, level, articleTitle, startTime, endTime, page, pagesize);
//            Long count = gcEduArticleService.getPatientHealthLogsCount(getUID(), articleType, level1Type, level2Type, level, articleTitle, startTime, endTime);
//            return new ResultPageListModel(
//                    page,
//                    pagesize,
//                    count.intValue()
//                    , eduArticlePatients);
//        } catch (Exception e) {
//            return new ResultPageListModel(BaseResultModel.statusEm.find_error.getCode(), BaseResultModel.statusEm.find_error.getMessage() + "," + e.getMessage());
//        }
//    }
//
//    /**
//     * * 参考原来的教育文章推送
//     * http://172.19.103.88:9092/wlyy//doctor/health/edu/send?code=2e6467b5bb2f4b81b598633624d7f98e&patient=e911d1b756cd4680ab241ab76a463282&teamCode=1&attachedContent=
//     *
//     * @return
//     */
//    @RequestMapping(value = "send", method = RequestMethod.POST)
//    @ApiOperation("文章推送")
//    public BaseResultModel send(
//            @ApiParam(name = "sendType", value = "发送类型 1医生发送 2卫纪委发送", required = true) @RequestParam(value = "sendType", required = true) Integer sendType,
//            @ApiParam(name = "sendCode", value = "发送人code", required = true) @RequestParam(value = "sendCode", required = true) String sendCode,
//            @ApiParam(name = "sendName", value = "发送人名", required = true) @RequestParam(value = "sendName", required = true) String sendName,
//            @ApiParam(name = "sendMessage", value = "发送人信息", required = false) @RequestParam(value = "sendMessage", required = false) String sendMessage,
//            @ApiParam(name = "teamId", value = "发送人是医生的时候,医生所属的团队", required = false) @RequestParam(value = "teamId", required = false) Long teamId,
//            @ApiParam(name = "labelCode", value = "所选群组,多个用逗号分隔", required = true) @RequestParam(value = "labelCode", required = false, defaultValue = "") String labelCode,
//            @ApiParam(name = "labelType", value = "标签类型  1:服务类型(卫计委分组) 2:健康情况 3:疾病类型 4:团队标签(自定义标签)", required = false) @RequestParam(value = "labelType", required = false, defaultValue = "") String labelType,
//            @ApiParam(name = "receiveCodes", value = "接收人code,多个逗号分割", required = false) @RequestParam(value = "receiveCodes", required = false, defaultValue = "") String receiveCodes,
//            @ApiParam(name = "unReceiveCodes", value = "不接收人code,多个逗号分割(如果同时存在receiveCodes和unReceiveCodes,也不会发送)", required = false) @RequestParam(value = "unReceiveCodes", required = false, defaultValue = "") String unReceiveCodes,
//            @ApiParam(name = "articleId", value = "文章ID", required = true) @RequestParam(value = "articleId", required = true) String articleId,
//            @ApiParam(name = "articlePic", value = "文章封面", required = true) @RequestParam(value = "articlePic", required = true) String articlePic,
//            @ApiParam(name = "articleTitle", value = "文章标题", required = true) @RequestParam(value = "articleTitle", required = true) String articleTitle,
//            @ApiParam(name = "articleContent", value = "文章内容", required = true) @RequestParam(value = "articleContent", required = true) String articleContent,
//            @ApiParam(name = "articleType", value = "文章类别", required = true) @RequestParam(value = "articleType", required = true) String articleType,
//            @ApiParam(name = "level1Type", value = "一级分类", required = true) @RequestParam(value = "level1Type", required = true) String level1Type,
//            @ApiParam(name = "level2Type", value = "二级分类", required = true) @RequestParam(value = "level2Type", required = true) String level2Type,
//            @ApiParam(name = "level", value = "等级", required = true) @RequestParam(value = "level", required = true) String level,
//            @ApiParam(name = "articleUrl", value = "宣教文章获取url", required = true) @RequestParam(value = "articleUrl", required = true) String articleUrl
//    ) {
//        try {
//            String[] patients = receiveCodes.split(",");//接收人的code
//            String[] unPatients = unReceiveCodes.split(",");//接收人的code
//            Set<String> patientSet = new HashSet<>(); //放入set中可以去重复
//
//            //得到需要发送的患者
//            gcEduArticleService.initPatient(patientSet, patients, unPatients, labelType, labelCode, teamId);
//            //获取保存发送记录
//            List<com.yihu.es.entity.HealthEduArticlePatient> healthEduArticlePatients = gcEduArticleService.getSaveArticle(patientSet, sendCode, sendName, sendType, sendMessage, teamId, articleId, articlePic, articleTitle, articleContent, articleType, level1Type, level2Type, level,articleUrl);
//            //推送微信模板消息和发送im消息
//            new Thread(() -> {
//                //发送任务到redis
//                sender(healthEduArticlePatients);
//            }).start();
//            return new BaseResultModel();
//        } catch (Exception e) {
//            return new BaseResultModel(BaseResultModel.statusEm.opera_error.getCode(), BaseResultModel.statusEm.opera_error.getMessage() + ":" + e.getMessage());
//        }
//    }
//
//    /**
//     * 发送到redis
//     *
//     * @param healthEduArticlePatients
//     */
//    public void sender(List<HealthEduArticlePatient> healthEduArticlePatients) {
//        //送到到队列
//        healthEduArticlePatients.stream().forEach(one -> {
//            jmsTemplate.send(channelName, new MessageCreator() {
//                @Override
//                public Message createMessage(Session session) throws JMSException {
//                    TextMessage textMessage = session.createTextMessage();
//                    textMessage.setText(net.sf.json.JSONObject.fromObject(one).toString());
//                    return textMessage;
//                }
//            });
//        });
//    }
//
//    @RequestMapping(value = "sendPatients", method = RequestMethod.POST)
//    @ApiOperation("文章群推送")
//    public BaseResultModel sendPatients(
//            @ApiParam(name = "sendType", value = "发送类型 1医生发送 2卫纪委发送", required = false) @RequestParam(value = "sendType", required = false,defaultValue = "2") Integer sendType,
//            @ApiParam(name = "labelUnitType", value = "标签类型  1:下属单位,多个用逗号分隔", required = false) @RequestParam(value = "labelUnitType", required = false, defaultValue = "") String labelUnitType,
//            @ApiParam(name = "labelSexType", value = "标签类型  2:性别,多个用逗号分隔", required = false) @RequestParam(value = "labelSexType", required = false, defaultValue = "") String labelSexType,
//            @ApiParam(name = "labelServeType", value = "标签类型  3:服务类型,多个用逗号分隔", required = false) @RequestParam(value = "labelServeType", required = false, defaultValue = "") String labelServeType,
//            @ApiParam(name = "labelDiseaseType", value = "标签类型  4:疾病类型,多个用逗号分隔", required = false) @RequestParam(value = "labelDiseaseType", required = false, defaultValue = "") String labelDiseaseType,
//            @ApiParam(name = "labelHealthType", value = "标签类型  5:健康情况,多个用逗号分隔", required = false) @RequestParam(value = "labelHealthType", required = false, defaultValue = "") String labelHealthType,
//            @ApiParam(name = "articleId", value = "文章ID", required = true) @RequestParam(value = "articleId", required = true) String articleId,
//            @ApiParam(name = "articlePic", value = "文章封面", required = true) @RequestParam(value = "articlePic", required = true) String articlePic,
//            @ApiParam(name = "articleTitle", value = "文章标题", required = true) @RequestParam(value = "articleTitle", required = true) String articleTitle,
//            @ApiParam(name = "articleContent", value = "文章内容", required = true) @RequestParam(value = "articleContent", required = true) String articleContent,
//            @ApiParam(name = "articleType", value = "文章类别", required = true) @RequestParam(value = "articleType", required = true) String articleType,
//            @ApiParam(name = "level1Type", value = "一级分类", required = true) @RequestParam(value = "level1Type", required = true) String level1Type,
//            @ApiParam(name = "level2Type", value = "二级分类", required = true) @RequestParam(value = "level2Type", required = true) String level2Type,
//            @ApiParam(name = "level", value = "等级", required = true) @RequestParam(value = "level", required = true) String level,
//            @ApiParam(name = "articleUrl", value = "宣教文章获取的url", required = true) @RequestParam(value = "articleUrl", required = true) String articleUrl
//    ){
//        try {
//
//            Set<String> patientSet = new HashSet<>(); //放入set中可以去重复
//            //得到需要发送的患者
//            gcEduArticleService.initPatient(patientSet,labelUnitType,labelSexType,labelServeType,labelDiseaseType,labelHealthType);
//            //获取保存发送记录
//            List<com.yihu.es.entity.HealthEduArticlePatient> healthEduArticlePatients = gcEduArticleService.getSaveArticle(patientSet, "", "", sendType, "", 0L, articleId, articlePic, articleTitle, articleContent, articleType, level1Type, level2Type, level,articleUrl);
//            //推送微信模板消息和发送im消息
//            new Thread(() -> {
//                //发送任务到redis
//                sender(healthEduArticlePatients);
//            }).start();
//            return new BaseResultModel();
//        }catch (Exception e) {
//            return new BaseResultModel(BaseResultModel.statusEm.opera_error.getCode(), BaseResultModel.statusEm.opera_error.getMessage() + ":" + e.getMessage());
//        }
//
//    }
//}

+ 314 - 314
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/service/GcEduArticleService.java

@ -1,92 +1,113 @@
package com.yihu.wlyy.web.third.gateway.service;
import com.yihu.wlyy.config.es.ElastricSearchSave;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.app.health.HealthEduArticleOpHistoryService;
import com.yihu.wlyy.util.ElasticsearchUtil;
import com.yihu.wlyy.web.third.gateway.vo.HealthEduArticlePatientModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by chenweida on 2017/8/31.
 */
@Service
public class GcEduArticleService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
    @Autowired
    private HealthEduArticlePatientDao healthEduArticlePatientDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private ElastricSearchSave elastricSearchSave;
    @Value("${es.type.HealthEduArticlePatient}")
    private String esType;
    @Value("${es.index.HealthEduArticlePatient}")
    private String esIndex;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    /**
     * 初始化需要发送的患者
     *
     * @param patientSet
     * @param patients
     * @param labelType
     * @param labelCode
     * @param teamId
     */
    public void initPatient(Set<String> patientSet, String[] patients, String[] unPatients, String labelType, String labelCode, Long teamId) {
        List params = new ArrayList();//sql参数
        StringBuffer sb = new StringBuffer();//sql
        //1 服务类型  2 健康情况 3 疾病类型 4 自定义标签
        if (!org.springframework.util.StringUtils.isEmpty(labelType)) {
//package com.yihu.wlyy.web.third.gateway.service;
//
//import com.yihu.wlyy.config.es.ElastricSearchSave;
//import com.yihu.wlyy.entity.doctor.profile.Doctor;
//import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
//import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
//import com.yihu.wlyy.entity.patient.SignFamily;
//import com.yihu.wlyy.repository.doctor.DoctorDao;
//import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
//import com.yihu.wlyy.repository.patient.SignFamilyDao;
//import com.yihu.wlyy.service.app.health.HealthEduArticleOpHistoryService;
//import com.yihu.wlyy.util.ElasticsearchUtil;
//import com.yihu.wlyy.web.third.gateway.vo.HealthEduArticlePatientModel;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
//
//import java.util.*;
//
///**
// * Created by chenweida on 2017/8/31.
// */
//@Service
//public class GcEduArticleService {
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
//    @Autowired
//    private HealthEduArticlePatientDao healthEduArticlePatientDao;
//    @Autowired
//    private DoctorDao doctorDao;
//
//    @Autowired
//    private ElastricSearchSave elastricSearchSave;
//
//    @Value("${es.type.HealthEduArticlePatient}")
//    private String esType;
//    @Value("${es.index.HealthEduArticlePatient}")
//    private String esIndex;
//
//    @Autowired
//    private ElasticsearchUtil elasticsearchUtil;
//
//    /**
//     * 初始化需要发送的患者
//     *
//     * @param patientSet
//     * @param patients
//     * @param labelType
//     * @param labelCode
//     * @param teamId
//     */
//    public void initPatient(Set<String> patientSet, String[] patients, String[] unPatients, String labelType, String labelCode, Long teamId) {
//        List params = new ArrayList();//sql参数
//        StringBuffer sb = new StringBuffer();//sql
//        //1 服务类型  2 健康情况 3 疾病类型 4 自定义标签
//        if (!org.springframework.util.StringUtils.isEmpty(labelType)) {
////            switch (labelType) {
////                case "1": {
////                    sb.append(" SELECT " +
////                            "  w.patient " +
////                            "FROM " +
////                            "  wlyy_sign_family w " +
////                            " WHERE " +
////                            "  w.`status` > 0 " +
////                            " AND w.code in ( select sign_code from  " +
////                            "  wlyy_sign_family_server where server_type=? ) ");
////                    params.add(labelCode);
////
////                    if (teamId != null && teamId > 0) {
////                        sb.append(" and w.admin_team_code=? ");
////                        params.add(teamId);
////                    }
////                    break;
////                }
////                case "2":
////                case "3":
////                case "4": {
////                    sb.append("SELECT w.patient FROM wlyy_sign_family w " +
////                            "WHERE " +
////                            "  w.patient in (SELECT  l.patient FROM  wlyy_sign_patient_label_info l WHERE l.label_type = ? AND l.label = ? and l.status=1) " +
////                            "AND w.`status` > 0");
////                    params.add(labelType);
////                    params.add(labelCode);
////                    if (teamId != null && teamId > 0) {
////                        sb.append(" and w.admin_team_code=? ");
////                        params.add(teamId);
////                    }
////                    break;
////                }
////            }
//
//            switch (labelType) {
//                case "1": {
//                    sb.append(" SELECT " +
//                            "  w.patient " +
//                            "FROM " +
//                            "  wlyy_sign_family w " +
//                            " WHERE " +
//                            "  w.`status` > 0 " +
//                            " AND w.code in ( select sign_code from  " +
//                            "  wlyy_sign_family_server where server_type=? ) ");
//                case "1":{
//                    sb.append(" select w.patient FROM wlyy_sign_family w  left join wlyy_sign_family_server s on w.code=s.sign_code " +
//                            "where w.`status` > 0 and s.server_type=? ");
//                    params.add(labelCode);
//
//                    if (teamId != null && teamId > 0) {
//                        sb.append(" and w.admin_team_code=? ");
//                        params.add(teamId);
//                    }
//                    break;
//                }
//                case "2":
//                case "3":
//                case "4": {
//                    sb.append("SELECT w.patient FROM wlyy_sign_family w " +
//                            "WHERE " +
//                            "  w.patient in (SELECT  l.patient FROM  wlyy_sign_patient_label_info l WHERE l.label_type = ? AND l.label = ? and l.status=1) " +
//                            "AND w.`status` > 0");
//                case "4":{
//                    sb.append(" SELECT w.patient FROM wlyy_sign_family w left join wlyy_sign_patient_label_info l on w.patient = l.patient " +
//                            "where w.`status` > 0 and l.label_type = ? AND l.label = ? and l.status=1 ");
//                    params.add(labelType);
//                    params.add(labelCode);
//                    if (teamId != null && teamId > 0) {
@ -96,233 +117,212 @@ public class GcEduArticleService {
//                    break;
//                }
//            }
            switch (labelType) {
                case "1":{
                    sb.append(" select w.patient FROM wlyy_sign_family w  left join wlyy_sign_family_server s on w.code=s.sign_code " +
                            "where w.`status` > 0 and s.server_type=? ");
                    params.add(labelCode);
                }
                case "2":
                case "3":
                case "4":{
                    sb.append(" SELECT w.patient FROM wlyy_sign_family w left join wlyy_sign_patient_label_info l on w.patient = l.patient " +
                            "where w.`status` > 0 and l.label_type = ? AND l.label = ? and l.status=1 ");
                    params.add(labelType);
                    params.add(labelCode);
                    if (teamId != null && teamId > 0) {
                        sb.append(" and w.admin_team_code=? ");
                        params.add(teamId);
                    }
                    break;
                }
            }
            List<String> groupPatient = jdbcTemplate.queryForList(sb.toString(), String.class, params.toArray());
            patientSet.addAll(groupPatient);
        }
        if (patients != null && patients.length > 0) {
            List<String> arrPatient = java.util.Arrays.asList(patients);
            patientSet.addAll(arrPatient);
        }
        if (unPatients != null && unPatients.length > 0) {
            for (String unPatient : unPatients) {
                if (patientSet.contains(unPatient)) {
                    patientSet.remove(unPatient);
                }
            }
        }
    }
    /**
     * 保存发送信息
     *
     * @param patientSet   患者set集和
     * @param sendCode     发送人code、
     * @param sendName     发送人名称
     * @param sendMessage  发送人携带的信息
     * @param teamId       发送人所属团队
     * @param articleId    文章列表
     * @param articlePic   文件封面
     * @param articleTitle 文章主题
     */
    @Transactional
    public List<com.yihu.es.entity.HealthEduArticlePatient> getSaveArticle(Set<String> patientSet,
                                                                        String sendCode,
                                                                        String sendName,
                                                                        Integer sendType,
                                                                        String sendMessage,
                                                                        Long teamId,
                                                                        String articleId,
                                                                        String articlePic,
                                                                        String articleTitle,
                                                                        String articleContent,
                                                                        String articleType,
                                                                        String level1Type,
                                                                        String level2Type,
                                                                        String level,
                                                                        String articleUrl) {
        List<com.yihu.es.entity.HealthEduArticlePatient> healthEduArticlePatients = new ArrayList<>();
        Doctor doctor = doctorDao.findByCode(sendCode);
        String batchNo = UUID.randomUUID().toString();
        Date createTime = new Date();
        for (String patient : patientSet) {
            SignFamily signFamily = signFamilyDao.findByjiatingPatient(patient);
            if (signFamily == null) {
                continue;
            }
            com.yihu.es.entity.HealthEduArticlePatient healthEduArticlePatient = new com.yihu.es.entity.HealthEduArticlePatient();
            healthEduArticlePatient.setSendCode(sendCode);
            healthEduArticlePatient.setSendName(sendName);
            healthEduArticlePatient.setSendType(sendType);
            healthEduArticlePatient.setPatient(patient);
            healthEduArticlePatient.setPatientName(signFamily.getName());
            healthEduArticlePatient.setAdminTeamCode(teamId);
            if (doctor != null) {
                healthEduArticlePatient.setHospital(doctor.getHospital());
                healthEduArticlePatient.setHospitalName(doctor.getHospitalName());
                healthEduArticlePatient.setTown(doctor.getTown());
                healthEduArticlePatient.setTownName(doctor.getTownName());
                healthEduArticlePatient.setSendLevel(doctor.getLevel()!=null?String.valueOf(doctor.getLevel()):"");
                healthEduArticlePatient.setSendPic(doctor.getPhoto());
                healthEduArticlePatient.setSendSex(doctor.getSex()!=null?String.valueOf(doctor.getSex()):"");
            }
            healthEduArticlePatient.setBatchNo(batchNo);
            healthEduArticlePatient.setCreateTime(createTime);
            healthEduArticlePatient.setArticleId(articleId);
            healthEduArticlePatient.setAttachedTitle(articleTitle);
            healthEduArticlePatient.setAttachedPic(articlePic);
            healthEduArticlePatient.setAttachedContent(articleContent);
            healthEduArticlePatient.setAttachedMessage(sendMessage);
            healthEduArticlePatient.setArticleType(articleType);
            healthEduArticlePatient.setLevel(level);
            healthEduArticlePatient.setLevel1Type(level1Type);
            healthEduArticlePatient.setLevel2Type(level2Type);
            healthEduArticlePatient.setType("1");//文章
            healthEduArticlePatient.setArticleUrl(articleUrl);
            healthEduArticlePatients.add(healthEduArticlePatient);
        }
        //保存到ES中
        elastricSearchSave.save(healthEduArticlePatients, esIndex, esType);
        return healthEduArticlePatients;
    }
    public List<HealthEduArticlePatientModel> getPatientHealthLogs(String sendCode, String articleType, String level1Type, String level2Type, String level, String attachedTitle, String startTime, String endTime, int page, int pagesize) {
        pagesize = page * pagesize;
        page = (page - 1) * pagesize;
        StringBuffer sql = new StringBuffer("select *,count(articleId) allCount from health_edu_article_patient_test  " +
                " where  sendCode='" + sendCode + "' ");
        if (!StringUtils.isEmpty(articleType)) {
            sql.append(" and  articleType='" + articleType + "'  ");
        }
        if (!StringUtils.isEmpty(attachedTitle)) {
            sql.append(" and  attachedTitle like '%" + attachedTitle + "%'  ");
        }
        if (!StringUtils.isEmpty(level1Type)) {
            sql.append(" and  level1Type='" + level1Type + "'  ");
        }
        if (!StringUtils.isEmpty(level2Type)) {
            sql.append(" and  level2Type='" + level2Type + "'  ");
        }
        if (!StringUtils.isEmpty(level)) {
            sql.append(" and  level='" + level + "'  ");
        }
        if (!StringUtils.isEmpty(startTime)) {
            sql.append(" and  createTime>='" + changeDate(startTime) + "'  ");
        }
        if (!StringUtils.isEmpty(endTime)) {
            sql.append(" and  createTime<='" + changeDate(endTime) + "'  ");
        }
        sql.append(" group by articleId order by createTime limit " + page + "," + pagesize);
        List<com.yihu.es.entity.HealthEduArticlePatient> esList = elasticsearchUtil.excute(sql.toString(), com.yihu.es.entity.HealthEduArticlePatient.class, esIndex, esType);
        List<HealthEduArticlePatientModel> returnList = new ArrayList<>();
        esList.stream().forEach(one -> {
            com.yihu.es.entity.HealthEduArticlePatient p = findOne(one.getArticleId());
            if (p != null) {
                p.setAllCount(one.getAllCount());
                HealthEduArticlePatientModel heapm = new HealthEduArticlePatientModel();
                BeanUtils.copyProperties(p, heapm);
                returnList.add(heapm);
            }
        });
        return returnList;
    }
    private com.yihu.es.entity.HealthEduArticlePatient findOne(String articleId) {
        String sql = "select level,level2Type,level1Type,attachedContent,attachedTitle,articleId,createTime,articleType,sendCode,sendName from health_edu_article_patient_test where articleId='" + articleId + "' order by createTime desc limit 0,1";
        com.yihu.es.entity.HealthEduArticlePatient esList = (com.yihu.es.entity.HealthEduArticlePatient) elasticsearchUtil.excuteOneObject(sql, com.yihu.es.entity.HealthEduArticlePatient.class, esIndex, esType);
        return esList;
    }
    public Long getPatientHealthLogsCount(String sendCode, String articleType, String level1Type, String level2Type, String level, String attachedTitle, String startTime, String endTime) {
        StringBuffer sql = new StringBuffer("select count(distinct articleId) count from health_edu_article_patient_test  " +
                " where  sendCode='" + sendCode + "' ");
        if (!StringUtils.isEmpty(articleType)) {
            sql.append(" and  articleType='" + articleType + "'  ");
        }
        if (!StringUtils.isEmpty(attachedTitle)) {
            sql.append(" and  attachedTitle like '%" + attachedTitle + "%'  ");
        }
        if (!StringUtils.isEmpty(level1Type)) {
            sql.append(" and  level1Type='" + level1Type + "'  ");
        }
        if (!StringUtils.isEmpty(level2Type)) {
            sql.append(" and  level2Type='" + level2Type + "'  ");
        }
        if (!StringUtils.isEmpty(level)) {
            sql.append(" and  level='" + level + "'  ");
        }
        if (!StringUtils.isEmpty(startTime)) {
            sql.append(" and  createTime>='" + changeDate(startTime) + "'  ");
        }
        if (!StringUtils.isEmpty(endTime)) {
            sql.append(" and  createTime<='" + changeDate(endTime) + "'  ");
        }
        sql.append(" group by articleId ");
        return elasticsearchUtil.excuteForLong(sql.toString(), esIndex, esType);
    }
    private String changeDate(String quotaDate) {
        return quotaDate + "T00:00:00+0800";
    }
    public void initPatient(Set<String> patientSet,String labelUnit,String labelSex,String labelServe,String labelDisease,String labelHealth){
        String tableSql = " select w.patient from wlyy_sign_family w ";
        String whereSql = " where w.status>0  ";
        if(!StringUtils.isEmpty(labelServe)){
            tableSql += " left join wlyy_sign_family_server s on w.code= s.sign_code ";
            whereSql += " and s.server_type in ("+labelServe+" ) ";
        }
        if(!StringUtils.isEmpty(labelHealth)||!StringUtils.isEmpty(labelDisease)){
            tableSql += " left join wlyy_sign_patient_label_info l on w.patient=l.patient ";
            whereSql += " and l.status=1 ";
            whereSql += " and ( ";
        }
        if(!StringUtils.isEmpty(labelHealth)){
            whereSql += " (l.label_type = 2 AND l.label in ("+labelHealth+")) ";
        }
        if(!StringUtils.isEmpty(labelDisease)){
            if(!whereSql.endsWith(" and ( ")) {
                whereSql += " or (l.label_type = 3 AND l.label in ("+labelDisease+"))) ";
            }else{
                whereSql += " (l.label_type = 1 AND l.label in ("+labelDisease+"))) ";
            }
        }
        if(!StringUtils.isEmpty(labelSex)){
            tableSql += " left join wlyy_patient p on p.code=w.patient ";
            whereSql += " and p.sex in ("+labelSex+") ";
        }
        if(!StringUtils.isEmpty(labelUnit)){
            whereSql += " and w.hospital in ("+labelUnit+") ";
        }
        List<String> groupPatient = jdbcTemplate.queryForList(tableSql+whereSql, String.class);
        patientSet.addAll(groupPatient);
    }
}
//            List<String> groupPatient = jdbcTemplate.queryForList(sb.toString(), String.class, params.toArray());
//            patientSet.addAll(groupPatient);
//        }
//        if (patients != null && patients.length > 0) {
//            List<String> arrPatient = java.util.Arrays.asList(patients);
//            patientSet.addAll(arrPatient);
//        }
//        if (unPatients != null && unPatients.length > 0) {
//            for (String unPatient : unPatients) {
//                if (patientSet.contains(unPatient)) {
//                    patientSet.remove(unPatient);
//                }
//            }
//        }
//    }
//
//    /**
//     * 保存发送信息
//     *
//     * @param patientSet   患者set集和
//     * @param sendCode     发送人code、
//     * @param sendName     发送人名称
//     * @param sendMessage  发送人携带的信息
//     * @param teamId       发送人所属团队
//     * @param articleId    文章列表
//     * @param articlePic   文件封面
//     * @param articleTitle 文章主题
//     */
//    @Transactional
//    public List<com.yihu.es.entity.HealthEduArticlePatient> getSaveArticle(Set<String> patientSet,
//                                                                        String sendCode,
//                                                                        String sendName,
//                                                                        Integer sendType,
//                                                                        String sendMessage,
//                                                                        Long teamId,
//                                                                        String articleId,
//                                                                        String articlePic,
//                                                                        String articleTitle,
//                                                                        String articleContent,
//                                                                        String articleType,
//                                                                        String level1Type,
//                                                                        String level2Type,
//                                                                        String level,
//                                                                        String articleUrl) {
//        List<com.yihu.es.entity.HealthEduArticlePatient> healthEduArticlePatients = new ArrayList<>();
//
//        Doctor doctor = doctorDao.findByCode(sendCode);
//        String batchNo = UUID.randomUUID().toString();
//        Date createTime = new Date();
//        for (String patient : patientSet) {
//            SignFamily signFamily = signFamilyDao.findByjiatingPatient(patient);
//            if (signFamily == null) {
//                continue;
//            }
//            com.yihu.es.entity.HealthEduArticlePatient healthEduArticlePatient = new com.yihu.es.entity.HealthEduArticlePatient();
//            healthEduArticlePatient.setSendCode(sendCode);
//            healthEduArticlePatient.setSendName(sendName);
//            healthEduArticlePatient.setSendType(sendType);
//            healthEduArticlePatient.setPatient(patient);
//            healthEduArticlePatient.setPatientName(signFamily.getName());
//            healthEduArticlePatient.setAdminTeamCode(teamId);
//            if (doctor != null) {
//                healthEduArticlePatient.setHospital(doctor.getHospital());
//                healthEduArticlePatient.setHospitalName(doctor.getHospitalName());
//                healthEduArticlePatient.setTown(doctor.getTown());
//                healthEduArticlePatient.setTownName(doctor.getTownName());
//                healthEduArticlePatient.setSendLevel(doctor.getLevel()!=null?String.valueOf(doctor.getLevel()):"");
//                healthEduArticlePatient.setSendPic(doctor.getPhoto());
//                healthEduArticlePatient.setSendSex(doctor.getSex()!=null?String.valueOf(doctor.getSex()):"");
//            }
//            healthEduArticlePatient.setBatchNo(batchNo);
//            healthEduArticlePatient.setCreateTime(createTime);
//
//            healthEduArticlePatient.setArticleId(articleId);
//            healthEduArticlePatient.setAttachedTitle(articleTitle);
//            healthEduArticlePatient.setAttachedPic(articlePic);
//            healthEduArticlePatient.setAttachedContent(articleContent);
//            healthEduArticlePatient.setAttachedMessage(sendMessage);
//            healthEduArticlePatient.setArticleType(articleType);
//            healthEduArticlePatient.setLevel(level);
//            healthEduArticlePatient.setLevel1Type(level1Type);
//            healthEduArticlePatient.setLevel2Type(level2Type);
//            healthEduArticlePatient.setType("1");//文章
//            healthEduArticlePatient.setArticleUrl(articleUrl);
//            healthEduArticlePatients.add(healthEduArticlePatient);
//
//        }
//        //保存到ES中
//        elastricSearchSave.save(healthEduArticlePatients, esIndex, esType);
//        return healthEduArticlePatients;
//    }
//
//    public List<HealthEduArticlePatientModel> getPatientHealthLogs(String sendCode, String articleType, String level1Type, String level2Type, String level, String attachedTitle, String startTime, String endTime, int page, int pagesize) {
//        pagesize = page * pagesize;
//        page = (page - 1) * pagesize;
//
//        StringBuffer sql = new StringBuffer("select *,count(articleId) allCount from health_edu_article_patient_test  " +
//                " where  sendCode='" + sendCode + "' ");
//        if (!StringUtils.isEmpty(articleType)) {
//            sql.append(" and  articleType='" + articleType + "'  ");
//        }
//        if (!StringUtils.isEmpty(attachedTitle)) {
//            sql.append(" and  attachedTitle like '%" + attachedTitle + "%'  ");
//        }
//        if (!StringUtils.isEmpty(level1Type)) {
//            sql.append(" and  level1Type='" + level1Type + "'  ");
//        }
//        if (!StringUtils.isEmpty(level2Type)) {
//            sql.append(" and  level2Type='" + level2Type + "'  ");
//        }
//        if (!StringUtils.isEmpty(level)) {
//            sql.append(" and  level='" + level + "'  ");
//        }
//        if (!StringUtils.isEmpty(startTime)) {
//
//            sql.append(" and  createTime>='" + changeDate(startTime) + "'  ");
//        }
//        if (!StringUtils.isEmpty(endTime)) {
//            sql.append(" and  createTime<='" + changeDate(endTime) + "'  ");
//        }
//        sql.append(" group by articleId order by createTime limit " + page + "," + pagesize);
//        List<com.yihu.es.entity.HealthEduArticlePatient> esList = elasticsearchUtil.excute(sql.toString(), com.yihu.es.entity.HealthEduArticlePatient.class, esIndex, esType);
//        List<HealthEduArticlePatientModel> returnList = new ArrayList<>();
//        esList.stream().forEach(one -> {
//            com.yihu.es.entity.HealthEduArticlePatient p = findOne(one.getArticleId());
//            if (p != null) {
//                p.setAllCount(one.getAllCount());
//                HealthEduArticlePatientModel heapm = new HealthEduArticlePatientModel();
//                BeanUtils.copyProperties(p, heapm);
//                returnList.add(heapm);
//            }
//        });
//        return returnList;
//    }
//
//    private com.yihu.es.entity.HealthEduArticlePatient findOne(String articleId) {
//        String sql = "select level,level2Type,level1Type,attachedContent,attachedTitle,articleId,createTime,articleType,sendCode,sendName from health_edu_article_patient_test where articleId='" + articleId + "' order by createTime desc limit 0,1";
//        com.yihu.es.entity.HealthEduArticlePatient esList = (com.yihu.es.entity.HealthEduArticlePatient) elasticsearchUtil.excuteOneObject(sql, com.yihu.es.entity.HealthEduArticlePatient.class, esIndex, esType);
//        return esList;
//    }
//
//    public Long getPatientHealthLogsCount(String sendCode, String articleType, String level1Type, String level2Type, String level, String attachedTitle, String startTime, String endTime) {
//        StringBuffer sql = new StringBuffer("select count(distinct articleId) count from health_edu_article_patient_test  " +
//                " where  sendCode='" + sendCode + "' ");
//        if (!StringUtils.isEmpty(articleType)) {
//            sql.append(" and  articleType='" + articleType + "'  ");
//        }
//        if (!StringUtils.isEmpty(attachedTitle)) {
//            sql.append(" and  attachedTitle like '%" + attachedTitle + "%'  ");
//        }
//        if (!StringUtils.isEmpty(level1Type)) {
//            sql.append(" and  level1Type='" + level1Type + "'  ");
//        }
//        if (!StringUtils.isEmpty(level2Type)) {
//            sql.append(" and  level2Type='" + level2Type + "'  ");
//        }
//        if (!StringUtils.isEmpty(level)) {
//            sql.append(" and  level='" + level + "'  ");
//        }
//        if (!StringUtils.isEmpty(startTime)) {
//
//            sql.append(" and  createTime>='" + changeDate(startTime) + "'  ");
//        }
//        if (!StringUtils.isEmpty(endTime)) {
//            sql.append(" and  createTime<='" + changeDate(endTime) + "'  ");
//        }
//        sql.append(" group by articleId ");
//        return elasticsearchUtil.excuteForLong(sql.toString(), esIndex, esType);
//    }
//
//    private String changeDate(String quotaDate) {
//        return quotaDate + "T00:00:00+0800";
//    }
//
//    public void initPatient(Set<String> patientSet,String labelUnit,String labelSex,String labelServe,String labelDisease,String labelHealth){
//
//        String tableSql = " select w.patient from wlyy_sign_family w ";
//        String whereSql = " where w.status>0  ";
//
//        if(!StringUtils.isEmpty(labelServe)){
//            tableSql += " left join wlyy_sign_family_server s on w.code= s.sign_code ";
//            whereSql += " and s.server_type in ("+labelServe+" ) ";
//        }
//        if(!StringUtils.isEmpty(labelHealth)||!StringUtils.isEmpty(labelDisease)){
//            tableSql += " left join wlyy_sign_patient_label_info l on w.patient=l.patient ";
//            whereSql += " and l.status=1 ";
//            whereSql += " and ( ";
//        }
//        if(!StringUtils.isEmpty(labelHealth)){
//            whereSql += " (l.label_type = 2 AND l.label in ("+labelHealth+")) ";
//        }
//        if(!StringUtils.isEmpty(labelDisease)){
//            if(!whereSql.endsWith(" and ( ")) {
//                whereSql += " or (l.label_type = 3 AND l.label in ("+labelDisease+"))) ";
//            }else{
//                whereSql += " (l.label_type = 1 AND l.label in ("+labelDisease+"))) ";
//            }
//        }
//        if(!StringUtils.isEmpty(labelSex)){
//            tableSql += " left join wlyy_patient p on p.code=w.patient ";
//            whereSql += " and p.sex in ("+labelSex+") ";
//        }
//        if(!StringUtils.isEmpty(labelUnit)){
//            whereSql += " and w.hospital in ("+labelUnit+") ";
//        }
//        List<String> groupPatient = jdbcTemplate.queryForList(tableSql+whereSql, String.class);
//        patientSet.addAll(groupPatient);
//    }
//}

+ 1 - 0
patient-co/patient-co-wlyy/src/main/resources/application-devtest.yml

@ -78,6 +78,7 @@ images:
sign:
  check_upload: http://172.19.103.88:8011/wlyy_service
  #check_upload: 192.168.131.24:8081
express:

+ 54 - 55
patient-co/patient-co-wlyy/src/main/resources/application-local.yml

@ -3,88 +3,87 @@ spring:
  profiles: local
  datasource:
    wlyy:
      url: jdbc:mysql://172.19.103.85/wlyy?useUnicode:true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: linzhou
      password: linzhou
    health:
      url: jdbc:mysql://172.19.103.85/device?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
      username: linzhou
      password: linzhou
     wlyy:
       url: jdbc:mysql://10.95.22.7:3306/wlyy?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
       username: wlyy
       password: jkzlehr@123
     health:
       url: jdbc:mysql://10.95.22.7:3306/device?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
       username: wlyy
       password: jkzlehr@123
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
#    password: jkzl_ehr
      host: 10.95.22.142 # Redis server host.
      port: 6380 # Redis server port.
      password: jkzlehr
server:
  server_url: http://ehr.yihu.com/wlyy/
  server_url: http://10.95.22.10:8011/wlyy/
im:
  im_list_get: http://172.19.103.88:3000/
  data_base_name: im_new
  im_list_get: http://10.95.22.138:3000/
  data_base_name: im
wechat:
  appId: wx1f129f7b51701428
  appSecret: 988f005d8309ed1795939e0f042431fb
  appId: wxad04e9c4c5255acf
  appSecret: ae77c48ccf1af5d07069f5153d1ac8d3
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fehr.yihu.com%2fwlyy
  wechat_base_url: http%3a%2f%2fwww.xmtyw.cn%2fwlyy
  accId: gh_ffd64560fb21
  message:
    ##医生追加建议提醒 --签约邀请
    doctor_invitel_template:  uXdBJVbrhKG-WLaCG4s8C4SXSr2kknQ94vKFt-3rIiA
    #咨询回复
    template_consult_notice: dr4QNyFoRvVsf8uWxXMC1dRyjwnbUuJwJ21vBLhf18
    #签约成功
    template_sign_success: VYGj8OUKj6FH4i4_nZS2UAHurJxQHx-7_OBPILIdB8s
    #签约失败
    template_sign_failed: m221Jrkm0UUY00ExTCpQNTB8t_1U_V4LR9Bg8BgH9-o
    #健康指导提醒
    template_health_notice: 5Nts8lA_at9Cd1JuTK-qDxx95lchpcmUfPTEwYDgXYQ
    #解约提醒
    template_termination:  qZm1NwSueAsbHaOf9DrnLoSj0X5gZuh9W7aDYzLWNds
    #预约成功
    template_appoint_success:  vU5x2tGyk1zUngBrEqMfnFqqMa6M8J98w8k5MCSUYM
    #预约取消
    template_appoint_failed:  r-bVEKgXVyl8O96saoJXlLd7DX1zW7fXA4a0PZHxiQM
    #缴费提醒
    template_expenses_remind:  pZby4Mz3H5angmjGTuvXzo9lwlaVfEiqORwI8soI-5E
    #健康教育
    template_healthy_article: aO_qqk5nAXaGXhsikPVLNelqzwlrp1LTPfIQ1qRMpxo
    #医生变更
    template_doctor_change:  V5h0F84t972kUzQvWy8qYrgdaYGJVj10pFeFVl19Nb8
    #问卷调查
    template_doctor_survey:  OqQXrb-e43_TJpq_70_K_y6vYJgY5mpjFYY4c5RWFP4
    #审核结果通知
    template_doctor_audit:  lCtOgJgL1tBJbAytqN7cn-FgCH_Usg99FENEy2TrC08
    #服务结果通知
    template_doctor_service: i34rq3xFLnpf_VN2Jor9n2YlQqJMM7oXyYvuctriISw
     ##医生追加建议提醒 --签约邀请
     doctor_invitel_template: MQn79bx1ofb6hekhmRIuqLU7KjySJQzaBzrimgqVrzA
     #咨询回复
     template_consult_notice: 0mF_vHj-ILx8EH8DwzmAi7LqzjqYiU9IrSRRmziTZyc
     #签约成功
     template_sign_success: 0D2vYZVRzFz15p9Y_pkZ1DKutDq8UOsks79FXUKS0tA
     #签约失败
     template_sign_failed: My2VNERjJt4NXR4Ibh42pdrP6B6ka8rQxZeWinQh99s
     #健康指导提醒
     template_health_notice: uv31ES_VCmq3tBYtyGmEQvIwU_zh9LDhF3bFpbIUt5g
     #解约提醒
     template_termination:  C0tdXtA_8k-Cy4a1EkzQuI877vqaqAtRkc-e_Gsd7sk
     #预约成功
     template_appoint_success:  FY3Pqa66tHIE1Fv-irbFBPOh5cYP71fkOzfZKH4S-Fo
     #预约取消
     template_appoint_failed:  tldWEb9AN7p_RoHoD8ml0GxWW3V1V_mpEEhp2v6p56s
     #缴费提醒
     template_expenses_remind:  AcrlihhoGbm22A8cdFFDQ4u38ptRw0aiIPf-aGvNxMM
     #健康教育
     template_healthy_article: a5-ZGf-IUUULsuRNoHWQiBMU6pSYhLgPPqV67SjdLRo
     #医生变更
     template_doctor_change:  dtzSHImbPKfwcrjWlJEjAw3lGlvrLjsobSOE8g4adZA
     #问卷调查
     template_doctor_survey:  8ZWKJmoJ7VR7Uk4YS7aa0Z94QzCkxsyTW6R4CHhUJII
     #审核结果通知
     template_doctor_audit:  egrX5Larpkv8opQW67_hwsZoT0OHwwUpE1v7HeU_Jnw
     #服务结果通知
     template_doctor_service:  xhi1LEudiZwJfZylOHuZNo8EiA73GtSshPQv5XOt9Lk
yihu:
  yihu_OpenPlatform_url: http://ssotest.yihu.cn/OpenPlatform/cgiBin/1.0/
  yihu_OpenPlatform_url: http://api.yihu.com.cn/OpenPlatform/cgiBin/1.0/
  yihu_OpenPlatform_appId: 9000276
  yihu_OpenPlatform_secret: OKC8BS1KGXTDE9GPP1EO4VYLUXF8DJ7QUP72H613ZXA
  yihu_OpenPlatform_secret: 2JGL19AH3JS55MQY6ZOFJE1JZJ1OF23GWV67MCDQV74
fastDFS:
  fastdfs_file_url: http://172.19.103.54:80/
  fastdfs_file_url: http://10.95.22.10:8011/
images:
  path: /var/local/upload/images
  renew_path: /usr/local/apache-tomcat-8.0.36/webapps/wlyy/images/renew.png
  sign_path: /usr/local/apache-tomcat-8.0.36/webapps/wlyy/images/familycontract.png
sign:
  check_upload: http://172.19.103.88:8011/wlyy_service
  check_upload: http://10.95.22.10:8011/wlyy_service
express:
  sf_url: http://218.17.248.244:11080/bsp-oisp/sfexpressService
  sf_url: http://bsp-ois.sit.sf-express.com:9080/bsp-ois/sfexpressService
#  sf_url: https://bsp-ois.sit.sf-express.com:9443/bsp-ois/sfexpressServic
  sf_code: SDDF
  sf_check_word: ttzlgGyOQu4L
  sf_code: BSPdevelop
  sf_check_word: j8DzkIFgmlomPt0aLuwU
pushMes:
# 1为推送redis,0为推送消息队列
  method: 1
@ -100,7 +99,6 @@ es:
  tPort: 9300
  clusterName: jkzl
#消息队列
activemq:
  username: admin
@ -108,3 +106,4 @@ activemq:
  url: tcp://172.19.103.87:61616
  queue:
    healtHarticleQueue: healthArticleChannel_devtest  #健康文章推送

+ 1 - 1
patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu_jimei.txt

@ -61,7 +61,7 @@
	  "sub_button":[
		{
		   "type":"view",
		   "name":"签约特色服务",
		   "name":"集美家签特色",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fdist%2fhtml%2fexclusive-service.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
		{