Prechádzať zdrojové kódy

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

huangwenjie 7 rokov pred
rodič
commit
c3647aa83c
74 zmenil súbory, kde vykonal 7355 pridanie a 2549 odobranie
  1. 5 3
      common/common-entity/src/main/java/com/yihu/device/entity/DevicePatientHealthIndex.java
  2. 21 8
      patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/account/CustomerService.java
  3. 7 2
      patient-co-manage/wlyy-manage/src/main/resources/application.yml
  4. 3 3
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/model/PatientHealthIndex.java
  5. 3 3
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java
  6. 2 2
      patient-co-service/wlyy_service/src/main/webapp/prescription_consulting/js/prescription_consulting_info.js
  7. 0 59
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  8. 0 93
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java
  9. 0 49
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java
  10. 4 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/common/account/DoctorService.java
  11. 11 7
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java
  12. 0 201
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/util/ElasticsearchUtil.java
  13. 366 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java
  14. 484 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java
  15. 564 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java
  16. 42 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java
  17. 48 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/data/DataController.java
  18. 65 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java
  19. 45 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java
  20. 88 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java
  21. 63 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java
  22. 49 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java
  23. 80 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/icd/Icd10Controller.java
  24. 350 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/im/imController.java
  25. 35 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java
  26. 399 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java
  27. 115 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java
  28. 61 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java
  29. 45 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java
  30. 108 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java
  31. 353 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java
  32. 326 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java
  33. 61 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java
  34. 65 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java
  35. 2033 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java
  36. 0 69
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/doctor/template/DoctorFeldsherTemplateController.java
  37. 0 175
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcEduArticleController.java
  38. 22 45
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcMessageController.java
  39. 0 271
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/third/gateway/service/GcEduArticleService.java
  40. 10 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/wechat/util/WeiXinAccessTokenUtils.java
  41. 34 2
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/wechat/util/WeiXinTempMsgSendUtils.java
  42. 4 4
      patient-co/patient-co-doctor-assistant/src/main/resources/application-devtest.yml
  43. 6 26
      patient-co/patient-co-doctor-assistant/src/main/resources/application-prod.yml
  44. 4 4
      patient-co/patient-co-doctor-assistant/src/main/resources/application-test.yml
  45. 0 90
      patient-co/patient-co-doctor-assistant/src/main/resources/wechat/weixin_menu.txt
  46. 0 92
      patient-co/patient-co-doctor-assistant/src/main/resources/wechat/weixin_menu_jimei.txt
  47. 90 90
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/activemq/StartListener.java
  48. 70 70
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  49. 93 93
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java
  50. 49 49
      patient-co/patient-co-wlyy-job/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java
  51. 59 59
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/ActiveMQConfig.java
  52. 93 93
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/es/ElasticFactory.java
  53. 49 49
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/config/es/ElastricSearchSave.java
  54. 2 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/health/repository/DevicePatientHealthIndexDao.java
  55. 2 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/repository/patient/PatientDao.java
  56. 5 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java
  57. 2 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/label/SignPatientLabelInfoService.java
  58. 40 10
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionInfoService.java
  59. 8 6
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/scheme/DoctorSchemeService.java
  60. 4 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/DoctorService.java
  61. 4 18
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/common/account/PatientService.java
  62. 201 201
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/ElasticsearchUtil.java
  63. 2 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java
  64. 2 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/health/DoctorHealthController.java
  65. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/patient/SignPatientLabelInfoController.java
  66. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/scheme/DoctroSchemeController.java
  67. 8 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/consult/ConsultController.java
  68. 4 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java
  69. 2 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/PatientHealthController.java
  70. 213 213
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcEduArticleController.java
  71. 314 314
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/gateway/service/GcEduArticleService.java
  72. 1 0
      patient-co/patient-co-wlyy/src/main/resources/application-devtest.yml
  73. 54 55
      patient-co/patient-co-wlyy/src/main/resources/application-local.yml
  74. 1 1
      patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu_jimei.txt

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

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

+ 21 - 8
patient-co-manage/wlyy-manage/src/main/java/com/yihu/wlyy/service/manager/account/CustomerService.java

@ -11,6 +11,8 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@ -33,6 +35,8 @@ public class CustomerService{
	@Value(("${doctorAssistant.api}")+"/wlyygc/doctor/message")
	private String messageApi;
	private Logger logger = LoggerFactory.getLogger(CustomerService.class);
	public Map<String,Object> findServerInfo(Patient patient) throws Exception {
		Map<String, Object> resp = new HashMap<>();
@ -119,10 +123,14 @@ public class CustomerService{
			List<NameValuePair> par = new ArrayList<NameValuePair>();
			par.add(new BasicNameValuePair("openIds", openId));
			par.add(new BasicNameValuePair("content", msg));
			JSONObject params = new JSONObject();
			String result = HttpClientUtil.post(messageApi+"/sendWechatMessage", par,"UTF-8");
			JSONObject resultJson = new JSONObject(result);
			if(1!=resultJson.getInt("successNum")){
			try {
				String result = HttpClientUtil.post(messageApi+"/sendWechatMessage", par,"UTF-8");
				logger.info("微信发送消息返回结果:"+result);
				JSONObject resultJson = new JSONObject(result);
				if(1!=resultJson.getInt("successNum")){
					resp.put("wechat","-1");//-1代表发送失败
				}
			}catch (Exception e){
				resp.put("wechat","-1");//-1代表发送失败
			}
		}
@ -130,13 +138,18 @@ public class CustomerService{
		//发送短信消息啦
		String mobile = doctor.getMobile();
		if(!StringUtils.isBlank(mobile)&&!"2".equals(type)){
			msg+="\n您可通过微信关注\"i健康智能助手\"公众号(微信号:厦门i健康)更快更便捷的获取服务信息。";
			msg+="\n您可通过微信关注\"i健康智能助手\"公众号更快更便捷的获取服务信息。";
			List<NameValuePair> par = new ArrayList<NameValuePair>();
			par.add(new BasicNameValuePair("mobiles", mobile));
			par.add(new BasicNameValuePair("content", msg));
			String result = HttpClientUtil.post(messageApi+"/sendMobileMessage",par,"UTF-8");
			JSONObject resultJson = new JSONObject(result);
			if(1!=resultJson.getInt("successNum")){
			try {
				String result = HttpClientUtil.post(messageApi+"/sendMobileMessage",par,"UTF-8");
				logger.info("发送短信消息返回结果:"+result);
				JSONObject resultJson = new JSONObject(result);
				if(1!=resultJson.getInt("successNum")){
					resp.put("mobile","-1");//-1代表发送失败
				}
			}catch (Exception e){
				resp.put("mobile","-1");//-1代表发送失败
			}
		}

+ 7 - 2
patient-co-manage/wlyy-manage/src/main/resources/application.yml

@ -74,7 +74,8 @@ im-service:
yueren:
  api: http://120.77.209.211:8080
doctorAssistant:
  api: http://127.0.0.1:8080
  api: http://192.168.131.113:8080
#  api: http://172.19.103.88:10090/wlyy
---
spring:
@ -105,6 +106,8 @@ im-service:
  im_service_url: http://172.19.103.88:3000/api/v2
yueren:
  api: http://120.77.209.211:8080
doctorAssistant:
  api: http://172.19.103.88:10090/wlyy
---
spring:
@ -132,4 +135,6 @@ service-gateway:
im-service:
  im_service_url: http://27.155.101.77:3000/api/v2
yueren:
  api: http://120.77.209.211:8080
  api: http://120.77.209.211:8080
doctorAssistant:
  api: http://www.xmtyw.cn/assistant

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

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

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

@ -423,20 +423,20 @@ public class DeviceService {
                }
                for (PatientHealthIndex patientHealthIndex : bloodPressurepatientHealthIndices) {
                    if(1 == patientHealthIndex.getStatus()){
                    if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                        bloodPressureBbnormalCount++;
                    }
                }
                for (PatientHealthIndex patientHealthIndex : bloodSuggurpatientHealthIndices) {
                    if(1 == patientHealthIndex.getStatus()){
                    if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                        bloodSuggurBbnormalCount++;
                    }
                }
                //连续3次异常,修改用户为预警状态
                if( (3 == bloodPressureBbnormalCount || 3 == bloodSuggurBbnormalCount) && 0 == patient.getStandardStatus()){
                if( (bloodPressureBbnormalCount >=3 || bloodSuggurBbnormalCount >=3) && 0 == patient.getStandardStatus()){
                    patient.setStandardStatus(1);
                }else{
                    Date end = new Date();

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

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

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

@ -1,59 +0,0 @@
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;
    }
}

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

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

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

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

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

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

+ 11 - 7
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/service/template/DoctorFeldsherTemplateService.java

@ -14,6 +14,7 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -41,6 +42,8 @@ public class DoctorFeldsherTemplateService extends BaseService {
    private WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    private ImUtill imUtill;
    @Value("${server.server_url}")
    private String server_url;
    private static final Logger logger = LoggerFactory.getLogger(DoctorFeldsherTemplateService.class);
@ -242,19 +245,20 @@ public class DoctorFeldsherTemplateService extends BaseService {
    }
    /**
     *  拼装医生助手 医生类模板消息并发送
     * @param doctorCode 医生code
     * @param sessionId 会话Id
     * @param sessionType 会话类型
     * 拼装医生助手 医生类模板消息并发送
     *
     * @param doctorCode   医生code
     * @param sessionId    会话Id
     * @param sessionType  会话类型
     * @param businessType 消息类型
     * @param from 发送者
     * @param content 消息内容
     * @param from         发送者
     * @param content      消息内容
     * @return
     */
    public Boolean sendDoctorTemplate(String doctorCode, String sessionId, String sessionType, String businessType, String from, String content) {
        try {
            String remark = "请进入手机APP查看,如尚未安装APP请点击详情下载安装";
            String url = "www.baidu.com";
            String url = server_url + "wx_doctor/html/home/html/jumpApp.html";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            JSONObject sendJson = new JSONObject();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 2033 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/doctor/account/DoctorController.java

@ -0,0 +1,2033 @@
package com.yihu.wlyy.web.doctor.account;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.profile.DoctorComment;
import com.yihu.wlyy.entity.doctor.team.sign.SignPatientLabel;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.organization.HospitalDept;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.patient.SocialSecurityInfo;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamDao;
import com.yihu.wlyy.repository.doctor.SignPatientLabelDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.service.app.consult.DoctorCommentService;
import com.yihu.wlyy.service.app.hospital.HospitalDeptService;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.service.common.account.RoleService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdcardValidator;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * 用户注册的Controller.
 *
 * @author calvin
 */
@Controller
@RequestMapping(value = "/doctor", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生")
public class DoctorController extends BaseController {
    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private DoctorCommentService doctorCommentService;
    @Autowired
    private DrHealthTeamService drHealthTeamService;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private ConsultTeamService consultTeamService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private HospitalDeptService hospitalDeptService;
    @Autowired
    private HospitalDeptService deptService;
    @Autowired
    private DoctorWorkTimeService workTimeService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    SignPatientLabelDao labelDao;
    @Autowired
    private CommonUtil CommonUtil;
    /**
     * 社区医院下医生列表查询接口 没分页
     *
     * @param hospital 医院标识
     * @return
     */
    @ApiOperation("社区医院下医生列表查询接口 没分页")
    @RequestMapping(value = "getDoctorsByhospitalNoPage",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorsByhospitalNoPage(
            @RequestParam(required = false) String hospital,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer type) {
        try {
            JSONArray array = new JSONArray();
            List<Map<String, Object>> list = familyContractService.getDoctorsByhospitalNoPage(hospital, name, type);
            if (list != null) {
                for (Map<String, Object> doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.get("id"));
                    // 医生标识
                    json.put("code", doctor.get("code"));
                    // 医生姓名
                    json.put("name", doctor.get("name"));
                    // 所在医院名称
                    json.put("hospital", doctor.get("hospital"));
                    // 所在医院名称
                    json.put("hospital_name", doctor.get("hospital_name"));
                    // 科室名称
                    json.put("dept_name", (doctor.get("dept_name") == null ||
                            StringUtils.isEmpty(doctor.get("dept_name").toString())) ? " " : doctor.get("dept_name"));
                    // 职称名称
                    json.put("job_name", (doctor.get("job_name") == null ||
                            StringUtils.isEmpty(doctor.get("job_name").toString())) ? " " : doctor.get("job_name"));
                    // 头像
                    json.put("photo", doctor.get("photo"));
                    // 简介
                    json.put("introduce", doctor.get("introduce"));
                    // 专长
                    json.put("expertise", doctor.get("expertise"));
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 社区医院下医生列表查询接口 有分页
     *
     * @param hospital 医院标识
     * @return
     */
    @ApiOperation("社区医院下医生列表查询接口 有分页")
    @RequestMapping(value = "getDoctorsByhospital",method ={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String getDoctorsByhospital(
            @RequestParam(required = false) String hospital, //医院code
            @RequestParam(required = false) String city, //市代码
            @RequestParam(required = false) String town, //区代码
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String name, //名称
            @RequestParam(required = true) Long id,
            @RequestParam(required = true) Integer pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = familyContractService.findDoctors(hospital, city, town, name, type, id, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    // 医生标识
                    json.put("code", doctor.getCode());
                    // 医生姓名
                    json.put("name", doctor.getName());
                    // 所在医院名称
                    json.put("hospital_name", doctor.getHospitalName());
                    // 科室名称
                    json.put("dept_name", StringUtils.isEmpty(doctor.getDeptName()) ? " " : doctor.getDeptName());
                    // 职称名称
                    json.put("job_name", StringUtils.isEmpty(doctor.getJobName()) ? " " : doctor.getJobName());
                    // 头像
                    json.put("photo", doctor.getPhoto());
                    // 简介
                    json.put("introduce", doctor.getIntroduce());
                    // 专长
                    json.put("expertise", doctor.getExpertise());
                    array.put(json);
                }
            }
            return write(200, "获取医院医生列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院医生列表失败!");
        }
    }
    /**
     * 社区医院列表查询接口
     *
     * @param type     医院类型:0全部,1大医院,2社区医院
     * @param province 患标识
     * @param city     城市标识
     * @param key      搜索关键字,用于搜索医院名称
     * @return
     */
    @ApiOperation("社区医院列表查询接口")
    @RequestMapping(value = "hospitals",method ={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String hospitals(
            int type,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String town,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Hospital> list = familyContractService.findHospitals(type, province, city, town, key, id, pagesize);
            if (list != null) {
                for (Hospital hospital : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    // 医院标识
                    json.put("code", hospital.getCode());
                    // 医院名称
                    json.put("name", hospital.getName());
                    // 省名
                    json.put("province_name", hospital.getProvinceName());
                    // 城市名
                    json.put("city_name", hospital.getCityName());
                    // 区县名
                    json.put("town_name", hospital.getTownName());
                    // 详细地址
                    json.put("address", hospital.getAddress());
                    // 简介
                    json.put("intro", hospital.getIntro());
                    // 医院图片
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "获取医院列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取医院列表失败!");
        }
    }
    /**
     * 查询存在医生的医院列表
     *
     * @param type     类型 1:医院 2社区
     * @param province 省份
     * @param city     城市
     * @param town     城镇
     * @param key      名字搜索
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    @ApiOperation("查询存在医生的医院列表")
    @RequestMapping(value = "hospitals_list",method =RequestMethod.POST)
    @ResponseBody
    public String hospitalL(@RequestParam(required = true) int type,
                            @RequestParam(required = false) String province,
                            @RequestParam(required = false) String city,
                            @RequestParam(required = false) String town,
                            @RequestParam(required = false) String key,
                            @RequestParam(required = true) int page,
                            @RequestParam(required = true) int pagesize) {
        try {
            if (type != 1 && type != 2) {
                return error(-1, "医院类型错误");
            }
            page = page >= 1 ? page - 1 : 0;
            List<Hospital> hos = hospitalService.getHospitals(type, province, city, town, key,null, page, pagesize);
            return write(200, "查询成功", "data", hos);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 查询某个医院存在医生科室列表
     *
     * @param hospital 医院
     * @param key      科室名字搜索
     * @param page     第几页
     * @param pagesize 页大小
     * @return
     */
    @ApiOperation("查询某个医院存在医生科室列表")
    @RequestMapping(value = "/dept_list",method =RequestMethod.POST)
    @ResponseBody
    public String deptList(@RequestParam(required = true) String hospital,
                           @RequestParam(required = false) String key,
                           @RequestParam(required = true) int page,
                           @RequestParam(required = true) int pagesize) {
        try {
            if (StringUtils.isEmpty(hospital)) {
                return error(-1, "医院不能为空");
            }
            page = page >= 1 ? page - 1 : 0;
            List<HospitalDept> dept = deptService.getHospitalDept(hospital, key, page, pagesize);
            return write(200, "查询成功", "data", dept);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据科室查询当前在工作医生
     *
     * @param dept
     * @param hospital
     * @param level
     * @param key
     * @param page
     * @param pagesize
     * @return
     */
    @ApiOperation("根据科室查询当前在工作医生")
    @RequestMapping(value = "/doctors_list",method =RequestMethod.POST)
    @ResponseBody
    public String findWorkingDoctorByDept(@RequestParam(required = false) String dept,
                                          @RequestParam(required = false) String hospital,
                                          @RequestParam(required = false, defaultValue = "1") String level,
                                          @RequestParam(required = false, defaultValue = "") String key,
                                          @RequestParam(required = false, defaultValue = "1") int page,
                                          @RequestParam(required = false, defaultValue = "15") int pagesize) {
        try {
            if (page >= 1) {
                page = page - 1;
            }
            JSONArray doctors = doctorInfoService.findWorkingDoctorListByDept(dept, hospital, level, key, page, pagesize);
            return write(200, "查询成功", "data", doctors);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据机构查找科室
     *
     * @param hospital 机构code
     * @param key      科室名称
     * @param id       主键
     * @param pagesize 每页显示条数
     * @return
     */
    @ApiOperation("根据机构查找科室")
    @RequestMapping(value = "findDeptByHsoptail",method =RequestMethod.POST)
    @ResponseBody
    public String findDeptByHsoptail(
            String hospital,
            @RequestParam(required = false) String key,
            long id,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<HospitalDept> list = hospitalDeptService.findDeptByHsoptail(hospital, key, id, pagesize);
            if (list != null) {
                for (HospitalDept dept : list) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", dept.getId());
                    // 科室标识
                    json.put("code", dept.getCode());
                    // 科室名称
                    json.put("name", dept.getName());
                    array.put(json);
                }
            }
            return write(200, "获取科室列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取科室列表失败!");
        }
    }
    /**
     * 根据科室查找医生
     *
     * @param dept     科室code
     * @param key      医生名称
     * @param page     当前页
     * @param pagesize 每页显示条数
     * @return
     */
    @ApiOperation("根据科室查找医生")
    @RequestMapping(value = "findDoctorByDept",method =RequestMethod.POST)
    @ResponseBody
    public String findDoctorByDept(
            @RequestParam(required = false) String dept,
            @RequestParam(required = false) String hosptial,
            @RequestParam(required = false) String key,
            int page,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            Page<Doctor> list = doctorInfoService.findDoctorByDept(dept, hosptial, key, page, pagesize);
            if (list != null) {
                for (Doctor doctor : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "获取科室列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取科室列表失败!");
        }
    }
    /**
     * 名医列表
     *
     * @param key      医生名称
     * @param type     是否是名医 1是  0不是
     * @param level    医生的等级 1专科医生,2全科医生,3健康管理师 不传默认是全部
     * @param page     当前页
     * @param pagesize 每页显示条数
     * @return
     */
    @ApiOperation("名医列表")
    @RequestMapping(value = "findFamousDoctor",method =RequestMethod.POST)
    @ResponseBody
    public String findFamousDoctor(
            @RequestParam(required = false) String key,
            @RequestParam(required = false) Integer level,
            Integer type,
            int page,
            int pagesize) {
        try {
            JSONArray array = new JSONArray();
            List<Doctor> list = doctorInfoService.findFamousDoctorList(key, type, page, pagesize, level);
            if (list != null) {
                for (Doctor doctor : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    json.put("expertise", doctor.getExpertise());
                    json.put("isworking", 1);
                    array.put(json);
                }
            }
            return write(200, "获取名医列表成功!", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "获取名医列表失败!");
        }
    }
    /**
     * 退出登录
     *
     * @return
     */
    @ApiOperation("退出登录")
    @RequestMapping(value = "loginout",method =RequestMethod.POST)
    @ResponseBody
    public String loginout() {
        try {
            tokenService.delToken(2, getUID());
            return success("已成功退出!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @ApiOperation("医生基本信息查询接口")
    @RequestMapping(value = "baseinfo",method ={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String baseinfo(
            @RequestParam(required = false) String code) {
        try {
            if (StringUtils.isEmpty(code)) {
                code = getUID();
            }
            Doctor temp = doctorInfoService.findDoctorByCode(code);
            Integer leader = doctorAdminTeamDao.findLeader(code);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置医生手机号码
                json.put("mobile", temp.getMobile());
                // 设置医生标识
                json.put("code", temp.getCode());
                // 设置医生姓名
                json.put("name", temp.getName());
                // 设置医生头像
                json.put("photo", temp.getPhoto());
                // 设置医生性别
                json.put("sex", temp.getSex());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置城市名称
                json.put("cityName", temp.getCityName());
                // 设置医院名称
                json.put("hospitalName", temp.getHospitalName());
                // 设置医院
                json.put("hospital", temp.getHospital());
                // 设置部门名称
                json.put("deptName", StringUtils.isNotEmpty(temp.getDeptName()) ? temp.getDeptName() : "");
                // 设置职称
                json.put("jobName", StringUtils.isNotEmpty(temp.getJobName()) ? temp.getJobName() : "");
                // 设置医生专长
                json.put("expertise", StringUtils.isNotEmpty(temp.getExpertise()) ? temp.getExpertise() : "");
                // 设置医生简介
                json.put("introduce", StringUtils.isNotEmpty(temp.getIntroduce()) ? temp.getIntroduce() : "");
                // 二维码地址
                json.put("qrcode", temp.getQrcode());
                // 审核总数
                json.put("signed_amount", familyContractService.countAmountSigned(getUID()));
                // 等审核总数
                json.put("unsign_amount", familyContractService.countAmountUnsign(getUID()));
                // 咨询统计
                Map<String, Long> consultCount = consultTeamService.getAllCount(getUID());
                // 咨询总数
                json.put("consultAmount", consultCount.get("all"));
                // 当天咨询数
                json.put("consultAmountToday", consultCount.get("today"));
                //身份类型
                json.put("level", temp.getLevel().intValue());
                //身份证号
                json.put("idcard", temp.getIdcard());
                //是否认证
                json.put("isCertified", temp.getIscertified());
                //是否名医
                json.put("isFamous", temp.getIsFamous());
                //是否医生提示 提示过是1 其他都是0
                json.put("isPasswordPrompt", StringUtils.isEmpty(temp.getIsPasswordPrompt()) ? "0" : temp.getIsPasswordPrompt());
                //获取医生角色和区域权限
                List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(temp.getCode());
                json.put("userRole", roleMap);
                json.put("evaluateScore", temp.getEvaluateScore());
//                是否团队长
                json.put("isLeader", leader == null ? "0" : "1");
//                团队长所管辖的团队code 一个团队长只管辖一个团队
                json.put("adminTeamCode", leader);
                return write(200, "医生信息查询成功!", "data", json);
            } else {
                return error(-1, "医生信息查询失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败!");
        }
    }
    /**
     * 医生基本信息查询接口
     *
     * @return
     */
    @ApiOperation("医生基本信息查询接口")
    @RequestMapping(value = "baseinfoCount",method =RequestMethod.POST)
    @ResponseBody
    public String baseinfoCount(
            String doctorType) {
        try {
            Doctor temp = doctorInfoService.findDoctorByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                int count = familyContractService.countAmountSigned(getUID());
                // 审核总数
                json.put("signed_amount", count);
                int count1 = familyContractService.countAmountUnsign(getUID());
                // 等审核总数
                json.put("unsign_amount", count1);
                return write(200, "医生信息查询成功!", "data", json);
            } else {
                return error(-1, "医生信息查询失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败!");
        }
    }
    /**
     * 患者基本信息保存
     *
     * @param photo     頭像
     * @param sex       性別
     * @param expertise 专长
     * @param introduce 简介
     * @param province  省标识
     * @param city      市标识
     * @return
     */
    @ApiOperation("患者基本信息保存")
    @RequestMapping(value = "save",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String save(
            @RequestParam(required = false) String photo,
            @RequestParam(required = false) Integer sex,
            @RequestParam(required = false) String expertise,
            @RequestParam(required = false) String introduce,
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String mobile) {
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            if (StringUtils.isNotEmpty(mobile)) {
                if (!mobile.equals(doctor.getMobile())) {
                    if (doctorInfoService.findNormalByMobile(mobile) != null) {
                        return error(-2, "该手机号码已被注册!");
                    }
                    doctor.setMobile(mobile);
                }
            }
            // 设置头像
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
                if (StringUtils.isNotEmpty(photo)) {
                    doctor.setPhoto(photo);
                }
            }
            // 设置性别
            if (sex != null) {
                doctor.setSex(sex);
            }
            // 设置生日
            // if (StringUtils.isNotEmpty(birthday)) {
            // doctor.setBirthday(DateUtil.strToDate(birthday, DateUtil.YYYY_MM_DD));
            // }
            // 设置医生专长
            if (StringUtils.isNotEmpty(expertise)) {
                doctor.setExpertise(expertise);
            }
            // 设置介绍内容
            if (StringUtils.isNotEmpty(introduce)) {
                doctor.setIntroduce(introduce);
            }
            // 设置省份标识
            if (StringUtils.isNotEmpty(province)) {
                doctor.setProvince(province);
            }
            // 设置城市标识
            if (StringUtils.isNotEmpty(city)) {
                doctor.setCity(city);
            }
            // 设置区县标识
            // if (StringUtils.isNotEmpty(town)) {
            // doctor.setTown(town);
            // }
            // 设置医院标识
            // if (StringUtils.isNotEmpty(hospital)) {
            // doctor.setHospital(hospital);
            // }
            // // 设置部门标识
            // if (StringUtils.isNotEmpty(dept)) {
            // doctor.setDept(dept);
            // }
            // // 设置职称
            // if (StringUtils.isNotEmpty(job)) {
            // doctor.setJob(job);
            // }
            if (doctorInfoService.updateDoctor(doctor) != null) {
                // 修改成功
                return write(200, "保存成功!", "data", doctor.getPhoto());
            } else {
                // 注册失败
                return error(-1, "保存失败!");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败!");
        }
    }
    /**
     * 患者评价查询接口
     *
     * @param id       最后一个id
     * @param pagesize 分页大小
     * @return
     */
    @ApiOperation("患者评价查询接口")
    @RequestMapping(value = "comments",method =RequestMethod.POST)
    @ResponseBody
    public String comments(Integer id, Integer pagesize) {
        try {
            Page<DoctorComment> page = doctorCommentService.findByDoctor(getUID(), id, pagesize);
            JSONArray array = new JSONArray();
            if (page != null) {
                for (DoctorComment dc : page) {
                    if (dc == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // id
                    json.put("id", dc.getId());
                    // 评价人姓名
                    json.put("name", dc.getUname());
                    // 设置评价内容
                    json.put("content", dc.getContent());
                    // 评价星级
                    json.put("star", dc.getStar());
                    // 评价类型:1视频咨询评价、2图文咨询评价
                    json.put("type", dc.getType());
                    // 评价时间
                    json.put("czrq", DateUtil.dateToStrLong(dc.getCzrq()));
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", page, array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据类别获取医院列表
     *
     * @param type
     * @param query    查询条件 医院名称
     * @param id
     * @param pageSize 页数
     * @return
     */
    @ApiOperation("根据类别获取医院列表")
    @RequestMapping(value = "/hospital_list",method =RequestMethod.POST)
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) Integer type,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) long id,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Hospital> hospitalList = hospitalService.getHospitalList(query, type, id, pageSize);
            JSONArray array = new JSONArray();
            if (hospitalList != null) {
                for (Hospital hospital : hospitalList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", hospital.getId());
                    json.put("code", hospital.getCode());
                    json.put("name", hospital.getName());
                    json.put("province", hospital.getProvince());
                    json.put("provinceName", hospital.getProvinceName());
                    json.put("city", hospital.getCity());
                    json.put("cityName", hospital.getCityName());
                    json.put("town", hospital.getTown());
                    json.put("townName", hospital.getTownName());
                    json.put("level", hospital.getLevel());
                    String levelName = "";
                    switch (hospital.getLevel()) {
                        case 1:
                            levelName = "医院";
                            break;
                        case 2:
                            levelName = "社区医院";
                            break;
                    }
                    json.put("levelName", levelName);
                    json.put("address", hospital.getAddress());
                    json.put("intro", hospital.getIntro());
                    json.put("photo", hospital.getPhoto());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 邀请医生咨询
     *
     * @param patientCode
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation("根据类别获取医院列表")
    @RequestMapping(value = "/hospital_list_type",method =RequestMethod.POST)
    @ResponseBody
    public String getHospitalList(
            @RequestParam(required = true) int doctorType,
            @RequestParam(required = true) int consultType,
            @RequestParam(required = true) String patientCode,
            @RequestParam(required = false) String name,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            if (doctorType == 3) {
                //查找所有的全科医生
                Doctor doctor = doctorInfoService.getDoctor(consultType, patientCode);
                return null;
            } else if (doctorType == 2) {
                //查找所有的专科医生
                Page<Doctor> doctorList = doctorInfoService.getDoctorListByPatientCode(consultType, patientCode, name, page, pageSize);
                JSONArray array = new JSONArray();
                if (doctorList != null) {
                    for (Doctor doctor : doctorList) {
                        JSONObject json = new JSONObject();
                        json.put("id", doctor.getId());
                        json.put("code", doctor.getCode());
                        json.put("name", doctor.getName());
                        json.put("photo", doctor.getPhoto());
                        json.put("sex", doctor.getSex());
                        String sexName = "";
                        switch (doctor.getSex()) {
                            case 1:
                                sexName = "男";
                                break;
                            case 2:
                                sexName = "女";
                                break;
                        }
                        json.put("sexName", sexName);
                        json.put("job", doctor.getJob());
                        json.put("jobName", doctor.getJobName());
                        json.put("hospital", doctor.getHospital());
                        json.put("hospitalName", doctor.getHospitalName());
                        json.put("dept", doctor.getDept());
                        json.put("deptName", doctor.getDeptName());
                        array.put(json);
                    }
                }
                return write(200, "查询成功!", "list", array);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            error(ex);
            return error(-1, "查询失败!");
        }
        return null;
    }
    /**
     * 根据医院标识获取医生信息
     *
     * @param hospital 医院标识
     * @param query    查询条件 :医生名称
     * @param page
     * @param pageSize 页数
     * @return
     */
    @ApiOperation("根据医院标识获取医生信息")
    @RequestMapping(value = "/doctor_list",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String query,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(query, hospital, page, pageSize,2);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("evaluateScore", doctor.getEvaluateScore());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 登录患者获取三师信息
     *
     * @return
     */
    @ApiOperation("登录患者获取三师信息")
    @RequestMapping(value = "teachers",method =RequestMethod.POST)
    @ResponseBody
    public String teachers(String patient) {
        try {
            // 查询签约信息
            SignFamily signContract = familyContractService.findBySsPatient(patient);
            if (signContract == null) {
                return error(1, "无三师签约信息");
            }
            JSONObject doctorJson = new JSONObject();
            // 设置签约日期
            doctorJson.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
            // 签约编号
            doctorJson.put("team_code", signContract.getTeamCode());
            // 查询三师医生信息
            List<Doctor> doctors = drHealthTeamService.findTeamDoctors(patient, 1);
            JSONArray jsonArray = new JSONArray();
            if (doctors != null) {
                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    // 类型:1专科医生,2全科医生,3健康管理师
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    jsonArray.put(json);
                }
            }
            doctorJson.put("list", jsonArray);
            return write(200, "查询成功!", "data", doctorJson);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * @param type 医生类别 1专科医生,2全科医生,3健康管理师
     * @return
     */
    @RequestMapping(value = "/doctor_combobox",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctorCombobxByHospital(
            @RequestParam(required = true) String hospital,
            @RequestParam(required = false) String type) {
        try {
            List<Doctor> doctorList = doctorInfoService.getDoctorCombobxByHospital(type, hospital);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    if (hospital == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", doctor.getPhoto());
                    json.put("sex", doctor.getSex());
                    String sexName = "";
                    switch (doctor.getSex()) {
                        case 1:
                            sexName = "男";
                            break;
                        case 2:
                            sexName = "女";
                            break;
                    }
                    json.put("sexName", sexName);
                    json.put("job", doctor.getJob());
                    json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("dept", doctor.getDept());
                    json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 患者端 专科医生列表
     *
     * @param name
     * @param paitentCode
     * @param page
     * @param pageSize
     * @return
     */
    @ApiOperation("专科医生列表")
    @RequestMapping(value = "/doctor_1_list",method =RequestMethod.POST)
    @ResponseBody
    public String doctor_1_list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String paitentCode,
            @RequestParam(required = true) Integer page,
            @RequestParam(required = true) Integer pageSize) {
        try {
            Page<Doctor> doctorList = doctorInfoService.getDoctorListByHospital(name, null, page, pageSize,1);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
//					json.put("photo", doctor.getPhoto());
//					json.put("sex", doctor.getSex());
//					String sexName = "";
//					switch (doctor.getSex()) {
//						case 1:
//							sexName = "男";
//							break;
//						case 2:
//							sexName = "女";
//							break;
//					}
//					//json.put("sexName", sexName);
//					json.put("job", doctor.getJob());
//					json.put("jobName", doctor.getJobName());
                    json.put("hospital", doctor.getHospital());
                    json.put("hospitalName", doctor.getHospitalName());
//					json.put("dept", doctor.getDept());
//					json.put("deptName", doctor.getDeptName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "list", array);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 把专科医生拉到团队里面
     *
     * @param teamCode   团队code
     * @param doctor     专科医生code
     * @param sickNCode  慢病code
     * @param sickName   慢病名字
     * @param doctorName 专科医生名字
     * @return
     */
    @ApiOperation("把专科医生拉到团队里面")
    @RequestMapping(value = "/doctor_1_Toteam",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String doctor_1_Toteam(
            @RequestParam(required = false) String teamCode, //没用
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = false) String groupCode,//没用
            @RequestParam(required = true) String doctor,
            @RequestParam(required = true) String doctorName,
            @RequestParam(required = true) String sickName,
            @RequestParam(required = true) String sickNCode) {
        try {
            doctorInfoService.doctor_1_Toteam(teamCode, doctor, doctorName, groupCode, super.getIMEI(), parientCode, sickName, sickNCode);
            return write(200, "成功!");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据病人ID查找团队里面的全科医生
     *
     * @param parientCode 病人code
     * @return
     */
    @ApiOperation("根据病人ID查找团队里面的全科医生")
    @RequestMapping(value = "/getDoctor2ByParient",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctor2ByParient(
            @RequestParam(required = true) String parientCode,
            @RequestParam(required = true) String consultCode) {
        try {
            Doctor doctor = doctorInfoService.getDoctor2ByParient(parientCode, consultCode);
            JSONObject json = null;
            if (doctor != null) {
                json = new JSONObject(doctor);
                if (json.has("password")) {
                    json.remove("password");
                }
                if (json.has("salt")) {
                    json.remove("salt");
                }
                JSONObject iswork = workTimeService.isDoctorWorking(doctor.getCode());
                if (iswork.getString("status").equals("1")) {
                    json.put("isworking", 1);
                } else {
                    json.put("isworking", 0);
                }
            }
            return write(200, "查询成功!", "doctor", json);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据病人ID查找所有的专科医生,如果团队有专科医生那么专科医生拍第一个
     *
     * @param parientCode 病人code
     * @return
     */
    @ApiOperation("根据病人ID查找所有的专科医生,如果团队有专科医生那么专科医生拍第一个")
    @RequestMapping(value = "/getDoctor1ByParient",method =RequestMethod.POST)
    @ResponseBody
    public String getDoctor1ByParient(
            @RequestParam(required = true) String consultCode,
            @RequestParam(required = true) String parientCode,
            Integer page,
            Integer pageSize) {
        try {
            Map<String, Object> doctorList = doctorInfoService.getDoctor1ByParient(consultCode, parientCode, page, pageSize);
            JSONObject jo = new JSONObject();
            List<JSONObject> doctors = doctorList.get("doctors") != null ? (List<JSONObject>) doctorList.get("doctors") : new ArrayList<>();
            for (JSONObject obj : doctors) {
                JSONObject iswork = workTimeService.isDoctorWorking(obj.getString("code"));
                if (iswork.getString("status").equals("1")) {
                    obj.put("isworking", 1);
                } else {
                    obj.put("isworking", 0);
                }
            }
            jo.put("totalPage", doctorList.get("totalPage"));
            jo.put("doctors", doctors);
            return write(200, "查询成功!", "data", jo);
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 验证患者的名字,身份证和医保卡
     *
     * @return
     */
    @ApiOperation("验证患者的名字,身份证和医保卡")
    @RequestMapping(value = "/validatePatient",method =RequestMethod.POST)
    @ResponseBody
    public String validatePatient(
            @RequestParam(required = true) String name,
            @RequestParam(required = true) String idcard,
            @RequestParam(required = true) String ssc) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空");
            }
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致,请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0 && ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                    return error(-1, "身份证号与医保卡号不一致,请检查后重新输入");
                }
            } else {
                return error(-1, "对不起,暂不支持16年6月份之后办理的医保卡注册");
            }
            return write(200, "查询成功!");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据身份证号
     *
     * @param idcard
     * @return
     */
    @ApiOperation("根据身份证号")
    @RequestMapping(value = "/patient_cardno",method =RequestMethod.POST)
    @ResponseBody
    public String getPatientCardNo(String idcard) {
        try {
            String cardNo = "";
            Patient patient = patientInfoService.findByIdcard(idcard);
            if (patient == null || StringUtils.isEmpty(patient.getSsc())) {
                SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18(idcard);
                if (socialSecurityInfo != null) {
                    cardNo = socialSecurityInfo.getCardno();
                }
            } else {
                cardNo = patient.getSsc();
            }
            return write(200, "查询成功!", "data", cardNo);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }
    /**
     * 根据level查找机构下的类别医生
     *
     * @param hospital
     * @param level
     * @return
     */
    @ApiOperation("根据level查找机构下的类别医生")
    @RequestMapping(value = "/findDoctorByLevelAndHospital",method =RequestMethod.POST)
    @ResponseBody
    public String findDoctorByLevelAndHospital(String hospital, Integer level) {
        try {
            List<Doctor> doctorList = doctorInfoService.findDoctorByLevelAndHospital(hospital, level);
            JSONArray array = new JSONArray();
            if (doctorList != null) {
                for (Doctor doctor : doctorList) {
                    JSONObject json = new JSONObject();
                    json.put("id", doctor.getId());
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    array.put(json);
                }
            }
            return write(200, "查询成功!", "doctors", array);
        } catch (Exception e) {
            return error(-1, "查询失败!");
        }
    }
    /**
     * 更新身份证号
     *
     * @param idcard
     * @return
     */
    @ApiOperation("更新身份证号")
    @RequestMapping(value = "/idcard_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateIdcard(String idcard) {
        try {
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不能为空");
            }
            if (doctorInfoService.updateDoctorIdcard(idcard, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生性别
     *
     * @param sex
     * @return
     */
    @ApiOperation("更新医生性别")
    @RequestMapping(value = "/sex_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateSex(int sex) {
        try {
            if (doctorInfoService.updateSex(sex, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生介绍
     *
     * @param introduce
     * @return
     */
    @ApiOperation("更新医生介绍")
    @RequestMapping(value = "/introduce_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateIntroduce(String introduce) {
        try {
            if (StringUtils.isEmpty(introduce)) {
                return error(-1, "身份证号不能为空");
            }
            if (doctorInfoService.updateIntroduce(introduce, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新医生专长
     *
     * @param expertise
     * @return
     */
    @ApiOperation("更新医生专长")
    @RequestMapping(value = "/expertise_update",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateExpertise(String expertise) {
        try {
            if (StringUtils.isEmpty(expertise)) {
                return error(-1, "专长不能为空");
            }
            if (doctorInfoService.updateExpertise(expertise, getUID())) {
                return write(200, "更新成功");
            } else {
                return error(-1, "更新失败");
            }
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 设置给医生名医
     *
     * @param doctorCode 医生code
     * @param status     1 是 0否
     * @return
     */
    @ApiOperation("设置给医生名医")
    @RequestMapping(value = "/setFamous",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String setFamous(String doctorCode, Integer status) {
        try {
            doctorInfoService.setFamous(doctorCode, status);
            return write(200, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 转换团队中的健康管理师
     *
     * @param newDoctorCode 新的健康管理师的code
     * @param oldDoctorCode 旧的健康管理师的code
     * @param patients      患者code 多个逗号分隔
     * @return
     */
    @ApiOperation("转换团队中的健康管理师")
    @RequestMapping(value = "/updateTeamHealthDoctors",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateTeamHealthDoctors(String newDoctorCode,
                                          @RequestParam(required = false) String oldDoctorCode,
                                          @RequestParam(required = false) String patients,
                                          @RequestParam(required = false) String isAll) {
        try {
            String status = redisTemplate.opsForValue().get("jianguanshifenpei:" + getUID());
            status = StringUtils.isEmpty(status) ? "0" : status;
            if (!status.equals("1")) {
                redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "1");
                redisTemplate.expire("jianguanshifenpei:" + getUID(), 20, TimeUnit.MINUTES);
            } else {
                return error(-2, "正在分配,请勿重复操作");
            }
            if (StringUtils.isNotEmpty(isAll) && isAll.equals("1")) {
                int result = doctorInfoService.updateTeamHealthDoctorsAll(newDoctorCode, getUID());
                redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
                redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
                if (result == 1) {
                    return write(200, "分配健管师成功");
                } else if (result == 2) {
                    return write(200, "部分居民因没有服务团队分配失败");
                }
            } else {
                if (StringUtils.isEmpty(patients)) {
                    redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
                    redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
                    return error(-1, "居民不能为空");
                }
                Map<String, Integer> returnMap = doctorInfoService.updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, getUID());
                redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
                redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
                return write(200, "已成功处理" + returnMap.get("success") + "个居民," + returnMap.get("error") + "个居民因有未结束的咨询,无法处理");
            }
            redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
            redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
            return write(200, "更新成功");
        } catch (Exception e) {
            error(e);
            redisTemplate.opsForValue().set("jianguanshifenpei:" + getUID(), "0");
            redisTemplate.expire("jianguanshifenpei:" + getUID(), 10, TimeUnit.MINUTES);
            return error(-1, "更新失败");
        }
    }
    /**
     * 转换团队中的全科医生
     *
     * @param newDoctorCode 新的全科医生的code
     * @param oldDoctorCode 旧的全科医生的code
     * @param patients      患者code 多个逗号分隔
     * @return
     */
    @ApiOperation("转换团队中的全科医生")
    @RequestMapping(value = "/updateTeamDoctors",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updateTeamDoctors(String newDoctorCode,
                                    String oldDoctorCode,
                                    String patients) {
        try {
            String status = redisTemplate.opsForValue().get("quankeyishengfenpei:" + getUID());
            status = StringUtils.isEmpty(status) ? "0" : status;
            if (!status.equals("1")) {
                redisTemplate.opsForValue().set("quankeyishengfenpei:" + getUID(), "1");
                redisTemplate.expire("quankeyishengfenpei:" + getUID(), 20, TimeUnit.MINUTES);
            } else {
                return error(-2, "正在分配,请勿重复操作");
            }
            Map<String, Integer> returnMap = doctorInfoService.updateTeamDoctors(newDoctorCode, oldDoctorCode, patients, getUID());
            redisTemplate.opsForValue().set("quankeyishengfenpei:" + getUID(), "0");
            redisTemplate.expire("quankeyishengfenpei:" + getUID(), 10, TimeUnit.MINUTES);
            return write(200, "已成功处理" + returnMap.get("success") + "个居民," + returnMap.get("error") + "个居民因有未结束的咨询,无法处理");
        } catch (Exception e) {
            redisTemplate.opsForValue().set("quankeyishengfenpei:" + getUID(), "0");
            redisTemplate.expire("quankeyishengfenpei:" + getUID(), 10, TimeUnit.MINUTES);
            e.printStackTrace();
            return error(-1, "更新失败");
        }
    }
    /**
     * 医生手机号变更
     *
     * @param mobile  新手机号
     * @param captcha 验证码
     * @param type    1:变更手机号  2:绑定手机号
     * @return
     */
    @ApiOperation("医生手机号变更")
    @RequestMapping(value = "/mobile_update", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String changeDoctorMobile(String mobile, String captcha, int type) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "请填写新手机号码");
            }
            if (StringUtils.isEmpty(captcha)) {
                return error(-1, "请输入验证码");
            }
            if (type != 1 && type != 2) {
                return error(-1, "操作类型参数错误");
            }
            int result = doctorInfoService.changeMobile(getUID(), mobile, captcha, type);
            if (result == -1) {
                return error(-1, "医生信息查找失败");
            } else if (result == -2) {
                return error(-1, "手机已注册");
            } else if (result == -3) {
                return error(-1, "验证码错误");
            } else if (result == 1) {
                return write(200, "手机号更新成功");
            } else {
                return write(-1, "手机号更新失败");
            }
        } catch (Exception e) {
            return error(-1, "手机号更新失败");
        }
    }
    /**
     * 手机号是否注册
     *
     * @param mobile 手机号
     * @return
     */
    @ApiOperation("手机号是否注册")
    @RequestMapping(value="/is_mobile_register",method =RequestMethod.POST)
    @ResponseBody
    public String isMobileRegister(String mobile) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号码不能为空");
            }
            int result = doctorInfoService.isMobileRegister(mobile);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 修改密码
     *
     * @param newPassword1 新密码1
     * @param newPassword2 新密码2
     * @param oldPassword  旧密码
     * @param doctorCode   医生code
     * @return
     */
    @ApiOperation("修改密码")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String updatePassword(String newPassword1,
                                 String newPassword2,
                                 String oldPassword,
                                 String doctorCode) {
        try {
            newPassword1 = RSAUtils.getInstance(doctorInfoService).decryptString(newPassword1);
            newPassword2 = RSAUtils.getInstance(doctorInfoService).decryptString(newPassword2);
            oldPassword = RSAUtils.getInstance(doctorInfoService).decryptString(oldPassword);
            newPassword1 = StringUtils.reverse(newPassword1);
            newPassword2 = StringUtils.reverse(newPassword2);
            oldPassword = StringUtils.reverse(oldPassword);
            doctorInfoService.updatePassword(newPassword1, newPassword2, oldPassword, doctorCode);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    /**
     * 当前医生是否与居民签约
     *
     * @param patient
     * @return
     */
    @ApiOperation("当前医生是否与居民签约")
    @RequestMapping(value = "/is_patient_signed",method =RequestMethod.GET)
    @ResponseBody
    public String isPatientSign(String patient) {
        try {
            if (StringUtils.isEmpty(patient)) {
                return error(-1, "居民不能为空");
            }
            boolean isSigned = doctorInfoService.isPatientSigned(patient, getUID());
            return write(200, "查询成功", "data", isSigned ? "1" : "0");
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
    /**
     * 心跳接口
     *
     * @return
     */
    @ApiOperation("心跳接口")
    @RequestMapping(value = "/islive",method =RequestMethod.POST)
    @ResponseBody
    public String islive() {
        try {
            return write(200, "成功");
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 分配及转移健管师
     *
     * @param newDoctorCode
     * @param oldDoctorCode
     * @param patients      多个患者用,隔开
     * @param group         团队标签分组名称
     * @param sendCount
     * @param teamId
     * @param typeId
     * @return
     */
    @ApiOperation("分配及转移健管师")
    @RequestMapping(value = "/allotOrMoveHealth",method =RequestMethod.POST)
    @ResponseBody
    @ObserverRequired
    public String allotOrMoveHealth(
            @RequestParam String newDoctorCode,
            @RequestParam(required = false) String oldDoctorCode,
            @RequestParam(required = false) String patients,
            @RequestParam(required = false) String group,
            @RequestParam(required = false) Integer sendCount,
            @RequestParam String teamId,
            @RequestParam(required = false) String typeId) {
        try {
            Long teamCode = Long.parseLong(teamId);
//            patients不为空是由团队中分配及转移的搜索居民 转移健管师 否则是分组分配健管师
            if (StringUtils.isNotEmpty(patients)) {
                String result = updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, null);
                return result;
            } else if(StringUtils.isNotEmpty(group)){
//            按条件获取居民
                patients = "";
                if (StringUtils.isEmpty(teamId)||StringUtils.isEmpty(typeId)||sendCount==null){
                    return write(-1, "参数不能为空!");
                }
                JSONObject list = familyContractService.findNoHealthSignFamilyHealth(null, typeId, null, teamCode);
                List<SignPatientLabel> s = labelDao.findByLabelTypeAndStatusAndTeamCode(typeId, 1, teamCode);
                for (SignPatientLabel label :s) {
//                    String labelName = label.getLabelCode();
                    String labelName = label.getLabelName();
                    if (labelName.equals(group)){
                        JSONArray jsonArray = list.getJSONArray(labelName);
                        for (int i=0;i<sendCount;i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String  patient = jsonObject.get("code").toString();
//                转移时需要剔除处于咨询状态的居民
                            if (StringUtils.isNotEmpty(oldDoctorCode)){
                                ConsultTeam consultTeam = consultTeamService.getConsultByPatientAndDoctor(patient, oldDoctorCode);
                                if (consultTeam == null) {
//                                   不是咨询状态
                                    patients+=(patient+",");
                                }
                            }else {
                                patients+=(patient+",");
                            }
                        }
                    }
                }
                patients =  patients.substring(0,patients.length()-1);
                String result = updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, null);
                return result;
            }else {
                List<SignFamily> signFamily = familyContractService.findNoHealthSignFamilyNum(teamCode);
                patients = "";
                if (StringUtils.isEmpty(teamId)||StringUtils.isEmpty(typeId)||sendCount==null){
                    return write(-1, "参数不能为空!");
                }
                for (SignFamily patient:signFamily) {
                    String code = patient.getPatient();
                    patients+=(code+",");
                }
                patients =  patients.substring(0,patients.length()-1);
                String result = updateTeamHealthDoctors(newDoctorCode, oldDoctorCode, patients, null);
                return result;
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败");
        }
    }
//    /**
//     * 设置审方密码
//     * @param password
//     * @return
//     */
//    @RequestMapping(value = "/setCheckPassword", method = RequestMethod.POST)
//    @ResponseBody
//    @ObserverRequired
//    public String setCheckPassword(@RequestParam String password){
//
//        try {
//
//            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            if (doctor == null) {
//                return error(-1, "密码设置失败!");
//            }
////            doctorInfoService.setCheckPassword(doctor,password);
//            return write(200, "密码设置成功");
//        }catch (Exception e){
//            error(e);
//            return invalidUserException(e, -1, "密码设置失败");
//        }
//    }
//    /**
//     * 修改审方密码
//     * @param oldPassword
//     * @param newPassword
//     * @return
//     */
//    @ObserverRequired
//    @ResponseBody
//    @RequestMapping(value = "/updateCheckPassword", method = RequestMethod.POST)
//    public String updateCheckPassword(@RequestParam String oldPassword,@RequestParam String newPassword){
//
//        try {
//            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            if (doctor == null) {
//                return error(-1, "修改审方密码失败!");
//            } else {
//                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(doctor.getCheckSalt()), oldPassword);
//                if (StringUtils.equals(doctor.getCheckPassword(), encodePWD)) {
////                    doctorInfoService.setCheckPassword(doctor,newPassword);
//                    return write(200, "密码设置成功");
//                } else {
//                    return error(-1, "修改失败:审方旧密码错误!");
//                }
//            }
//        } catch (Exception e) {
//            error(e);
//            return invalidUserException(e, -1, "修改失败!");
//        }
//    }
    //获取实名软证书的过期时间
    @ApiOperation("获取实名软证书的过期时间")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/getAuthenticationCAOvertime", method = RequestMethod.GET)
    public String getAuthenticationCAOvertime(){
        try {
//            Doctor doctor = doctorInfoService.findDoctorByCode(getRepUID());
            JSONObject data = doctorInfoService.getCAPastDue(getUID(),new JSONObject());
            return write(200, "获取信息成功!", "data", data);
        }catch (Exception e) {
            error(e);
            return error(-1, "获取信息失败!");
        }
    }
    //判断是否在线上安装证书
    @ObserverRequired
    @ApiOperation("判断是否在线上安装证书")
    @ResponseBody
    @RequestMapping(value = "/isAuthentication", method = RequestMethod.GET)
    public String isAuthentication(){
        try {
            //0de6a26a62dd11e69faffa163e8aee56
            JSONObject data = doctorInfoService.isAuthentication(getUID());
            return write(200, "获取信息成功!", "data", data);
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    //修改实名软证书调用保护口令
    @ApiOperation("修改实名软证书调用保护口令")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/updateAuthenticationPassword", method = RequestMethod.POST)
    public String updateAuthenticationPassword(
            @RequestParam(value = "strOldCalledPasswd",required = true) String strOldCalledPasswd,
            @RequestParam(value = "strNewCalledPasswd",required = true) String strNewCalledPasswd){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            boolean b = doctorInfoService.updateAuthenticationPassword(doctor.getIdcard(),strOldCalledPasswd,strNewCalledPasswd,getUID());//hxmD201703150222
            if(b){
                return write(200, "修改密码成功!", "data", b);
            }
            return error(-1, "修改密码失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 初始设置实名软证书调用保护口令
     */
    @ApiOperation("初始设置实名软证书调用保护口令")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/installAuthenticationPassword", method = RequestMethod.POST)
    public String installAuthenticationPassword(@RequestParam(value = "strNewCalledPasswd",required = true) String strNewCalledPasswd){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            String strOldCalledPasswd = StringUtils.isNotEmpty(doctor.getCheckPassword())?doctor.getCheckPassword():"11111111";
            boolean b = doctorInfoService.updateAuthenticationPassword(doctor.getIdcard(),strOldCalledPasswd,strNewCalledPasswd,getUID());
            if(b){
                return write(200, "设置密码成功!", "data", b);
            }
            return error(-1, "设置密码失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 重置密码
     */
    @ApiOperation("重置实名软证书调用保护口令")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/resetAuthenticationPassword", method = RequestMethod.POST)
    public String resetAuthenticationPassword(@RequestParam(value = "strNewCalledPasswd",required = true) String strNewCalledPasswd){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
            boolean b = doctorInfoService.updateAuthenticationPassword(doctor.getIdcard(),doctor.getCheckPassword(),strNewCalledPasswd,getUID());
            if(b){
                return write(200, "重置密码成功!", "data", b);
            }
            return error(-1, "重置密码失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 请求实名软证书并进行数字签名
     */
    @ApiOperation("请求实名软证书并进行数字签名")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/requestRealNameSoftCertAndSign", method = RequestMethod.POST)
    public String requestRealNameSoftCertAndSign(
            @ApiParam(required = true, name = "strRealNameSoftCertCalledPasswd", value = "证书被调用保护口令") @RequestParam(value = "strRealNameSoftCertCalledPasswd",required = true) String strRealNameSoftCertCalledPasswd,
            @ApiParam(required = true, name = "strOriginalData", value = "原文") @RequestParam(value = "strOriginalData",required = true) String strOriginalData,
            @ApiParam(required = true, name = "prescriptionCode", value = "处方code") @RequestParam(value = "prescriptionCode",required = true) String prescriptionCode){
        try {
            Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
//            JSONObject obj = doctorInfoService.requestRealNameSoftCertAndSign(doctor.getIdcard(),strRealNameSoftCertCalledPasswd,strOriginalData,srcBusinessStreamNO);
            JSONObject jsonObject = doctorInfoService.requestRealNameSoftCertAndSign(doctor.getIdcard(),strRealNameSoftCertCalledPasswd,strOriginalData,prescriptionCode);
//            if(b){
            return write(200, "获取信息成功!", "data", jsonObject);
//            }
//            return error(-1, "认证失败!");
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 校验医师输入的CA证书是否正确
     * @return
     */
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/checkCertificate", method = RequestMethod.GET)
    @ApiOperation("校验医师输入的身份证是否正确")
    public String checkCertificate(
            @ApiParam(required = true, name = "certificateNum", value = "证书编号") @RequestParam(value = "certificateNum",required = true) String certificateNum){
        try {
            boolean b = doctorInfoService.checkCertificate(getUID(),certificateNum);
            return write(200, "获取信息成功!", "data", b);
        }catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
    /**
     * 验证签名( ( 带多服务器负载均衡) )
     */
    @ApiOperation("验证签名")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/verifySignOnMultiServer", method = RequestMethod.GET)
    public String verifySignOnMultiServer(
            @ApiParam(required = true, name = "strSignData", value = "签名值") @RequestParam(value = "strSignData",required = true) String strSignData,
            @ApiParam(required = true, name = "strCertData", value = "证书主体数据") @RequestParam(value = "strCertData",required = true) String strCertData,
            @ApiParam(required = true, name = "strOriginalData", value = "原文数据") @RequestParam(value = "strOriginalData",required = true) String strOriginalData){
            try {
                boolean bl = doctorInfoService.verifySignOnMultiServer(strSignData,strCertData,strOriginalData,getUID());
                return write(200, "获取信息成功!", "data", bl);
            }catch (Exception e) {
                error(e);
                return error(-1, e.getMessage());
            }
    }
    @ApiOperation("取消认证")
    @ObserverRequired
    @ResponseBody
    @RequestMapping(value = "/cancelAuthentication", method = RequestMethod.GET)
    public String cancelAuthentication(){
        try {
            if(doctorInfoService.cancelAuthentication(getUID())){
                return write(200, "取消认证成功!");
            }else{
                return error(-1, "取消认证失败!");
            }
        }catch (Exception e) {
            error(e);
            return error(-1, "取消认证失败!");
        }
    }
}

+ 0 - 69
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/doctor/template/DoctorFeldsherTemplateController.java

@ -1,69 +0,0 @@
package com.yihu.wlyy.web.doctor.template;
import com.yihu.wlyy.aop.ObserverRequired;
import com.yihu.wlyy.entity.template.DoctorGuidanceTemp;
import com.yihu.wlyy.repository.template.DoctorGuidanceTempDao;
import com.yihu.wlyy.service.template.DoctorFeldsherTemplateService;
import com.yihu.wlyy.service.template.DoctorGuidanceTempService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * 医生健康指导模板
 * <p>
 * Created by Reece on 2017/9/14.
 */
@RestController
@RequestMapping(value = "/doctor/feldsher")
@Api(description = "医生健康指导模板")
public class DoctorFeldsherTemplateController extends BaseController {
    @Autowired
    private DoctorFeldsherTemplateService feldsherTemplateService;
    @Autowired
    DoctorGuidanceTempDao guidanceTempDao;
    /**
     * @param doctorCode   医生code
     * @param sessionId    会话Id
     * @param sessionType  会话类型
     * @param businessType 消息类型
     * @param from         发送者
     * @param content      消息内容
     * @return
     */
    @RequestMapping(value = "/sendDoctorTemplate", method = RequestMethod.GET)
    @ApiOperation(value = "医生助手给医生发送模板消息")
    public String sendDoctorTemplate(@RequestParam @ApiParam(value = "医生code") String doctorCode,
                                     @RequestParam @ApiParam(value = "会话Id", required = false) String sessionId,
                                     @RequestParam @ApiParam(value = "会话类型", required = false) String sessionType,
                                     @RequestParam @ApiParam(value = "消息类型") String businessType,
                                     @RequestParam @ApiParam(value = "发送者", required = false) String from,
                                     @RequestParam @ApiParam(value = "消息内容") String content) {
        try {
            Boolean flag = feldsherTemplateService.sendDoctorTemplate(doctorCode, sessionId, sessionType, businessType, from, content);
            if (flag){
                return write(200, "发送成功!");
            }else {
                return write( -1, "发送失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return invalidUserException(e, -1, "发送失败!");
        }
    }
}

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

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

+ 22 - 45
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/third/gateway/controller/doctor/GcMessageController.java

@ -15,6 +15,7 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@ -47,6 +48,10 @@ public class GcMessageController {
    private SMSService smsService;
    @Autowired
    private DoctorDao doctorDao;
    @Value("${wechat.message.template_doctor_survey}")
    private String templateId;
    @Value("${server.server_url}")
    private String server_url;
    @RequestMapping(value = "/sendWXTemplate", method = RequestMethod.POST)
    @ApiOperation("给患者发送微信模板消息")
@ -124,53 +129,25 @@ public class GcMessageController {
        Integer success = 0;
        Integer error = 0;
        List<String> errorLiust = new ArrayList<>();
        String templateId = "OqQXrb-e43_TJpq_70_K_y6vYJgY5mpjFYY4c5RWFP4";
//            String templateId = "";
        String url = "www.baidu.com";//要带基本地址
        String[] codeArr = openIds.split(",");
        for (String openId : codeArr) {
//                String openId = "o7NFZw1QM4YR1O19mLjwfX1Hh11A";
//                String name = "吴家莲";
//                String mobile = "13611153674";
            try {
                JSONObject sendJson = packageTemplate("消息头", "备注", "续方提醒", "2017年9月16日 18:00");
                weiXinTempMsgSendUtils.sendTemplateMessage(templateId, openId, url, sendJson);
                success++;
            } catch (Exception e) {
                logger.error("openids " + openIds + " send Template error:" + e.getMessage());
                error++;
                errorLiust.add(openIds);
        try {
            String url = server_url + "wx_doctor/html/home/html/jumpApp.html";
            String[] codeArr = openIds.split(",");
            for (String openId : codeArr) {
                try {
                    JSONObject sendJson = weiXinTempMsgSendUtils.packageTemplate("消息头", "备注", content, "2017年9月16日 18:00");
                    weiXinTempMsgSendUtils.sendTemplateMessage(templateId, openId, url, sendJson);
                    success++;
                } catch (Exception e) {
                    logger.error("openids " + openIds + " send Template error:" + e.getMessage());
                    error++;
                    errorLiust.add(openIds);
                }
            }
            return new ResultBatchModel(success, error, errorLiust);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBatchModel(-1, "发送失败!", success, error, errorLiust);
        }
        return new ResultBatchModel(success, error, errorLiust);
    }
    /**
     * 构建微信模板内容消息体 默认字体黑色
     * @param first
     * @param remark
     * @param keywords
     * @return
     */
    public JSONObject packageTemplate(String first,String remark,String ... keywords) {
        JSONObject data = new JSONObject();
        Map keywordFirst = new HashMap();
        keywordFirst.put("color","#000000");
        keywordFirst.put("value",first);
        Map keywordRemark = new HashMap();
        keywordRemark.put("color","#000000");
        keywordRemark.put("value",remark);
        data.put("first",keywordFirst);
        data.put("remark",keywordRemark);
        for (int i=0;i<keywords.length;i++) {
            Map keyword1 = new HashMap();
            keyword1.put("color","#000000");
            keyword1.put("value",keywords[i]);
            data.put("keyword"+(i+1),keyword1);
        }
        System.out.println(data.toString());
        return data;
    }
}

+ 0 - 271
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/third/gateway/service/GcEduArticleService.java

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

+ 10 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/wechat/util/WeiXinAccessTokenUtils.java

@ -5,6 +5,8 @@ import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.SystemConf;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@ -18,6 +20,7 @@ public class WeiXinAccessTokenUtils {
    private AccessTokenService accessTokenService;
    @Autowired
    private HttpUtil httpUtil;
    private static Logger logger = LoggerFactory.getLogger(WeiXinAccessTokenUtils.class);
    @Value("${wechat.appId}")
    private String appId;
@ -36,6 +39,8 @@ public class WeiXinAccessTokenUtils {
            if (accessTokens != null) {
                for (AccessToken accessToken : accessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAdd_timestamp()) < (accessToken.getExpires_in() * 1000)) {
                        logger.info("accId==================>"+accessToken.getAcc_id());
                        logger.info("accessToken==================>"+accessToken.getAccess_token());
                        return accessToken.getAccess_token();
                    } else {
                        accessTokenService.delAccessToken(accessToken);
@ -45,7 +50,11 @@ public class WeiXinAccessTokenUtils {
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String params = "grant_type=client_credential&appid=" +appId + "&secret=" + appSecret;
            logger.info("url ==========>"+token_url+"?"+params);
            logger.info("accId ==========>"+accId);
            String result = httpUtil.sendGet(token_url, params);
            logger.info("accId ==========>"+accId);
            logger.info("getAccessToken params ==========>"+params);
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
@ -55,6 +64,7 @@ public class WeiXinAccessTokenUtils {
                newaccessToken.setExpires_in(Long.parseLong(expires_in));
                newaccessToken.setAcc_id(accId);
                accessTokenService.addAccessToken(newaccessToken);
                logger.info("accessToken ========>"+token);
                return token;
            } else {
                return null;

+ 34 - 2
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/wechat/util/WeiXinTempMsgSendUtils.java

@ -6,6 +6,9 @@ import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by lyr on 2016/08/22.
 */
@ -56,13 +59,42 @@ public class WeiXinTempMsgSendUtils {
        // 发送模板消息
        String result = httpUtil.sendPost(TEMP_MSG_SEND_URL + accessToken, params.toString());
        System.out.println("weixinReturn:"+result);
        System.out.println("weixinReturn:" + result);
        JSONObject jsonResult = new JSONObject(result);
        String returnCode=jsonResult.get("errcode").toString();
        String returnCode = jsonResult.get("errcode").toString();
        if ("0".equals(returnCode)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 构建微信模板内容消息体 默认字体黑色
     *
     * @param first    消息头
     * @param remark   备注
     * @param keywords 消息体
     * @return
     */
    public JSONObject packageTemplate(String first, String remark, String... keywords) throws Exception{
        JSONObject data = new JSONObject();
        Map keywordFirst = new HashMap();
        keywordFirst.put("color", "#000000");
        keywordFirst.put("value", first);
        Map keywordRemark = new HashMap();
        keywordRemark.put("color", "#000000");
        keywordRemark.put("value", remark);
        data.put("first", keywordFirst);
        data.put("remark", keywordRemark);
        for (int i = 0; i < keywords.length; i++) {
            Map keyword1 = new HashMap();
            keyword1.put("color", "#000000");
            keyword1.put("value", keywords[i]);
            data.put("keyword" + (i + 1), keyword1);
        }
        return data;
    }
}

+ 4 - 4
patient-co/patient-co-doctor-assistant/src/main/resources/application-devtest.yml

@ -26,11 +26,11 @@ im:
  data_base_name: im_new
wechat:
  appId: wx1f129f7b51701428
  appSecret: 988f005d8309ed1795939e0f042431fb
  appId: wx088a4d8e8208e6ce
  appSecret: ab3cdd509fb76fd0149e8864c97e8ddb
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fehr.yihu.com%2fwlyy
  accId: gh_ffd64560fb21
  wechat_base_url: http%3a%2f%2fwww.xmtyw.cn%2fassistant
  accId: gh_b0f086d0d2f5
  message:
    ##医生追加建议提醒 --签约邀请
    doctor_invitel_template:  uXdBJVbrhKG-WLaCG4s8C4SXSr2kknQ94vKFt-3rIiA

+ 6 - 26
patient-co/patient-co-doctor-assistant/src/main/resources/application-prod.yml

@ -17,24 +17,24 @@ spring:
    password: jkzl_ehr
server:
  server_url: http://www.xmtyw.cn/wlyy/
  server_url: http://www.xmtyw.cn/assistant/
im:
  im_list_get: http://120.41.253.95:3000/
  im_list_get: http://27.155.101.77:3000/
  data_base_name: im
wechat:
  appId: wx088a4d8e8208e6ce
  appSecret: ab3cdd509fb76fd0149e8864c97e8ddb
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fwww.xmtyw.cn%2fwlyy
  wechat_base_url: http%3a%2f%2fwww.xmtyw.cn%2fassistant
  accId: gh_b0f086d0d2f5
  message:
   ##医生追加建议提醒 --签约邀请
   template_consult_notice: G1rV78-HhvS5LUAAEwCAxOhooFuKAoGTRYo_Hmh6uqo
   ##医生追加建议提醒 --签约邀请
   doctor_invitel_template: MQn79bx1ofb6hekhmRIuqLU7KjySJQzaBzrimgqVrzA
   #咨询回复
   template_consult_notice: 0mF_vHj-ILx8EH8DwzmAi7LqzjqYiU9IrSRRmziTZyc
   #签约成功
   template_sign_success: 0D2vYZVRzFz15p9Y_pkZ1DKutDq8UOsks79FXUKS0tA
   #签约失败
@ -60,7 +60,6 @@ wechat:
   #服务结果通知
   template_doctor_service:  xhi1LEudiZwJfZylOHuZNo8EiA73GtSshPQv5XOt9Lk
yihu:
  yihu_OpenPlatform_url: http://api.yihu.com.cn/OpenPlatform/cgiBin/1.0/
  yihu_OpenPlatform_appId: 9000276
@ -88,23 +87,4 @@ pushMes:
# 1为推送redis,0为推送消息队列
  method: 0
  # redis队列名称
  redis_prescription_title: redisPrescription
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient_prod
  type:
    HealthEduArticlePatient: health_edu_article_patient_prod
  host: 172.19.103.68
  port: 9200
  tPort: 9300
  clusterName: jkzl
#消息队列
activemq:
  username: admin
  password: admin
  url: tcp://172.19.103.87:61616
  queue:
    healtHarticleQueue: healthArticleChannel  #健康文章推送
  redis_prescription_title: redisPrescription

+ 4 - 4
patient-co/patient-co-doctor-assistant/src/main/resources/application-test.yml

@ -25,11 +25,11 @@ im:
  data_base_name: im_new
wechat:
  appId: wx1f129f7b51701428
  appSecret: 988f005d8309ed1795939e0f042431fb
  appId: wx088a4d8e8208e6ce
  appSecret: ab3cdd509fb76fd0149e8864c97e8ddb
  wechat_token: 27eb3bb24f149a7760cf1bb154b08040
  wechat_base_url: http%3a%2f%2fehr.yihu.com%2fwlyy
  accId: gh_ffd64560fb21
  wechat_base_url: http%3a%2f%2fwww.xmtyw.cn%2fassistant
  accId: gh_b0f086d0d2f5
  message:
   ##医生追加建议提醒 --签约邀请
   doctor_invitel_template: uXdBJVbrhKG-WLaCG4s8C4SXSr2kknQ94vKFt-3rIiA

+ 0 - 90
patient-co/patient-co-doctor-assistant/src/main/resources/wechat/weixin_menu.txt

@ -1,90 +0,0 @@
{
"button":[
   {
	  "name":"家庭医生",
	  "sub_button":[
		  {
			"type":"view",
			"name":"签约管理",
			"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fqygl%2fhtml%2fsigning_management.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		  },
		  {
			"type":"view",
			"name":"医生咨询",
			"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyszx%2fhtml%2fdoctor-consultation.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		  },
		  {
			"type":"view",
			"name":"医生指导",
			"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyszd%2fhtml%2fdoctor-guidance.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		  },
		  {
            "type":"view",
            "name":"健康文章",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjkjy%2fhtml%2farticle_list.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
          }
	  ]
   },
   {
	  "name":"健康管理",
	  "sub_button":[
		 {
			  "type":"view",
			  "name":"预约挂号",
			  "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdyy%2fhtml%2fappointment-register.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		 },
		 {
               "type":"view",
               "name":"健康记录",
               "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjkjl%2fhtml%2fhealth-record.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
         },
		{
			"type":"click",
			"name":"健康档案",
			"key":"jiankangdangan"
		},
         {
            "type":"view",
            "name":"疾病社区",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjbsq%2fhtml%2fdisease-community.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        },
        {
            "type":"view",
            "name":"热量查询",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2frlcx%2fhtml%2fserach-index.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        }
	  ]
   },
   {
	  "name":"我的",
	  "sub_button":[
		{
		   "type":"view",
		   "name":"我的资料",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fgrzx%2fhtml%2fmy-detail.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
        {
           "type":"view",
           "name":"我的家庭",
           "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjtgx%2fhtml%2ffamily.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        },
		{
		   "type":"view",
		   "name":"我的设备",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdsb%2fhtml%2fmy-equipments.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
        {
         	"type":"click",
         	"name":"操作说明",
         	"key":"caozuoshuoming"
        },
        {
        	 "type":"view",
        	 "name":"意见反馈",
        	 "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyjfk%2fhtml%2ffeedback.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        }
	 ]
  }
]
}

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

@ -1,92 +0,0 @@
{
"button":[
   {
	  "name":"家庭医生",
	  "sub_button":[
		  {
			"type":"view",
			"name":"签约管理",
			"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fqygl%2fhtml%2fsigning_management.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		  },
		  {
			"type":"view",
			"name":"医生咨询",
			"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyszx%2fhtml%2fdoctor-consultation.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		  },
		  {
			"type":"view",
			"name":"医生指导",
			"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyszd%2fhtml%2fdoctor-guidance.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		  },
		  {
            "type":"view",
            "name":"健康文章",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjkjy%2fhtml%2farticle_list.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
          }
	  ]
   },
   {
	  "name":"健康管理",
	  "sub_button":[
		 {
			  "type":"view",
			  "name":"预约挂号",
			  "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdyy%2fhtml%2fappointment-register.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		 },
		 {
               "type":"view",
               "name":"健康记录",
               "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjkjl%2fhtml%2fhealth-record.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
         },
		{
			"type":"click",
			"name":"健康档案",
			"key":"jiankangdangan"
		},
         {
            "type":"view",
            "name":"疾病社区",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjbsq%2fhtml%2fdisease-community.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        },
        {
            "type":"view",
            "name":"热量查询",
            "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2frlcx%2fhtml%2fserach-index.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        }
	  ]
   },
   {
	  "name":"我的",
	  "sub_button":[
		{
		   "type":"view",
		   "name":"签约特色服务",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fdist%2fhtml%2fexclusive-service.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
		{
		   "type":"view",
		   "name":"我的资料",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fgrzx%2fhtml%2fmy-detail.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
        {
           "type":"view",
           "name":"我的家庭",
           "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjtgx%2fhtml%2ffamily.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        },
		{
		   "type":"view",
		   "name":"我的设备",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdsb%2fhtml%2fmy-equipments.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
        {
        	 "type":"view",
        	 "name":"意见反馈",
        	 "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fyjfk%2fhtml%2ffeedback.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
        }
	 ]
  }],
    "matchrule":{
      "tag_id":"105"
      }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -820,20 +820,20 @@ public class PatientHealthIndexService extends BaseService {
        }
        for (DevicePatientHealthIndex patientHealthIndex : bloodPressurepatientHealthIndices) {
            if(1 == patientHealthIndex.getStatus()){
            if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                bloodPressureBbnormalCount++;
            }
        }
        for (DevicePatientHealthIndex patientHealthIndex : bloodSuggurpatientHealthIndices) {
            if(1 == patientHealthIndex.getStatus()){
            if(patientHealthIndex.getStatus() != null && 1 == patientHealthIndex.getStatus()){
                bloodSuggurBbnormalCount++;
            }
        }
        //连续3次异常,修改用户为预警状态
        if( (3 == bloodPressureBbnormalCount || 3 == bloodSuggurBbnormalCount) && 0 == patient.getStandardStatus()){
        if( (bloodPressureBbnormalCount >=3 || bloodSuggurBbnormalCount >=3) && 0 == patient.getStandardStatus()){
            patient.setStandardStatus(1);
        }else{
            Date end = new Date();
@ -942,7 +942,7 @@ public class PatientHealthIndexService extends BaseService {
        }
        sql = sql +conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by sort_date desc ,record_date desc limit "+0+" ,"+1000+" ";
                " order by record_date desc ,sort_date desc limit "+0+" ,"+1000+" ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:list){
            JSONObject json = new JSONObject();
@ -1043,7 +1043,7 @@ public class PatientHealthIndexService extends BaseService {
                    " and record_date <= '"+end+"' " +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by sort_date desc ,record_date desc limit "+pageRequest.getOffset()+" ,"+pageRequest.getPageSize()+" ";
                    " order by record_date desc ,sort_date desc limit "+pageRequest.getOffset()+" ,"+pageRequest.getPageSize()+" ";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            for (Map<String,Object> map:list){
                JSONObject json = new JSONObject();

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

@ -3883,11 +3883,11 @@ public class SignPatientLabelInfoService extends BaseService {
                                //判断微信绑定情况
                                re = openid1.compareTo(openid2);
                            }else{
                                re = disease2 - disease1;
                                re = disease1 - disease2;
                            }
                        }else{
                            re = diseaseCondition2 - diseaseCondition1;
                            re = diseaseCondition1 - diseaseCondition2;
                        }

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -290,6 +290,7 @@ public class DoctorHealthController extends BaseController {
			}
			return write(200, "查询成功", "data", map);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
@ -392,7 +393,7 @@ public class DoctorHealthController extends BaseController {
				return error(-1, "保存失败!");
			}
			List<Patient> patients = patientService.findAllSignPatientTeamcode(teamcode);
			List<Patient> patients = patientService.findAllSignPatientTeamcode(teamcode,getUID());
			if(!patients.isEmpty()){

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

@ -845,7 +845,7 @@ public class SignPatientLabelInfoController extends BaseController {
            @ApiParam(name="startdate", value="体征数据开始时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "startdate",required = false,defaultValue = "2017-9-10 00:00:00")  String startdate,
            @ApiParam(name="enddate", value="体征数据结束时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "enddate",required = false,defaultValue = "2017-9-16 23:59:59")  String enddate){
        try {
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode,getcolor,getstands,gethealthindex,startdate,enddate);
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode,getcolor,getstands,gethealthindex,startdate,enddate,getUID());
            return write(200, "查询成功", "data", result);
        }catch (Exception e){
            //日志文件中记录异常信息

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

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

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

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

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

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

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

@ -283,6 +283,7 @@ public class PatientHealthController extends BaseController {
            }
            return write(200, "查询成功", "data", map);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
@ -406,6 +407,7 @@ public class PatientHealthController extends BaseController {
            return success("新增患者指标成功!");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }

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

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

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

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

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

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

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

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

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

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