Browse Source

Merge branch 'dev' of yeshijie/patient-co-management into dev

yeshijie 7 years ago
parent
commit
b633efd9d5

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

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

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