trick9191 před 7 roky
rodič
revize
3bfed0ae6d
32 změnil soubory, kde provedl 1781 přidání a 487 odebrání
  1. 18 0
      common/common-entity/src/main/java/com/yihu/es/entity/HealthEduArticlePatient.java
  2. 139 0
      common/common-entity/src/main/java/com/yihu/wlyy/entity/message/MessageNoticeSetting.java
  3. 8 4
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftBaseService.java
  4. 8 6
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java
  5. 11 16
      patient-co-service/wlyy_service/src/main/resources/application.yml
  6. 90 90
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/activemq/StartListener.java
  7. 70 70
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  8. 2 2
      patient-co/patient-co-wlyy-job/src/main/resources/application-devtest.yml
  9. 59 59
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  10. 19 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/message/MessageNoticeSettingDao.java
  11. 5 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java
  12. 19 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/PatientInfoService.java
  13. 37 10
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java
  14. 62 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/message/MessageService.java
  15. 270 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java
  16. 117 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/message/SendMessageService.java
  17. 1 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java
  18. 402 148
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/fzzb/HealthEducationArticleService.java
  19. 55 18
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/CommonUtil.java
  20. 49 27
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java
  21. 80 4
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthEduArticleController.java
  22. 39 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/message/DoctorMessageController.java
  23. 66 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/PatientInfoController.java
  24. 96 6
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/EsStatisticsController.java
  25. 3 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcEduArticleController.java
  26. 13 8
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/service/GcEduArticleService.java
  27. 18 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/vo/HealthEduArticlePatientModel.java
  28. 17 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/wechat/util/WeiXinTempMsgSendUtils.java
  29. 1 1
      patient-co/patient-co-wlyy/src/main/resources/application-dev.yml
  30. 3 3
      patient-co/patient-co-wlyy/src/main/resources/application-devtest.yml
  31. 1 1
      patient-co/patient-co-wlyy/src/main/resources/application-localtest.yml
  32. 3 3
      patient-co/patient-co-wlyy/src/main/resources/application-test.yml

+ 18 - 0
common/common-entity/src/main/java/com/yihu/es/entity/HealthEduArticlePatient.java

