Przeglądaj źródła

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

humingfen 7 lat temu
rodzic
commit
ca118627ef
37 zmienionych plików z 3188 dodań i 157 usunięć
  1. 2 2
      common/common-entity/src/main/java/com/yihu/wlyy/entity/device/PatientDevice.java
  2. 19 1
      common/common-entity/src/main/java/com/yihu/wlyy/entity/job/QuartzJobConfig.java
  3. 40 0
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/util/DateUtil.java
  4. 37 15
      patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java
  5. 62 0
      patient-co-service/wlyy_service/pom.xml
  6. 104 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticFactory.java
  7. 1374 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticsearchUtil.java
  8. 56 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/ZysoftServiceController.java
  9. 316 0
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/entity/vo/SaveModel.java
  10. 347 3
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java
  11. 1 1
      patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/guahao/GuahaoService.java
  12. 68 0
      patient-co-service/wlyy_service/src/main/resources/application.yml
  13. 31 0
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java
  14. 17 1
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/business/MysqlToEsQuotaJob.java
  15. 53 16
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/JobService.java
  16. 99 1
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/DateUtil.java
  17. 18 1
      patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/vo/WlyyJobConfigVO.java
  18. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/aop/ObserverRequiredAOP.java
  19. 14 7
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/DeviceDetailService.java
  20. 2 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceLogService.java
  21. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java
  22. 8 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/CreditLogService.java
  23. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionDispensaryCodeService.java
  24. 64 8
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/SignWebService.java
  25. 89 55
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/statisticsES/StatisticsESService.java
  26. 10 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/DateUtil.java
  27. 1 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/HttpClientUtil.java
  28. 160 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/data/DataHandingService.java
  29. 38 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/data/DataHandlingController.java
  30. 10 3
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/device/DoctorDeviceController.java
  31. 80 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/imm/DoctorImmController.java
  32. 12 2
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/message/DoctorMessageController.java
  33. 7 1
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java
  34. 0 19
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/bank/CreditsLogController.java
  35. 21 5
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/EsStatisticsController.java
  36. 20 0
      patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/health/bank/AccountController.java
  37. 5 5
      patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu.txt

+ 2 - 2
common/common-entity/src/main/java/com/yihu/wlyy/entity/device/PatientDevice.java

@ -15,7 +15,7 @@ public class PatientDevice extends IdEntity {
    // 设备ID
    private Long deviceId;
    // 设备标识 1血糖仪,2.血压计
    // 设备标识
    private String deviceSn;
    //sim卡号
    private String sim;
@ -23,7 +23,7 @@ public class PatientDevice extends IdEntity {
    private String deviceName;
    // 用户code
    private String user;
    // 设备类型标识
    // 设备类型标识 1血糖仪,2.血压计
    private String categoryCode;
    // 用户类型标准 -1代表单用户
    private String userType;

+ 19 - 1
common/common-entity/src/main/java/com/yihu/wlyy/entity/job/QuartzJobConfig.java

@ -27,7 +27,8 @@ public class QuartzJobConfig implements java.io.Serializable {
	private String sqlYear;
	private String cacheKey;//缓存的key
	private String extractType;// 1或者为空:数据库 2ES
	private Integer incrementInterval; //增量的时间间隔(1天,2周,3月)
    private String timeLevel;//1增量 2到达量 3生成到达量也生成增量
	private String startTime;
@ -199,4 +200,21 @@ public class QuartzJobConfig implements java.io.Serializable {
	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}
	@Column(name = "increment_interval", length = 2)
	public Integer getIncrementInterval() {
		return incrementInterval;
	}
	public void setIncrementInterval(Integer incrementInterval) {
		this.incrementInterval = incrementInterval;
	}
    @Column(name = "time_level", length = 1)
    public String getTimeLevel() {
        return timeLevel;
    }
    public void setTimeLevel(String timeLevel) {
        this.timeLevel = timeLevel;
    }
}

+ 40 - 0
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/util/DateUtil.java

@ -14,6 +14,8 @@
 ***************************************************************************/
package com.yihu.hos.device.common.util;
import org.apache.commons.lang3.StringUtils;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
@ -1559,4 +1561,42 @@ public class DateUtil {
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_YMDHMSDATE_FORMAT);
        return formatter.format(dateDate);
    }
    /**
     * 获取现在时间
     *
     * @return返回短时间格式 yyyy-MM-dd
     */
    public static java.util.Date getNowDateShort() {
        java.util.Date currentTime = new java.util.Date();
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_YMD_FORMAT);
        String dateString = formatter.format(currentTime);
        return strToDate(dateString, DEFAULT_DATE_YMD_FORMAT);
    }
    /**
     * 将短时间格式字符串转换为时间
     *
     * @param strDate
     * @return
     */
    public static java.util.Date strToDate(String strDate, String format) {
        if (StringUtils.isEmpty(strDate)) {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        return formatter.parse(strDate, pos);
    }
    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd
     */
    public static String getStringDateShort() {
        java.util.Date currentTime = new java.util.Date();
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_YMD_FORMAT);
        return formatter.format(currentTime);
    }
}

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

@ -472,6 +472,24 @@ public class DeviceService extends BaseService{
                userType = "-1";
            }
            PatientDevice patientDevice = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn,type,userType);
            int dataUoloadCount = 0;
            if (patientDevice!=null){
                String today = DateUtil.getStringDateShort();
                String startTime = today+" 00:00:00";
                String endTime = today+" 23:59:59";
                int dateType =1;
                if (deviceType==1){
                    dateType=2;
                }else if (deviceType==2){
                    dateType=1;
                }
                String countSql = "SELECT count(*) num FROM device.wlyy_patient_health_index where `user`='"+patientDevice.getUser()+"' and type = "+dateType+" AND record_date >"+startTime+" and record_date <= "+endTime;
                Map<String,Object> countMap = jdbcTemplate.queryForMap(countSql);
                dataUoloadCount = Integer.valueOf(String.valueOf(countMap.get("num")));
            }else {
                throw new Exception("This device is not relate patient!");
            }
            PatientHealthIndex result = savePatientDeviceData(deviceSn, type, data, uploadTime, userType, json);
            if (result == null) {
                throw new Exception("This device is not relate patient!");
@ -481,21 +499,23 @@ public class DeviceService extends BaseService{
                Patient patient = patientDao.findByCode(patientCode);
                //增加积分
                String sql = "select count(*) num from wlyy.wlyy_devices where device_code = '"+deviceSn+"'";
                Map<String,Object> deviceCountMap = jdbcTemplate.queryForMap(sql);
                if (Integer.valueOf(String.valueOf(deviceCountMap.get("num")))>0){
                    String url = wlyyService + "healthBank/insertCredits";
                    List<NameValuePair> params = new ArrayList<>();
                    params.add(new BasicNameValuePair("creditsDetail", "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\"MEASURE\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+result.getUser()+"\",\"hospital\":\"350205\"}"));
                    String response = HttpClientUtil.post(url, params, "UTF-8");
                    System.out.println(response);
                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
                    String status = jsonObject.getString("status");
                    if (!"200".equals(status)){
                        logger.error(jsonObject.getString("msg"));
                    }
                if (dataUoloadCount>0 && "350205".equals(patient.getTown())){
                    String sql = "select count(*) num from device.wlyy_devices where device_code = '"+deviceSn+"'";
                    Map<String,Object> deviceCountMap = jdbcTemplate.queryForMap(sql);
                    if (Integer.valueOf(String.valueOf(deviceCountMap.get("num")))>0){
                        String url = wlyyService + "healthBank/insertCredits";
                        List<NameValuePair> params = new ArrayList<>();
                        params.add(new BasicNameValuePair("creditsDetail", "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\"MEASURE\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+result.getUser()+"\",\"hospital\":\"350205\"}"));
                        String response = HttpClientUtil.post(url, params, "UTF-8");
                        System.out.println(response);
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(response);
                        String status = jsonObject.getString("status");
                        if (!"200".equals(status)){
                            logger.error(jsonObject.getString("msg"));
                        }
                /*if (Integer.valueOf(String.valueOf(deviceCountMap.get("num")))>0){
                    String url = wlyyService + "/healthBank/insertCredits";
                    org.json.JSONObject params = new org.json.JSONObject();
@ -508,7 +528,9 @@ public class DeviceService extends BaseService{
                        logger.error(jsonObject.getString("msg"));
                    }
                }*/
                    }
                }
                //血糖、血压数据需校验,如果超标,需要发送消息给医生
	            if (1 == deviceType || 2 == deviceType) {
		            verifyHealthIndex(result);

+ 62 - 0
patient-co-service/wlyy_service/pom.xml

@ -195,6 +195,68 @@
            <version>2.5.0</version>
        </dependency>
        <!-- 智业接口引用 END -->
        <!--elasticsearch start-->
        <!--      <dependency>
                  <groupId>org.elasticsearch</groupId>
                  <artifactId>elasticsearch</artifactId>
                  <version>2.4.4</version>
              </dependency>
              <dependency>
                  <groupId>io.searchbox</groupId>
                  <artifactId>jest</artifactId>
                  <version>2.4.0</version>
              </dependency>-->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.ylz</groupId>
            <artifactId>onpay-java-sdk-all</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.5</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>2.4.4</version>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.1.0</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest-common</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--elasticsearch end-->
    </dependencies>
    <build>

+ 104 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticFactory.java

@ -0,0 +1,104 @@
package com.yihu.wlyy.service.common.util;
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 java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
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;//http://59.61.92.90:9065,http://59.61.92.90:9067
    @Value("${es.tHost}")
    private String tHost;// 59.61.92.90:9066,59.61.92.90:9068
    @Value("${es.clusterName}")
    private String clusterName;
//-----------------------------------jestClient----------------------------------------
    /**
     * @param "http://localhost:9200"
     * @return
     */
    public JestClient getJestClient() {
        if (factory == null) {
            //初始化链接
            init();
        }
        return factory.getObject();
    }
    /**
     * 初始化链接
     * 9200
     */
    public synchronized void init() {
        String[] hostArray = esHost.split(",");
        // Construct a new Jest client according to configuration via factory
        factory = new JestClientFactory();
        HttpClientConfig httpClientConfig = new HttpClientConfig
                .Builder(Arrays.asList(hostArray))
                .multiThreaded(true)
                .maxTotalConnection(50)// 最大链接
                .maxConnectionIdleTime(10, TimeUnit.MINUTES)//链接等待时间
                .connTimeout(60 * 1000*10)
                // .discoveryEnabled(true)
                .readTimeout(60 * 1000*10)//60秒
                .build();
        factory.setHttpClientConfig(httpClientConfig);//得到链接
    }
    //-----------------------------------TransportClient----------------------------------------
    private TransportClient transportClient;
    public Client getTransportClient() {
        try {
            initTranClient();
            return transportClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 9300
     *
     * @throws UnknownHostException
     */
    private synchronized void initTranClient() throws UnknownHostException {
        if (transportClient == null) {
            String[] hosts = tHost.split(",");
            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();
            for (String oneHost : hosts) {
                String[] hostAndport = oneHost.split(":");
                transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAndport[0]), Integer.valueOf(hostAndport[1])));
            }
        }
    }
}

+ 1374 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/common/util/ElasticsearchUtil.java

@ -0,0 +1,1374 @@
package com.yihu.wlyy.service.common.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.service.entity.vo.SaveModel;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
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.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
 * 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);
    private final String commonParams = "xmijk_quota";
    
    
    @Autowired
    private ElasticFactory elasticFactory;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
    private String esIndex;
    public List excute(String sql, Class clazz, String esType, String esIndex) {
        List saveModels = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //解决 group by之后默认是200的问题
            if (sql.toLowerCase().contains("group by")) {
                sql = sql + " limit 0,2000";
            }
            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();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1 || select.isAgg) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().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).startsWith("_")) {
                            if(heads.get(i).contains("_id")){
                                clazz.getMethod("setId", String.class).invoke(saveModel, value);
                            }
                            continue;
                        }
                        key = "set" + UpFirstStr(heads.get(i));
                        if (heads.get(i).contains("quotaDate") || heads.get(i).contains("createTime") || heads.get(i).contains("date_histogram")) {
                            if (heads.get(i).contains("date_histogram")) {
                                key = "setQuotaDate";
                            }
                            
                            try {
                                //yyyy-MM-dd'T'HH:mm:ssXX
                                value = dateFormat.parse(String.valueOf(one.get(i)));
                            } catch (Exception e) {
                                //yyyy-MM-dd HH:mm:ss
                                try {
                                    value = dateFormat1.parse(String.valueOf(one.get(i)));
                                }catch (Exception e1){
                                    Timestamp ts = new Timestamp(Long.parseLong(String.valueOf(one.get(i))));
                                    try {
                                        Date date = new Date();
                                        date = ts;
                                        value =date;
                                    
                                    } catch (Exception e2) {
                                        value = String.valueOf(one.get(i));
                                    }
                                }
                                
                            }
//                            value = DateUtil.strToDate(String.valueOf(value).replace("T00:00:00+0800", " 00:00:00"), "yyyy-MM-dd HH:mm:ss");
                        }
                        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, Double.class).invoke(saveModel, value);
                        } else if (value instanceof Date) {
                            clazz.getMethod(key, Date.class).invoke(saveModel, value);
                        } else if (value instanceof List) {
                            clazz.getMethod(key, List.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(0)).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, Double.class).invoke(saveModel, value);
                    } else if (value instanceof Date) {
                        clazz.getMethod(key, Date.class).invoke(saveModel, value);
                    }
                }
            } catch (Exception e) {
                logger.warn(e.getMessage());
            }
            return saveModel;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
    /**
     * 0级指标查询列表
     * 获取所有指标的增量、到达量
     * 备注:原来接口的一级指标对应现在的
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param interval  1日 2周 3月
     * @param lowLevel  下一级区域等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,sum(result1) result1, sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 一级指标查询列表
     * 获取一级指标的增量、到达量
     * 备注:原接口的二级指标对应现在的一级指标
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param slaveKey1 一级维度
     * @param interval  1日 2周 3月
     * @param lowLevel  下个等级
     * @return
     * @throws Exception
     */
    public List findDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,sum(result1) result1, sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2,quotaDate from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotEmpty(slaveKey1) && !commonParams.equals(slaveKey1)) {
            sql.append(" and slaveKey1='" + slaveKey1 + "'  ");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 二级指标查询列表
     * 获取二级指标的增量、到达量
     * 备注:原接口的三级指标对应现在的二级指标
     *
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param area      区域code
     * @param level     等级
     * @param index     指标
     * @param timeLevel 1增量 2到达量
     * @param slaveKey1 一级维度code
     * @param slaveKey2 二级维度code
     * @param interval  1日 2周 3月
     * @param lowLevel  下一等级
     * @return
     */
    public List findDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel) {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,slaveKey2,slaveKey2Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey1) || commonParams.equals(slaveKey1)) {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
            if (!org.springframework.util.StringUtils.isEmpty(slaveKey2) || commonParams.equals(slaveKey2)) {
                groupBy.append(",slaveKey2,slaveKey2Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotBlank(slaveKey1) && (!commonParams.equals(slaveKey1))) {
            sql.append(" and slaveKey1='" + slaveKey1 + "'");
        }
        if (StringUtils.isNotBlank(slaveKey2) && (!commonParams.equals(slaveKey2))) {
            sql.append(" and slaveKey2='" + slaveKey2 + "'");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
     *
     * @param quotaDate
     */
    private String changeDate(String quotaDate) {
        try {
            quotaDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd").parse(quotaDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return quotaDate;
    }
    public String changeTime(String time) {
        try {
            if (time.length() == 10) {
                time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd").parse(time));
            } else if (time.length() == 19) {
                time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXX").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }
    //获取最新更新的时间
    public String getQuotaTime() {
        String date = redisTemplate.opsForValue().get("quota:date");
//        date = date.replace(" ","T")+"+0800";
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    /**
     * 获取一个指标下所有一级维度按维度分组的数据
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @return
     * @throws Exception
     */
    public List findDateAllQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.teamLevel.equals(low_level)) {
            sql.append("select team,teamName,slaveKey1,slaveKey1Name,sum(result1) result1, sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by team,teamName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital,hospitalName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town,townName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName,slaveKey1,slaveKey1Name");
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city,cityName,slaveKey1,slaveKey1Name,sum(result1) result1,sum(result2) result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName,slaveKey1,slaveKey1Name");
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.teamLevel.equals(level + "")) {
                sql.append(" team='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='5'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00') ");
            }
        }
        sql.append(groupBy);
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 0级维度
     * 查询某一天某一个0级维度的指标
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel0(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel0(quotaDate, quotaDate, area, level, index, timelevel, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 0级维度
     * 查询某个时间区间某一个0级维度的指标
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key 不传返回全部
     * @return
     */
    public SaveModel findOneDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null);
        if (list.size() > 0) {
            return (SaveModel) list.get(0);
        } else {
            return null;
        }
    }
    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public SaveModel findOneDateQuotaLevel1NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一个时间区间某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timelevel
     * @return
     * @throws Exception
     */
    public SaveModel findOneDateQuotaLevel1NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某个时间区间某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key 不传返回全部
     * @return
     */
    public SaveModel findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, commonParams, null, null);
        return list;
    }
    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
     *
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, commonParams, null, null);
        return list;
    }
    /**
     * 2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return list;
    }
    /**
     * 根据2级维度的2级指标去聚合 没有一级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 根据2级维度的1级指标去聚合 没有2级维度
     * 查询某一天某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 2级维度
     * 查询某个时间区间某一个2级维度的某个1级维度和2级维度下的指标  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd
     * @param endDate   结束时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public SaveModel findOneDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, null);
        return (SaveModel) list.get(0);
    }
    /**
     * 2级维度
     * 查询某一天某个1级维度下所有2级维度的指标  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd
     * @param area      code  厦门市 350200
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel // 1日 2年
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findOneDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, commonParams, null, null);
        return list;
    }
    /**
     * 折线图
     * 0级维度
     * 查询某个0级维度的指标折线图
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @return
     * @throws Exception
     */
    public List<SaveModel> findLineChartDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, interval, null);
        return list;
    }
    /**
     * 折线图
     * 1级维度
     * 查询某个1级维度的某个1级维度下的折线图 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, interval, null);
        return list;
    }
    /**
     * 折线图
     * 1级维度
     * 查询某个1级维度的某个1级维度下的折线图 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel1NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, null, interval, null);
        return list;
    }
    /**
     * 折线图
     * 2级维度
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, interval, null);
        return list;
    }
    /**
     * 折线图
     * 2级维度只根绝第二个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey1(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey2) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, null, slaveKey2);
        return list;
    }
    /**
     * 折线图
     * 2级维度只根绝第一个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval, String slaveKey1) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, slaveKey1, null);
        return list;
    }
    /**
     * 折线图
     * 2级维度只根绝第一个指标聚合
     * 查询某个2级维度的某个1级维度和2级维度下的折线图  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param interval  1日 2周 3月 (按照日周月聚合)
     * @return
     */
    public List<SaveModel> findLineChartDateQuotaLevel2NoSlaveKey1NoSlaveKey2(String startDate, String endDate, String area, int level, String index, String timelevel, String interval) throws Exception {
        List list = findLineChartDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, interval, null, null);
        return list;
    }
    /**
     * 列表
     * 0级维度
     * 查询某一天某个0级维度的指标列表
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @return
     * @throws Exception
     */
    public List<SaveModel> findListDateQuotaLevel0(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel0(quotaDate, quotaDate, area, level, index, timelevel, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 0级维度
     * 查询某个区间某个0级维度的指标列表
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队.
     * @return
     * @throws Exception
     */
    public List<SaveModel> findListDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel0(startDate, endDate, area, level, index, timelevel, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 1级维度
     * 查询某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 1级维度
     * 查询某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel1(quotaDate, quotaDate, area, level, index, timelevel, null, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 1级维度
     * 查询某个区间某个1级维度的某个1级维度下的列表 例如查询65岁以上患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 2级维度
     * 查询某个2级维度的某个1级维度和2级维度下的列表  例如查询65岁以上的高血压患者
     *
     * @param quotaDate 时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, lowLevel);
        return list;
    }
    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey1(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, slaveKey2, null, lowLevel);
        return list;
    }
    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, slaveKey1, null, null, lowLevel);
        return list;
    }
    public List<SaveModel> findListDateQuotaLevel2NoSlaveKey1NoSlaveKey2(String quotaDate, String area, int level, String index, String timelevel, String lowLevel) throws Exception {
        List list = findDateQuotaLevel2(quotaDate, quotaDate, area, level, index, timelevel, null, null, null, lowLevel);
        return list;
    }
    /**
     * 列表
     * 2级维度
     * 查询某个区间某个2级维度的某个1级维度和2级维度下的列表  例如查询65岁以上的高血压患者
     *
     * @param startDate 开始时间 yyyy-mm-dd  包含头
     * @param endDate   结束时间 yyyy-mm-dd  包含头
     * @param area      code  厦门市 350200 code 和level是对应的
     * @param level     等级 1 省 2 市 3 区县 4 机构 5团队
     * @param index     指标code
     * @param timelevel 1增量   2到达量(按照年度)
     * @param lowLevel  下一级区域等级   1 省 2 市 3 区县 4 机构 5团队
     * @param slaveKey1 一级维度的key
     * @param slaveKey2 二级维度的key
     * @return
     */
    public List<SaveModel> findListDateQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timelevel, String lowLevel, String slaveKey1, String slaveKey2) throws Exception {
        if (org.springframework.util.StringUtils.isEmpty(slaveKey1)) {
            slaveKey1 = commonParams;
        }
        if (org.springframework.util.StringUtils.isEmpty(slaveKey2)) {
            slaveKey2 = commonParams;
        }
        List list = findDateQuotaLevel2(startDate, endDate, area, level, index, timelevel, slaveKey1, slaveKey2, null, lowLevel);
        return list;
    }
    /**
     * 将参数转换成需要的SaveModel里的标识
     *
     * @param level 等级  4 市  3区  2社区 1团队
     *              转换后的level  等级  2 市  3区  4社区 5团队
     * @return
     * @author zhangdan
     * @time 2017-10-18
     */
    public int changeLevel(int level) {
        int resultLevel = 0;
        if (level == 1) {
            //团队转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.teamLevel);
        } else if (level == 2) {
            //社区转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.OrgLevel);
        } else if (level == 3) {
            //区转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.townLevel);
        } else if (level == 4) {
            //市转成SaveModel里的标识
            resultLevel = Integer.valueOf(SaveModel.cityLevel);
        }
        if (resultLevel == 0) {
            resultLevel = level;
        }
        return resultLevel;
    }
    public List<Map<String, Object>> excuteDataModel(String sql) {
        List<Map<String, Object>> returnModels = new ArrayList<>();
        try {
            SQLExprParser parser = new ElasticSqlExprParser(sql);
            SQLExpr expr = parser.expr();
            SQLQueryExpr queryExpr = (SQLQueryExpr) expr;
//            if (parser.getLexer().token() != Token.EOF) {
//                throw new ParserException("illegal sql expr : " + sql);
//            }
            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对象
                Client client = elasticFactory.getTransportClient();
                queryAction = new DefaultQueryAction(client, select);
                requestBuilder = queryAction.explain();
            }
            SearchResponse response = (SearchResponse) requestBuilder.get();
            Object queryResult = null;
            if (sql.toUpperCase().indexOf("GROUP") != -1 || sql.toUpperCase().indexOf("SUM") != -1) {
                queryResult = response.getAggregations();
            } else {
                queryResult = response.getHits();
            }
            ObjectResult temp = new ObjectResultsExtractor(true, true, true).extractResults(queryResult, true);
            List<String> heads = temp.getHeaders();
            temp.getLines().stream().forEach(one -> {
                try {
                    Map<String, Object> oneMap = new HashMap<String, Object>();
                    for (int i = 0; i < one.size(); i++) {
                        String key = null;
                        Object value = one.get(i);
                        key = heads.get(i);
                        oneMap.put(key, value);
                    }
                    returnModels.add(oneMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnModels;
    }
}

+ 56 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/controller/ZysoftServiceController.java

@ -266,6 +266,62 @@ public class ZysoftServiceController {
			}
		}
	}
	
	@RequestMapping(value = "getstatictag",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("查询服务记录指标")
	/**
	 *  查询服务记录指标
	 *  data={
	        "type":1,//1咨询量,2健康教育量,3代预约量,4长处方续方两,5体征测量总数,6体征异常量
		    "idcard":"350681111111111111",//身份证
	        "data_type":"1",//1血糖,2血压
		    "start_time":"2017-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
		    "end_time":"2018-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
	     
		 }
	 */
	public Result getStaticTag(@ApiParam(name="data",value="json串",defaultValue = "{}")
	                               @RequestParam(value = "data",required = true) String data){
		try {
			com.alibaba.fastjson.JSONObject result = zysoftService.getStaticTag(data);
			return Result.success("请求成功!",result);
		} catch (Exception ex) {
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
	
	}
	@RequestMapping(value = "getstatictagbyidcard",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation("根据身份证号查询服务记录指标")
	public Result getStaticTagByIdcard(@ApiParam(name="idcard",value="居民身份证号",defaultValue = "350211195007234014")
	                           @RequestParam(value = "idcard",required = true) String idcard,
	                           @ApiParam(name="start_time",value="开始时间YYYY-MM-DD HH:MM:SS格式",defaultValue = "2017-07-01 00:00:00")
	                           @RequestParam(value = "start_time",required = true) String start_time,
	                           @ApiParam(name="end_time",value="开始时间YYYY-MM-DD HH:MM:SS格式",defaultValue = "2018-07-01 00:00:00")
	                           @RequestParam(value = "end_time",required = true) String end_time){
		try {
			com.alibaba.fastjson.JSONArray result = zysoftService.getstatictagbyidcard(idcard,start_time,end_time);
			return Result.success("请求成功!",result);
		} catch (Exception ex) {
			if(ex instanceof ApiException)
			{
				ApiException apiEx = (ApiException) ex;
				return Result.error(apiEx.errorCode(),ex.getMessage());
			}
			else{
				return Result.error(ex.getMessage());
			}
		}
		
	}
}

+ 316 - 0
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/entity/vo/SaveModel.java

@ -0,0 +1,316 @@
package com.yihu.wlyy.service.entity.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.searchbox.annotations.JestId;
import org.springframework.data.annotation.CreatedDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by chenweida on 2017/6/1.
 */
public class SaveModel {
    private final static String teamKey = "team";
    private final static String OrgKey = "hospital";
    private final static String townKey = "town";
    private final static String cityKey = "city";
    public final static String interval_day="1";
    public final static String interval_week="2";
    public final static String interval_month="3";
    public final static String teamLevel = "5";
    public final static String OrgLevel = "4";
    public final static String townLevel = "3";
    public final static String cityLevel = "2";
    private static final Map<String, String> fieldsSithch = new HashMap<>();
    public final static String timeLevel_ZL="1";//增量
    public final static String timeLevel_DDL="2";//到达量
    @JestId
    private String id;
    private String saasId;//saasId
    private String quotaCode;//指标code
    private Date quotaDate;//统计时间
    private String city;//城市代码 350200
    private String cityName;//
    private String town;//区代码 350206
    private String townName;//
    private String hospital;//机构code
    private String hospitalName;//
    private String team;//团队的code
    private String teamName;//
    private String slaveKey1;//从维度  1级维度
    private String slaveKey1Name;
    private String slaveKey2;//从维度  2级维度
    private String slaveKey2Name;
    private String slaveKey3;//从维度  3级维度
    private String slaveKey3Name;
    private String slaveKey4;//从维度  4级维度
    private String slaveKey4Name;
    private Double result1 = 0.0;//统计结果(如:评分总合)
    private Double result2 = 0.0;//统计结果
    private String areaLevel;// 1 省 2 市 3 区县 4 机构 5团队
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd'T'HHmmss.SSS'Z'")
    @CreatedDate
    private Date createTime;//创建时间
    private String timeLevel;// 1日 2年
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd ")
    public Date getQuotaDate() {
        return quotaDate;
    }
    public void setQuotaDate(Date quotaDate) {
        this.quotaDate = quotaDate;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }
    //@Field(type = FieldType.String, analyzer="ngram_analyzer")//使用ngram进行单字分词
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    public String getTeam() {
        return team;
    }
    public void setTeam(String team) {
        this.team = team;
    }
    public String getSlaveKey1() {
        return slaveKey1;
    }
    public void setSlaveKey1(String slaveKey1) {
        this.slaveKey1 = slaveKey1;
    }
    public String getSlaveKey2() {
        return slaveKey2;
    }
    public void setSlaveKey2(String slaveKey2) {
        this.slaveKey2 = slaveKey2;
    }
    public String getSlaveKey3() {
        return slaveKey3;
    }
    public void setSlaveKey3(String slaveKey3) {
        this.slaveKey3 = slaveKey3;
    }
    public String getSlaveKey4() {
        return slaveKey4;
    }
    public void setSlaveKey4(String slaveKey4) {
        this.slaveKey4 = slaveKey4;
    }
    public Double getResult1() {
        return result1;
    }
    public void setResult1(Double result1) {
        this.result1 = result1;
    }
    public Double getResult2() {
        return result2;
    }
    public void setResult2(Double result2) {
        this.result2 = result2;
    }
    public String getSlaveKey1Name() {
        return slaveKey1Name;
    }
    public void setSlaveKey1Name(String slaveKey1Name) {
        this.slaveKey1Name = slaveKey1Name;
    }
    public String getSlaveKey2Name() {
        return slaveKey2Name;
    }
    public void setSlaveKey2Name(String slaveKey2Name) {
        this.slaveKey2Name = slaveKey2Name;
    }
    public String getSlaveKey3Name() {
        return slaveKey3Name;
    }
    public void setSlaveKey3Name(String slaveKey3Name) {
        this.slaveKey3Name = slaveKey3Name;
    }
    public String getSlaveKey4Name() {
        return slaveKey4Name;
    }
    public void setSlaveKey4Name(String slaveKey4Name) {
        this.slaveKey4Name = slaveKey4Name;
    }
    public String getCityName() {
        return cityName;
    }
    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
    public String getTownName() {
        return townName;
    }
    public void setTownName(String townName) {
        this.townName = townName;
    }
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getTeamName() {
        return teamName;
    }
    public void setTeamName(String teamName) {
        this.teamName = teamName;
    }
    public String getQuotaCode() {
        return quotaCode;
    }
    public void setQuotaCode(String quotaCode) {
        this.quotaCode = quotaCode;
    }
    public String getAreaLevel() {
        return areaLevel;
    }
    public void setAreaLevel(String areaLevel) {
        this.areaLevel = areaLevel;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTimeLevel() {
        return timeLevel;
    }
    public void setTimeLevel(String timeLevel) {
        this.timeLevel = timeLevel;
    }
    /**
     * 根据级别得到key
     * 1 省 2 市 3 区县 4 机构 5团队
     *
     * @param level
     * @return
     */
    public static String getAreaLevelKey(String level) {
        switch (level) {
            case teamLevel: {
                return teamKey;
            }
            case OrgLevel: {
                return OrgKey;
            }
            case townLevel: {
                return townKey;
            }
            case cityLevel: {
                return cityKey;
            }
            default: {
                return teamKey;
            }
        }
    }
}

+ 347 - 3
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/ZysoftService.java

@ -1,22 +1,33 @@
package com.yihu.wlyy.service.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.service.common.http.HttpApiException;
import com.yihu.wlyy.service.common.model.Result;
import com.yihu.wlyy.service.common.util.ElasticFactory;
import com.yihu.wlyy.service.common.util.ElasticsearchUtil;
import com.yihu.wlyy.service.common.util.StringUtil;
import com.yihu.wlyy.service.dao.PatientDao;
import com.yihu.wlyy.service.entity.DoctorMapping;
import com.yihu.wlyy.service.entity.Message;
import com.yihu.wlyy.service.entity.Patient;
import com.yihu.wlyy.service.entity.prescription.Prescription;
import com.yihu.wlyy.service.entity.prescription.PrescriptionExpressage;
import com.yihu.wlyy.service.entity.prescription.PrescriptionLog;
import com.zoe.phip.ssp.sdk.ApiException;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
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 java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
 * Created by hzp on 2016/9/9.
@ -24,6 +35,11 @@ import java.util.Map;
 */
@Service
public class ZysoftService {
    
    @Value("${es.type.HealthEduArticlePatient}")
    private String esType;
    @Value("${es.index.HealthEduArticlePatient}")
    private String esIndex;
    @Autowired
    private LogService logService;
@ -34,6 +50,17 @@ public class ZysoftService {
    private Boolean openCrypto;
    //默认重复次数
    private int retryTimes = 3;
    
    @Autowired
    PatientDao patientDao;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private ElasticFactory elasticFactory;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    /**
     * 基卫二次封装Get接口
@ -875,4 +902,321 @@ public class ZysoftService {
        
        return response;
	}
    
    /**
     *  查询服务记录指标
     *  data={
         "type":1,//1咨询量,2健康教育量,3代预约量,4长处方续方两,5体征测量总数,6体征异常量
         "idcard":"350681111111111111",//身份证
         "start_time":"2017-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
         "end_time":"2018-07-01 00:00:00",//YYYY-MM-DD HH:MM;SS格式的日期
     }
     */
    public com.alibaba.fastjson.JSONObject getStaticTag(String data) {
        String error = null;
        String status = "1";
        String errMsg = null;
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        
        try{
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(data);
            String type = json.getString("type");//
            String idcard = json.getString("idcard");//身份证
            String start_time = json.getString("start_time");//开始时间
            String end_time = json.getString("end_time");//结束时间
            String data_type = json.getString("data_type");//1血糖,2血压
            
            String name = "";//居民姓名
            String datatype = "";//1血糖,2血压
            Long total = new Long("0");
            String sql = "";//待执行的SQL语句
            Map<String, Object> totalCountMap = new HashMap<>();
            
            
            if(StringUtils.isBlank(idcard)){
                throw new Exception("身份证号不允许为空");
            }
            
            if(StringUtils.isBlank(start_time) || StringUtils.isBlank(end_time)){
                throw new Exception("开始时间和结束时间不能为空");
            }
            
            Patient patient = patientDao.findByIdcard(idcard);
            System.out.println(patient.getCode());
            if(StringUtils.isNotBlank(patient.getCode())){
                name = patient.getName();
                result.put("name",name);
                result.put("idcard",patient.getIdcard());
            }else{
                throw new Exception(idcard+"-该身份证号找不到居民");
            }
            
            //1咨询量
            if("1".equals(type)){
                sql = "select count(1) AS totalCount from wlyy_consult where patient ='"+patient.getCode()+"' and czrq BETWEEN '"+start_time+"' and '"+end_time+"'";
                
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type","0");
            }
    
            //2健康教育量
            if("2".equals(type)){
                //查询总数sql
                String countSql = "SELECT COUNT(*) AS count FROM " + esType + "  where patientCode= '" + patient.getCode() + "' and userType = 1";
                Long totalES = elasticsearchUtil.excuteForLong(countSql,esIndex, esType);
                JSONArray re = new JSONArray();
                result.put("total",totalES);
                result.put("type","0");
            
            }
    
            //3代预约量
            if("3".equals(type)){
                sql = "select count(1) AS totalCount from wlyy_patient_reservation where patient='"+patient.getCode()+"' and doctor is not null and czrq BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type","0");
            }
    
            //4长处方续方量
            if("4".equals(type)){
                sql = "select count(1) AS totalCount from wlyy_prescription where patient ='"+patient.getCode()+"' and create_time BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type","0");
            }
            
            //5体征测量总数
            if("5".equals(type)){
                sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type='"+data_type+"'and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type",data_type);
            }
            
            //6体征异常量
            if("6".equals(type)){
                sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type='"+data_type+"' and status = 1 and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
    
                totalCountMap = jdbcTemplate.queryForMap(sql);
                if (totalCountMap.get("totalCount") == null) {
                    totalCountMap.put("totalCount", 0);
                }
                total = (Long)totalCountMap.get("totalCount");
                result.put("total",String.valueOf(total));
                result.put("type",data_type);
            }
        
        }catch (JSONException ex){
            ex.printStackTrace();
            error = ex.getMessage();
            errMsg = ex.getMessage();
            status = "0";
        }catch (Exception e){
            e.printStackTrace();
            error = e.getMessage();
            status = "0";
        }
    
        return result;
    }
    
    /**
     * 根据身份证号查询服务记录指标
     * @param idcard
     * @return
     */
    public com.alibaba.fastjson.JSONArray getstatictagbyidcard(String idcard,String start_time,String end_time) {
        String error = null;
        String status = "1";
        String errMsg = null;
        com.alibaba.fastjson.JSONArray result = new JSONArray();
    
        try{
            String name = "";//居民姓名
            String datatype = "";//1血糖,2血压
            Long total = new Long("0");
            String sql = "";//待执行的SQL语句
            Map<String, Object> totalCountMap = new HashMap<>();
        
        
            if(StringUtils.isBlank(idcard)){
                throw new Exception("身份证号不允许为空");
            }
        
            if(StringUtils.isBlank(start_time) || StringUtils.isBlank(end_time)){
                throw new Exception("开始时间和结束时间不能为空");
            }
        
            Patient patient = patientDao.findByIdcard(idcard);
            System.out.println(patient.getCode());
            if(StringUtils.isNotBlank(patient.getCode())){
                name = patient.getName();
            }else{
                throw new Exception(idcard+"-该身份证号找不到居民");
            }
        
            //1咨询量
            com.alibaba.fastjson.JSONObject obj1 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from wlyy_consult where patient ='"+patient.getCode()+"' and czrq BETWEEN '"+start_time+"' and '"+end_time+"'";
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj1.put("dataType","1");
            obj1.put("total",String.valueOf(total));
            obj1.put("type","0");
            obj1.put("name",name);
            obj1.put("idcard",patient.getIdcard());
            result.add(obj1);
            
        
            //2健康教育量
            com.alibaba.fastjson.JSONObject obj2 = new com.alibaba.fastjson.JSONObject();
            //查询总数sql
            String countSql = "SELECT COUNT(*) AS count FROM " + esType + "  where patientCode= '" + patient.getCode() + "' and userType = 1";
            Long totalES = elasticsearchUtil.excuteForLong(countSql,esIndex, esType);
            JSONArray re = new JSONArray();
            obj2.put("dataType","2");
            obj2.put("total",totalES);
            obj2.put("type","0");
            obj2.put("name",name);
            obj2.put("idcard",patient.getIdcard());
            result.add(obj2);
        
            //3代预约量
            com.alibaba.fastjson.JSONObject obj3 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from wlyy_patient_reservation where patient='"+patient.getCode()+"' and doctor is not null and czrq BETWEEN '"+start_time+"' and '"+end_time+"'";
        
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj3.put("dataType","3");
            obj3.put("total",String.valueOf(total));
            obj3.put("type","0");
            obj3.put("name",name);
            obj3.put("idcard",patient.getIdcard());
            result.add(obj3);
        
            //4长处方续方量
            com.alibaba.fastjson.JSONObject obj4 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from wlyy_prescription where patient ='"+patient.getCode()+"' and create_time BETWEEN '"+start_time+"' and '"+end_time+"'";
        
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj4.put("dataType","4");
            obj4.put("total",String.valueOf(total));
            obj4.put("type","0");
            obj4.put("name",name);
            obj4.put("idcard",patient.getIdcard());
            result.add(obj4);
        
            //5体征测量总数
            //血糖
            com.alibaba.fastjson.JSONObject obj51 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type=1 and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
        
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj51.put("dataType","5");
            obj51.put("total",String.valueOf(total));
            obj51.put("type","1");//血糖
            obj51.put("name",name);
            obj51.put("idcard",patient.getIdcard());
            result.add(obj51);
    
            //血压
            com.alibaba.fastjson.JSONObject obj52 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type=2 and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
    
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj52.put("dataType","5");
            obj52.put("total",String.valueOf(total));
            obj52.put("type","2");//血压
            obj52.put("name",name);
            obj52.put("idcard",patient.getIdcard());
            result.add(obj52);
        
            //6体征异常量
            //血糖
            com.alibaba.fastjson.JSONObject obj61 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type=1 and status = 1 and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
        
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj61.put("dataType","6");
            obj61.put("total",String.valueOf(total));
            obj61.put("type","1");//血糖
            obj61.put("name",name);
            obj61.put("idcard",patient.getIdcard());
            result.add(obj61);
    
            //血压
            com.alibaba.fastjson.JSONObject obj62 = new com.alibaba.fastjson.JSONObject();
            sql = "select count(1) AS totalCount from device.wlyy_patient_health_index where `user` ='"+patient.getCode()+"' and type=2 and status = 1 and record_date BETWEEN '"+start_time+"' and '"+end_time+"'";
    
            totalCountMap = jdbcTemplate.queryForMap(sql);
            if (totalCountMap.get("totalCount") == null) {
                totalCountMap.put("totalCount", 0);
            }
            total = (Long)totalCountMap.get("totalCount");
            obj62.put("dataType","6");
            obj62.put("total",String.valueOf(total));
            obj62.put("type","2");//血压
            obj62.put("name",name);
            obj62.put("idcard",patient.getIdcard());
            result.add(obj62);
            
            
        
        }catch (JSONException ex){
            ex.printStackTrace();
            error = ex.getMessage();
            errMsg = ex.getMessage();
            status = "0";
        }catch (Exception e){
            e.printStackTrace();
            error = e.getMessage();
            status = "0";
        }
    
        return result;
    }
}

+ 1 - 1
patient-co-service/wlyy_service/src/main/java/com/yihu/wlyy/service/service/guahao/GuahaoService.java

@ -1562,7 +1562,7 @@ public class GuahaoService {
        Map<String,String> params = new HashMap<>();
        params.put("act", "findWzymBymykh");
        params.put("accId", "q9Bt3TE00KaigEW5EJVIMA==");
        params.put("_token", "525870222");
        params.put("_token", "118328844");
        params.put("etmykh", "0052182708");
        return ylzImmGetSecond(apiString,"计免预约-获取计划免疫接种记录",params);
    }

+ 68 - 0
patient-co-service/wlyy_service/src/main/resources/application.yml

@ -84,6 +84,23 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://192.168.131.113:8081
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://172.19.103.68:9200
  tHost: 172.19.103.68:9300
  clusterName: jkzl
---
spring:
  profiles: devtest
@ -112,6 +129,23 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://192.168.131.113:8081
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://172.19.103.68:9200
  tHost: 172.19.103.68:9300
  clusterName: jkzl
---
spring:
  profiles: test
@ -139,6 +173,23 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://172.19.103.88:9092/wlyy
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUp: wlyy_followup
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    FollowUpContent: wlyy_followup_content
    Statistics: wlyy_quota_test
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://172.19.103.68:9200
  tHost: 172.19.103.68:9300
  clusterName: jkzl
---
spring:
  profiles: production
@ -166,3 +217,20 @@ zyapi:
#    i健康项目地址
wlyy:
  api: http://www.xmtyw.cn/wlyy
es:
  index:
    HealthEduArticlePatient: health_edu_article_patient
    Statistics: wlyy_quota_prod
    FollowUp: wlyy_followup
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  type:
    HealthEduArticlePatient: health_edu_article_patient
    Statistics: wlyy_quota_prod
    FollowUpContent: wlyy_followup_content
    QuestionnaireWinning: wlyy_questionnaire_winning
    patientDevice: wlyy_patient_device
  host:  http://59.61.92.90:9065,http://59.61.92.90:9067
  tHost: 59.61.92.90:9066,59.61.92.90:9068
  clusterName: jkzl

+ 31 - 0
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/controller/JobController.java

@ -317,4 +317,35 @@ public class JobController extends BaseController {
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
    /************************************************************************************/
    /**
     * 生成过去某一天到某一天的全部的数据
     *
     * @param start
     * @param end
     * @return
     */
    @ApiOperation(value = "生成过去某一天到某一天的全部的数据(包含头尾)按周或月统计")
    @RequestMapping(value = "productDataByDayToDay2", method = RequestMethod.GET)
    public String productDataByDayToDay2( @ApiParam(name = "start", value = "yyyy-MM-dd", required = true)@RequestParam(value = "start", required = true)String start,
                                         @ApiParam(name = "end", value = "yyyy-MM-dd", required = true)@RequestParam(value = "end", required = true)String end,
                                          @ApiParam(name = "incrementInterval", value = "2周,3月", required = true)@RequestParam(value = "incrementInterval", required = true)Integer incrementInterval,
                                          @ApiParam(name = "id", value = "指标id,逗号分隔(为空表示全部)", required = false)@RequestParam(value = "id", required = false)String id) {
        try {
            if(incrementInterval==2){
                jobService.productWeekByDayToDay(start,end,id);
            }else if(incrementInterval==3){
                jobService.productMonthByDayToDay(start,end,id);
            }else{
                return success("启动失败!");
            }
            return success("启动成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "启动失败:" + e.getMessage());
        }
    }
}

+ 17 - 1
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/job/business/MysqlToEsQuotaJob.java

@ -63,6 +63,7 @@ public class MysqlToEsQuotaJob implements Job {
    private String year;//要统计的年份
    private Date quotaDate;//统计的时间
    private String timeLevel;//1 日 2年
    private Integer incrementInterval;//增量的时间间隔(天)
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
@ -107,6 +108,7 @@ public class MysqlToEsQuotaJob implements Job {
        this.timeLevel = map.getString("timeLevel");
        this.endTime = map.getString("endTime");
        this.startTime = map.getString("startTime");
        this.incrementInterval = (Integer) map.get("incrementInterval");
        //为空默认是统计昨天的数据  统计昨天的数据是从 前天的下午17:00:00 到昨天的下午17:00:00
        //初始化结束时间
        if (StringUtils.isEmpty(endTime)) {
@ -123,7 +125,8 @@ public class MysqlToEsQuotaJob implements Job {
        } else {
            //增量
            if (StringUtils.isEmpty(startTime)) {
                startTime = new LocalDate(new DateTime().minusDays(2)).toString("yyyy-MM-dd") + " 17:00:00"; //2017-06-01 17:00:00
//                startTime = new LocalDate(new DateTime().minusDays(2)).toString("yyyy-MM-dd") + " 17:00:00"; //2017-06-01 17:00:00
                getStartTime();
            } else {
                startTime = startTime + " 17:00:00";
            }
@ -326,4 +329,17 @@ public class MysqlToEsQuotaJob implements Job {
            return (1900 + today.getYear() - 1) + "";
        }
    }
    public void getStartTime() throws Exception{
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        if(this.incrementInterval==1){//日
            startTime = new LocalDate(new DateTime().minusDays(2)).toString("yyyy-MM-dd") + " 17:00:00";
        }else if(this.incrementInterval==2){//周
            Date monday = DateUtil.getMondayOfThisDayToDate(sf.parse(endTime));
            startTime =sf.format(monday)+ " 17:00:00";
        }else if(this.incrementInterval==3){//月
            Date fristDay = DateUtil.getFristDayOfMonthToDate(sf.parse(endTime));
            startTime = sf.format(fristDay)+ " 17:00:00";
        }
    }
}

+ 53 - 16
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/service/JobService.java

@ -6,6 +6,7 @@ import com.yihu.wlyy.statistics.dao.QuartzJobConfigDao;
import com.yihu.wlyy.statistics.dao.SignFamilyDao;
import com.yihu.wlyy.statistics.etl.cache.Cache;
import com.yihu.wlyy.statistics.job.business.CacheCleanJob;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.QuartzHelper;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import org.springframework.beans.BeanUtils;
@ -45,8 +46,9 @@ public class JobService {
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id, "1");
        if (quartzJobConfig != null) {
            for (int j = 1; j <= 2; j++) {
                if (breakPoint(quartzJobConfig, j)) continue;
                quartzHelper.removeJob(quartzJobConfig.getId() + "-" + j);
                wlyyJobConfigDao.updateStatus(quartzJobConfig.getId(),"0") ;;
                wlyyJobConfigDao.updateStatus(quartzJobConfig.getId(), "0");
            }
        } else {
            throw new Exception("任务已经停止");
@ -70,9 +72,11 @@ public class JobService {
        if (quartzJobConfigs != null && quartzJobConfigs.size() > 0) {
            for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
                for (int j = 1; j <= 2; j++) {
                    if (breakPoint(quartzJobConfig, j)) continue;
                    quartzHelper.removeJob(quartzJobConfig.getId() + "-" + j);
                    wlyyJobConfigDao.updateStatus(quartzJobConfig.getId(),"0") ;;
                    wlyyJobConfigDao.updateStatus(quartzJobConfig.getId(), "0");
                    ;
                }
            }
        } else {
@ -108,10 +112,11 @@ public class JobService {
        params.put("jobConfig", wlyyJobConfigVO.getId());
        if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
            for (int j = 1; j <= 2; j++) {
                if (breakPoint(wlyyJobConfigVO, j)) continue;
                params.put("timeLevel", j + "");
                //往quartz框架添加任务
                quartzHelper.addJob(getRightClass(quartzJobConfig), quartzJobConfig.getQuartzCron(), quartzJobConfig.getId() + "-" + j, params);
               wlyyJobConfigDao.updateStatus(quartzJobConfig.getId(),"1") ;//设置任务状态是启动 }
                wlyyJobConfigDao.updateStatus(quartzJobConfig.getId(), "1");//设置任务状态是启动 }
            }
        }
    }
@ -125,6 +130,7 @@ public class JobService {
        Map<String, String> params = new HashMap<String, String>();
        params.put("jobConfig", wlyyJobConfigVO.getId());
        for (int i = 1; i <= 2; i++) {
            if (breakPoint(wlyyJobConfigVO, i)) continue;
            params.put("timeLevel", i + "");
            //往quartz框架添加任务
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
@ -134,6 +140,32 @@ public class JobService {
        }
    }
    private boolean breakPoint(WlyyJobConfigVO wlyyJobConfigVO, int i) {
        //如果为空或者等3说明纪要生成到达量也要生成增量
        if (StringUtils.isEmpty(wlyyJobConfigVO.getTimeLevel()) || Integer.valueOf(wlyyJobConfigVO.getTimeLevel()) == 3) {
            return false;
        }
        //如果不为空 并且是1或者2 说明只要增量或者只要到达量
        if (!(StringUtils.isEmpty(wlyyJobConfigVO.getTimeLevel())) && Integer.valueOf(wlyyJobConfigVO.getTimeLevel()) == i) {
            return false;
        }
        if(wlyyJobConfigVO.getIncrementInterval()!=1){
            return true;
        }
        return true;
    }
    private boolean breakPoint(QuartzJobConfig wlyyJobConfigVO, int i) {
        //如果为空或者等3说明纪要生成到达量也要生成增量
        if (StringUtils.isEmpty(wlyyJobConfigVO.getTimeLevel()) || Integer.valueOf(wlyyJobConfigVO.getTimeLevel()) == 3) {
            return false;
        }
        //如果不为空 并且是1或者2 说明只要增量或者只要到达量
        if (!(StringUtils.isEmpty(wlyyJobConfigVO.getTimeLevel())) && Integer.valueOf(wlyyJobConfigVO.getTimeLevel()) == i) {
            return false;
        }
        return true;
    }
    public void productDataByDay(Integer day) throws Exception {
        List<QuartzJobConfig> quartzJobConfigs = wlyyJobConfigDao.findByIds();
@ -146,6 +178,7 @@ public class JobService {
            params.put("jobConfig", wlyyJobConfigVO.getId());
            for (int i = 1; i <= day; i++) {
                for (int j = 1; j <= 2; j++) {
                    if (breakPoint(wlyyJobConfigVO, j)) continue;
                    params.put("timeLevel", j + "");
                    //往quartz框架添加任务
                    params.put("startTime", getYesterday(0 - i - 1));
@ -167,7 +200,7 @@ public class JobService {
    }
    public void productDataByOneDay(String yesterday) throws Exception {
        String sql="select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        String sql = "select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
@ -179,7 +212,7 @@ public class JobService {
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<QuartzJobConfig> quartzJobConfigs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(QuartzJobConfig.class));
        List<QuartzJobConfig> quartzJobConfigs = jdbcTemplate.query(sql, new BeanPropertyRowMapper(QuartzJobConfig.class));
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
@ -192,6 +225,7 @@ public class JobService {
            params.put("endTime", yesterday);
            for (int j = 1; j <= 2; j++) {
                if (breakPoint(wlyyJobConfigVO, j)) continue;
                params.put("timeLevel", j + "");
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
@ -238,6 +272,7 @@ public class JobService {
        params.put("endTime", yesterday);
        for (int j = 1; j <= 2; j++) {
            if (breakPoint(wlyyJobConfigVO, j)) continue;
            params.put("timeLevel", j + "");
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
@ -262,6 +297,7 @@ public class JobService {
            params.put("startTime", getYesterday(0 - i - 1));
            params.put("endTime", getYesterday(0 - i));
            for (int j = 1; j <= 2; j++) {
                if (breakPoint(wlyyJobConfigVO, j)) continue;
                params.put("timeLevel", j + "");
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
@ -270,6 +306,7 @@ public class JobService {
            }
        }
    }
    public void productDataByDayToDay(String start, String end) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
@ -280,7 +317,7 @@ public class JobService {
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            Cache.cleanCache();//清空缓存
           // Thread.sleep(60000L);//休息60秒
            // Thread.sleep(60000L);//休息60秒
            productDataByOneDay(getYesterday(i, startDate));
        }
    }
@ -316,10 +353,10 @@ public class JobService {
            throw new Exception("日期参数错误");
        }
        int day = daysBetween(startDate, endDate);
        String [] idStr=ids.split(",");
        String[] idStr = ids.split(",");
        for (int i = 0; i < day; i++) {
            Cache.cleanCache();//清空缓存
            for(String id:idStr){
            for (String id : idStr) {
                productDataByOneDayWithId(getYesterday(i, startDate), id);
            }
        }
@ -327,7 +364,7 @@ public class JobService {
    //================================================没有休眠时间=============================================================
    public void productDataByDayToDayAndIdNoSleep(String start, String end, String id,Long sleepTime) throws Exception {
    public void productDataByDayToDayAndIdNoSleep(String start, String end, String id, Long sleepTime) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse(start);
        Date endDate = sdf.parse(end);
@ -337,12 +374,12 @@ public class JobService {
        int day = daysBetween(startDate, endDate);
        for (int i = 0; i < day; i++) {
            Cache.cleanCache();//清空缓存
            productDataByOneDayWithIdNoSleep(getYesterday(i, startDate), id,sleepTime);
            productDataByOneDayWithIdNoSleep(getYesterday(i, startDate), id, sleepTime);
        }
    }
    public void productDataByOneDayWithIdNoSleep(String yesterday, String id,Long sleepTime) throws Exception {
    public void productDataByOneDayWithIdNoSleep(String yesterday, String id, Long sleepTime) throws Exception {
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
        if (date == null) {
@ -373,13 +410,13 @@ public class JobService {
            if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
            }
            Thread.sleep(sleepTime*1000L);
            Thread.sleep(sleepTime * 1000L);
        }
    }
    public void productDataByOneDayNoSleep(String yesterday,Long sleepTime) throws Exception {
        String sql="select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
    public void productDataByOneDayNoSleep(String yesterday, Long sleepTime) throws Exception {
        String sql = "select * from wlyy_job_config_new a where  a.del='1' and a.id !=11 order by a.id asc";
        SimpleDateFormat dataSimple = new SimpleDateFormat("yyyy-MM-dd");
        Date date = dataSimple.parse(yesterday);
@ -391,7 +428,7 @@ public class JobService {
        calendar.add(calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nowDate = calendar.getTime();   //这个时间就是日期往后推一天的结果
        String daybefore = new SimpleDateFormat("yyyy-MM-dd").format(nowDate.getTime());
        List<QuartzJobConfig> quartzJobConfigs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(QuartzJobConfig.class));
        List<QuartzJobConfig> quartzJobConfigs = jdbcTemplate.query(sql, new BeanPropertyRowMapper(QuartzJobConfig.class));
        for (QuartzJobConfig quartzJobConfig : quartzJobConfigs) {
            WlyyJobConfigVO wlyyJobConfigVO = new WlyyJobConfigVO();
@ -408,7 +445,7 @@ public class JobService {
                if (!StringUtils.isEmpty(quartzJobConfig.getJobClass())) {
                    quartzHelper.startNow(getRightClass(quartzJobConfig), quartzJobConfig.getId() + UUID.randomUUID().toString().replace("-", ""), params);
                }
                Thread.sleep(sleepTime*1000L);
                Thread.sleep(sleepTime * 1000L);
            }
        }

+ 99 - 1
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/util/DateUtil.java

@ -179,7 +179,7 @@ public class DateUtil {
	 * 将短时间格式时间转换为字符串 yyyy-MM-dd
	 *
	 * @param dateDate
	 * @param k
	 * @param
	 * @return
	 */
	public static String dateToStr(Date dateDate, String format) {
@ -717,4 +717,102 @@ public class DateUtil {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.YEAR);
	}
	/**
	 * 获取周一
	 * @return
	 */
	public static String getMondayOfThisDate(Date date) {
		SimpleDateFormat df2 = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
		return df2.format(getMondayOfThisDayToDate(date));
	}
	/**
	 * 获取周一
	 * @return
	 */
	public static Date getMondayOfThisDayToDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 1);
		return c.getTime();
	}
    /**
     * 得到本周周日
     *
     * @return yyyy-MM-dd
     */
    public static String getSundayOfThisDate(Date date) {
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0)
            day_of_week = 7;
        c.add(Calendar.DATE, -day_of_week + 7);
        return df2.format(c.getTime());
    }
	/**
	 * 获取当月第一天
	 * @return
	 */
	public static String getFristDayOfMonth(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(getFristDayOfMonthToDate(date));
	}
	public static Date getFristDayOfMonthToDate(Date date) {
		// 获取前月的第一天
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
		return c.getTime();
	}
	/**
	 * 获取当月的最后一天
	 * @param date
	 * @return
	 */
	public static String getLastDayOfMonth(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(getLastDayOfMonthToDate(date));
	}
	public static Date getLastDayOfMonthToDate(Date date){
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		return ca.getTime();
	}
	//获取输入时间是当前年度的第几周
	public static Integer week(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setFirstDayOfWeek(Calendar.MONDAY);
		calendar.setTime(date);
		return calendar.get(Calendar.WEEK_OF_YEAR);
	}
	//获取输入时间是当前年度的第几周
	public static Integer month(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setFirstDayOfWeek(Calendar.MONDAY);
		calendar.setTime(date);
		return calendar.get(Calendar.MONTH);
	}
	/**
	 * 获取某年最后一天日期
	 * @param year 年份
	 * @return Date
	 */
	public static Date getYearLast(int year){
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		calendar.roll(Calendar.DAY_OF_YEAR, -1);
		Date currYearLast = calendar.getTime();
		return currYearLast;
	}
}

+ 18 - 1
patient-co/patient-co-statistics-es/src/main/java/com/yihu/wlyy/statistics/vo/WlyyJobConfigVO.java

@ -22,7 +22,8 @@ public class WlyyJobConfigVO implements  Serializable {
    private String sqlDay;//按日统计
    private String sqlYear;//按年统计
    private String cacheKey;//缓存的key
    private Integer incrementInterval;//增量的时间间隔(1天,2周,3月)
    private String timeLevel;//1增量 2到达量 3生成到达量也生成增量
    public WlyyJobConfigVO() {
    }
@ -154,4 +155,20 @@ public class WlyyJobConfigVO implements  Serializable {
    public void setCacheKey(String cacheKey) {
        this.cacheKey = cacheKey;
    }
    public Integer getIncrementInterval() {
        return incrementInterval;
    }
    public void setIncrementInterval(Integer incrementInterval) {
        this.incrementInterval = incrementInterval;
    }
    public String getTimeLevel() {
        return timeLevel;
    }
    public void setTimeLevel(String timeLevel) {
        this.timeLevel = timeLevel;
    }
}

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/aop/ObserverRequiredAOP.java

@ -16,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
 * Created by Trick on 2017/6/24.
 * Created by Trick on 2017/6/24..
 */
@Aspect
@Component

+ 14 - 7
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/DeviceDetailService.java

@ -75,7 +75,7 @@ public class DeviceDetailService extends BaseService {
		}
		//设备表没有数据则插入一条数据
		if (deviceDetail==null){
			insertDevice(patientDevice,String.valueOf(adminTeam),hospitalName,hospital);
			insertDevice(patientDevice,String.valueOf(adminTeam),hospitalName,hospital,"");
			deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		}
@ -108,7 +108,7 @@ public class DeviceDetailService extends BaseService {
	 * @param orgCode
	 * @throws Exception
	 */
	public void insertDevice(PatientDevice patientDevice, String adminTeam, String orgName, String orgCode)throws Exception{
	public void insertDevice(PatientDevice patientDevice, String adminTeam, String orgName, String orgCode,String bindCount)throws Exception{
		//获取原始数据
		DeviceDetail deviceDetail = new DeviceDetail();
		Patient patient = patientDao.findByCode(patientDevice.getUser());
@ -122,7 +122,7 @@ public class DeviceDetailService extends BaseService {
		deviceDetail.setGrantAdminTeam(adminTeam);
		deviceDetail.setGrantOrgCode(orgCode);
		deviceDetail.setIsBinding(1);
		deviceDetail.setGrantTime(new Date());
		deviceDetail.setGrantTime(patientDevice.getCzrq());
		deviceDetail.setApplyDate(DateUtil.getStringDate("yyyy-MM-dd HH:mm:ss"));
		deviceDetail.setOrgName(orgName);
@ -130,12 +130,15 @@ public class DeviceDetailService extends BaseService {
			deviceDetail.setDeviceModel(device.getModel());
		}
		if (Integer.valueOf(patientDevice.getUserType())>0){
			deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
		if (StringUtils.isNotEmpty(bindCount)){
			deviceDetail.setBindingCount(bindCount);
		}else {
			deviceDetail.setBindingCount("{\"1\":\"0\"}");
			if (Integer.valueOf(patientDevice.getUserType())>0){
				deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
			}else {
				deviceDetail.setBindingCount("{\"1\":\"0\"}");
			}
		}
		if (patient!=null){
			deviceDetail.setLinkman(patient.getName());
			deviceDetail.setTel(patient.getPhone());
@ -169,4 +172,8 @@ public class DeviceDetailService extends BaseService {
			//deviceDetailDao.updateUnbindAll(2,deviceSn);
		}
	}
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
}

+ 2 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceLogService.java

@ -62,6 +62,7 @@ public class PatientDeviceLogService extends BaseService {
            patientDeviceLog.setOperator(patientDevice.getAgent());
        }
        patientDeviceLog.setCreateTime(new Date());
        patientDeviceLog.setIsDel(1);
        patientDeviceLogDao.save(patientDeviceLog);
    }
@ -98,7 +99,7 @@ public class PatientDeviceLogService extends BaseService {
        }
        //筛选条件--一个月内未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("3",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM device.wlyy_patient_health_index WHERE DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= DATE(record_date))";
            sql += " and b.patient NOT IN (SELECT user FROM device.wlyy_patient_health_index WHERE DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= DATE(record_date))";
        }
        //筛选条件--超过一个月未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("4",noGaugeDay)){

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/device/PatientDeviceService.java

@ -1161,7 +1161,7 @@ public class PatientDeviceService extends BaseService {
    public Map<String,Object> getDeviceByDeviceSn(String deviceSn)throws Exception {
        Map<String,Object> map  = new HashedMap();
        String sql = "SELECT d.id,d.device_name deviceName,d.device_model deviceMode,d.sim,d.device_activity_type deviceActivityType,e.is_multi_user isMultiUser,e.category_code as deviceType,e.multi_user multiUser,e.id as device_id FROM wlyy_devices d LEFT JOIN dm_device e ON d.device_model = e.model WHERE d.device_code='"+deviceSn+"'";
        String sql = "SELECT d.id,d.device_name deviceName,d.device_model deviceMode,d.sim,e.is_multi_user isMultiUser,e.category_code as deviceType,e.multi_user multiUser,e.id as device_id FROM device.wlyy_devices d LEFT JOIN wlyy.dm_device e ON d.device_model = e.model WHERE d.device_code='"+deviceSn+"'";
        List<Map<String,Object>> mapSqlList = jdbcTemplate.queryForList(sql);
        if (mapSqlList!=null && mapSqlList.size()>0){
            map = mapSqlList.get(0);

+ 8 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/bank/CreditLogService.java

@ -137,6 +137,7 @@ public class CreditLogService {
        object.put("name",patient.getName());
        object.put("idCard",patient.getIdcard());
        object.put("openId",patient.getOpenid());
        object.put("unionId",patient.getUnionid());
        String url =getBaseUrl() + "createCreditsDetail";
        Map<String,String> params = new HashMap<>();
        params.put("creditsDetail",object.toJSONString());
@ -494,8 +495,14 @@ public class CreditLogService {
        String response = null;
        String url =getBaseUrl() + "doctorAddIntegrate";
        JSONArray array = object.getJSONArray("patientIds");
        JSONArray jsonArray  = new JSONArray();
        for (int i =0 ;i<array.size();i++){
            Patient patient = patientDao.findByCode(array.getString(i));
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(patient);
            jsonArray.add(jsonObject);
        }
        JSONObject object1 = new JSONObject();
        object1.put("patientIds",array);
        object1.put("patient",jsonArray);
        object1.put("ruleId",object.getString("ruleId"));
        object1.put("description",object.getString("description"));
        JSONObject object2 = null;

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/prescription/PrescriptionDispensaryCodeService.java

@ -237,7 +237,7 @@ public class PrescriptionDispensaryCodeService extends BaseService {
        //String jgsID= "";//配送员用户ID后4位
//        String jgsCode = code+"1234";//code+jgsID.substring(jgsID.length()-4);
        // 生成二维码
        InputStream ipt = QrcodeUtil.createQrcode(code,300,"png");
        InputStream ipt = QrcodeUtil.createQrcode(jgsCode,300,"png");
//        Prescription类  取药类型:1 自取 2快递配送 3健管师配送
    

+ 64 - 8
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/sign/SignWebService.java

@ -5,6 +5,7 @@ import com.yihu.wlyy.entity.address.Street;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.charge.WlyyCharge;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
@ -27,7 +28,9 @@ import com.yihu.wlyy.repository.message.MessageDao;
import com.yihu.wlyy.repository.patient.*;
import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
import com.yihu.wlyy.service.app.statistics.ServiceStatisticsService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.DoctorService;
@ -39,6 +42,7 @@ import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ElasticsearchUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
@ -130,10 +134,14 @@ public class SignWebService extends BaseService {
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    /**
     * 厦门市
     */
    public static String city = "350200";
    @Autowired
    private ServiceStatisticsService serviceStatisticsService;
    /**
     * 根据医生代码及签约状态编码 获取该医生签约患者的信息列表
@ -632,6 +640,7 @@ public class SignWebService extends BaseService {
            if (adminTeam == null) adminTeam = new AdminTeam();
            if (doctor == null) doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataType","sign");//家庭医生签约服务包
            jsonObject.put("hospitalName", renew.getHospitalName());
            jsonObject.put("hospital", renew.getHospital());
            jsonObject.put("code", renewCode);
@ -703,6 +712,7 @@ public class SignWebService extends BaseService {
            if (adminTeam == null) adminTeam = new AdminTeam();
            if (doctor == null) doctor = new Doctor();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataType","sign");//家庭医生签约服务包
            jsonObject.put("hospitalName", signFamily.getHospitalName());
            jsonObject.put("hospital", signFamily.getHospital());
            jsonObject.put("code", signCode);
@ -763,6 +773,36 @@ public class SignWebService extends BaseService {
            jsonObject.put("statusName", statusName);
            jsonArray.add(jsonObject);
        }
        
        List<PatientDevice> patientDevices = patientDeviceDao.findByPatient(patient);
        for (PatientDevice patientDevice: patientDevices) {
            JSONObject jsonObject = new JSONObject();
            SignFamily signFamily = signFamilyDao.findByPatient(patient);//签约社区
            if(StringUtils.isNotBlank(patientDevice.getDoctor())){
                Doctor deviceDoctor = doctorService.findDoctorByCode(patientDevice.getDoctor());
                jsonObject.put("doctor",patientDevice.getDoctor());//操作医生代码
                jsonObject.put("doctorName",deviceDoctor.getName());//操作医生姓名
            }
            jsonObject.put("dataType","device");//家庭医生签约服务包
            jsonObject.put("deviceId",patientDevice.getDeviceId());//设备ID
            jsonObject.put("deviceSn",patientDevice.getDeviceSn());//设备SN码
            jsonObject.put("sim",patientDevice.getSim());//设备SIM卡号
            jsonObject.put("deviceName",patientDevice.getDeviceName());//设备名称
            jsonObject.put("user",patientDevice.getUser());//居民CODE
            jsonObject.put("categoryCode",patientDevice.getCategoryCode());//1血糖仪,2.血压计
            jsonObject.put("userType",patientDevice.getUserType());//-1代表单用户
            jsonObject.put("userIdcard",patientDevice.getUserIdcard());//用户身份证号
            jsonObject.put("agent",patientDevice.getAgent());//代绑人代码(家人)
            jsonObject.put("agentName",patientDevice.getAgentName());//代绑人姓名
            jsonObject.put("createTime",patientDevice.getCzrq());//操作时间
            jsonObject.put("agreementPhoto",patientDevice.getAgreementPhoto());//上传的协议图片地址
            jsonObject.put("hospitalName",signFamily.getHospitalName());//社区名称
            jsonArray.add(jsonObject);
        }
        
        
        
        Collections.sort(jsonArray, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
@ -2124,21 +2164,37 @@ public class SignWebService extends BaseService {
                " WHERE w.doctor in(" + doctorCodeSql + ") AND w.patient ='" + patient + "'" +
                " AND w.czrq <='" + DateUtil.getSignYear() + "-07-01' AND w.czrq >='" + (DateUtil.getSignYear() - 1) + "-07-01'  ";
        //获取健康教育
        String article_sql = "SELECT COUNT(1) AS articleCount FROM wlyy_health_edu_article_patient  w,wlyy_health_edu_article w2 WHERE w.article = w2.code " +
                "AND  w.doctor IN(" + doctorCodeSql + ") AND w.patient ='" + patient + "' " +
                "AND w.czrq <='" + DateUtil.getSignYear() + "-07-01' AND w.czrq >='" + (DateUtil.getSignYear() - 1) + "-07-01'  ";
//        String article_sql = "SELECT COUNT(1) AS articleCount FROM wlyy_health_edu_article_patient  w,wlyy_health_edu_article w2 WHERE w.article = w2.code " +
//                "AND  w.doctor IN(" + doctorCodeSql + ") AND w.patient ='" + patient + "' " +
//                "AND w.czrq <='" + DateUtil.getSignYear() + "-07-01' AND w.czrq >='" + (DateUtil.getSignYear() - 1) + "-07-01'  ";
        //获取健康指导
        String guidance_sql = "SELECT COUNT(1) AS guidanceCount  FROM wlyy_patient_health_guidance  w " +
                "WHERE w.doctor IN(" + doctorCodeSql + ") and w.patient ='" + patient + "' AND w.czrq <='" + DateUtil.getSignYear() + "-07-01' AND w.czrq >='" + (DateUtil.getSignYear() - 1) + "-07-01'  ";
//        String guidance_sql = "SELECT COUNT(1) AS guidanceCount  FROM wlyy_patient_health_guidance  w " +
//                "WHERE w.doctor IN(" + doctorCodeSql + ") and w.patient ='" + patient + "' AND w.czrq <='" + DateUtil.getSignYear() + "-07-01' AND w.czrq >='" + (DateUtil.getSignYear() - 1) + "-07-01'  ";
        //咨询量
        List<Map<String, Object>> consultResult = jdbcTemplate.queryForList(consult_sql);
        //待预约量
        List<Map<String, Object>> reservationResult = jdbcTemplate.queryForList(reservation_sql);
        //健康教育量
        List<Map<String, Object>> articleResult = jdbcTemplate.queryForList(article_sql);
        //List<Map<String, Object>> articleResult = jdbcTemplate.queryForList(article_sql);
        Calendar today = Calendar.getInstance();
        today.set(Calendar.DATE, 1);
        JSONObject article = serviceStatisticsService.getArticleStatistics(patient,signFamily.getAdminTeamId(), DateUtil.dateToStrShort(signFamily.getBegin()), DateUtil.dateToStrShort(signFamily.getEnd()), DateUtil.dateToStrShort(today.getTime()));
        List<Map<String, Object>> articleResult = new ArrayList<>();
        Map<String,Object> ac = new HashedMap();
        ac.put("articleCount",article.getInt("year"));
        articleResult.add(ac);
        //健康指导量
        List<Map<String, Object>> guidanceResult = jdbcTemplate.queryForList(guidance_sql);
        //List<Map<String, Object>> guidanceResult = jdbcTemplate.queryForList(guidance_sql);
        String monthBegin = DateUtil.dateToStrShort(today.getTime()) + " 00:00:00";
        String yearBegin = DateUtil.dateToStrShort(signFamily.getBegin()) + " 00:00:00";
        String yearEnd = DateUtil.dateToStrShort(signFamily.getEnd()) + " 23:59:59";
        JSONObject guidance = serviceStatisticsService.getGuidanceStatistics(patient, signFamily.getAdminTeamId(), yearBegin, yearEnd, monthBegin);
        List<Map<String, Object>> guidanceResult =  new ArrayList<>();
        Map<String,Object> gui = new HashedMap();
        gui.put("guidanceCount",guidance.getInt("year"));
        guidanceResult.add(gui);
        Long consultTotal = 0L;
        if (consultResult != null && consultResult.size() > 0) {

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

@ -793,6 +793,18 @@ public class StatisticsESService {
        return filesize + "%";
    }
    public Double getRange2(int first, int second, int i) {
        if (second == 0 && first > 0) {
            return 1.0;
        } else if (second == 0 && first == 0) {
            return 0.0;
        }
        Double size =  (first * 100.0) / second;
//        DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
//        String filesize = df.format(size);
        return size;
    }
    /**
     * 统计65以上人群数据
     *
@ -5182,7 +5194,8 @@ public class StatisticsESService {
        //String lastDate = year + "-06-30";
        //String timeKey = elasticsearchUtil.getQuotaTime();
        String timeKey = DateUtil.getStringDateShort();//当前时间
        String mondayTime = DateUtil.getMondayOfThisDate(new Date());//本周一开始时间
        String currentTime = DateUtil.getStringDate();
        String mondayTime = DateUtil.getMondayOfThisDate(new Date())+" 00:00:00";//本周一开始时间
        String low_level = String.valueOf(StringUtils.isEmpty(lowLevel) ? (level + 1) : lowLevel);
        Map<String, Object> resultMap = new HashedMap();
        DecimalFormat df = new DecimalFormat("0.00");
@ -5195,24 +5208,26 @@ public class StatisticsESService {
        SaveModel anomalySaveModel = null;
        String allCountSql = "";
        String anomalyCountSql = "";
        String useCountSql = "";
        List<SaveModel> allAmountList = null;//发放量列表
        List<SaveModel> bindingAmountList = null;//绑定量列表
        String areaCondition = "";
        if (SaveModel.OrgLevel.equals(level + "")) {
            areaCondition = " and d.grant_org_code like '" + area + "' ";
        } else if (SaveModel.townLevel.equals(level + "")) {
            areaCondition = " and d.grant_org_code like '" + area.substring(0, 4) + "%' ";
            areaCondition = " and d.grant_org_code like '" + area.substring(0, 6) + "%' ";
        } else if (SaveModel.cityLevel.equals(level + "")) {
            areaCondition = " and d.grant_org_code like '" + area.substring(0, 2) + "%' ";
            areaCondition = " and d.grant_org_code like '" + area.substring(0, 4) + "%' ";
        }
//SELECT DISTINCT p.device_sn as healthProblem,"team" as team FROM device.wlyy_patient_health_index p WHERE p.type IN (1, 2) and p.del=1
        switch (deviceType) {
            case "1": {
                grantSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_85, SaveModel.timeLevel_DDL, "hemopiezometer");
                bindingSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_86, SaveModel.timeLevel_DDL, "hemopiezometer");
                allCountSql = "SELECT COUNT(*) FROM device.wlyy_devices d where device_name like '%血压%' " + areaCondition;
                startUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(mondayTime, mondayTime, area, level, index_87, SaveModel.timeLevel_DDL, "hemopiezometer", null, null);
                endUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index_87, SaveModel.timeLevel_DDL, "hemopiezometer", null, null);
                useCountSql = "SELECT COUNT(DISTINCT p.device_sn)  FROM device.wlyy_patient_health_index p LEFT JOIN device.wlyy_devices d on d.device_code=p.device_sn WHERE p.type IN (1, 2) and p.del=1 and p.type=1 and p.czrq>= '"+mondayTime+"' AND p.czrq < '"+currentTime+"' "+areaCondition ;
//                startUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(mondayTime, mondayTime, area, level, index_87, SaveModel.timeLevel_DDL, "hemopiezometer", null, null);
//                endUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index_87, SaveModel.timeLevel_DDL, "hemopiezometer", null, null);
                anomalySaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_88, SaveModel.timeLevel_DDL, "hemopiezometer");
                anomalyCountSql = " SELECT COUNT(i.id) FROM device.wlyy_patient_health_index i left join device.wlyy_devices d on i.device_sn=d.device_code where i.type =1 and i.status=1 and i.del=1 " + areaCondition;
                allAmountList = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index_85, SaveModel.timeLevel_DDL, "hemopiezometer", "", low_level);
@ -5223,8 +5238,9 @@ public class StatisticsESService {
                grantSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_85, SaveModel.timeLevel_DDL, "glucometer");
                bindingSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_86, SaveModel.timeLevel_DDL, "glucometer");
                allCountSql = "SELECT COUNT(*) FROM device.wlyy_devices d where device_name like '%血糖%' " + areaCondition;
                startUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(mondayTime, mondayTime, area, level, index_87, SaveModel.timeLevel_DDL, "glucometer", null, null);
                endUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index_87, SaveModel.timeLevel_DDL, "glucometer", null, null);
                useCountSql = "SELECT COUNT(DISTINCT p.device_sn)  FROM device.wlyy_patient_health_index p LEFT JOIN device.wlyy_devices d on d.device_code=p.device_sn WHERE p.type IN (1, 2) and p.del=1 and p.type=2 and p.czrq>= '"+mondayTime+"' AND p.czrq < '"+currentTime+"' "+areaCondition ;
//                startUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(mondayTime, mondayTime, area, level, index_87, SaveModel.timeLevel_DDL, "glucometer", null, null);
//                endUseSaveModel = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index_87, SaveModel.timeLevel_DDL, "glucometer", null, null);
                anomalySaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_88, SaveModel.timeLevel_DDL, "glucometer");
                anomalyCountSql = " SELECT COUNT(i.id) FROM device.wlyy_patient_health_index i left join device.wlyy_devices d on i.device_sn=d.device_code where i.type =2 and i.status=1 and i.del=1 " + areaCondition;
                allAmountList = elasticsearchUtil.findDateQuotaLevel1(timeKey, timeKey, area, level, index_85, SaveModel.timeLevel_DDL, "glucometer", "", low_level);
@ -5236,9 +5252,10 @@ public class StatisticsESService {
                bindingSaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_86, SaveModel.timeLevel_DDL);
                anomalySaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_88, SaveModel.timeLevel_DDL);
                allCountSql = "SELECT COUNT(*) FROM device.wlyy_devices d where 1=1 " + areaCondition;
                useCountSql = "SELECT COUNT(DISTINCT p.device_sn)  FROM device.wlyy_patient_health_index p LEFT JOIN device.wlyy_devices d on d.device_code=p.device_sn WHERE p.type IN (1, 2) and p.del=1  and p.czrq>= '"+mondayTime+"' AND p.czrq < '"+currentTime+"' "+areaCondition ;
                anomalyCountSql = " SELECT COUNT(i.id) FROM device.wlyy_patient_health_index i left join device.wlyy_devices d on i.device_sn=d.device_code where  i.status=1 and i.del=1 " + areaCondition;
                startUseSaveModel = elasticsearchUtil.findDateQuotaLevel0(mondayTime, mondayTime, area, level, index_87, SaveModel.timeLevel_DDL, null, null);
                endUseSaveModel = elasticsearchUtil.findDateQuotaLevel0(timeKey, timeKey, area, level, index_87, SaveModel.timeLevel_DDL, null, null);
//                startUseSaveModel = elasticsearchUtil.findDateQuotaLevel0(mondayTime, mondayTime, area, level, index_87, SaveModel.timeLevel_DDL, null, null);
//                endUseSaveModel = elasticsearchUtil.findDateQuotaLevel0(timeKey, timeKey, area, level, index_87, SaveModel.timeLevel_DDL, null, null);
                allAmountList = elasticsearchUtil.findDateQuotaLevel0(timeKey, timeKey, area, level, index_85, SaveModel.timeLevel_DDL, "", low_level);
                bindingAmountList = elasticsearchUtil.findDateQuotaLevel0(timeKey, timeKey, area, level, index_86, SaveModel.timeLevel_DDL, "", low_level);
@ -5259,12 +5276,13 @@ public class StatisticsESService {
            resultMap.put("totalGrantRange", 0.0 + "%");//发放率
            resultMap.put("totalBindingRange", 0.0 + "%");//绑定率
        }
        Double startTotalUseAccount = startUseSaveModel.size() > 0 ? startUseSaveModel.get(0).getResult1() : 0.0;
        Double endTotalUseAccount = endUseSaveModel.size() > 0 ? endUseSaveModel.get(0).getResult1() : 0.0;
        Double totalUseAccount = endTotalUseAccount-startTotalUseAccount;
        resultMap.put("totalUse", endTotalUseAccount-startTotalUseAccount);//本周使用量
//        Double startTotalUseAccount = startUseSaveModel.size() > 0 ? startUseSaveModel.get(0).getResult1() : 0.0;
//        Double endTotalUseAccount = endUseSaveModel.size() > 0 ? endUseSaveModel.get(0).getResult1() : 0.0;
//        Double totalUseAccount = endTotalUseAccount-startTotalUseAccount;
        Integer useCount = jdbcTemplate.queryForObject(useCountSql, Integer.class);
        resultMap.put("totalUse", useCount);//本周使用量
        if (grantSaveModel.getResult1() > 0) {
            resultMap.put("totalUseRange", df.format(totalUseAccount > 0.0 ? ((totalUseAccount) / (grantSaveModel.getResult1() * 1.0000) * 100) : 0.0) + "%");//本周使用率
            resultMap.put("totalUseRange", df.format(useCount.doubleValue() > 0.0 ? ((useCount.doubleValue()) / (grantSaveModel.getResult1() * 1.0000) * 100) : 0.0) + "%");//本周使用率
        } else {
            resultMap.put("totalUseRange", 0.0 + "%");//本周使用率
        }
@ -5362,53 +5380,64 @@ public class StatisticsESService {
        String index_91 = "91";//健康银行全部活动报名数(人)
        String index_1 = "1";//签约已缴费指标(总人数按签约人数计算)
        String index_92 = "92";//健康银行活动参与数(人次)
        String index_93 = "93";//健康银行活动获取积分数(人次)
        String timeKey = DateUtil.getStringDateShort();//当前时间
        DecimalFormat df = new DecimalFormat("0.00");
        String areaCondition = "";
        String areaCondition2 = "";
        //发布活动数
        if (SaveModel.OrgLevel.equals(level + "")) {
            areaCondition = " and d.area like '" + area + "' ";
            areaCondition2 = " and t.org_code like '" + area + "' ";
//            areaCondition2 = " and t.org_code like '" + area + "' ";
        } else if (SaveModel.townLevel.equals(level + "")) {
            areaCondition = " and d.area like '" + area.substring(0, 4) + "%' ";
            areaCondition2 = " and t.org_code like '" + area.substring(0, 4) + "%' ";
            areaCondition = " and d.area like '" + area.substring(0, 6) + "%' ";
//            areaCondition2 = " and t.org_code like '" + area.substring(0, 4) + "%' ";
        } else if (SaveModel.cityLevel.equals(level + "")) {
            areaCondition = " and d.area like '" + area.substring(0, 2) + "%' ";
            areaCondition2 = " and t.org_code like '" + area.substring(0, 2) + "%' ";
            areaCondition = " and d.area like '" + area.substring(0, 4) + "%' ";
//            areaCondition2 = " and t.org_code like '" + area.substring(0, 2) + "%' ";
        }
        String activitySql = "select count(1) from wlyy_health_bank_activity d where d.status=1  " + areaCondition;
        String activitySql = "select count(1) from wlyy_health_bank.wlyy_health_bank_activity d where d.status=1  " + areaCondition;
        Integer activityCount = jdbcTemplate.queryForObject(activitySql, Integer.class);//发布活动数
        SaveModel activitySaveModel = null;//活动报名人次总量
        SaveModel participantSaveModel = null;//活动参与人次总量
        SaveModel creditsSaveModel = null;//活动获取积分人次总量
        if(StringUtils.isNotEmpty(slaveKey1)){
            activitySaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_89, SaveModel.timeLevel_DDL,slaveKey1);
            participantSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_92, SaveModel.timeLevel_DDL,slaveKey1);
            activitySaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_89, SaveModel.timeLevel_DDL,slaveKey1);//活动报名人次总量
            participantSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_92, SaveModel.timeLevel_DDL,slaveKey1);//活动参与人次总量
            creditsSaveModel = elasticsearchUtil.findOneDateQuotaLevel1(timeKey, area, level, index_93, SaveModel.timeLevel_DDL,slaveKey1);//活动获取积分人次总量
            resultMap = applyList(index_1,index_89,area,level, sort,lowLevel,slaveKey1,resultMap);//列表
        }else{
            activitySaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_89, SaveModel.timeLevel_DDL);
            participantSaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_92, SaveModel.timeLevel_DDL);
            activitySaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_89, SaveModel.timeLevel_DDL);//活动报名人次总量
            participantSaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_92, SaveModel.timeLevel_DDL);//活动参与人次总量
            creditsSaveModel = elasticsearchUtil.findOneDateQuotaLevel0(timeKey, area, level, index_93, SaveModel.timeLevel_DDL);//活动获取积分人次总量
            resultMap = applyList(index_1,index_91,area,level, sort,lowLevel,slaveKey1,resultMap);//列表
        }
        Double applyCount = activitySaveModel!=null?activitySaveModel.getResult1():0.0;//报名数
        Double participantCount = participantSaveModel!=null?participantSaveModel.getResult1():0.0;//已参与
        Double creditsCount = creditsSaveModel!=null?creditsSaveModel.getResult1():0.0;//以获取积分人数(人次)
        if(!StringUtils.isNotEmpty(slaveKey1)){
            resultMap.put("activityCount",activityCount);//发布活动数
            resultMap.put("participantCount",participantSaveModel!=null?participantSaveModel.getResult1().intValue():0);//参与活动人数
            resultMap.put("applyCount",applyCount);//(报名数)参与活动人数
        }else{
            String dayStart =  DateUtil.dateToStrLong(new Date(DateUtil.getDayStartTime(new Date()).getTime()));
            String currentTime  = DateUtil.getStringDate();
            String sql = " select count(1) from health_bank.wlyy_health_bank_active_record r join wlyy.wlyy_admin_team t on r.team_id=t.id where r.create_time>='"+dayStart+"' and r.create_time<='"+currentTime+"' r.activity_id='"+slaveKey1+"' "+areaCondition2;
            Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
            resultMap.put("dayActiveCount",count!=null?count.intValue():0);//今日活跃量
            resultMap.put("activityPatient",activitySaveModel.getResult1().intValue());//单个活动报名人数
//            String dayStart =  DateUtil.dateToStrLong(new Date(DateUtil.getDayStartTime(new Date()).getTime()));
//            String currentTime  = DateUtil.getStringDate();
//            String sql = " select count(1) from health_bank.wlyy_health_bank_active_record r join wlyy.wlyy_admin_team t on r.team_id=t.id where r.create_time>='"+dayStart+"' and r.create_time<='"+currentTime+"' r.activity_id='"+slaveKey1+"' "+areaCondition2;
//            Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
//            resultMap.put("dayActiveCount",count!=null?count.intValue():0);//今日活跃量
            resultMap.put("participantCount",participantCount.intValue());//单个活动参与人数
            resultMap.put("applyCount",applyCount.intValue());//单个活动报名人数
        }
        //居民活跃统计
        resultMap.put("activityPatientRange","80%");//已报名
        resultMap.put("participantRange","60%");//已参与
        resultMap.put("expiryRange","20%");//已兑奖
//        resultMap.put("activityPatientRange",df.format(participantCount > 0.0 ? ((participantCount) / (allCount * 1.0000) * 100) : 0.0) + "%");//已报名
        resultMap.put("participantRange",df.format(participantCount > 0.0 ? ((participantCount) / (applyCount * 1.0000) * 100) : 0.0) + "%");//已参与
        resultMap.put("creditsRange",df.format(creditsCount > 0.0 ? ((creditsCount) / (applyCount * 1.0000) * 100) : 0.0) + "%");//已获取积分
        resultMap.put("expiryRange","0%");//已兑奖
        return resultMap;
    }
@ -5425,14 +5454,14 @@ public class StatisticsESService {
        if (SaveModel.OrgLevel.equals(level + "")) {
            condition = " and a.area like '" + area + "' ";
        } else if (SaveModel.townLevel.equals(level + "")) {
            condition = " and a.area like '" + area.substring(0, 4) + "%' ";
            condition = " and a.area like '" + area.substring(0, 6) + "%' ";
        } else if (SaveModel.cityLevel.equals(level + "")) {
            condition = " and a.area like '" + area.substring(0, 2) + "%' ";
            condition = " and a.area like '" + area.substring(0, 4) + "%' ";
        }
        if (StringUtils.isNotEmpty(id)) {
            condition += " and a.id=" + id;
            condition += " and a.id='" + id+"'";
        }
        String sql = " select * from health_bank.wlyy_health_bank_activity a where a.status=1 " + condition;
        String sql = " select * from wlyy_health_bank.wlyy_health_bank_activity a where a.status=1 " + condition;
        return jdbcTemplate.queryForList(sql);
    }
@ -5501,25 +5530,30 @@ public class StatisticsESService {
                }
                reMap.put("allNum", allAmount);
                reMap.put("applyNum", applyAmount);
                reMap.put("rate", getRange(applyAmount, allAmount, 2));//参与率是 报名数/签约数
                reMap.put("rate", getRange2(applyAmount, allAmount, 2));//参与率是 报名数/签约数
                if ((level == 2 && "5".equals(lowLevel)) || (level == 4) || (level == 3 && "5".equals(lowLevel))) {
                    translateTeamLeaderName(resultList);
                }
                //对结果进行排序
                Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        int map1value = (int) o1.get("allNum");
                        int map2value = (int) o2.get("allNum");
                        if (map1value - map2value > 0) {
                            return sort == 1 ? -1 : 1;
                        } else if (map1value - map2value < 0) {
                            return sort == 1 ? 1 : -1;
                        } else {
                            return 0;
                        }
            }
            //对结果进行排序
            Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    double map1value = (double) o1.get("rate");
                    double map2value = (double) o2.get("rate");
                    if (map1value - map2value > 0.0) {
                        return sort == 1 ? -1 : 1;
                    } else if (map1value - map2value < 0) {
                        return sort == 1 ? 1 : -1;
                    } else {
                        return 0;
                    }
                });
                }
            });
            DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
            for(Map<String, Object> one:resultList){
                one.put("rate",df.format(one.get("rate"))+"%");
            }
            resultMap.put("list", resultList);
            return resultMap;

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

@ -1169,6 +1169,16 @@ public class DateUtil {
		c.add(Calendar.DATE, -day_of_week + 1);
		return df2.format(c.getTime());
	}
	public static String getMondayOfThisDate(Date date,String format) {
		SimpleDateFormat df2 = new SimpleDateFormat(format);
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		if (day_of_week == 0)
			day_of_week = 7;
		c.add(Calendar.DATE, -day_of_week + 1);
		return df2.format(c.getTime());
	}
	/**
	 * 得到本周周日

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/util/HttpClientUtil.java

@ -122,7 +122,7 @@ public class HttpClientUtil {
     */
    public  String httpPost(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(10000).build();//设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();//设置请求和传输超时时间
        try {
            HttpPost httpPost = new HttpPost(url);

+ 160 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/data/DataHandingService.java

@ -1,9 +1,12 @@
package com.yihu.wlyy.web.data;
import com.alibaba.fastjson.JSON;
import com.yihu.device.entity.DeviceDetail;
import com.yihu.es.entity.HealthEduArticleES;
//import com.yihu.es.entity.MapDataDTO;
import com.yihu.wlyy.config.es.ElastricSearchSave;
import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.entity.device.PatientDeviceLog;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.manage.User;
import com.yihu.wlyy.entity.patient.Patient;
@ -11,22 +14,27 @@ import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.manage.UserDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.util.Base64Utils;
import com.yihu.wlyy.util.ElasticsearchUtil;
import com.yihu.wlyy.util.LatitudeUtils;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.repository.patient.PatientDeviceLogDao;
import com.yihu.wlyy.service.app.device.DeviceDetailService;
import com.yihu.wlyy.service.app.device.PatientDeviceService;
import com.yihu.wlyy.service.app.health.bank.CreditLogService;
import com.yihu.wlyy.util.*;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
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.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
@ -49,7 +57,13 @@ public class DataHandingService {
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private CreditLogService creditLogService;
    @Transactional
    public String producePatientAndDoctorPassword() {
@ -118,7 +132,7 @@ public class DataHandingService {
    }
    @Transactional
    private void saveUser(Doctor doctor) {
    public void saveUser(Doctor doctor) {
        User userTemp = new User();
        userTemp.setCode(doctor.getCode());
        userTemp.setMobile(doctor.getMobile());
@ -230,4 +244,145 @@ public class DataHandingService {
        }
        return  flag;
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateToPaitentDevcieLog()throws Exception{
        List<PatientDevice> patientDeviceList = patientDeviceDao.findAll();
        List<PatientDeviceLog> patientDeviceLogList = new ArrayList<>();
        for (PatientDevice patientDevice : patientDeviceList){
            PatientDeviceLog patientDeviceLog = new PatientDeviceLog();
            patientDeviceLog.setDeviceId(patientDevice.getDeviceId());
            patientDeviceLog.setAgreementPhoto(patientDevice.getAgreementPhoto());
            if (!StringUtils.isEmpty(patientDevice.getDoctor())){
                patientDeviceLog.setOperator(patientDevice.getDoctor());
                patientDeviceLog.setOperatorName(patientDevice.getDoctorName());
                patientDeviceLog.setRole(1);
            }else if (!StringUtils.isEmpty(patientDevice.getAgent())){
                patientDeviceLog.setOperator(patientDevice.getAgent());
                patientDeviceLog.setOperatorName(patientDevice.getAgentName());
                patientDeviceLog.setRole(2);
            }
            patientDeviceLog.setCreateTime(patientDevice.getCzrq());
            patientDeviceLog.setDeviceSn(patientDevice.getDeviceSn());
            patientDeviceLog.setDeviceName(patientDevice.getDeviceName());
            patientDeviceLog.setCategoryCode(patientDevice.getCategoryCode());
            patientDeviceLog.setPatient(patientDevice.getUser());
            patientDeviceLog.setOperateCode(1);
            patientDeviceLog.setIsDel(1);
            patientDeviceLogList.add(patientDeviceLog);
        }
        patientDeviceLogDao.save(patientDeviceLogList);
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateDevice()throws Exception{
        String patientDeviceSql = "SELECT pd.*,sf.admin_team_code,sf.hospital FROM wlyy_patient_device pd LEFT JOIN wlyy_sign_family sf ON pd.`user` = sf.patient where sf.`status`>0 GROUP BY pd.id";
        List<Map<String,Object>> patientDeviceList = jdbcTemplate.queryForList(patientDeviceSql);
        String deviceSql = "SELECT * FROM device.wlyy_devices";
        List<DeviceDetail> deviceDetailList = jdbcTemplate.query(deviceSql,new BeanPropertyRowMapper<>(DeviceDetail.class));
        Map<String,List<String>> map = new HashedMap();
        for (Map<String,Object> patientDeviceMap : patientDeviceList) {
            List<String> userTypeList = null;
            if (map.containsKey(String.valueOf(patientDeviceMap.get("device_sn")))) {
                userTypeList = map.get(String.valueOf(patientDeviceMap.get("device_sn")));
                if (userTypeList == null) {
                    userTypeList = new ArrayList<>();
                    userTypeList.add(String.valueOf(patientDeviceMap.get("user_type")));
                    map.put(String.valueOf(patientDeviceMap.get("device_sn")), userTypeList);
                } else {
                    boolean flag = false;
                    if (!userTypeList.contains(String.valueOf(patientDeviceMap.get("user_type")))) {
                        flag = true;
                    }
                    if (flag) {
                        userTypeList.add(String.valueOf(patientDeviceMap.get("user_type")));
                        map.put(String.valueOf(patientDeviceMap.get("device_sn")), userTypeList);
                    }
                }
            }
        }
        for (Map<String,Object> patientDeviceMap : patientDeviceList) {
            String deviceSn = String.valueOf(patientDeviceMap.get("device_sn"));
            int i = 0;
            for (DeviceDetail deviceDetail: deviceDetailList){
                if (deviceDetail.getDeviceCode().equals(deviceSn)){
                    i++;
                }
            }
            PatientDevice patientDevice = MapListUtils.convertMap2Bean(patientDeviceMap,PatientDevice.class);
            if (i==1){
                List<String> userTypeList = map.get(patientDevice.getDeviceSn());
                String bindCount = "";
                int size = userTypeList.size();
                if (size==1){
                    if (Integer.valueOf(patientDevice.getUserType())>0 && Integer.valueOf(patientDevice.getUserType())==1){
                        bindCount = "{\"1\":\"1\",\"2\":\"0\"}";
                    }else if (Integer.valueOf(patientDevice.getUserType())>0 && Integer.valueOf(patientDevice.getUserType())==2){
                        bindCount = "{\"1\":\"0\",\"2\":\"1\"}";
                    }else if (Integer.valueOf(patientDevice.getUserType())<0){
                        bindCount = "{\"1\":\"1\"}";
                    }
                }else if (size>1){
                    if (Integer.valueOf(patientDevice.getUserType())>0){
                        bindCount = "{\"1\":\"1\",\"2\":\"1\"}";
                    }else if (Integer.valueOf(patientDevice.getUserType())<0){
                        bindCount = "{\"1\":\"2\"}";
                    }
                }
                String sql = "UPDATE device.wlyy_devices SET is_grant=1,grant_admin_team='"+String.valueOf(patientDeviceMap.get
                        ("admin_team_code"))+"',grant_org_code='"+String.valueOf(patientDeviceMap.get("hospital"))+"',is_binding="+size+",binding_count='"+bindCount
                        +"',grant_time="+patientDevice.getCzrq()+" where device_code='"+patientDevice.getDeviceSn()+"'";
                jdbcTemplate.update(sql);
            }
            //如果wlyy_devices表里没有对应的数据 则增加一条。
            if (i==0){
                String bindCount = "";
                if (Integer.valueOf(patientDevice.getUserType())>0 && Integer.valueOf(patientDevice.getUserType())==1){
                    bindCount = "{\"1\":\"1\",\"2\":\"0\"}";
                }else if (Integer.valueOf(patientDevice.getUserType())>0 && Integer.valueOf(patientDevice.getUserType())==2){
                    bindCount = "{\"1\":\"0\",\"2\":\"1\"}";
                }else if (Integer.valueOf(patientDevice.getUserType())<0){
                    bindCount = "{\"1\":\"1\"}";
                }
                deviceDetailService.insertDevice(patientDevice,String.valueOf(patientDeviceMap.get("admin_team_code")),String.valueOf(patientDeviceMap.get("hospital_name")),String.valueOf(patientDeviceMap.get("hospital")),bindCount);
            }
        }
    }
    public void addPointOldDeviceBind()throws Exception{
        String sql = "SELECT pd.*,p.town FROM wlyy_patient_device pd LEFT JOIN wlyy_patient p ON pd.`user` = p.`code`";
        List<Map<String,Object>> patientDeviceList = jdbcTemplate.queryForList(sql);
        Map<String,String> map = new HashedMap();
        for (Map<String,Object> patientDeviceMap : patientDeviceList) {
            if (org.apache.commons.lang.StringUtils.equals(String.valueOf(patientDeviceMap.get("town")),"350205")){
                String deviceType=null;
                if (!map.containsKey(String.valueOf(patientDeviceMap.get("user")))) {
                    deviceType = map.get(String.valueOf(patientDeviceMap.get("user")));
                    if (StringUtils.isEmpty(deviceType)) {
                        deviceType = String.valueOf(patientDeviceMap.get("category_code"));
                        map.put(String.valueOf(patientDeviceMap.get("user")), deviceType);
                    }
                }
            }
        }
        for (Map.Entry<String,String> entry : map.entrySet()){
            String flagStr ="";
            if ("1".equals(entry.getValue())){
                flagStr="GLU_BIND";
            }else if ("2".equals(entry.getValue())){
                flagStr="BP_BIND";
            }
            String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\""+flagStr+"\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+entry.getKey()+"\",\"hospital\":\"350205\"}";
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(creditDetail);
            com.alibaba.fastjson.JSONObject response = creditLogService.insert(jsonObject);
            String status = response.getString("status");
            if (!"200".equals(status)){
                logger.info("添加积分失败!");
            }
        }
    }
}

+ 38 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/data/DataHandlingController.java

@ -278,7 +278,45 @@ public class DataHandlingController extends BaseController {
    }
    //将wlyy_patient_device的数据清洗至wlyy_patietn_devcie_log
    @RequestMapping(value ="/updateToPatientDevcieLog",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("将wlyy_patient_device的数据清洗至wlyy_patietn_devcie_log")
    public String updateToPatientDeviceLog(){
        try {
            dataHandingService.updateToPaitentDevcieLog();
            return write(200,"清洗数据成功!");
        }catch (Exception e){
            System.out.println("将wlyy_patient_device的数据清洗至wlyy_patietn_devcie_log失败:--->"+e.getMessage());
            return write(-1,"清洗数据失败");
        }
    }
    //将devcie库中wlyy_device新增的字段补充完整
    @RequestMapping(value ="/updateDevice",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("将devcie库中wlyy_device新增的字段补充完整")
    public String updateDevice(){
        try {
            dataHandingService.updateDevice();
            return write(200,"清洗数据成功!");
        }catch (Exception e){
            System.out.println("将devcie库中wlyy_device新增的字段补充完整失败:--->"+e.getMessage());
            return write(-1,"清洗数据失败");
        }
    }
    //从wlyy_patient_device清洗出海沧区的用户增加设备绑定积分
    @RequestMapping(value = "/addPointOldDeviceBind",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("从wlyy_patient_device清洗出海沧区的用户增加设备绑定积分")
    public String addPointOldDeviceBind(){
        try {
            dataHandingService.addPointOldDeviceBind();
            return write(200,"清洗数据成功!");
        }catch (Exception e){
            System.out.println("从wlyy_patient_device清洗出海沧区的用户增加设备绑定积分失败:--->"+e.getMessage());
            return write(-1,"清洗数据失败");
        }
    }
}

+ 10 - 3
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/device/DoctorDeviceController.java

@ -121,7 +121,7 @@ public class DoctorDeviceController extends BaseController {
	@ResponseBody
	@ObserverRequired
	public String SavePatientDeviceAndCredit(@ApiParam(name="data",value="设备数据json",defaultValue = "{\"user\":\"915cca0a-5b1d-11e6-834 4-fa163e8aee56\",\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"16C000337\",\"categoryCode\": \"1\",\"userType\": \"-1\"}") @RequestParam(value="data",required = true) String data,
											 @ApiParam(name = "agreementPhoto",value = "协议图片临时路径")@RequestParam(value = "agreementPhoto",required = true)String agreementPhoto) {
											 @ApiParam(name = "agreementPhoto",value = "协议图片临时路径")@RequestParam(value = "agreementPhoto",required = false)String agreementPhoto) {
		try {
			PatientDevice device = objectMapper.readValue(data,PatientDevice.class);
			// 设置操作医生标识
@ -145,8 +145,14 @@ public class DoctorDeviceController extends BaseController {
			deviceDetailService.updateAfterBinding(device,new Date(),flag);
			Patient patient = patientDao.findByCode(device.getUser());
			//调用增加积分接口  海沧区的居民才能添加积分
			if (flag){
				String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\"BIND\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+device.getUser()+"\",\"hospital\":\""+patient.getTown()+"\"}";
			if (flag && "350205".equals(patient.getTown())){
				String flagStr ="";
				if ("1".equals(device.getCategoryCode())){
					flagStr="GLU_BIND";
				}else if ("2".equals(device.getCategoryCode())){
					flagStr="BP_BIND";
				}
				String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\""+flagStr+"\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+device.getUser()+"\",\"hospital\":\""+patient.getTown()+"\"}";
				JSONObject jsonObject = JSONObject.parseObject(creditDetail);
				JSONObject response = creditLogService.insert(jsonObject);
				String status = response.getString("status");
@ -396,6 +402,7 @@ public class DoctorDeviceController extends BaseController {
			}
			return write(200, "获取设备成功!", "data",patientDeviceService.getDeviceByDeviceSn(deviceSn));
		}catch (Exception e){
			logger.error(e.getMessage());
			error(e);
			return write(-1,"程序出错!");
		}

+ 80 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/doctor/imm/DoctorImmController.java

@ -0,0 +1,80 @@
package com.yihu.wlyy.web.doctor.imm;
import com.yihu.wlyy.entity.imm.ChildInfoVO;
import com.yihu.wlyy.service.imm.ChildFamilyImmuneService;
import com.yihu.wlyy.service.imm.ChildInfoService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * 医生端免疫计划接口
 * @author huangwenjie
 * @date 2018/6/20 15:49
 */
@RestController
@RequestMapping(value = "/doctor/imm", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-计划免疫接口")
public class DoctorImmController extends BaseController {
	@Autowired
	private ChildFamilyImmuneService childFamilyImmuneService;
	@Autowired
	private ChildInfoService childInfoService;
	
	/**
	 * 家庭免疫成员查询
	 * @param patient 居民CODE
	 * @return
	 */
	@RequestMapping(value = "/members", method = RequestMethod.GET)
	@ApiOperation(value = "家庭成员查询")
	public String getPatientFamilyMembers(@RequestParam(required = false) String patient) {
		try {
			List<Map<String, Object>> immrs = childFamilyImmuneService.getImmunemembers(patient);
			JSONArray jsonArray = new JSONArray();
			if (immrs != null) {
				for (Map<String, Object> map : immrs) {
					JSONObject json = new JSONObject();
					json.put("child_code", map.get("child_code"));//儿童编码
					json.put("name", map.get("name"));//儿童姓名
					json.put("photo", map.get("photo"));//头像
					json.put("idcard", map.get("idcard"));//新生儿身份证号
					json.put("barcode", map.get("barcode"));//新生儿条码
					json.put("family_code", map.get("family_code"));//家人CODE
					json.put("relation", map.get("relation"));//---1父亲 2母亲 3老公 4老婆 5儿子 6女儿 7其他
					json.put("del", map.get("del"));//0为有效,1为删除状态
					jsonArray.put(json);
				}
			}
			return write(200, "查询成功", "data", jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
			return error(-1, "查询失败");
		}
	}
	
	@RequestMapping(value = "/getImmChildInfo", method = RequestMethod.GET)
	@ApiOperation(value = "根据新生儿编码获取新生儿基础信息")
	public String getImmChildInfo(@ApiParam(name = "code", value = "新生儿CODE", defaultValue = "")
	                              @RequestParam(value = "code", required = true) String code){
		try {
			ChildInfoVO childInfo = childInfoService.getChildInfoVOByCode(code);
			return write(200,"查询成功!","data",childInfo);
		} catch (Exception e) {
			error(e);
			return error(-1, e.getMessage());
		}
	}
}

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

@ -266,8 +266,18 @@ public class DoctorMessageController extends BaseController {
                                                 @RequestParam(value = "pagesize", required = true) Integer pagesize) throws Exception {
        try {
            List<Map<String, String>> list = messageService.getHealthIndexMessageByPatient(getUID(), patient, type, page, pagesize);
            return write(200, "获取超标指标消息成功", "data", list);
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", 200);
            map.put("msg", "获取超标指标消息成功");
            map.put("data", list);
            String tzCode ="";
            for (Map<String, String> one:list){
                tzCode+=","+one.get("tzCode");
            }
            map.put("tzCode",StringUtils.isNotEmpty(tzCode)?tzCode.substring(1):"");
            return mapper.writeValueAsString(map);
        } catch (Exception ex) {
            ex.printStackTrace();
            return invalidUserException(ex, -1, "查询失败");

+ 7 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/device/PatientDeviceController.java

@ -237,7 +237,13 @@ public class PatientDeviceController extends BaseController {
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            if (flag && "350205".equals(patient.getTown())){
                String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\"BIND\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+device.getUser()+"\",\"hospital\":\""+patient.getTown()+"\"}";
                String flagStr ="";
                if ("1".equals(device.getCategoryCode())){
                    flagStr="GLU_BIND";
                }else if ("2".equals(device.getCategoryCode())){
                    flagStr="BP_BIND";
                }
                String creditDetail = "{\"tradeType\":\"HEALTH_TASK\",\"flag\":\""+flagStr+"\",\"tradeDirection\":1,\"status\":1,\"patientId\":\""+device.getUser()+"\",\"hospital\":\""+patient.getTown()+"\"}";
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(creditDetail);
                com.alibaba.fastjson.JSONObject response = creditLogService.insert(jsonObject);
                System.out.println("添加积分返回数据======"+response.toJSONString());

+ 0 - 19
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/patient/health/bank/CreditsLogController.java

@ -225,24 +225,5 @@ public class CreditsLogController extends BaseController {
        }
    }
    /**
     * 步数获取积分
     *
     * @param creditsDetail {"patientId":"","transactionId":"","stepNumber":""}
     * @return
     */
    @RequestMapping(value = "/stepAddIntegrate",method = RequestMethod.POST)
    @ApiOperation("步数获取积分")
    public String stepAddIntegrate(@ApiParam(name = "creditsDetail",value = "对象JSON")
                         @RequestParam(name = "creditsDetail") String creditsDetail){
        try {
            JSONObject object = JSONObject.parseObject(creditsDetail);
            JSONObject result = service.insert(object);
            return write(200,"获取成功","data",result);
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}

+ 21 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/statistic/EsStatisticsController.java

@ -2211,6 +2211,11 @@ public class EsStatisticsController extends BaseController {
                                    @ApiParam(name = "lowLevel", value = "(下一个级别)只有可能是 1,2,3,不传默认是level-1;") @RequestParam(required = false) String lowLevel,
                                    @RequestParam(required = false) String year){
        try{
            if(StringUtils.isNotEmpty(lowLevel)){
                lowLevel = elasticsearchUtil.changeLevel(Integer.parseInt(lowLevel))+"";
            }else{
                lowLevel = elasticsearchUtil.changeLevel(level - 1)+"";
            }
            level = elasticsearchUtil.changeLevel(level);
            Map<String, Object> resultMap = statisticsESService.statisticsActivity(area,level,sort,lowLevel,activityCode);
            return write(200, "查询成功", "data", resultMap);
@ -2340,6 +2345,7 @@ public class EsStatisticsController extends BaseController {
        //                                   @RequestParam(required = true) String index,
                                           @ApiParam(name = "level", value = "地区级别,1 团队,2 机构,3 区,4 市") @RequestParam(required = true) int level,
                                           @ApiParam(name = "activityCode", value = "活动的id") @RequestParam(required = false) String activityCode,
//                                           @ApiParam(name = "index", value = "报名量91,活跃量(95天,90周,94月)") @RequestParam(required = true) String index,
                                           @RequestParam(required = false) String year) {
        try {
            level = elasticsearchUtil.changeLevel(level);
@ -2347,10 +2353,12 @@ public class EsStatisticsController extends BaseController {
//            JSONObject json = statisticsESService.getDateTotal(startDate, endDate, interval, area, level, "90", lowCode, year,SaveModel.timeLevel_ZL);
//            result.put("index_89", json);
            String index = "";
            if(StringUtils.isNotEmpty(activityCode)){
            if(interval==1){
                index="91,95";
            }else if(interval==2){
                index="91,90";
            }else{
                index="89,90";
            }else if(interval==2){
                index="91,94";
            }
            if (index != null) {
                if (org.springframework.util.StringUtils.isEmpty(year)) {
@ -2358,9 +2366,17 @@ public class EsStatisticsController extends BaseController {
                    year =  Constant.getNowYearByDate(endDate);
                }
                String[] indexes = index.split(",");
                for (String idx : indexes) {
                    JSONObject json = statisticsESService.getDateTotal(startDate, endDate, interval, area, level, idx, activityCode, year,SaveModel.timeLevel_DDL);
                    result.put("index_"+idx, json);
                    if("91".equals(idx)){
                        JSONObject json = statisticsESService.getDateTotal(startDate, endDate, interval, area, level, idx, activityCode, year,SaveModel.timeLevel_DDL);
                        result.put("index_"+idx, json);
                    }else{
                        JSONObject json = statisticsESService.getDateTotal(startDate, endDate, interval, area, level, idx, activityCode, year,SaveModel.timeLevel_ZL);
                        result.put("index_90", json);
                    }
                }
            }
            return write(200, "查询成功!", "data", result);

+ 20 - 0
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/health/bank/AccountController.java

@ -79,5 +79,25 @@ public class AccountController extends BaseController {
        }
    }
    /**
     * 步数获取积分
     *
     * @param creditsDetail {"patientId":"","transactionId":"","stepNumber":""}
     * @return
     */
    @RequestMapping(value = "/stepAddIntegrate",method = RequestMethod.POST)
    @ApiOperation("步数获取积分")
    public String stepAddIntegrate(@ApiParam(name = "creditsDetail",value = "对象JSON")
                                   @RequestParam(name = "creditsDetail") String creditsDetail){
        try {
            JSONObject object = JSONObject.parseObject(creditsDetail);
            JSONObject result = service.stepAddIntegrate(object);
            return write(200,"获取成功","data",result);
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}

+ 5 - 5
patient-co/patient-co-wlyy/src/main/resources/wechat/weixin_menu.txt

@ -79,11 +79,11 @@
		   "name":"我的设备",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fwdsb%2fhtml%2fmy-equipments.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		},
        {
         	"type":"click",
         	"name":"操作说明",
         	"key":"caozuoshuoming"
        }
		{
		   "type":"view",
		   "name":"健康银行",
		   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=server_url%2fwx%2fhtml%2fjkjf%2fhtml%2funopened.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect"
		}
	 ]
  }
]