@ -20,6 +20,8 @@ public class HealthEduArticlePatient {
    private String patient; // 患者标识
    @Transient
    private String patientName;    // 患者标识
    private String doctorCode;  //推送的医生code(包括医生本人、卫计委)
    private String doctorName;  //推送的医生名称(包括医生本人、卫计委)
    private String sendCode;   // 发送人code
    private String sendName;   // 发送人名称
    private String sendPic;   // 发送人头像
@ -292,4 +294,20 @@ public class HealthEduArticlePatient {
    public void setPatients(List<Patient> patients) {
        this.patients = patients;
    }
    public String getDoctorCode() {
        return doctorCode;
    }
    public void setDoctorCode(String doctorCode) {
        this.doctorCode = doctorCode;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
}

+ 139 - 0
common/common-entity/src/main/java/com/yihu/wlyy/entity/message/MessageNoticeSetting.java

@ -0,0 +1,139 @@
package com.yihu.wlyy.entity.message;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.wlyy.entity.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 消息提醒设置
 * @author yeshijie on 2017/11/27.
 *
 */
@Entity
@Table(name = "wlyy_message_notice_setting")
public class MessageNoticeSetting extends IdEntity{
    private String user;//'用户code'
    private String type;// '类型(1医生,2居民)'
    private Integer masterSwitch;// '总开关' (1开,0关)
    private Integer imSwitch;//'im消息开关'(1开,0关)
    private Integer familyTopicSwitch;// '健管师邀请后推送开关'(1开,0关)
    private Integer signSwitch;// '签约消息开关'(1开,0关)
    private Integer healthSignSwitch;// '体征消息开关'(1开,0关)
    private Integer systemSwitch;// '系统消息开关'(1开,0关)
    private Integer prescriptionSwitch;// '续方消息开关'(1开,0关)
    private Integer soundSwitch;// '铃声提醒开关'(1开,0关)
    private Integer vibrationSwitch;// '振动提醒开关'(1开,0关)
    private Integer coordinationSwitch;// '协同消息开关'(1开,0关)
    private Date createTime;// '创建时间'
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public Integer getMasterSwitch() {
        return masterSwitch;
    }
    public void setMasterSwitch(Integer masterSwitch) {
        this.masterSwitch = masterSwitch;
    }
    public Integer getImSwitch() {
        return imSwitch;
    }
    public void setImSwitch(Integer imSwitch) {
        this.imSwitch = imSwitch;
    }
    public Integer getFamilyTopicSwitch() {
        return familyTopicSwitch;
    }
    public void setFamilyTopicSwitch(Integer familyTopicSwitch) {
        this.familyTopicSwitch = familyTopicSwitch;
    }
    public Integer getSignSwitch() {
        return signSwitch;
    }
    public void setSignSwitch(Integer signSwitch) {
        this.signSwitch = signSwitch;
    }
    public Integer getHealthSignSwitch() {
        return healthSignSwitch;
    }
    public void setHealthSignSwitch(Integer healthSignSwitch) {
        this.healthSignSwitch = healthSignSwitch;
    }
    public Integer getSystemSwitch() {
        return systemSwitch;
    }
    public void setSystemSwitch(Integer systemSwitch) {
        this.systemSwitch = systemSwitch;
    }
    public Integer getPrescriptionSwitch() {
        return prescriptionSwitch;
    }
    public void setPrescriptionSwitch(Integer prescriptionSwitch) {
        this.prescriptionSwitch = prescriptionSwitch;
    }
    public Integer getSoundSwitch() {
        return soundSwitch;
    }
    public void setSoundSwitch(Integer soundSwitch) {
        this.soundSwitch = soundSwitch;
    }
    public Integer getVibrationSwitch() {
        return vibrationSwitch;
    }
    public void setVibrationSwitch(Integer vibrationSwitch) {
        this.vibrationSwitch = vibrationSwitch;
    }
    public Integer getCoordinationSwitch() {
        return coordinationSwitch;
    }
    public void setCoordinationSwitch(Integer coordinationSwitch) {
        this.coordinationSwitch = coordinationSwitch;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name="create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 8 - 4
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftBaseService.java

@ -50,6 +50,10 @@ public class ZysoftBaseService {
    private String internet;
    @Value("${zysoftApi.base}")
    private String base;
    @Value("${zysoftApi.imm}")
    private String imm;
    @Value("${zyapi.openCrypto}")
    private Boolean openCrypto;
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
@ -146,13 +150,13 @@ public class ZysoftBaseService {
        int times = 0;
        try {
            re = ZysoftApi.getSingleton().get(baseApi, paramsList, null,true);
            re = ZysoftApi.getSingleton().get(baseApi, paramsList, null,openCrypto);
            if(needRetry)
            {
                while(retryTimes>0 && re.contains("接口调用传入的参数[msgHeader]格式不正确"))    //基卫bug预防,重调接口
                {
                    re = ZysoftApi.getSingleton().post(baseApi, paramsList, null,true);
                    re = ZysoftApi.getSingleton().post(baseApi, paramsList, null,openCrypto);
                    retryTimes --;
                    times++;
                }
@ -221,13 +225,13 @@ public class ZysoftBaseService {
        int times = 0;
        try {
            re = ZysoftApi.getSingleton().post(baseApi, paramsList, null,true);
            re = ZysoftApi.getSingleton().post(baseApi, paramsList, null,openCrypto);
            if(needRetry)
            {
                int maxTimes = retryTimes;
                while(maxTimes>0 && re.contains("接口调用传入的参数[msgHeader]格式不正确"))    //基卫bug预防,重调接口
                {
                    re = ZysoftApi.getSingleton().post(baseApi, paramsList, null,true);
                    re = ZysoftApi.getSingleton().post(baseApi, paramsList, null,openCrypto);
                    maxTimes --;
                    times++;
                }

+ 8 - 6
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java

@ -9,6 +9,7 @@ import com.yihu.wlyy.service.entity.DoctorMapping;
import com.zoe.phip.ssp.sdk.ApiException;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.PrintWriter;
@ -29,7 +30,8 @@ public class ZysoftService {
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${zyapi.openCrypto}")
    private Boolean openCrypto;
    //默认重复次数
    private int retryTimes = 3;
@ -58,13 +60,13 @@ public class ZysoftService {
        int times = 0;
        try {
            re = ZysoftApi.getSingleton().get("base/CallEhrInterface", paramsList, null,true);
            re = ZysoftApi.getSingleton().get("base/CallEhrInterface", paramsList, null,openCrypto);
            if(needRetry)
            {
                while(retryTimes>0 && re.contains("接口调用传入的参数[msgHeader]格式不正确"))    //基卫bug预防,重调接口
                {
                    re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,true);
                    re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,openCrypto);
                    retryTimes --;
                    times++;
                }
@ -130,13 +132,13 @@ public class ZysoftService {
        int times = 0;
        try {
            re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,true);
            re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,openCrypto);
            if(needRetry)
            {
                int maxTimes = retryTimes;
                while(maxTimes>0 && re.contains("接口调用传入的参数[msgHeader]格式不正确"))    //基卫bug预防,重调接口
                {
                    re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,true);
                    re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,openCrypto);
                    maxTimes --;
                    times++;
                }
@ -200,7 +202,7 @@ public class ZysoftService {
        String error = "";
        try {
            re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,true);
            re = ZysoftApi.getSingleton().post("base/CallEhrInterface", paramsList, null,openCrypto);
            Map<String,String> map = objectMapper.readValue(re,Map.class);
            String code = map.get("CODE");

+ 11 - 16
patient-co-service/wlyy_service/src/main/resources/application.yml

@ -74,6 +74,9 @@ spring:
im:
  data_base_name: im_new
zyapi:
  openCrypto: false
---
spring:
  profiles: devtest
@ -92,6 +95,9 @@ spring:
#    password: jkzl_ehr
im:
  data_base_name: im_new
zyapi:
  openCrypto: false
---
spring:
  profiles: test
@ -109,6 +115,9 @@ spring:
#    password: jkzl_ehr
im:
  data_base_name: im_new
zyapi:
  openCrypto: false
---
spring:
  profiles: production
@ -126,20 +135,6 @@ spring:
    password: jkzlehr
im:
  data_base_name: im
---
spring:
  profiles: local
  datasource:
    url: jdbc:mysql://10.95.22.7:3306/wlyy?useUnicode=true&characterEncoding=utf-8&autoReconnect=true
    username: wlyy
    password: jkzlehr@123
    driverClassName: com.mysql.jdbc.Driver
    maxTotal: 500
    maxIdle: 30
  redis:
    host: 10.95.22.142 # Redis server host.
    port: 6380 # Redis server port.
    password: jkzlehr
im:
  data_base_name: im
zyapi:
  openCrypto: true

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

+ 2 - 2
patient-co/patient-co-wlyy-job/src/main/resources/application-devtest.yml

@ -21,7 +21,7 @@ channel:
  redis:
    host: 172.19.103.88 # Redis server host.
    port: 6379 # Redis server port.
    password: jkzl_ehr
    password:
server:
  server_url: http://ehr.yihu.com/wlyy/
@ -105,7 +105,7 @@ activemq:
  password: admin
  url: tcp://172.19.103.87:61616
  queue:
    healtHarticleQueue: healthArticleChannel_devtest  #健康文章推送
    healtHarticleQueue: healthArticleChannel_devtest
  consumers:
    count: 10 #消费者集群数

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

+ 19 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/message/MessageNoticeSettingDao.java

@ -0,0 +1,19 @@
package com.yihu.wlyy.repository.message;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.message.MessageNoticeSetting;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * @author yeshijie on 2017/11/27.
 */
public interface MessageNoticeSettingDao extends PagingAndSortingRepository<MessageNoticeSetting, Long>, JpaSpecificationExecutor<MessageNoticeSetting> {
    @Query("from MessageNoticeSetting a where a.user = ?1 and a.type=?2")
    MessageNoticeSetting findByUserAndType(String user,String type);
    @Query("from MessageNoticeSetting a where a.id = ?1")
    MessageNoticeSetting findById(Long id);
}

+ 5 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/SignFamilyDao.java

@ -29,6 +29,11 @@ public interface SignFamilyDao extends PagingAndSortingRepository<SignFamily, Lo
    @Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1")
    int updatePatientMobile(String patient, String mobile);
    //更新有效签约患者手机号
    @Modifying
    @Query("update SignFamily a set a.mobile = ?2 where a.patient = ?1 and a.status > 0 ")
    int updateSignMobile(String patient, String mobile);
    @Query("select a from SignFamily a where a.idcard = ?1 and status = ?2 and a.type = 2")
    SignFamily findByPatientStatus(String idcard, int status);

+ 19 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/account/PatientInfoService.java

@ -131,6 +131,25 @@ public class PatientInfoService extends BaseService {
        return 1;
    }
    /**
     * 患者更换手机号
     *
     * @param patient 患者code
     * @param mobile  新手机号
     * @return
     */
    public int updateMobile(String patient, String mobile) throws Exception {
        Patient p = patientDao.findByCode(patient);
        if (p == null) {
            return -1;
        }
        p.setMobile(mobile);
        patientDao.save(p);
        signFamilyDao.updateSignMobile(patient, mobile);
        return 1;
    }
    /**
     * 手机号是否注册
     *

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

@ -392,16 +392,22 @@ public class SignPatientLabelInfoService extends BaseService {
//                if (p == null) {
//                    continue;
//                }
                PatientVO p = new PatientVO();
                List<PatientVO> plist = new ArrayList<>();
                if(sign.get("patient") != null){
                    String patientsql = "select a.*,b.deviceType as deviceType,c.disease as disease from wlyy_patient a" +
                            "  left join (select user,sum(category_code) deviceType FROM wlyy_patient_device GROUP BY user) b on a.code = b.user" +
                            "  left join (select patient,group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 and status=1 " +
                            " and (label = 1 or label = 2) and patient = '"+sign.get("patient").toString()+"' GROUP BY patient) c on a.code = c.patient" +
                            " where a.status =1 and a.code = '"+sign.get("patient").toString()+"'";
                    p = (PatientVO)jdbcTemplate.queryForObject(patientsql,new BeanPropertyRowMapper(PatientVO.class));
    
                    plist = jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));
                    
                    if(plist.isEmpty()){
                        continue;
                    }else{
                        p = plist.get(0);
                    }
                }else{
                    continue;
                }
@ -3821,14 +3827,21 @@ public class SignPatientLabelInfoService extends BaseService {
//                }
                //查找居民 改造成获取绑定的设备和疾病类型--huangwenjie-2017.11.21
                PatientVO p = new PatientVO();
                List<PatientVO> plist = new ArrayList<>();
                if(sign.get("patient") != null){
                    String patientsql = "select a.*,b.deviceType as deviceType,c.disease as disease from wlyy_patient a" +
                            "  left join (select user,sum(category_code) deviceType FROM wlyy_patient_device GROUP BY user) b on a.code = b.user" +
                            "  left join (select patient,group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 AND status =1 " +
                            "  left join (select patient,group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 and status=1 " +
                            " and (label = 1 or label = 2) and patient = '"+sign.get("patient").toString()+"' GROUP BY patient) c on a.code = c.patient" +
                            " where a.status =1 and a.code = '"+sign.get("patient").toString()+"'";
                    p = (PatientVO)jdbcTemplate.queryForObject(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        
                    plist = jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        
                    if(plist.isEmpty()){
                        continue;
                    }else{
                        p = plist.get(0);
                    }
                }else{
                    continue;
                }
@ -4259,14 +4272,21 @@ public class SignPatientLabelInfoService extends BaseService {
        if (signList != null && signList.size() > 0) {
            for (Map<String, Object> sign : signList) {
                PatientVO p = new PatientVO();
                List<PatientVO> plist = new ArrayList<>();
                if(sign.get("patient") != null){
                    String patientsql = "select a.*,b.deviceType as deviceType,c.disease as disease from wlyy_patient a" +
                            "  left join (select user,sum(category_code) deviceType FROM wlyy_patient_device GROUP BY user) b on a.code = b.user" +
                            "  left join (select patient,group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 and status=1 " +
                            " and (label = 1 or label = 2) and patient = '"+sign.get("patient").toString()+"' GROUP BY patient) c on a.code = c.patient" +
                            " where a.status =1 and a.code = '"+sign.get("patient").toString()+"'";
                    p = (PatientVO)jdbcTemplate.queryForObject(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        
                    plist = jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        
                    if(plist.isEmpty()){
                        continue;
                    }else{
                        p = plist.get(0);
                    }
                }else{
                    continue;
                }
@ -4463,14 +4483,21 @@ public class SignPatientLabelInfoService extends BaseService {
        if (signList != null && signList.size() > 0) {
            for (Map<String, Object> sign : signList) {
                PatientVO p = new PatientVO();
                List<PatientVO> plist = new ArrayList<>();
                if(sign.get("patient") != null){
                    String patientsql = "select a.*,b.deviceType as deviceType,c.disease as disease from wlyy_patient a" +
                            "  left join (select user,sum(category_code) deviceType FROM wlyy_patient_device GROUP BY user) b on a.code = b.user" +
                            "  left join (select patient,group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 and status=1 " +
                            " and (label = 1 or label = 2) and patient = '"+sign.get("patient").toString()+"' GROUP BY patient) c on a.code = c.patient" +
                            " where a.status =1 and a.code = '"+sign.get("patient").toString()+"'";
                    p = (PatientVO)jdbcTemplate.queryForObject(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        
                    plist = jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        
                    if(plist.isEmpty()){
                        continue;
                    }else{
                        p = plist.get(0);
                    }
                }else{
                    continue;
                }

+ 62 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/message/MessageService.java

@ -3,10 +3,12 @@ package com.yihu.wlyy.service.app.message;
import com.yihu.device.entity.DevicePatientHealthIndex;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.message.MessageNoticeSetting;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.health.repository.DevicePatientHealthIndexDao;
import com.yihu.wlyy.repository.consult.ConsultTeamDao;
import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.message.MessageNoticeSettingDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
@ -21,6 +23,7 @@ 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;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@ -52,6 +55,12 @@ public class MessageService extends BaseService {
    private DevicePatientHealthIndexDao devicePatientHealthIndexDao;
    @Autowired
    private HttpClientUtil HttpClientUtil;
    @Autowired
    private MessageNoticeSettingDao messageNoticeSettingDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String MESSAGE_NOTICESETTING = "wlyy:message:setting:";
    @Value("${im.im_list_get}")
    private String im_list_get;
@ -485,4 +494,57 @@ public class MessageService extends BaseService {
            messageDao.setMessageReaded(doctor, type);
        }
    }
    /**
     * 获取消息提醒设置
     * @param user
     * @param type
     * @return
     */
    public com.alibaba.fastjson.JSONObject getMessageNoticSetting(String user, String type){
        com.alibaba.fastjson.JSONObject re = null;
        String key = MESSAGE_NOTICESETTING+user+":"+type;
        String response = redisTemplate.opsForValue().get(key);
        if(StringUtils.isBlank(response)){
            MessageNoticeSetting messageNoticeSetting = messageNoticeSettingDao.findByUserAndType(user,type);
            if(messageNoticeSetting == null){
                messageNoticeSetting = new MessageNoticeSetting();
                messageNoticeSetting.setCreateTime(new Date());
                messageNoticeSetting.setFamilyTopicSwitch(1);
                messageNoticeSetting.setCoordinationSwitch(1);
                messageNoticeSetting.setHealthSignSwitch(1);
                messageNoticeSetting.setImSwitch(1);
                messageNoticeSetting.setMasterSwitch(1);
                messageNoticeSetting.setPrescriptionSwitch(1);
                messageNoticeSetting.setSignSwitch(1);
                messageNoticeSetting.setSoundSwitch(1);
                messageNoticeSetting.setSystemSwitch(1);
                messageNoticeSetting.setType(type);
                messageNoticeSetting.setUser(user);
                messageNoticeSetting.setVibrationSwitch(1);
                messageNoticeSettingDao.save(messageNoticeSetting);
            }
            response = com.alibaba.fastjson.JSONObject.toJSONString(messageNoticeSetting);
            redisTemplate.opsForValue().set(key,response);
        }
        re = com.alibaba.fastjson.JSONObject.parseObject(response);
        return re;
    }
    /**
     * 更新消息提醒设置
     * @param messageNoticeSetting
     */
    public void saveMessageNoticeSetting(MessageNoticeSetting messageNoticeSetting){
        MessageNoticeSetting oldSetting = messageNoticeSettingDao.findById(messageNoticeSetting.getId());
        messageNoticeSetting.setUser(oldSetting.getUser());
        messageNoticeSetting.setCreateTime(oldSetting.getCreateTime());
        messageNoticeSetting.setType(oldSetting.getType());
        messageNoticeSettingDao.save(messageNoticeSetting);
        //更新缓存
        String key = MESSAGE_NOTICESETTING+oldSetting.getUser()+":"+oldSetting.getType();
        String response = com.alibaba.fastjson.JSONObject.toJSONString(messageNoticeSetting);
        redisTemplate.opsForValue().set(key,response);
    }
}

+ 270 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java

@ -586,9 +586,9 @@ public class StatisticsESService {
     * @param level   级别
     * @return
     */
    public JSONObject getSignRate(String endDate, String area, int level, String year) throws Exception {
    public JSONObject getSignRate(String endDate, String area, int level, String year,String index) throws Exception {
        SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, area, level, "1", "2");
        SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, area, level, index, SaveModel.timeLevel_DDL);
        long signAmount = saveModel.getResult2().longValue();
        PopulationBase peopleNum = getPopulationBase(area, year);
        JSONObject json = new JSONObject();
@ -686,6 +686,73 @@ public class StatisticsESService {
        return json;
    }
    /**
     * 查询截止某个日期线上签约率
     * @author zhangdan 2017-11-27
     *
     * @param endDate
     * @param area
     * @param level
     * @param year
     * @param signAmount
     * @return
     * @throws Exception
     */
    public JSONObject getSignOnlineRate(String endDate, String area, int level, String year,long signAmount) throws Exception {
        if (endDate.compareTo(dateFormat.format(new Date())) >= 0) {
            endDate = elasticsearchUtil.getQuotaTime();
        }
        SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, area, level, "72", "2");
        long signOnLineAmount = saveModel.getResult2().longValue();
        DecimalFormat df = new DecimalFormat("0.0000");
        JSONObject json = new JSONObject();
        json.put("rate", (signOnLineAmount>0 ? df.format((signOnLineAmount * 1.0000) / signAmount * 100):0));
        json.put("rateString", signOnLineAmount + "/" + signAmount);
        json.put("signOnline", signOnLineAmount);
        json.put("sign", signAmount);
        return json;
    }
    public JSONObject getGroupInfoOnline(String endDate, String lowCode, String area, int level, String year) throws Exception {
        List<SaveModel> list = elasticsearchUtil.findDateQuotaLevel1(endDate, endDate, area, level, "17", "2", lowCode, null, null);
        List<SaveModel> onlineList = elasticsearchUtil.findDateQuotaLevel1(endDate, endDate, area, level, "17", "2", lowCode, null, null);
        long total = 0;
        long onlineTotal = 0;
        if (list.size() > 0) {
            total = list.get(0).getResult2().longValue();
        }
        if (onlineList.size() > 0) {
            onlineTotal = onlineList.get(0).getResult2().longValue();
        }
        int num = 0;
        PopulationBase peopleNum = getPopulationBase(area, year);
        if (peopleNum != null) {
            if (lowCode.equals("3")) {
                num = peopleNum.getSixFiveNum();
            } else if (lowCode.equals("1")) {
                num = peopleNum.getGxyNum();
            } else if (lowCode.equals("2")) {
                num = peopleNum.getTnbNum();
            }
        }
        JSONObject json = new JSONObject();
        DecimalFormat df = new DecimalFormat("0.0000");
        json.put("sign", total);
        JSONObject signRate = new JSONObject();
        signRate.put("sign", total);
        signRate.put("people", num);
        signRate.put("rate", df.format((total * 1.0000) / num * 100));
        signRate.put("rateString", total + "/" + num);
        json.put("signRate", signRate);
        JSONObject signOnlineRate = new JSONObject();
        signOnlineRate.put("signOnline", onlineTotal);
        signOnlineRate.put("sign", total);
        signOnlineRate.put("rate", df.format((onlineTotal * 1.0000) / total * 100));
        signOnlineRate.put("rateString", onlineTotal + "/" + total);
        json.put("signOnlineRate", signOnlineRate);
        return json;
    }
    /**
     * 获取2个数的百分比
@ -1782,7 +1849,7 @@ public class StatisticsESService {
                map.put("signRegulationNum", signRegulationNum);//调控量
                if (!low_level.equals("5")) {
                    String code = map.get("code").toString();
                    String code = String.valueOf(map.get("code"));
                    PopulationBase peopleNum = getPopulationBase(code, year);
                    if (peopleNum != null) {
                        map.put("rate", df.format(((long) map.get("amount") * 1.0000) / peopleNum.getNum() * 100));
@ -4173,5 +4240,205 @@ public class StatisticsESService {
        return resultJSON;
    }
    /**
     * 线上签约各个地区等级的到达量情况
     * @author zhangdan 2017-11-28
     *
     * @param date
     * @param area
     * @param level
     * @param index
     * @param sort
     * @param lowLevel
     * @param year
     * @return
     * @throws Exception
     */
    public JSONArray getLowLevelTotalOnlineTeamLeader(String date, String area, int level, String index, int sort, String lowLevel, String year,String lowCode) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String low_level = String.valueOf(org.springframework.util.StringUtils.isEmpty(lowLevel) ? (level + 1) : lowLevel);
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (date.compareTo(dateFormat.format(new Date())) >= 0) {
            date = elasticsearchUtil.getQuotaTime();
        }
        List<SaveModel> esModelList = null;
        List<SaveModel> totalModelList = null;
        if (StringUtils.isNotEmpty(lowCode)){
            esModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel1(date, area, level, index, SaveModel.timeLevel_DDL, low_level,lowCode);
            totalModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel1(date, area, level, "17", SaveModel.timeLevel_DDL, low_level,lowCode);
        }else{
            esModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel0(date, area, level, index, SaveModel.timeLevel_DDL, low_level);
            totalModelList = (List<SaveModel>) elasticsearchUtil.findListDateQuotaLevel0(date, area, level, "1", SaveModel.timeLevel_DDL, low_level);
        }
        if (esModelList != null && esModelList.size() > 0) {
            for (SaveModel one : esModelList) {
                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("amount", one.getResult2().intValue());
                if (low_level.equals("3") && one.getTown() != null) {
                    maps.put("code", one.getTown());
                    maps.put("name", one.getTownName());
                } else if (low_level.equals("4") && one.getHospital() != null) {
                    maps.put("code", one.getHospital());
                    maps.put("name", one.getHospitalName());
                } else if (low_level.equals("5") && one.getTeam() != null) {
                    maps.put("code", one.getTeam());
                    maps.put("name", one.getTeamName());
                }
                resultList.add(maps);
            }
        }
        // 结果为空时,自建结果集
        if (resultList == null || resultList.size() < 1) {
            resultList = getLowLevelMapKey(level, low_level, area);
        }
        if (resultList != null) {
            DecimalFormat df = new DecimalFormat("0.0000");
            for (int i = 0; i < resultList.size(); i++) {
                Map<String, Object> map = resultList.get(i);
                long signOnline =Long.valueOf(String.valueOf(map.get("amount")));
                map.put("amount", map.get("amount") != null ? signOnline : 0L);
                for (SaveModel totalOne : totalModelList) {
                    if (low_level.equals("3") && String.valueOf(map.get("code")).equals(totalOne.getTown())) {
                        map.put("signAmount",totalOne.getResult2().longValue());
                        map.put("rate",df.format(signOnline*1.0/totalOne.getResult2().longValue()*1000));
                    } else if (low_level.equals("4") &&  String.valueOf(map.get("code")).equals(totalOne.getHospital())) {
                        map.put("signAmount",totalOne.getResult2().longValue());
                        map.put("rate",df.format(signOnline*1.0/totalOne.getResult2().longValue()*1000));
                    } else if (low_level.equals("5") && totalOne.getTeam() != null) {
                        map.put("signAmount",totalOne.getResult2().longValue());
                        map.put("rate",df.format(signOnline*1.0/totalOne.getResult2().longValue()*1000));
                    }
                }
                /*if (!low_level.equals("5")) {
                    String code = String.valueOf(map.get("code"));
                    PopulationBase peopleNum = getPopulationBase(code, year);
                    if (peopleNum != null) {
                        map.put("rate", df.format(((long) map.get("amount") * 1.0000) / peopleNum.getNum() * 100));
                        map.put("taskRate", df.format(((long) map.get("amount") * 1.0000) / peopleNum.getTaskNum() * 100));
                        map.put("targetRate", df.format(peopleNum.getTaskNum() * 1.0000 / peopleNum.getNum() * 100));
                        map.put("rateString", map.get("amount") + "/" + peopleNum.getNum());
                        map.put("taskRateString", map.get("amount") + "/" + peopleNum.getTaskNum());
                        map.put("targetRateString", peopleNum.getTaskNum() + "/" + peopleNum.getNum());
                        map.put("num", peopleNum.getNum());
                        map.put("task", peopleNum.getTaskNum());
                    }
                }*/
            }
            if ((level == 2 && "5".equals(lowLevel)) || (level == 4) || (level == 3 && "5".equals(lowLevel))) {
                translateTeamLeaderName(resultList);
            }
            Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    long map1value = (long) o1.get("amount");
                    long map2value = (long) o2.get("amount");
                    if (map1value - map2value > 0) {
                        return sort == 1 ? -1 : 1;
                    } else if (map1value - map2value < 0) {
                        return sort == 1 ? 1 : -1;
                    } else {
                        return 0;
                    }
                }
            });
            return new JSONArray(resultList);
        } else {
            return new JSONArray();
        }
    }
    public JSONObject getRenewPercentOnline(String index, Integer level, String area, String year, String lowCode) {
        JSONObject jo = new JSONObject();
        String renewOnlineIndex = "";//线上续签index
        String signIndex ="1";
        String renewIndex = index;//续签index.
        String date = year + "-06-30";
        try {
            if (level == 5) {
                //团队的线上续签
                if (StringUtils.isNoneBlank(lowCode)) {
                    //服务类型维度
                    renewOnlineIndex = "81";
                } else {
                    renewOnlineIndex = "77";
                }
            } else if (level == 4) {
                //社区的线上续签
                if (StringUtils.isNoneBlank(lowCode)) {
                    //服务类型维度
                    renewOnlineIndex = "80";
                } else {
                    renewOnlineIndex = "76";
                }
            } else if (level ==3){
                //区的线上续签
                if (StringUtils.isNoneBlank(lowCode)) {
                    //服务类型维度
                    renewOnlineIndex = "79";
                } else {
                    renewOnlineIndex = "75";
                }
            }else{
                //市的线上续签
                if (StringUtils.isNoneBlank(lowCode)) {
                    //服务类型维度
                    renewOnlineIndex = "78";
                } else {
                    renewOnlineIndex = "74";
                }
            }
            String timeKey = elasticsearchUtil.getQuotaTime();
            SaveModel renewSaveModel = new SaveModel();
            SaveModel signSaveModel = new SaveModel();
            SaveModel renewOnlineSaveMolde = new SaveModel();
            if (StringUtils.isNotBlank(lowCode)) {
                //续签量
                renewSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, renewIndex, SaveModel.timeLevel_DDL, lowCode);
                //线上续签量
                renewOnlineSaveMolde = elasticsearchUtil.findOneDateQuotaLevel1(timeKey,area,level,renewOnlineIndex,SaveModel.timeLevel_DDL,lowCode);
            } else {
                //续签量
                renewSaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, renewIndex, SaveModel.timeLevel_DDL);
                renewOnlineSaveMolde = elasticsearchUtil.findOneDateQuotaLevel0(timeKey,area,level,renewOnlineIndex,SaveModel.timeLevel_DDL);
            }
            int renewNum = renewSaveModel.getResult2().intValue();
            int renewOnlineNum = renewOnlineSaveMolde.getResult2().intValue();
            //根据年度获取去年的签约数 签约指标是1
            if (StringUtils.isNoneBlank(lowCode)) {
                if ("3".equals(lowCode)) {
                    //老年人
                    lowCode = "3";
                } else if ("4".equals(lowCode)) {
                    //高血压
                    lowCode = "1";
                } else if ("5".equals(lowCode)) {
                    //糖尿病
                    lowCode = "2";
                }
                signIndex = "17";
                signSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(date, area, level, signIndex, SaveModel.timeLevel_DDL, lowCode);
            } else {
                signSaveModel = elasticsearchUtil.findOneDateQuotaLevel0(date, area, level, signIndex, SaveModel.timeLevel_DDL);
            }
            //签约量
            int signNum = signSaveModel.getResult2().intValue();
            jo.put("yesterYearSign", signNum);//去年的签约量
            jo.put("thisYearRenew", renewNum);//今年的续签量
            jo.put("thisYearRenewOnline",renewOnlineNum);//今年的线上续签量
            jo.put("renewRange", getRange(renewNum, signNum, 2));//续签率  50.00%
            jo.put("renewRangeOnline", getRange(renewOnlineNum, renewNum, 2));//线上续签率  50.00%
        } catch (Exception e) {
            e.getMessage();
            jo.put("status", "0");
            jo.put("error", "查询失败" + e.getMessage());
            return jo;
        }
        return jo;
    }
}

+ 117 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/message/SendMessageService.java

@ -0,0 +1,117 @@
package com.yihu.wlyy.service.message;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.message.Message;
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.BaseService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import com.yihu.wlyy.wechat.util.WeiXinTempMsgSendUtils;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 消息类发送(系统消息、模板消息、短信消息)
 * <p>
 * Created by Reece on 2017/11/27/007.
 */
@Service
@Transactional
public class SendMessageService extends BaseService {
    @Autowired
    private WeiXinTempMsgSendUtils tempMsgSendUtils;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private SMSService smsService;
    @Autowired
    WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private PatientDao patientDao;
    private static final Logger logger = LoggerFactory.getLogger(SendMessageService.class);
    /**
     * 拼装参数并发送模板消息
     *
     * @param type     typeMsg对应参数
     * @param patient  居民code
     * @param url      带参数跳转链接
     * @param first
     * @param remark
     * @param keywords
     * @return
     */
    public Boolean sendTemplate(int type, String patient, String url, String first, String remark, String... keywords) {
        Boolean flag = false;
        try {
            Patient patient1 = patientDao.findByCode(patient);
            String openid = patient1.getOpenid();
            String name = patient1.getName();
            String accessToken = weiXinAccessTokenUtils.getAccessToken();
            JSONObject data = tempMsgSendUtils.getTemplateContent(first, remark, keywords);
            data.put("url", url+"&represented="+patient);
            if (StringUtils.isNotEmpty(openid)) {
                pushMsgTask.putWxMsg(accessToken, type, openid, name, data);
                flag = true;
            }else {
                //发送代理人
                JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient, openid);
                if (jsonArray != null && jsonArray.length() > 0) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject j = jsonArray.getJSONObject(i);
                        Patient member = (Patient) j.get("member");
                        JSONObject json = data;
                        data.remove("first");
                        data.remove("url");
                        data.put("url",url+"&represented="+member.getCode());
                        data.put("first", weiXinOpenIdUtils.getTitleMes(patient1, j.getInt("relation"), name) + first);
                        pushMsgTask.putWxMsg(accessToken, type, member.getOpenid(), name, data);
                        flag = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return flag;
    }
    /**
     * 拼装参数并发送短信消息
     *
     * @param mobile 发送手机号
     * @param msg    发送短信内容
     * @return
     */
    public String sendMessage(String mobile, String msg) {
        String response = null;
        try {
            //发送短信消息,调用总部发送信息的接口
            JSONObject resultJson = smsService.sendMsg(mobile, msg);
            if (resultJson != null && resultJson.getInt("result") != 0) {
                response = "短信提醒失败!(原因:" + resultJson.getString("description") + ")";
            }
            response = "短信发送成功!";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}

+ 1 - 2
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java

@ -108,8 +108,7 @@ public class DoctorFeldsherTemplateService extends BaseService {
            Doctor doctor = doctorDao.findByCode(doctorCode);
            String doctorName = doctor.getName();
//            String doctorOpenId = doctor.getOpenid();
            String doctorOpenId = "o7NFZw1QM4YR1O19mLjwfX1Hh11A";
            String doctorOpenId = doctor.getOpenid();
            String first = businessType;
            sendJson.put("keyword1", content);

+ 402 - 148
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/fzzb/HealthEducationArticleService.java

@ -7,6 +7,7 @@ import com.yihu.es.entity.HealthEduArticlePatient;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ElasticsearchUtil;
import com.yihu.wlyy.util.HttpClientUtil;
@ -29,7 +30,7 @@ import java.util.*;
 * Created by yeshijie on 2017/9/11.
 */
@Service
public class HealthEducationArticleService extends BaseService{
public class HealthEducationArticleService extends BaseService {
    private static Logger logger = LoggerFactory.getLogger(HealthEducationArticleService.class);
@ -47,10 +48,14 @@ public class HealthEducationArticleService extends BaseService{
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HealthEducationArticleService healthEducationArticleService;
    @Autowired
    private PatientService patientService;
    @Value("${jkEdu.web.articleBaseUrl}")
    private String articleBaseUrl;
//    private String baseUrl = "http://service.yihu.com:8085/WsPlatform/rest";
    private String baseUrl = "http://172.17.110.230:83/WsPlatform/rest";
//    private String baseUrl = "http://172.19.103.87:9088/JkEdu";
    //    private String baseUrl = "http://service.yihu.com:8085/WsPlatform/rest";
//    private String baseUrl = "http://172.17.110.230:83/WsPlatform/rest";
//    private String baseUrl = articleBaseUrl+"/WsPlatform/rest";
    @Value("${yihu.yihu_OpenPlatform_appId}")
    private String clientId;
@ -68,128 +73,132 @@ public class HealthEducationArticleService extends BaseService{
    /**
     * 封装入参
     *
     * @param api
     * @param param
     * @param version
     * @return
     */
    public Map<String,String> getParamsMap(String api,String param,String version){
        Map<String,String> params = new HashMap<>();
    public Map<String, String> getParamsMap(String api, String param, String version) {
        Map<String, String> params = new HashMap<>();
        JSONObject authInfo = new JSONObject();
        authInfo.put("clientId",clientId);//填渠道ID(必填,固定为9000276)
        authInfo.put("clientVersion",clientVersion);//接入方系统版本号(非必须,默认 1.0)
        authInfo.put("sign","");//(保留,非必填)
        authInfo.put("sessionKey","");//(保留,非必填)
        params.put("AuthInfo",authInfo.toString());
        authInfo.put("clientId", clientId);//填渠道ID(必填,固定为9000276)
        authInfo.put("clientVersion", clientVersion);//接入方系统版本号(非必须,默认 1.0)
        authInfo.put("sign", "");//(保留,非必填)
        authInfo.put("sessionKey", "");//(保留,非必填)
        params.put("AuthInfo", authInfo.toString());
        params.put("SequenceNoString", DateUtil.getUserDate(DateUtil.YYYYMMddHHmmssSSS));//请求序列号,yyyyMMddHHmmssSSS 格式的时间戳
        params.put("Api",api);//Api 名称    需要调用的 API 名称
        params.put("Param",param);//本次请求的方法参数   Json结构的字符串
        params.put("ParamType","0");//指定 param 参数的类型,固定传0
        params.put("OutType","0");//指定返回 JSON/Xml 结构的字符串,固定传0
        params.put("V",version);//API 版本号。版本号为整型,从数字 1 开始递增.
        params.put("Api", api);//Api 名称    需要调用的 API 名称
        params.put("Param", param);//本次请求的方法参数   Json结构的字符串
        params.put("ParamType", "0");//指定 param 参数的类型,固定传0
        params.put("OutType", "0");//指定返回 JSON/Xml 结构的字符串,固定传0
        params.put("V", version);//API 版本号。版本号为整型,从数字 1 开始递增.
        return params;
    }
    /**
     * 获取文章列表
     * @param articleTitle 否 文章标题
     * @param articleState 否 传1
     *
     * @param articleTitle         否 文章标题
     * @param articleState         否 传1
     * @param firstLevelCategoryId 否    一级类别ID ,多个逗号隔开
     * @param pageIndex 否    起始页数 0开始,默认0
     * @param pageSize 否    每页显示数 ,默认5
     * @param userId 是    当前用户ID
     * @param pageIndex            否    起始页数 0开始,默认0
     * @param pageSize             否    每页显示数 ,默认5
     * @param userId               是    当前用户ID
     * @return
     */
    public JSONArray getDoctorArticalList(String articleTitle, Integer articleState, String firstLevelCategoryId, Integer pageIndex, Integer pageSize,String userId) throws Exception{
    public JSONArray getDoctorArticalList(String articleTitle, Integer articleState, String firstLevelCategoryId, Integer pageIndex, Integer pageSize, String userId) throws Exception {
        JSONArray re = new JSONArray();
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("articleTitle",articleTitle);
            param.put("articleState",articleState);
            param.put("firstLevelCategoryId",firstLevelCategoryId);
            param.put("pageIndex",pageIndex);
            param.put("pageSize",pageSize);
            param.put("userId",userId);
            String response = httpClientUtil.httpPost(baseUrl,getParamsMap(getDoctorArticalList,param.toString(),"1"));
            param.put("articleTitle", articleTitle);
            param.put("articleState", articleState);
            param.put("firstLevelCategoryId", firstLevelCategoryId);
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("userId", userId);
            String response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(getDoctorArticalList, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return re;
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
            return json.getJSONArray("Result");
        }else {
        } else {
            throw new Exception(json.getString("Message"));
        }
    }
    /**
     * 获取文章详情
     *
     * @param articleId 文章id
     * @return
     */
    public JSONObject getArticalById(String articleId) throws Exception{
    public JSONObject getArticalById(String articleId) throws Exception {
        JSONObject re = new JSONObject();
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("articleId",articleId);
            String response = httpClientUtil.httpPost(baseUrl,getParamsMap(getArticalById,param.toString(),"1"));
            param.put("articleId", articleId);
            String response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(getArticalById, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return re;
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
            JSONArray result = json.getJSONArray("Result");
            if(result.size()>0){
            if (result.size() > 0) {
                return result.getJSONObject(0);
            }
            return re;
        }else {
        } else {
            throw new Exception(json.getString("Message"));
        }
    }
    /**
     * 获取收藏文章列表
     * @param articleTitle 否 文章标题
     * @param articleState 否 传1
     *
     * @param articleTitle         否 文章标题
     * @param articleState         否 传1
     * @param firstLevelCategoryId 否    一级类别ID ,多个逗号隔开
     * @param pageIndex 否    起始页数 0开始,默认0
     * @param pageSize 否    每页显示数 ,默认5
     * @param userId 是    当前用户ID
     * @param userType 是    1 医生 2 居民
     * @param pageIndex            否    起始页数 0开始,默认0
     * @param pageSize             否    每页显示数 ,默认5
     * @param userId               是    当前用户ID
     * @param userType             是    1 医生 2 居民
     * @return
     */
    public JSONArray getCollectionArticalList(String articleTitle, Integer articleState, String firstLevelCategoryId,
                                              Integer pageIndex, Integer pageSize,String userId,Integer userType) throws Exception{
                                              Integer pageIndex, Integer pageSize, String userId, Integer userType) throws Exception {
        JSONArray re = new JSONArray();
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("articleTitle",articleTitle);
            param.put("articleState",articleState);
            param.put("firstLevelCategoryId",firstLevelCategoryId);
            param.put("pageIndex",pageIndex);
            param.put("pageSize",pageSize);
            param.put("userId",userId);
            param.put("userType",userType);
            String response = httpClientUtil.httpPost(baseUrl,getParamsMap(getCollectionArticalList,param.toString(),"1"));
            param.put("articleTitle", articleTitle);
            param.put("articleState", articleState);
            param.put("firstLevelCategoryId", firstLevelCategoryId);
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("userId", userId);
            param.put("userType", userType);
            String response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(getCollectionArticalList, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return re;
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
            return json.getJSONArray("Result");
        }else {
        } else {
            throw new Exception(json.getString("Message"));
        }
    }
@ -197,154 +206,158 @@ public class HealthEducationArticleService extends BaseService{
    /**
     * 获取文章类别
     *
     * @param categoryLevel 是    获取类别:1、一级类别 2、二级类别
     * @return
     */
    public JSONArray getCategoryList(String categoryLevel) throws Exception{
    public JSONArray getCategoryList(String categoryLevel) throws Exception {
        JSONArray re = new JSONArray();
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("categoryLevel",categoryLevel);
            param.put("categoryLevel", categoryLevel);
            String response = httpClientUtil.httpPost(baseUrl,getParamsMap(getCategoryList,param.toString(),"1"));
            String response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(getCategoryList, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return re;
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
            return json.getJSONObject("Result").getJSONArray("result");
        }else {
        } else {
            throw new Exception(json.getString("Message"));
        }
    }
    /**
     * 取消收藏文章
     *
     * @param articleId 是 文章id
     * @param userId 是    当前用户ID
     * @param userType 是    1 医生 2 居民
     * @param userId    是    当前用户ID
     * @param userType  是    1 医生 2 居民
     * @return
     */
    public void cancelArticleCollection(String articleId,String userId,Integer userType) throws Exception{
    public void cancelArticleCollection(String articleId, String userId, Integer userType) throws Exception {
        String response = "";
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("articleId",articleId);
            param.put("userId",userId);
            param.put("userType",userType);
            param.put("articleId", articleId);
            param.put("userId", userId);
            param.put("userType", userType);
            response = httpClientUtil.httpPost(baseUrl,getParamsMap(cancelArticleCollection,param.toString(),"1"));
            response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(cancelArticleCollection, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
        }else {
        } else {
            new Exception(json.getString("Message"));
        }
    }
    /**
     * 收藏文章列表
     * @param articleId 文章id
     * @param articleCategoryId 文章类别ID
     *
     * @param articleId           文章id
     * @param articleCategoryId   文章类别ID
     * @param articleCategoryName 文章类别名称
     * @param userId 是    当前用户ID
     * @param userType 是    1 医生 2 居民
     * @param userId              是    当前用户ID
     * @param userType            是    1 医生 2 居民
     * @return
     */
    public void saveArticleCollection(String articleId, String articleCategoryId, String articleCategoryName,String userId,Integer userType){
    public void saveArticleCollection(String articleId, String articleCategoryId, String articleCategoryName, String userId, Integer userType) {
        String response = "";
        JSONObject json = null;
        try{
        try {
            Doctor doctor = doctorDao.findByCode(userId);
            String orgName = doctor.getHospitalName();//用户所属机构
            String orgId = doctor.getHospital();//用户所属机构ID
            String cName = doctor.getName();//用户名
            JSONObject param = new JSONObject();
            param.put("articleId",articleId);
            param.put("cName",cName);
            param.put("articleCategoryId",articleCategoryId);
            param.put("articleCategoryName",articleCategoryName);
            param.put("orgName",orgName);
            param.put("orgId",orgId);
            param.put("userId",userId);
            param.put("userType",userType);
            response = httpClientUtil.httpPost(baseUrl,getParamsMap(saveArticleCollection,param.toString(),"1"));
            param.put("articleId", articleId);
            param.put("cName", cName);
            param.put("articleCategoryId", articleCategoryId);
            param.put("articleCategoryName", articleCategoryName);
            param.put("orgName", orgName);
            param.put("orgId", orgId);
            param.put("userId", userId);
            param.put("userType", userType);
            response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(saveArticleCollection, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
        }else {
        } else {
            new Exception(json.getString("Message"));
        }
    }
    /**
     * 获取医生发表的文章列表
     * @param articleTitle 否 文章标题
     * @param articleState 否 传1
     *
     * @param articleTitle         否 文章标题
     * @param articleState         否 传1
     * @param firstLevelCategoryId 否    一级类别ID ,多个逗号隔开
     * @param pageIndex 否    起始页数 0开始,默认0
     * @param pageSize 否    每页显示数 ,默认5
     * @param userId 是    当前用户ID
     * @param pageIndex            否    起始页数 0开始,默认0
     * @param pageSize             否    每页显示数 ,默认5
     * @param userId               是    当前用户ID
     * @return
     */
    public JSONArray getDoctorArticalByUserId(String articleTitle, Integer articleState, String firstLevelCategoryId,
                                              Integer pageIndex, Integer pageSize,String userId) throws Exception{
                                              Integer pageIndex, Integer pageSize, String userId) throws Exception {
        JSONArray re = new JSONArray();
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("articleTitle",articleTitle);
            param.put("articleState",articleState);
            param.put("firstLevelCategoryId",firstLevelCategoryId);
            param.put("pageIndex",pageIndex);
            param.put("pageSize",pageSize);
            param.put("userId",userId);
            String response = httpClientUtil.httpPost(baseUrl,getParamsMap(getDoctorArticalByUserId,param.toString(),"1"));
            param.put("articleTitle", articleTitle);
            param.put("articleState", articleState);
            param.put("firstLevelCategoryId", firstLevelCategoryId);
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("userId", userId);
            String response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(getDoctorArticalByUserId, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return re;
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
            return json.getJSONArray("Result");
        }else {
        } else {
            throw new Exception(json.getString("Message"));
        }
    }
    public JSONArray getArticalList(String articleId,int articleState,int pageIndex,int pageSize) throws Exception{
    public JSONArray getArticalList(String articleId, int articleState, int pageIndex, int pageSize) throws Exception {
        JSONArray re = new JSONArray();
        JSONObject json = null;
        try{
        try {
            JSONObject param = new JSONObject();
            param.put("articleId",articleId);
            param.put("articleState",articleState);
            param.put("pageIndex",pageIndex);
            param.put("pageSize",pageSize);
            String response = httpClientUtil.httpPost(baseUrl,getParamsMap(getArticalList,param.toString(),"1"));
            param.put("articleId", articleId);
            param.put("articleState", articleState);
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            String response = httpClientUtil.httpPost(articleBaseUrl+"/WsPlatform/rest", getParamsMap(getArticalList, param.toString(), "1"));
            json = JSON.parseObject(response);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return re;
        }
        if("10000".equals(json.getString("Code"))){
        if ("10000".equals(json.getString("Code"))) {
            return json.getJSONArray("Result");
        }else {
        } else {
            throw new Exception(json.getString("Message"));
        }
    }
@ -367,40 +380,122 @@ public class HealthEducationArticleService extends BaseService{
//        return null;
//    }
    public JSONArray labelWithPushPatients(String labelType){
    public JSONArray labelWithPushPatients(String labelType, String condition,String teamCode) {
        String[] cond = {};
        if (!StringUtils.isEmpty(condition)) {
            cond = condition.split(",");
        }
        StringBuilder whereSql = new StringBuilder();
        String tableSql = "";
        for (String one : cond) {
            if ("1".equals(one)) {//有绑定设备
                tableSql = "LEFT JOIN wlyy_patient_device d on d.user=aa.patient and d.device_id is not null ";
            } else if ("2".equals(one)) {//孕产妇
//                temp.add("41");
                whereSql.append(" and tt LIKE '%41%' ");
            } else if ("3".equals(one)) {//65岁以上老年人
//                temp.add("13");
                whereSql.append(" and tt LIKE '%13%' ");
            }
        }
        String sql = "";
        List<DictModel> returnList = null;
        Map<String, Object> map = null;
        JSONArray re = new JSONArray();
        switch (labelType) {
            case "1": {
                sql = "select s.code code,s.name name from wlyy_sign_dict s where s.year='2017' order by s.sort asc";
                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
                sql = "select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
                        " left join wlyy_sign_family_server s on w.code= s.sign_code "+
                        " left join wlyy_patient p on p.code=w.patient "+
                        " where w.status>0 and p.town='350211' ";
                for(DictModel one:returnList){
                    sql +=" s.server_type='"+one.getCode()+"'";
                    Map<String, Object> map = jdbcTemplate.queryForMap(sql);
                for (DictModel one : returnList) {
//                    sql = "select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_family_server s on w.code= s.sign_code "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211' ";
//                    sql +=" and s.server_type='"+one.getCode()+"'";
                    sql = " SELECT count(DISTINCT(aa.patient)) AS num FROM " +
                            " ( SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l, " +
                            " wlyy_sign_family_server q WHERE w. STATUS > 0 AND l. STATUS = 1 AND w.team_code=" +teamCode+
                            " AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' " +
                            " AND w. CODE = q.sign_code AND q.server_type = 1 ) a " +
                            " GROUP BY a.patient HAVING 1 = 1 AND tt LIKE '%1" + one.getCode() + "%' " + whereSql.toString() + ") aa " + tableSql;
                    map = jdbcTemplate.queryForMap(sql);
                    JSONObject obj = new JSONObject();
                    obj.put("code",one.getCode());
                    obj.put("name",one.getName());
                    obj.put("num",(Long)map.get("num"));
                    obj.put("code", one.getCode());
                    obj.put("name", one.getName());
                    obj.put("num", (Long) map.get("num"));
                    re.add(obj);
                }
                break;
            }
            case "2": {
                sql = "select label_code code, label_name name from wlyy_sign_patient_label  where label_type=2 and status=1";
                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
                for (DictModel one : returnList) {
//                    sql =" select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_patient_label_info l on w.patient=l.patient "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211' and l.status=1 and l.label_type = 2 AND l.label ="+one.getCode();
                    sql = " select count(DISTINCT(aa.patient)) as num from ( " +
                            " SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l " +//AND w.team_code=" +teamCode+
                            " WHERE w. STATUS > 0 and l.status=1 AND  w.team_code="+teamCode+" AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' ) a " +
                            " GROUP BY a.patient HAVING tt LIKE '%2" + one.getCode() + "%' " + whereSql.toString() + ") aa " + tableSql;
                    map = jdbcTemplate.queryForMap(sql);
                    JSONObject obj = new JSONObject();
                    obj.put("code", one.getCode());
                    obj.put("name", one.getName());
                    obj.put("num", (Long) map.get("num"));
                    re.add(obj);
                }
                break;
            }
            case "3": {
                sql = "select label_code code, label_name name from wlyy_sign_patient_label  where label_type=3 and status=1";
                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
                for (DictModel one : returnList) {
//                    sql =" select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_patient_label_info l on w.patient=l.patient "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211'  and l.status=1 and l.label_type = 3 AND l.label ="+one.getCode();
                    sql = " select count(DISTINCT(aa.patient)) as num from ( " +
                            " SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l " +
                            " WHERE w. STATUS > 0 and l.status=1 AND  w.team_code="+teamCode+" AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' ) a " +
                            " GROUP BY a.patient HAVING tt LIKE '%3" + one.getCode() + "%' " + whereSql.toString() + ") aa " + tableSql;
                    map = jdbcTemplate.queryForMap(sql);
                    JSONObject obj = new JSONObject();
                    obj.put("code", one.getCode());
                    obj.put("name", one.getName());
                    obj.put("num", (Long) map.get("num"));
                    re.add(obj);
                }
                break;
            }
            case "4": {
                sql = "select label_code code, label_name name from wlyy_sign_patient_label  where label_type=4 and status=1";
                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
                for (DictModel one : returnList) {
//                    sql =" select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_patient_label_info l on w.patient=l.patient "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211'  and l.status=1 and l.label_type = 4 AND l.label ='"+one.getCode()+"'";
                    sql = " select count(DISTINCT(aa.patient)) as num from ( " +
                            " SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l " +
                            " WHERE w. STATUS > 0 and l.status=1 AND  w.team_code="+teamCode+" AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' ) a " +
                            " GROUP BY a.patient HAVING tt LIKE '%4" + one.getCode() + "%' " + whereSql.toString() + ") aa " + tableSql;
                    map = jdbcTemplate.queryForMap(sql);
                    JSONObject obj = new JSONObject();
                    obj.put("code", one.getCode());
                    obj.put("name", one.getName());
                    obj.put("num", (Long) map.get("num"));
                    re.add(obj);
                }
                break;
            }
@ -408,7 +503,7 @@ public class HealthEducationArticleService extends BaseService{
        return re;
    }
    public JSONArray pushArticleLogs(int page, int pagesize,String patientCode)throws Exception{
    public JSONArray pushArticleLogs(int page, int pagesize, String patientCode) throws Exception {
        pagesize = page * pagesize;
        page = (page - 1) * pagesize;
@ -416,11 +511,12 @@ public class HealthEducationArticleService extends BaseService{
//        StringBuffer sql2 = new StringBuffer("select *  from   " + esType +
//                " where  sendCode='" + sendCode + "' ");
//        sql2.append("  order by createTime limit " + page + "," + pagesize);
        String sql = "SELECT * FROM "+esType+"  where nested(patients.code)= '"+patientCode+"' order by createTime desc limit "+ page + "," + pagesize;
        String sql = "SELECT * FROM " + esType + "  where nested(patients.code)= '" + patientCode + "' order by createTime desc limit " + page + "," + pagesize;
        List<com.yihu.es.entity.HealthEduArticlePatient> esList = elasticsearchUtil.excute(sql, com.yihu.es.entity.HealthEduArticlePatient.class, esIndex, esType);
        HealthEduArticlePatientModel heapm = null;
        com.alibaba.fastjson.JSONObject article = null;
        List<HealthEduArticlePatientModel> result = new ArrayList<>();
        Doctor doctor = null;
        for (HealthEduArticlePatient one : esList) {
            article = healthEducationArticleService.getArticalById(one.getArticleId());
            heapm = new HealthEduArticlePatientModel();
@ -440,6 +536,9 @@ public class HealthEducationArticleService extends BaseService{
            heapm.setPointNumber(Integer.valueOf(article.getString("pointNumber")));//文章点赞数
            heapm.setArticleCover(article.getString("articleCover"));//封面
            heapm.setComputeTime(computeTime(article.getString("insertTime")));
            heapm.setOperatorName(article.getString("operatorName"));
            doctor = doctorDao.findByCode(one.getDoctorCode());
            heapm.setPhoto(doctor.getPhoto());
            result.add(heapm);
            // heapm.setTime();//时间  xx小时前  2017-10-11
        }
@ -449,8 +548,7 @@ public class HealthEducationArticleService extends BaseService{
    }
    public  String computeTime(String create) {
    public String computeTime(String create) {
        Date createDate = DateUtil.strToDate(create, "yyyy-MM-dd HH:mm:ss.SSS");
        Date nowDate = new Date();
        //计算2个时间差
@ -459,15 +557,171 @@ public class HealthEducationArticleService extends BaseService{
        long hour = l / (60 * 60 * 1000); //小时
        long min = l / (60 * 1000);//分钟
        long s = l / 1000;//秒
        if(s<60){
            return s+"秒前";
        if (s < 60) {
            return s + "秒前";
        }
        if (min < 60) {
            return min + "分钟前";
        }
        if (hour < 24) {
            return hour + "小时前";
        }
        return DateUtil.dateToStr(createDate, "yyyy-MM-dd");
    }
    public JSONObject pushArticleConfirm(String articleId,String labelType, String condition, String groupType,String teamCode) throws Exception{
        JSONObject article = healthEducationArticleService.getArticalById(articleId);
        Set<String> patientSet = new HashSet<>();
        initPatient(patientSet,labelType,condition,groupType,teamCode);
        long num = patientSet.size();
        JSONObject result = new JSONObject();
        result.put("num", num);
        result.put("articleTitle", article.getString("articleTitle"));
        return result;
    }
    public void initPatient(Set<String> patientSet, String labelType, String condition, String groupType,String teamCode) {
        String[] cond = {};
        String[] group = {};
        if (!StringUtils.isEmpty(condition)) {
            cond = condition.split(",");
        }
        if(min<60){
            return min+"分钟前";
        StringBuilder whereSql = new StringBuilder();
        String tableSql = "";
        for (String one : cond) {
            if ("1".equals(one)) {//有绑定设备
                tableSql = " LEFT JOIN wlyy_patient_device d on d.user=aa.patient and d.device_id is not null ";
            } else if ("2".equals(one)) {//孕产妇
//                temp.add("41");
                whereSql.append(" and tt LIKE '%41%' ");
            } else if ("3".equals(one)) {//65岁以上老年人
//                temp.add("13");
                whereSql.append(" and tt LIKE '%13%' ");
            }
        }
        if(hour<24){
            return hour+"小时前";
        if (!StringUtils.isEmpty(groupType)) {
            group = groupType.split(",");
        }
        return DateUtil.dateToStr(createDate,"yyyy-MM-dd");
        StringBuilder whereSql2 = new StringBuilder();
//        for (String one : group) {
//            whereSql2.append(" and tt LIKE '%" + labelType + one + "%' ");
//        }
//        String whereSql2Str = whereSql2.toString().substring(3);
        String sql = "";
        Map<String, Object> map = null;
        List<String> groupPatient = null;
        List<String> resultList = new ArrayList<>();
        switch (labelType) {
            case "1": {
//                sql = "select s.code code,s.name name from wlyy_sign_dict s where s.year='2017' order by s.sort asc";
//                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
//                for(DictModel one:returnList){
//                    sql = "select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_family_server s on w.code= s.sign_code "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211' ";
//                    sql +=" and s.server_type='"+one.getCode()+"'";
                for (String one : group) {
                    sql = " SELECT DISTINCT(aa.patient)  FROM " +
                            " ( SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l, " +
                            " wlyy_sign_family_server q WHERE w. STATUS > 0 AND l. STATUS = 1 AND w.team_code=" +teamCode+
                            " AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' " +
                            " AND w. CODE = q.sign_code AND q.server_type = 1 ) a " +
                            " GROUP BY a.patient HAVING 1 = 1  " + whereSql +  " and tt LIKE '%" + labelType + one + "%'  ) aa " + tableSql;
                    groupPatient = jdbcTemplate.queryForList(sql, String.class);
//                    JSONObject obj = new JSONObject();
//                    obj.put("code",one.getCode());
//                    obj.put("name",one.getName());
//                    obj.put("num",(Long)map.get("num"));
//                    re.add(obj);
//                }
                    resultList.addAll(groupPatient);
                }
                break;
            }
            case "2": {
//                sql = "select label_code code, label_name name from wlyy_sign_patient_label  where label_type=2 and status=1";
//                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
//                for(DictModel one:returnList){
//                    sql =" select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_patient_label_info l on w.patient=l.patient "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211' and l.status=1 and l.label_type = 2 AND l.label ="+one.getCode();
                for (String one : group) {
                    sql = " select DISTINCT(aa.patient) from ( " +
                            " SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l " +
                            " WHERE w. STATUS > 0 and l.status=1 AND w.team_code="+teamCode+" AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' ) a " +
                            " GROUP BY a.patient HAVING 1=1 " + whereSql + "  and tt LIKE '%" + labelType + one + "%' ) aa " + tableSql;
//                    map = jdbcTemplate.queryForMap(sql);
//                JSONObject obj = new JSONObject();
//                obj.put("code",one.getCode());
//                obj.put("name",one.getName());
//                obj.put("num",(Long)map.get("num"));
//                re.add(obj);
                    groupPatient = jdbcTemplate.queryForList(sql, String.class);
                    resultList.addAll(groupPatient);
//                }
                }
                break;
            }
            case "3": {
//                sql = "select label_code code, label_name name from wlyy_sign_patient_label  where label_type=3 and status=1";
//                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
//                for(DictModel one:returnList){
//                    sql =" select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_patient_label_info l on w.patient=l.patient "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211'  and l.status=1 and l.label_type = 3 AND l.label ="+one.getCode();
                for (String one : group) {
                    sql = " select DISTINCT(aa.patient)  from ( " +
                            " SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l " +
                            " WHERE w. STATUS > 0 and l.status=1 AND w.team_code="+teamCode+" AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' ) a " +
                            " GROUP BY a.patient HAVING 1=1 " + whereSql + " and tt LIKE '%" + labelType + one + "%') aa " + tableSql;
//                    map = jdbcTemplate.queryForMap(sql);
//                    JSONObject obj = new JSONObject();
//                    obj.put("code",one.getCode());
//                    obj.put("name",one.getName());
//                    obj.put("num",(Long)map.get("num"));
//                    re.add(obj);
                    groupPatient = jdbcTemplate.queryForList(sql, String.class);
                    resultList.addAll(groupPatient);
//                }
                }
                break;
            }
            case "4": {
//                sql = "select label_code code, label_name name from wlyy_sign_patient_label  where label_type=4 and status=1";
//                returnList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictModel.class));
//                for(DictModel one:returnList){
//                    sql =" select count(DISTINCT(w.patient)) as num from wlyy_sign_family w "+
//                            " left join wlyy_sign_patient_label_info l on w.patient=l.patient "+
//                            " left join wlyy_patient p on p.code=w.patient "+
//                            " where w.status>0 and p.town='350211'  and l.status=1 and l.label_type = 4 AND l.label ='"+one.getCode()+"'";
                for (String one : group) {
                    sql = " select DISTINCT(aa.patient) from ( " +
                            " SELECT a.patient, GROUP_CONCAT( concat(a.label_type, a.label) ) tt " +
                            " FROM ( SELECT l.* FROM wlyy_sign_family w, wlyy_sign_patient_label_info l " +
                            " WHERE w. STATUS > 0 and l.status=1 AND w.team_code="+teamCode+" AND w.patient = l.patient AND LEFT (w.hospital, 6) = '350211' ) a " +
                            " GROUP BY a.patient HAVING 1=1 " + whereSql.toString() + " and tt LIKE '%" + labelType + one + "%') aa " + tableSql;
//                    map = jdbcTemplate.queryForMap(sql);
//                    JSONObject obj = new JSONObject();
//                    obj.put("code",one.getCode());
//                    obj.put("name",one.getName());
//                    obj.put("num",(Long)map.get("num"));
//                    re.add(obj);
                    groupPatient = jdbcTemplate.queryForList(sql, String.class);
                    resultList.addAll(groupPatient);
//                }
                }
                break;
            }
        }
        patientSet.addAll(resultList);
    }
}

+ 55 - 18
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/CommonUtil.java

@ -9,14 +9,17 @@ import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
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 org.springframework.web.context.request.RequestContextHolder;
@ -29,6 +32,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -44,6 +48,8 @@ public class CommonUtil {
    private String neiwangWlyy;  //内网的项目地址
    @Value("${neiwang.enable}")
    private Boolean isneiwang = false;  //如果不是内网项目要转到到内网wlyy在上传
    @Autowired
    private HttpClientUtil httpClientUtil;
    /**
     * 获取图片全路径
@ -149,7 +155,7 @@ public class CommonUtil {
            }
            return fileUrls;
        } else {
            String fileUrls = toNeiWang(voices,"");
            String fileUrls = toNeiWang(voices, "");
            return fileUrls;
        }
    }
@ -246,13 +252,12 @@ public class CommonUtil {
            return fileUrls;
        } else {
            String fileUrls = toNeiWang(files,tempPath);
            String fileUrls = toNeiWang(files, tempPath);
            return fileUrls;
        }
    }
    public void changeToMp3(String sourcePath, String targetPath) {
        File source = new File(sourcePath);
        File target = new File(targetPath);
@ -332,7 +337,6 @@ public class CommonUtil {
    }
    public String getSubString(String content, int min, int max) {
        if (StringUtils.isBlank(content)) {
            return "";
@ -427,7 +431,7 @@ public class CommonUtil {
                MultipartFile multipartFile = one.getValue().get(0);
                logger.info(" picture to neiwang file size:" + multipartFile.getSize());
                logger.info(" picture to neiwang file name:" + multipartFile.getName());
                responseEntity = request(url, multipartFile,type);
                responseEntity = request(url, multipartFile, type);
            }
            logger.info(" picture to neiwang responseEntity:" + responseEntity);
            logger.info(" picture to neiwang end");
@ -451,37 +455,61 @@ public class CommonUtil {
     * 如果是外网那是发送到内网的服务器
     *
     * @param files
     *
     * @return
     */
    public String toNeiWang(String files,String tempPath) throws FileNotFoundException {
        logger.info(" toNeiWang start files :"+tempPath+files);
    public String toNeiWang(String files, String tempPath) throws FileNotFoundException {
        logger.info(" toNeiWang start files :" + tempPath + files);
        //转发到内网服务器
        String[] fileArray = files.split(",");
        String fileUrls = "";
        for (String file : fileArray) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            File f = new File(tempPath+file);
            logger.info(" toNeiWang File exists :"+f.exists());
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            File f = new File(tempPath + file);
            logger.info(" toNeiWang File exists :" + f.exists());
            if (f.exists()) {
                String fileName = f.getName();
                InputStream in = new FileInputStream(f);
                String returnStr=request(request, in, fileName);
                logger.info("returnStr :"+returnStr);
                logger.info("fileName :"+fileName);
                logger.info("result :"+returnStr.toString());
                String returnStr = request(request, in, fileName);
                logger.info("returnStr :" + returnStr);
                logger.info("fileName :" + fileName);
                logger.info("result :" + returnStr.toString());
                if (returnStr != null) {
                    //1.3.7去掉前缀
                    fileUrls += returnStr;
                    f.delete();
                }
            } else {
                String path = tempPath + file;
                String returnStr = request(request, path);
                logger.info("result :" + returnStr.toString());
                if (returnStr != null) {
                    //1.3.7去掉前缀
                    fileUrls += returnStr;
                }
            }
        }
        logger.info(" toNeiWang end files :"+fileUrls);
        logger.info(" toNeiWang end files :" + fileUrls);
        return fileUrls;
    }
    public String request(String remote_url, MultipartFile file,String type) {
    private String request(HttpServletRequest request, String path) {
        String url = neiwangWlyy + "/wlyy/upload/commonUpload";//uri请求路径 http://172.19.103.88/wlyy/upload/chat
        String result = "";
        try {
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("filePaths", path));
            // 将响应内容转换为字符串
            result = httpClientUtil.post(url, params, "UTF-8");
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public String request(String remote_url, MultipartFile file, String type) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        logger.info(file.getOriginalFilename());
        String result = "";
@ -491,7 +519,9 @@ public class CommonUtil {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            builder.addTextBody("type",type); //发送类型
            if (!org.springframework.util.StringUtils.isEmpty(type)) {
                builder.addTextBody("type", type); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
@ -525,7 +555,9 @@ public class CommonUtil {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", in, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            builder.addTextBody("type",request.getParameter("type")); //发送类型
            if (!org.springframework.util.StringUtils.isEmpty(request.getParameter("type"))) {
                builder.addTextBody("type", request.getParameter("type")); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
@ -544,6 +576,11 @@ public class CommonUtil {
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

+ 49 - 27
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java

@ -51,7 +51,7 @@ import java.util.*;
@Api(description = "文件上传")
public class FileUploadController extends BaseController {
    private Logger logger= LoggerFactory.getLogger(FileUploadController.class);
    private Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    @ApiParam
    FastDFSUtil fastDFSUtil;
    @Autowired
@ -62,7 +62,6 @@ public class FileUploadController extends BaseController {
    private Boolean isneiwang = false;  //如果不是内网项目要转到到内网wlyy在上传
    /**
     * 患者头像上传
     *
@ -102,7 +101,7 @@ public class FileUploadController extends BaseController {
                return error(-1, "上传失败");
            }
        } else {
            return  CommonUtil.toNeiWang(request, response);
            return CommonUtil.toNeiWang(request, response);
        }
    }
@ -163,7 +162,7 @@ public class FileUploadController extends BaseController {
                json.put("msg", "上传成功");
                // 图片标识对象的HTTP链接
                json.put("urls", urls);
               logger.info("图片上传:" + json.toString());
                logger.info("图片上传:" + json.toString());
                return json.toString();
            } catch (Exception e) {
                error(e);
@ -178,7 +177,7 @@ public class FileUploadController extends BaseController {
                return error(-1, "上传失败");
            }
        } else {
            return  CommonUtil.toNeiWang(request, response);
            return CommonUtil.toNeiWang(request, response);
        }
    }
@ -275,14 +274,14 @@ public class FileUploadController extends BaseController {
                json.put("msg", "上传成功");
                // 图片标识对象的HTTP链接
                json.put("urls", urls);
               logger.info("附件上传:" + json.toString());
                logger.info("附件上传:" + json.toString());
                return json.toString();
            } catch (Exception e) {
                error(e);
                return error(-1, "上传失败");
            }
        } else {
            return  CommonUtil.toNeiWang(request, response);
            return CommonUtil.toNeiWang(request, response);
        }
    }
@ -341,7 +340,7 @@ public class FileUploadController extends BaseController {
                json.put("msg", "上传成功");
                // 图片标识对象的HTTP链接
                json.put("urls", urls);
               logger.info("语音上传:" + json.toString());
                logger.info("语音上传:" + json.toString());
                return json.toString();
            } catch (Exception e) {
                error(e);
@ -356,7 +355,7 @@ public class FileUploadController extends BaseController {
                return error(-1, "上传失败");
            }
        } else {
            return  CommonUtil.toNeiWang(request, response);
            return CommonUtil.toNeiWang(request, response);
        }
    }
@ -402,7 +401,7 @@ public class FileUploadController extends BaseController {
            String urls = String.join(",", tempPaths);
            return urls;
        } else {
            return  CommonUtil.toNeiWang(request, response);
            return CommonUtil.toNeiWang(request, response);
        }
    }
@ -470,7 +469,7 @@ public class FileUploadController extends BaseController {
                    json.put("msg", "上传成功");
                    // 图片标识对象的HTTP链接
                    json.put("urls", urls);
                   logger.info("图片上传:" + json.toString());
                    logger.info("图片上传:" + json.toString());
                    return json.toString();
                } catch (Exception e) {
                    error(e);
@ -485,7 +484,7 @@ public class FileUploadController extends BaseController {
                    return error(-1, "上传失败");
                }
            } else {
                return  CommonUtil.toNeiWang(request, response);
                return CommonUtil.toNeiWang(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
@ -499,22 +498,45 @@ public class FileUploadController extends BaseController {
    @ApiOperation("公共的文件上传")
    public String commonUpload(HttpServletRequest request) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 文件保存的临时路径
            FastDFSUtil fastDFSUtil = new FastDFSUtil();
            String paths = request.getParameter("filePaths");
            String fileUrls = "";
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                InputStream in = mf.getInputStream();
                ObjectNode result = fastDFSUtil.upload(in, fileName.substring(fileName.lastIndexOf(".") + 1), "");
                if (result != null) {
                    fileUrls += (StringUtils.isEmpty(fileUrls) ? "" : ",")
                            + result.get("groupName").toString().replaceAll("\"", "") + "/"
                            + result.get("remoteFileName").toString().replaceAll("\"", "");
            if (StringUtils.isBlank(paths)) {
                //为空是文件上传
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                // 文件保存的临时路径
                FastDFSUtil fastDFSUtil = new FastDFSUtil();
                Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
                String fileName = null;
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    // 上传文件
                    MultipartFile mf = entity.getValue();
                    fileName = mf.getOriginalFilename();
                    InputStream in = mf.getInputStream();
                    ObjectNode result = fastDFSUtil.upload(in, fileName.substring(fileName.lastIndexOf(".") + 1), "");
                    in.close();
                    if (result != null) {
                        fileUrls += (StringUtils.isEmpty(fileUrls) ? "" : ",")
                                + result.get("groupName").toString().replaceAll("\"", "") + "/"
                                + result.get("remoteFileName").toString().replaceAll("\"", "");
                    }
                }
            } else {
                String[] pathArr = paths.split(",");
                for (String path : pathArr) {
                    //传路径自己去路径上传
                    File file = new File(path);
                    String fileName = null;
                    if (file.exists()) {
                        fileName = file.getName();
                        InputStream in = new FileInputStream(file);
                        ObjectNode result = fastDFSUtil.upload(in, fileName.substring(fileName.lastIndexOf(".") + 1), "");
                        in.close();
                        if (result != null) {
                            fileUrls += (StringUtils.isEmpty(fileUrls) ? "" : ",")
                                    + result.get("groupName").toString().replaceAll("\"", "") + "/"
                                    + result.get("remoteFileName").toString().replaceAll("\"", "");
                        }
                    }
                }
            }
            return fileUrls;

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

@ -1,8 +1,10 @@
package com.yihu.wlyy.web.doctor.health;
import com.yihu.es.entity.*;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.education.*;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.event.ApplicationEvent;
@ -36,11 +38,18 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.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.*;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.*;
/**
@ -90,6 +99,10 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
    private HealthEducationArticleService healthEducationArticleService;
    @Autowired
    private GcEduArticleService gcEduArticleService;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Value("${activemq.queue.healtHarticleQueue}")
    private String channelName;
    /**
     * 查询
     *
@ -766,7 +779,7 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
    @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 = "firstLevelCategoryId", value = "文章1级类别", required = false) @RequestParam(value = "firstLevelCategoryId", required = false) String firstLevelCategoryId,
//            @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,
@ -781,7 +794,7 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
            if (pagesize > 1000) {
                pagesize = 1000;
            }
            List<HealthEduArticlePatientModel> eduArticlePatients = gcEduArticleService.pushArticleLogs(page,pagesize,getUID(),2);
            List<HealthEduArticlePatientModel> eduArticlePatients = gcEduArticleService.pushArticleLogs(page,pagesize,getUID(),2,firstLevelCategoryId);
            Long count = gcEduArticleService.pushArticleLogsCount(getUID(),2);
            return new ResultPageListModel(
                    page,
@ -796,11 +809,13 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
    @RequestMapping(value = "labelWithPushPatients", method = RequestMethod.GET)
    @ApiOperation("查询推送对象 ")
    public String labelWithPushPatients(
            @ApiParam(name = "labelType", value = "1:服务类型(卫计委分组) 2:健康情况 3:疾病类型 4:团队标签(自定义标签)", required = true) @RequestParam(value = "labelType", required = true) String labelType){
            @ApiParam(name = "teamCode", value = "团队code", required = true) @RequestParam(value = "teamCode", required = true) String teamCode,
            @ApiParam(name = "labelType", value = "1:服务类型(卫计委分组) 2:健康情况 3:疾病类型 4:团队标签(自定义标签)", required = true) @RequestParam(value = "labelType", required = true) String labelType,
            @ApiParam(name = "codition", value = "多个筛选条件以逗号分割", required = false) @RequestParam(value = "codition", required = false) String codition){
        try {
            com.alibaba.fastjson.JSONArray response = healthEducationArticleService.labelWithPushPatients(labelType);
            com.alibaba.fastjson.JSONArray response = healthEducationArticleService.labelWithPushPatients(labelType,codition,teamCode);
//            Long count = healthEducationArticleService.pushArticleLogsCount("ece5c665b16542b0847e52b4a9fee44a");
            return write(200,"查询成功!","data",response);
        }catch (Exception e) {
@ -808,4 +823,65 @@ public class DoctorHealthEduArticleController extends WeixinBaseController {
            return error(-1,"查询失败!");
        }
    }
    @ApiOperation("确认推送人数")
    @RequestMapping(value = "pushArticleConfirm",method = RequestMethod.GET)
    public String pushArticleConfirm(
            @ApiParam(name = "teamCode", value = "团队code", required = true) @RequestParam(value = "teamCode", required = true) String teamCode,
            @ApiParam(name = "labelType", value = "1:服务类型(卫计委分组) 2:健康情况 3:疾病类型 4:团队标签(自定义标签)", required = true) @RequestParam(value = "labelType", required = true) String labelType,
            @ApiParam(name = "condition", value = "多个筛选条件以逗号分割", required = false) @RequestParam(value = "condition", required = false) String condition,
            @ApiParam(name = "groupType", value = "多个分组以逗号分割", required = false) @RequestParam(value = "groupType", required = false) String groupType,
            @ApiParam(name = "articleId", value = "文章ID", required = true) @RequestParam(value = "articleId", required = true) String articleId){
        try {
            com.alibaba.fastjson.JSONObject response = healthEducationArticleService.pushArticleConfirm(articleId,labelType,condition,groupType,teamCode);
            return write(200,"查询成功!","data",response);
        }catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败!");
        }
    }
    @RequestMapping(value = "sendArticleToPatients", method = RequestMethod.POST)
    @ApiOperation("文章群推送")
    public BaseResultModel sendArticleToPatients(
            @ApiParam(name = "teamCode", value = "团队code", required = true) @RequestParam(value = "teamCode", required = true) String teamCode,
            @ApiParam(name = "labelType", value = "1:服务类型(卫计委分组) 2:健康情况 3:疾病类型 4:团队标签(自定义标签)", required = true) @RequestParam(value = "labelType", required = true) String labelType,
            @ApiParam(name = "condition", value = "多个筛选条件以逗号分割", required = false) @RequestParam(value = "condition", required = false) String condition,
            @ApiParam(name = "groupType", value = "多个分组以逗号分割", required = false) @RequestParam(value = "groupType", required = false) String groupType,
            @ApiParam(name = "articleId", value = "文章ID", required = true) @RequestParam(value = "articleId", required = true) String articleId,
            @ApiParam(name = "sendName", value = "发送方名称(如:医生发送:医生名称)", required = true) @RequestParam(value = "sendName", required = true) String sendName){
        try {
            Set<String> patientSet = new HashSet<>(); //放入set中可以去重复
            //得到需要发送的患者
            healthEducationArticleService.initPatient(patientSet, labelType, condition, groupType,teamCode);
            com.yihu.es.entity.HealthEduArticlePatient healthEduArticlePatient = gcEduArticleService.getSaveArticle(patientSet, getUID(), sendName, 1, "", 0L, articleId);
            //推送微信模板消息和发送im消息
            new Thread(() -> {
                //发送任务到redis
                sender(healthEduArticlePatient);
            }).start();
            return new BaseResultModel();
        }catch (Exception e) {
            return new BaseResultModel(BaseResultModel.statusEm.opera_error.getCode(), BaseResultModel.statusEm.opera_error.getMessage() + ":" + e.getMessage());
        }
    }
    /**
     * 发送到redis
     *
     */
    public void sender(com.yihu.es.entity.HealthEduArticlePatient healthEduArticlePatient) {
        //送到到队列
        List<Patient> patients = healthEduArticlePatient.getPatients();
        patients.stream().forEach(one -> {
            healthEduArticlePatient.setPatient(one.getCode());
            jmsTemplate.send(channelName, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    TextMessage textMessage = session.createTextMessage();
                    textMessage.setText(net.sf.json.JSONObject.fromObject(healthEduArticlePatient).toString());
                    return textMessage;
                }
            });
        });
    }
}

+ 39 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/message/DoctorMessageController.java

@ -1,7 +1,13 @@
package com.yihu.wlyy.web.doctor.message;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.message.Message;
import com.yihu.wlyy.entity.message.MessageNoticeSetting;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@ -16,11 +22,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;
import java.util.List;
import java.util.Map;
@ -31,6 +32,7 @@ public class DoctorMessageController extends BaseController {
    @Autowired
    private MessageService messageService;
    private ObjectMapper objectMapper = new ObjectMapper();
    @RequestMapping(value = "messages")
    @ResponseBody
@ -366,4 +368,36 @@ public class DoctorMessageController extends BaseController {
            return error(-1, "设置失败");
        }
    }
    @RequestMapping(value = "getMessageNoticeSetting",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取消息设置")
    public String getMessageNoticeSetting(){
        try {
            com.alibaba.fastjson.JSONObject messageNoticeSetting = messageService.getMessageNoticSetting(getUID(),"1");
            return write(200,"查询成功","data",messageNoticeSetting);
        } catch (Exception e){
            e.printStackTrace();
            return error(-1,"查询失败");
        }
    }
    @RequestMapping(value = "saveMessageNoticeSetting",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("保存消息提醒设置")
    @ObserverRequired
    public String saveMessageNoticeSetting(@ApiParam(name = "json", value = "数据json")
                                           @RequestParam(value = "json", required = true) String json){
        try {
            MessageNoticeSetting messageNoticeSetting = objectMapper.readValue(json, MessageNoticeSetting.class);
            if(messageNoticeSetting.getId()==null){
                return error(-1, "参数错误");
            }
            messageService.saveMessageNoticeSetting(messageNoticeSetting);
            return write(200, "设置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "设置失败");
        }
    }
}

+ 66 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/PatientInfoController.java

@ -26,7 +26,11 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 医生端:患者分组管理
@ -48,6 +52,9 @@ public class PatientInfoController extends BaseController {
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private SendMessageService sendMessageService;
    /**
     * 获取患者基本信息
     *
@ -388,6 +395,65 @@ public class PatientInfoController extends BaseController {
        }
    }
    /**
     * 修改居民手机号码
     * @param patient 居民code
     * @param newMobile 新手机号
     * @param oldMobile 旧手机号
     * @return
     */
    @ObserverRequired
    @RequestMapping(value = "/updateMobile", method = RequestMethod.POST)
    @ResponseBody
    public String updatePatientMobile(@ApiParam(value = "居民code", name = "patient") @RequestParam(required = true) String patient,
                         @ApiParam(value = "新手机号", name = "newMobile") @RequestParam(required = true) String newMobile,
                         @ApiParam(value = "旧手机号", name = "oldMobile") @RequestParam(required = false) String oldMobile) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不允许为空!");
            }
            if (StringUtils.isEmpty(newMobile)) {
                return error(-1, "新手机号不允许为空!");
            }
            String keyword = "新手机号码"+newMobile;
            if (StringUtils.isNotEmpty(oldMobile)) {
                keyword = "原关联手机号码"+oldMobile+"变更为"+keyword;
            }
            String reg = "^1[34578][0-9]{9}$";
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(newMobile);
            Boolean flag = matcher.matches();
            if (!flag){
                return error(-1, "新手机号格式不正确!");
            }
            Patient patient1 = patientDao.findByCode(patient);
            String patientName = patient1.getName();
            String openid = patient1.getOpenid();
            int result = patientInfoService.updateMobile(patient, newMobile);
            if (result == -1) {
                return error(-1, "居民信息查找失败");
            } else if (result == 1) {
                String first = patientName+",您好!\n"+"您的家庭医生已将您账号关联的手机号码进行变更";
                String remark = "您可使用新手机号码登录i健康平台";
                String url = "/grzx/html/my-detail.html?openid=" + openid + "&toUser=" + patient + "&toName=" + patientName;
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Boolean mark = sendMessageService.sendTemplate(10,patient,url,first,remark,patientName,format.format(new Date()),keyword);
                if (!mark){
                    String msg = patientName+",您好!您的家庭医生已将您账号关联的手机号码变更:"+keyword+".您可以使用新手机号码登录i健康平台.";
                    sendMessageService.sendMessage(newMobile,msg);
                }
                return write(200, "手机号更新成功");
            } else {
                return write(-1, "手机号更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "注册失败!");
        }
    }
    @RequestMapping(value = "getArchiveComboList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("获取居民建档详细信息下拉列表集合")

+ 96 - 6
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/EsStatisticsController.java

@ -373,7 +373,6 @@ public class EsStatisticsController extends BaseController {
    /**
     * 获取签约率、签约完成率 续签率
     * t
     *
     * @param endDate 截止日期
     * @param area    区域
@ -405,10 +404,10 @@ public class EsStatisticsController extends BaseController {
//                JSONObject signRate = statisticsAllService.getSignRate(endDate, area, level,year);
//                JSONObject signTaskRate = statisticsAllService.getSignTaskRate(endDate, area, level,year);
                long sign = statisticsESService.getIndexTotal(endDate, area, level, "1", "2");
                long sign = statisticsESService.getIndexTotal(endDate, area, level, "1", SaveModel.timeLevel_DDL);
                long weiJf = statisticsESService.getWeiJiaoFei(endDate, area, level);
                JSONObject jo = statisticsESService.getRenewPercent(level + "", area, Constant.getNowYear());
                JSONObject signRate = statisticsESService.getSignRate(endDate, area, level, year);
                JSONObject signRate = statisticsESService.getSignRate(endDate, area, level, year,"1");
                JSONObject signTaskRate = statisticsESService.getSignTaskRate(endDate, area, level, year);
                result.put("sign", sign);
@ -520,7 +519,7 @@ public class EsStatisticsController extends BaseController {
     * @param date
     * @param area
     * @param level   level1_type等级 1:团队 2社区机构 3区级 4市级
     * @param index   quotoCode 18/19两率  2  3  4  5  7  9  10  13 17 20 21  28 29
     * @param index   quotoCode 18/19两率  2  3  4  5  7  9  10  13 17 20 21  28 29 72 73
     * @param sort    0:升序 1:降序
     * @param lowCode
     * @return
@ -552,7 +551,9 @@ public class EsStatisticsController extends BaseController {
                if (index.equals("17")) {
                    //sort=1&date=2017-07-13&level=4&index=17&area=350200&lowLevel=1&lowCode=3
                    result.put("index_" + index, statisticsESService.getLevelTwoLowLevelTotalTeamLeader(date, area, level, index, sort, lowLevel, lowCode, year));
                } else {
                }else if (index.equals("73")){
                    result.put("index_"+index, statisticsESService.getLowLevelTotalOnlineTeamLeader(date,area,level,index,sort,lowLevel,year,lowCode));
                } else{
                    result.put("index_" + index, statisticsESService.getLevelTwoLowLevelTotal(date, area, level, index, sort, lowLevel, lowCode, year));
                }
            } else {
@ -571,7 +572,9 @@ public class EsStatisticsController extends BaseController {
                        // sort=1&date=2017-07-13&level=4&index=13&area=350200&lowCode=
                        idx="1";
                        result.put("index_" + idx, statisticsESService.getLowLevelTotalTeamLeader(date, area, level, idx, sort, lowLevel, year));
                    } else {
                    }else if(idx.equals("72")){
                        result.put("index_"+idx, statisticsESService.getLowLevelTotalOnlineTeamLeader(date,area,level,idx,sort,lowLevel,year,""));
                    }else {
                        result.put("index_" + idx, statisticsESService.getLowLevelTotal(date, area, level, idx, sort, lowLevel, year));
                    }
                }
@ -1864,4 +1867,91 @@ public class EsStatisticsController extends BaseController {
    }
    /*=================================长处方分析end==============================================*/
    /*==================================版本1.4.1统计优化开始start=====================================*/
    /**
     * 获取签约率、签约完成率 续签率
     *
     * @param endDate 截止日期
     * @param area    区域
     * @param level   区域级别 4:城市 3:区 2:社区 1:团队
     * @return
     */
    @RequestMapping(value = "/sign_info_online")
    @ResponseBody
    public String getAreaSignInfoOnline(@RequestParam(required = true) String endDate,
                                  @RequestParam(required = true) String area,
                                  @RequestParam(required = true) int level,
                                  @RequestParam(required = false) String lowCode,
                                  @RequestParam(required = false) String year) {
        try {
            //新版与旧版统计适配
            level = elasticsearchUtil.changeLevel(level);
            JSONObject result = new JSONObject();
            //year没传默认是今年
            if (org.springframework.util.StringUtils.isEmpty(year)) {
                year = Constant.getNowYear();
            }
            if (StringUtils.isEmpty(lowCode)) {
                //总签约数量
                long sign = statisticsESService.getIndexTotal(endDate, area, level, "1", SaveModel.timeLevel_DDL);
                //总线上签约数量
                long signOnline = statisticsESService.getIndexTotal(endDate,area,level,"72",SaveModel.timeLevel_DDL);
                //总签约率
                JSONObject signRate = statisticsESService.getSignRate(endDate, area, level, year,"1");
                //线上签约率=线上签约人数/总签约量
                JSONObject signOnlineRate = statisticsESService.getSignOnlineRate(endDate,area,level,year,sign);
                //result.put("sign", sign);
                result.put("signOnline", signOnline);
                result.put("signRate", signRate);
                result.put("signOnlineRate", signOnlineRate);
            } else {
                //如果年度不是当前年度 就根据endDate 找到那个年度的最后一天的数据
                if (!Constant.getNowYear().equals(year)) {
                    endDate = (Integer.valueOf(year) + 1) + "-06-30";
                }
                result = statisticsESService.getGroupInfoOnline(endDate, lowCode, area, level, year);
            }
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取 线上续签率和续签率
     * 前端:线上续签
     *
     * @param index 29,43,44 (51,53,54 服务类型维度)
     * @param level 等级  4 市  3区  2社区 1团队
     * @param code  市 默认是厦门市 350200  区 就是区的code  社区就是社区的code 团队就是团队的code.
     * @param year  年份 非比传
     * @param lowCode 服务类型维度code(老年人3,高血压1,糖尿病2)
     * @return
     */
    @RequestMapping(value = "/getRenewPercentOnline", method = RequestMethod.GET)
    @ResponseBody
    public String getRenewPercentOnline(
            @RequestParam(required = true) String index,//续签index
            @RequestParam(required = true) int level,
            @RequestParam(required = true) String code,
            @RequestParam(required = false) String year,
            @RequestParam(required = false) String lowCode) {
        try {
            //year没传默认是今年
            /*if (org.springframework.util.StringUtils.isEmpty(year)) {
                year = Constant.getNowYear();
            }*/
            return write(200,"查询成功!","data",statisticsESService.getRenewPercentOnline(index,elasticsearchUtil.changeLevel(level),code,year,lowCode));
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    /*==================================版本1.4.1统计优化结束 end=====================================*/
}

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

@ -152,6 +152,7 @@ public class GcEduArticleController extends WeixinBaseController {
        List<Patient> patients = healthEduArticlePatient.getPatients();
        patients.stream().forEach(one -> {
            healthEduArticlePatient.setPatient(one.getCode());
            healthEduArticlePatient.setPatients(null);
            jmsTemplate.send(channelName, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
@ -200,13 +201,14 @@ public class GcEduArticleController extends WeixinBaseController {
    @RequestMapping(value = "pushArticleLogs", method = RequestMethod.GET)
    @ApiOperation("查询卫计委给患者推送记录 ")
    public ResultPageListModel<HealthEduArticlePatientModel> pushArticleLogs(
            @ApiParam(name = "firstLevelCategoryId", value = "文章所属一级类别ID", required = false) @RequestParam(value = "firstLevelCategoryId", required = false) String firstLevelCategoryId,
            @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 (pagesize > 1000) {
                pagesize = 1000;
            }
            List<HealthEduArticlePatientModel> eduArticlePatients = gcEduArticleService.pushArticleLogs(page,pagesize,getUID(),1);
            List<HealthEduArticlePatientModel> eduArticlePatients = gcEduArticleService.pushArticleLogs(page,pagesize,getUID(),1,firstLevelCategoryId);
            Long count = gcEduArticleService.pushArticleLogsCount(getUID(),1);
            return new ResultPageListModel(
                    page,

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

@ -224,17 +224,18 @@ public class GcEduArticleService {
        HealthEduArticlePatient healthEduArticlePatient = new HealthEduArticlePatient();
        //1、医生,2、卫计委
        //如果是卫计委得区别角色
        Doctor doctor = null;
        Doctor doctor = doctorDao.findByCode(sendCode);
        if (sendType == 2) {
            String sql = "select r.code as roleCode from wlyy_user_role u " +
                    "left join wlyy_role r on r.`code`=u.role where u.user='" + sendCode + "'";
                    "left join wlyy_role r on r.`code`=u.role where u.user='" + sendCode + "' and LENGTH(u.role)=6";
            Map<String, Object> result = jdbcTemplate.queryForMap(sql);
            //角色的code值
            healthEduArticlePatient.setSendCode(result.get("roleCode") + "");
        } else {
            doctor = doctorDao.findByCode(sendCode);
            healthEduArticlePatient.setSendCode(sendCode);
        }
        healthEduArticlePatient.setDoctorCode(sendCode);
        healthEduArticlePatient.setDoctorName(doctor.getName());
        healthEduArticlePatient.setSendName(sendName);
        healthEduArticlePatient.setSendType(sendType);
        healthEduArticlePatient.setAdminTeamCode(teamId);
@ -250,6 +251,7 @@ public class GcEduArticleService {
        healthEduArticlePatient.setBatchNo(batchNo);
        healthEduArticlePatient.setCreateTime(new Date());
        //通过文章id 获取文章详情
        JSONObject article = healthEducationArticleService.getArticalById(articleId);
@ -263,7 +265,7 @@ public class GcEduArticleService {
        healthEduArticlePatient.setLevel1Type(article.get("firstLevelCategoryId") + "");
        healthEduArticlePatient.setLevel2Type(article.get("secondLevelCategoryId") + "");
        healthEduArticlePatient.setType("1");//文章
        healthEduArticlePatient.setArticleUrl(articleBaseUrl+"/web/jkEdu/articleDetail.html?behavior=4&articleId="+articleId);
        healthEduArticlePatient.setArticleUrl(articleBaseUrl+"JkEduWeb/web/jkEdu/articleDetail.html?behavior=4&articleId="+articleId);
        healthEduArticlePatient.setPatients(patientList);
        //保存到ES中
@ -497,19 +499,22 @@ public class GcEduArticleService {
     * @return
     * @throws Exception
     */
    public List<HealthEduArticlePatientModel> pushArticleLogs(int page, int pagesize, String sendCode,int sendType) throws Exception {
    public List<HealthEduArticlePatientModel> pushArticleLogs(int page, int pagesize, String sendCode,int sendType,String firstLevelCategoryId) throws Exception {
        pagesize = page * pagesize;
        page = (page - 1) * pagesize;
        if(sendType==1){
            String sql = "select r.code as roleCode from wlyy_user_role u " +
                    "left join wlyy_role r on r.`code`=u.role where u.user='" + sendCode + "'";
                    "left join wlyy_role r on r.`code`=u.role where u.user='" + sendCode + "' and LENGTH(u.role)=6";
            Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
            sendCode = resultMap.get("roleCode").toString();
        }
        StringBuffer sql2 = new StringBuffer("select *  from   " + esType +
                " where  sendCode='" + sendCode + "' ");
                " where  sendCode='" + sendCode + "'");
        if(!StringUtils.isEmpty(firstLevelCategoryId)){
            sql2.append("and level1Type="+firstLevelCategoryId);
        }
        sql2.append("  order by createTime limit " + page + "," + pagesize);
        List<com.yihu.es.entity.HealthEduArticlePatient> esList = elasticsearchUtil.excute(sql2.toString(), com.yihu.es.entity.HealthEduArticlePatient.class, esIndex, esType);
        Map<String, HealthEduArticlePatientModel> result = new HashMap<>();
@ -586,7 +591,7 @@ public class GcEduArticleService {
        if(sendType==1){
            String sql = "select r.code as roleCode from wlyy_user_role u " +
                    "left join wlyy_role r on r.`code`=u.role where u.user='" + sendCode + "'";
                    "left join wlyy_role r on r.`code`=u.role where u.user='" + sendCode + "'"+ " and LENGTH(u.role)=6";;
            Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
            sendCode = resultMap.get("roleCode").toString();

+ 18 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/vo/HealthEduArticlePatientModel.java

@ -47,6 +47,8 @@ public class HealthEduArticlePatientModel {
    private String articleCover="";//封面图
    private String computeTime;//时间
    private String photo;//医生头像
    private String operatorName;//文章作者
    public String getSendCode() {
        return sendCode;
@ -175,4 +177,20 @@ public class HealthEduArticlePatientModel {
    public void setComputeTime(String computeTime) {
        this.computeTime = computeTime;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
    public String getOperatorName() {
        return operatorName;
    }
    public void setOperatorName(String operatorName) {
        this.operatorName = operatorName;
    }
}

+ 17 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/wechat/util/WeiXinTempMsgSendUtils.java

@ -97,4 +97,21 @@ public class WeiXinTempMsgSendUtils {
        return data;
    }
    /**
     * 构建微信模板内容消息体 加入队列发送无字体格式
     *
     * @param first    消息头
     * @param remark   备注
     * @param keywords 消息体
     * @return
     */
    public JSONObject getTemplateContent(String first, String remark, String... keywords) throws Exception{
        JSONObject data = new JSONObject();
        data.put("first", first);
        data.put("remark", remark);
        for (int i = 0; i < keywords.length; i++) {
            data.put("keyword" + (i + 1), keywords[i]);
        }
        return data;
    }
}

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

@ -113,7 +113,7 @@ es:
#集美宣教居民端健康文章
jkEdu:
  web:
    articleBaseUrl: http://172.19.103.87:9088/jkeduweb
    articleBaseUrl: http://172.19.103.87:9088/
#消息队列
activemq:

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

@ -97,11 +97,11 @@ pushMes:
  redis_prescription_title: redisPrescription
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient_test2
    HealthEduArticlePatient: health_edu_article_patient_test3
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
  type:
    HealthEduArticlePatient: health_edu_article_patient_test2
    HealthEduArticlePatient: health_edu_article_patient_test3
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
  host:  http://172.19.103.68:9200
@ -112,7 +112,7 @@ es:
#http://172.19.103.87:9088/JkEduWeb
jkEdu:
  web:
    articleBaseUrl: http://172.19.103.87:9088/jkeduweb
    articleBaseUrl: http://172.19.103.87:9088/
#消息队列

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

@ -110,7 +110,7 @@ es:
#集美宣教居民端健康文章
jkEdu:
  web:
    articleBaseUrl: http://172.19.103.87:9088/jkeduweb
    articleBaseUrl: http://172.19.103.87:9088/
#消息队列
activemq:

+ 3 - 3
patient-co/patient-co-wlyy/src/main/resources/application-test.yml

@ -94,11 +94,11 @@ pushMes:
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient_test
    HealthEduArticlePatient: health_edu_article_patient_test3
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
  type:
    HealthEduArticlePatient: health_edu_article_patient_test
    HealthEduArticlePatient: health_edu_article_patient_test3
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
  host:  http://172.19.103.68:9200
@ -108,7 +108,7 @@ es:
#集美宣教居民端健康文章
jkEdu:
  web:
    articleBaseUrl: http://172.19.103.87:9088/jkeduweb
    articleBaseUrl: http://172.19.103.87:9088/
#消息队列
activemq: