Sfoglia il codice sorgente

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

wangzhinan 3 anni fa
parent
commit
aa33eebd87
68 ha cambiato i file con 5881 aggiunte e 3188 eliminazioni
  1. 7 2
      business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java
  2. 37 0
      business/push-service/pom.xml
  3. 6 0
      business/push-service/readme.MD
  4. 24 0
      business/push-service/src/main/java/com/yihu/jw/push/dao/GetuiClientDao.java
  5. 26 0
      business/push-service/src/main/java/com/yihu/jw/push/dao/PushHospitalSysDictDao.java
  6. 239 0
      business/push-service/src/main/java/com/yihu/jw/push/service/GetuiService.java
  7. 73 17
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/GetuiUtil.java
  8. 38 1
      common/common-entity/sql记录
  9. 14 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/common/GetuiClientDO.java
  10. 71 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BasePatientStepDo.java
  11. 122 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepX1device.java
  12. 4 0
      common/common-rest-model/pom.xml
  13. 153 0
      common/common-web/src/main/resources/logback-spring.xml-bak
  14. 8 3
      server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java
  15. 5 2
      server/svr-authentication/src/main/java/com/yihu/jw/security/dao/patient/BaseGetuiClientDao.java
  16. 2 1
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java
  17. 55 0
      svr/svr-base/src/main/java/com/yihu/jw/base/filter/XssAndHttpServletRequestWrapper.java
  18. 25 0
      svr/svr-base/src/main/java/com/yihu/jw/base/filter/XssFiter.java
  19. 8 5
      svr/svr-cloud-care/pom.xml
  20. 28 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/PatientConsultEndpoint.java
  21. 12 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/message/DoctorMessageEndpoint.java
  22. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/security/SecurityMonitoringOrderEndpoint.java
  23. 155 78
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/DetectionPlatformEndpoint.java
  24. 123 48
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/OpenStatisticsEndpoint.java
  25. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/third/platForm/PatientInfoPlatFormEndpoint.java
  26. 13 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/activity/ChildActivityRegistrationService.java
  27. 6 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/assistance/EmergencyAssistanceService.java
  28. 5 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultService.java
  29. 53 15
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java
  30. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doctor/CareDoctorService.java
  31. 1015 803
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java
  32. 68 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/DetectionPlatformService.java
  33. 960 599
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsService.java
  34. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/third/PatientInfoPlatFormService.java
  35. 37 6
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MessageUtil.java
  36. 14 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BasePatientStepDao.java
  37. 12 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BaseSleepX1deviceDao.java
  38. 45 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceController.java
  39. 92 4
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/DeviceService.java
  40. 5 1
      svr/svr-cloud-job/pom.xml
  41. 5 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/service/BirthdayReminderService.java
  42. 37 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/util/MessageUtil.java
  43. 34 0
      svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/controller/TransforController.java
  44. 6 0
      svr/svr-iot/pom.xml
  45. 333 0
      svr/svr-iot/src/main/java/com/yihu/elasticsearch/ElasticSearchHelper.java
  46. 157 0
      svr/svr-iot/src/main/java/com/yihu/elasticsearch/ElasticSearchPool.java
  47. 50 152
      svr/svr-iot/src/main/java/com/yihu/iot/controller/common/FileUploadController.java
  48. 529 445
      svr/svr-iot/src/main/java/com/yihu/iot/controller/monitorPlatform/MonitorPlatformController.java
  49. 13 0
      svr/svr-iot/src/main/java/com/yihu/iot/service/analyzer/IotAnalyzerService.java
  50. 1038 683
      svr/svr-iot/src/main/java/com/yihu/iot/service/monitorPlatform/MonitorPlatformService.java
  51. 106 25
      svr/svr-iot/src/main/resources/application.yml
  52. 1 1
      svr/svr-iot/src/main/resources/bootstrap.yml
  53. 0 13
      svr/svr-statistics-es/pom.xml
  54. 0 13
      svr/svr-statistics/pom.xml
  55. 0 8
      svr/svr-wlyy-health-bank/pom.xml
  56. 2 2
      svr/svr-wlyy-health-bank/src/main/java/com/yihu/jw/config/jpa/WlyyHealthBankJpa.java
  57. 0 1
      svr/svr-wlyy-health-bank/src/main/java/com/yihu/jw/service/ExchangeGoodsService.java
  58. 0 13
      svr/svr-wlyy-specialist/pom.xml
  59. 1 170
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/controller/common/FileUploadController.java
  60. 0 12
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/PatientLabelDao.java
  61. 0 12
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/PatientLabelInfoDao.java
  62. 0 12
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/SpecialistArticleDao.java
  63. 0 12
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/SpecialistConsultDao.java
  64. 0 12
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/SpecialistDao.java
  65. 1 1
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/service/SpecialistScreenResultService.java
  66. 1 1
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/service/SpecialistService.java
  67. 2 1
      svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/util/AddressUtils.java
  68. 1 1
      wlyy-parent-pom/pom.xml

+ 7 - 2
business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java

@ -344,8 +344,11 @@ public class ElasticsearchUtil {
            String sqlArea = " select area_level from wlyy_job_config_new where id='"+index+"' ";
            List<String> areaLevels = jdbcTemplate.queryForList(sqlArea,String.class);
            if (areaLevels.size()>0){
                areaLevel = areaLevels.get(0);
                if (StringUtils.isNotBlank(areaLevels.get(0))){
                    areaLevel = areaLevels.get(0);
                }
            }
        }
@ -1144,7 +1147,9 @@ public class ElasticsearchUtil {
            String sqlArea = " select area_level from wlyy_job_config_new where id='"+index+"' ";
            List<String> areaLevels = jdbcTemplate.queryForList(sqlArea,String.class);
            if (areaLevels.size()>0){
                areaLevel = areaLevels.get(0);
                if (StringUtils.isNotBlank(areaLevels.get(0))){
                    areaLevel = areaLevels.get(0);
                }
            }
        }

+ 37 - 0
business/push-service/pom.xml

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-lib-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-lib-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>push-service</artifactId>
    <version>${parent.version}</version>
    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 个推v2sdk -->
        <dependency>
            <groupId>com.getui.push</groupId>
            <artifactId>restful-sdk</artifactId>
            <version>1.0.0.1</version>
        </dependency>
    </dependencies>
</project>

+ 6 - 0
business/push-service/readme.MD

@ -0,0 +1,6 @@
推送服务
GetuiUil  个推推送服务
个推参数在字典表 缓存在redis中

+ 24 - 0
business/push-service/src/main/java/com/yihu/jw/push/dao/GetuiClientDao.java

@ -0,0 +1,24 @@
package com.yihu.jw.push.dao;
import com.yihu.jw.entity.care.common.GetuiClientDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/12/27
 * @Description:
 */
public interface GetuiClientDao extends PagingAndSortingRepository<GetuiClientDO, String>, JpaSpecificationExecutor<GetuiClientDO> {
    @Query("from GetuiClientDO p where p.user = ?1 and p.type=?2 and p.clientId=?3 and p.clientType=?4")
    List<GetuiClientDO> findByUser(String user, Integer type,String clientId,String clientType);
    @Query("from GetuiClientDO p where p.user = ?1 and p.type=?2")
    List<GetuiClientDO> findByUser(String user, Integer type);
}

+ 26 - 0
business/push-service/src/main/java/com/yihu/jw/push/dao/PushHospitalSysDictDao.java

@ -0,0 +1,26 @@
package com.yihu.jw.push.dao;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2019/6/17.
 */
public interface PushHospitalSysDictDao extends PagingAndSortingRepository<WlyyHospitalSysDictDO, String>, JpaSpecificationExecutor<WlyyHospitalSysDictDO> {
    WlyyHospitalSysDictDO findByHospitalAndDictCode(String hospital, String dictCode);
    List<WlyyHospitalSysDictDO> findByHospitalAndDictNameOrderBySortAsc(String hospital, String dictName);
    WlyyHospitalSysDictDO findById(String id);
    List<WlyyHospitalSysDictDO> findByDictName(String dictName);
    @Query("from WlyyHospitalSysDictDO where 1=1")
    List<WlyyHospitalSysDictDO> findAlldict();
    @Query("from WlyyHospitalSysDictDO where dictCode = ?1")
    List<WlyyHospitalSysDictDO> findByDictCode(String dictCode);
}

+ 239 - 0
business/push-service/src/main/java/com/yihu/jw/push/service/GetuiService.java

@ -0,0 +1,239 @@
package com.yihu.jw.push.service;
import com.alibaba.fastjson.JSONObject;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.Settings;
import com.getui.push.v2.sdk.dto.req.Strategy;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.AndroidDTO;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.android.ThirdNotification;
import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.push.dao.PushHospitalSysDictDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
 * Created with IntelliJ IDEA.
 * 个推推送工具类
 * @Author: yeshijie
 * @Date: 2021/7/8
 * @Description:
 */
@Service
public class GetuiService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PushHospitalSysDictDao sysDictDao;
    private static final Logger logger = LoggerFactory.getLogger(GetuiService.class);
    private static PushApi pushApi;
    private String AppID;
    private String AppKey;
    private String AppSecret;
    private String MasterSecret;
//    public static String AppID = "I6JAs97T818HD0hGzG1EH4";
//    public static String AppKey = "JC2LAW9IK27pansBB4jN87";
//    public static String AppSecret = "Sn9PLz1hA6NNgyb7WHx45";
//    public static String MasterSecret = "Rd86CP8bOy7RHyTf4ZE3R4";
    public String cloudCareDoctor = "com.zjxl.medicalcare.doctor";
    public String cloudCarePatientPad = "com.zjxl.medicalcare.patient.pad";
    private String key = "hz_yxyzh_push_getui";
    /**
     * 初始化接口参数
     */
    private void init(){
        if(redisTemplate.hasKey(key+ ":AppID")){
            AppID = redisTemplate.opsForValue().get(key + ":AppID");
            AppKey = redisTemplate.opsForValue().get(key + ":AppKey");
            AppSecret = redisTemplate.opsForValue().get(key + ":AppSecret");
            MasterSecret = redisTemplate.opsForValue().get(key + ":MasterSecret");
            synchronized (GetuiService.class){
                if(pushApi == null){
                    pushApi = getPushApi();
                }
            }
            return;
        }
        forceInit();
    }
    /**
     * 如果修改了数据库参数,调用下这个方法
     */
    public void forceInit(){
        List<WlyyHospitalSysDictDO> dictDOList = sysDictDao.findByDictName(key);
        for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:dictDOList){
            if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("AppID")){
                AppID=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":AppID",AppID);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("AppKey")){
                AppKey=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":AppKey",AppKey);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("AppSecret")){
                AppSecret=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":AppSecret",AppSecret);
            }else if (wlyyHospitalSysDictDO.getDictCode().equalsIgnoreCase("MasterSecret")){
                MasterSecret=wlyyHospitalSysDictDO.getDictValue();
                redisTemplate.opsForValue().set(key + ":MasterSecret",MasterSecret);
            }
        }
        pushApi = getPushApi();
    }
    private PushApi getPushApi(){
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        //填写应用配置
        apiConfiguration.setAppId(AppID);
        apiConfiguration.setAppKey(AppKey);
        apiConfiguration.setMasterSecret(MasterSecret);
        // 接口调用前缀,请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
        apiConfiguration.setDomain("https://restapi.getui.com/v2/");
        // 实例化ApiHelper对象,用于创建接口对象
        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        // 创建对象,建议复用。目前有PushApi、StatisticApi、UserApi
        PushApi pushApi = apiHelper.creatApi(PushApi.class);
        return pushApi;
    }
    /**
     * Rest-V2厂商推送
     * type 1 安卓 2 ios
     */
    public void push2(String cid,int type,JSONObject json){
        init();
        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<Audience>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");//requestid需要每次变化唯一
        //配置推送条件
        // 1: 表示该消息在用户在线时推送个推通道,用户离线时推送厂商通道;
        // 2: 表示该消息只通过厂商通道策略下发,不考虑用户是否在线;
        // 3: 表示该消息只通过个推通道下发,不考虑用户是否在线;
        // 4: 表示该消息优先从厂商通道下发,若消息内容在厂商通道代发失败后会从个推通道下发。
        Strategy strategy=new Strategy();
        strategy.setDef(1);
        Settings settings=new Settings();
        settings.setStrategy(strategy);
        pushDTO.setSettings(settings);
        settings.setTtl(3600000);//消息有效期,走厂商消息需要设置该值
        PushChannel pushChannel = new PushChannel();
        if(type == 1){
            //安卓离线厂商通道推送消息体
            AndroidDTO androidDTO = new AndroidDTO();
            Ups ups = new Ups();
            ThirdNotification notification1 = new ThirdNotification();
            notification1.setTitle(json.getString("title"));
            notification1.setBody(json.getString("body"));
            notification1.setClickType("intent");
            //component 包名 调起app
            String intent = "intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;" +
                    "component="+json.getString("platform")+"/io.dcloud.PandoraEntry;S.UP-OL-SU=true;" +
                    "S.title="+json.getString("title")+";" +
                    "S.content="+json.getString("body")+";" +
                    "S.url="+json.getString("url")+";end";
            notification1.setIntent(intent);
            ups.setNotification(notification1);
            //各厂商自有功能单项设置
            //ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
            //ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
            //ups.addOption("HW", "/message/android/notification/importance", "HIGH");
            //ups.addOption("VV","classification",1);
            androidDTO.setUps(ups);
            pushChannel.setAndroid(androidDTO);
        } else{
            //推送苹果离线通知标题内容
            Alert alert=new Alert();
            alert.setTitle(json.getString("title"));
            alert.setBody(json.getString("body"));
            Aps aps = new Aps();
            //1表示静默推送(无通知栏消息),静默推送时不需要填写其他参数。
            //苹果建议1小时最多推送3条静默消息
            aps.setContentAvailable(0);
            aps.setSound("default");
            aps.setAlert(alert);
            IosDTO iosDTO = new IosDTO();
            iosDTO.setAps(aps);
            iosDTO.setType("notify");
            iosDTO.setPayload(json.getString("payload"));
            pushChannel.setIos(iosDTO);
        }
        pushDTO.setPushChannel(pushChannel);
        // PushMessage在线走个推通道才会起作用的消息体
        PushMessage pushMessage = new PushMessage();
//        pushMessage.setTransmission(" {title:\""+json.getString("title")+"\",content:\""+json.getString("body")+"\",payload:\""+json.getString("payload")+"\"}");
        pushMessage.setTransmission(" {\"title\":\""+json.getString("title")+"\",\"content\":\""+json.getString("body")+"\",\"url\":\""+json.getString("url")+"\"}");
        pushDTO.setPushMessage(pushMessage);
        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid(cid);
        // 进行cid单推
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success
            logger.info("发送成功:"+apiResult.getData());
        } else {
            // failed
            logger.info("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }
    /**
     * 单推
     */
    public ApiResult<Map<String, Map<String, String>>> pushToSingleByCid(String cid, JSONObject json) {
        init();
        //根据cid进行单推
        PushDTO<Audience> pushDTO = new PushDTO<>();
        // 设置推送参数
        pushDTO.setRequestId(System.currentTimeMillis() + "");
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);
        GTNotification notification = new GTNotification();
        pushMessage.setNotification(notification);
        notification.setTitle(json.getString("title"));
        notification.setBody(json.getString("body"));
        notification.setClickType(json.getString("clickType"));
        notification.setUrl(json.getString("url"));
        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
        audience.addCid(cid);
        //消息离线时间设置
        Settings settings = new Settings();
        //	消息离线时间设置,单位毫秒,-1表示不设离线,-1 ~ 3 * 24 * 3600 * 1000(3天)之间
        settings.setTtl(3 * 24 * 3600 * 1000);
        pushDTO.setSettings(settings);
        // 进行cid单推
        return pushApi.pushToSingleByCid(pushDTO);
    }
}

+ 73 - 17
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/GetuiUtil.java

@ -1,4 +1,4 @@
package com.yihu.jw.care.util;
package com.yihu.jw.push.util;
import com.alibaba.fastjson.JSONObject;
import com.getui.push.v2.sdk.ApiHelper;
@ -18,9 +18,12 @@ import com.getui.push.v2.sdk.dto.req.message.android.Ups;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
@ -38,6 +41,8 @@ public class GetuiUtil {
    public static String AppKey = "JC2LAW9IK27pansBB4jN87";
    public static String AppSecret = "Sn9PLz1hA6NNgyb7WHx45";
    public static String MasterSecret = "Rd86CP8bOy7RHyTf4ZE3R4";
    public static String cloudCareDoctor = "com.zjxl.medicalcare.doctor";
    public static String cloudCarePatientPad = "com.zjxl.medicalcare.patient.pad";
    private static PushApi getPushApi(){
@ -56,6 +61,40 @@ public class GetuiUtil {
    }
    public static void main(String[] args) {
/*        String url = "http://sdk.open.api.igexin.com/apiex.htm";
        IGtPush push = new IGtPush(url, AppKey, MasterSecret);
        TransmissionTemplate t = new TransmissionTemplate();
        t.setAppId(AppID);
        t.setAppkey(AppKey);
        t.setTransmissionContent("{title:\"标题\",content:\"内容\",payload:\"自定义数据\"}");
        t.setTransmissionType(1);
        // 定义"点击链接打开通知模板",并设置标题、内容、链接
//        LinkTemplate template = new LinkTemplate();
//        template.setAppId(appId);
//        template.setAppkey(appKey);
//        template.setTitle("你好你好");
//        template.setText("哦,好吧");
//        template.setLogoUrl("");
//        template.setUrl("http://getui.com");
        List<String> appIds = new ArrayList<String>();
        appIds.add(AppID);
        // 定义"AppMessage"类型消息对象,设置消息内容模板、发送的目标App列表、是否支持离线发送、以及离线消息有效期(单位毫秒)
        SingleMessage message = new SingleMessage();
        message.setData(t);
        message.setOffline(true);
        message.setOfflineExpireTime(1000 * 600);
        // 指定向哪儿推
        Target target = new Target();
        target.setAppId(AppID);
        target.setClientId("d2fee750dcdf7a2567444b1d4f629305");
        IPushResult ret = push.pushMessageToSingle(message, target);
        System.out.println(ret.getResponse().toString());*/
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("title","title");
//        jsonObject.put("body","body");
@ -68,14 +107,25 @@ public class GetuiUtil {
//        } else {
//            System.out.println("个推推送失败:code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
//        }
        String cid = "d0e395d2e04b1da6f45a4f700883297d";
//        String cid = "d2fee750dcdf7a2567444b1d4f629305";
        String cid = "a7fff64dd3dfd12ee43a1b94f3266cfa";
        String title = "ios11:49标题";
        String body = "安卓离线展示的内容";
        String url = "https://www.baidu.com/";
//        String url = "/archives/index";
        JSONObject payload = new JSONObject();
        payload.put("title",title);
        payload.put("body",body);
        payload.put("url",url);
        JSONObject json = new JSONObject();
        json.put("title","安卓11:38标题");
        json.put("body","安卓离线展示的内容");
        json.put("url","https://www.baidu.com/");
        json.put("clickType","url");
        json.put("platform","patient");
        json.put("payload","payload");
        json.put("title",title);
        json.put("body",body);
        json.put("url",url);
//        json.put("clickType","url");
        json.put("platform",cloudCareDoctor);
        json.put("payload",payload.toString());
        String str = "{\"payload\":\"{\\\"title\\\":\\\"安防紧急预警\\\",\\\"body\\\":\\\"您好,张民居民发起紧急呼叫,请关注并及时处理。\\\",\\\"url\\\":\\\"/sos/index?tabActive=1\\\"}\",\"title\":\"安防紧急预警\",\"body\":\"您好,张民居民发起紧急呼叫,请关注并及时处理。\",\"url\":\"/sos/index?tabActive=1\",\"platform\":\"com.zjxl.medicalcare.doctor\"}";
        push2(cid,1,json);
    }
@ -105,17 +155,20 @@ public class GetuiUtil {
            //安卓离线厂商通道推送消息体
            AndroidDTO androidDTO = new AndroidDTO();
            Ups ups = new Ups();
            ThirdNotification notification1 = new ThirdNotification();;
            ups.setNotification(notification1);
            notification1.setTitle("安卓11:38标题");
            notification1.setBody("安卓离线展示的内容");
            ThirdNotification notification1 = new ThirdNotification();
            notification1.setTitle(json.getString("title"));
            notification1.setBody(json.getString("body"));
            notification1.setUrl(json.getString("url"));
            notification1.setClickType("intent");
            //component 包名 调起app
            String intent = "intent:#Intent;launchFlags=0x04000000;action=android.intent.action.oppopush;" +
                    "component=com.xmeye.ehospital."+json.getString("platform")+"/io.dcloud.PandoraEntry;S.UP-OL-SU=true;" +
                    "component="+json.getString("platform")+"/io.dcloud.PandoraEntry;S.UP-OL-SU=true;" +
                    "S.title="+json.getString("title")+";" +
                    "S.content="+json.getString("body")+";" +
                    "S.payload="+json.getString("payload")+";end";
                    "S.url="+json.getString("url")+";end";
            notification1.setIntent(intent);
            ups.setNotification(notification1);
            //各厂商自有功能单项设置
            //ups.addOption("HW", "/message/android/notification/badge/class", "io.dcloud.PandoraEntry ");
            //ups.addOption("HW", "/message/android/notification/badge/add_num", 1);
@ -137,14 +190,17 @@ public class GetuiUtil {
            IosDTO iosDTO = new IosDTO();
            iosDTO.setAps(aps);
            iosDTO.setType("notify");
//            iosDTO.setAutoBadge("+1");
            iosDTO.setPayload(json.getString("payload"));
            pushChannel.setIos(iosDTO);
        }
        pushDTO.setPushChannel(pushChannel);
        // PushMessage在线走个推通道才会起作用的消息体
        PushMessage pushMessage = new PushMessage();
//        pushMessage.setTransmission(" {\"title\":\""+json.getString("title")+"\",\"content\":\""+json.getString("body")+"\",\"payload\":\""+json.getString("payload")+"\"}");
        pushMessage.setTransmission(" {\"title\":\""+json.getString("title")+"\",\"content\":\""+json.getString("body")+"\",\"url\":\""+json.getString("url")+"\"}");
        pushDTO.setPushMessage(pushMessage);
        pushMessage.setTransmission(" {title:\""+json.getString("title")+"\",content:\""+json.getString("body")+"\",payload:\""+json.getString("payload")+"\"}");
        // 设置接收人信息
        Audience audience = new Audience();
        pushDTO.setAudience(audience);
@ -154,10 +210,10 @@ public class GetuiUtil {
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            // success
            System.out.println("发送成功:"+apiResult.getData());
            logger.info("发送成功:"+apiResult.getData());
        } else {
            // failed
            System.out.println("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
            logger.info("code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }

+ 38 - 1
common/common-entity/sql记录

@ -1600,4 +1600,41 @@ CREATE TABLE wlyy_patient_safe_area_confirm (
  `manage_status` tinyint(2) DEFAULT '0' COMMENT '电子围栏确认情况 0待确认 1已确认',
  `del` varchar(1) DEFAULT '1' COMMENT '作废标识,1正常,0作废',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='患者电子围栏新增记录';
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='患者电子围栏新增记录';
-- 2021-12-22
CREATE TABLE `base_patient_step` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `patient` varchar(50) DEFAULT NULL COMMENT '居民id',
  `device_sn` varchar(50) DEFAULT NULL COMMENT '手表sn',
   steps varchar(6) default null COMMENT '步数',
	 `day` varchar(10) DEFAULT null COMMENT '日期',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '产生日期',
  `del` int(1) DEFAULT NULL COMMENT '是否有效 1有效 0无效',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8 COMMENT='患者手表步数';
-- 2021-12-27
CREATE TABLE `base_activity_click` (
  `id` varchar(50) NOT NULL,
  `activity_type` tinyint(2) DEFAULT NULL COMMENT '活动类型 1-活动浏览2公益课程播放',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='幼儿活动点击次数统计表';
CREATE TABLE `base_sleep_x1device` (
  `id` varchar(50) NOT NULL,
  `patient` varchar(50) DEFAULT NULL COMMENT '居民id',
  `device_sn` varchar(50) DEFAULT NULL COMMENT '手表sn',
  `sleep_time` varchar(50) DEFAULT NULL COMMENT '睡眠时长 分钟',
  `deep_sleep` varchar(50) DEFAULT NULL COMMENT '深睡时长 分钟',
  `light_sleep` varchar(50) DEFAULT NULL COMMENT '浅睡时长 分钟',
  `awake_time` varchar(50) DEFAULT NULL COMMENT '清醒时长 分钟',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '开始时间',
  `end_time` timestamp NULL DEFAULT NULL COMMENT '结束时间',
  `interval_time` int(11) NULL DEFAULT NULL COMMENT '固定30分钟',
  `total` int(11) NULL DEFAULT NULL COMMENT '检测次数',
  `del` int(1) DEFAULT NULL COMMENT '是否有效 1有效 0无效',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='爱牵挂X1手表睡眠数据';

+ 14 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/common/GetuiClientDO.java

@ -30,6 +30,11 @@ public class GetuiClientDO extends UuidIdentityEntityWithCreateTime {
     */
    private String clientId;
    /**
     * 类型1 安卓 2ios
     */
    private String clientType;
    @Column(name = "user")
    public String getUser() {
        return user;
@ -56,4 +61,13 @@ public class GetuiClientDO extends UuidIdentityEntityWithCreateTime {
    public void setClientId(String clientId) {
        this.clientId = clientId;
    }
    @Column(name = "client_type")
    public String getClientType() {
        return clientType;
    }
    public void setClientType(String clientType) {
        this.clientType = clientType;
    }
}

+ 71 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BasePatientStepDo.java

@ -0,0 +1,71 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Bing on 2021/12/22.
 */
@Entity
@Table(name="base_patient_step")
public class BasePatientStepDo extends IdEntity{
    private String patient;
    private String deviceSn;
    private String steps;
    private String day;
    private Date createTime;
    private Integer del;
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getSteps() {
        return steps;
    }
    public void setSteps(String steps) {
        this.steps = steps;
    }
    public String getDay() {
        return day;
    }
    public void setDay(String day) {
        this.day = day;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 122 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/BaseSleepX1device.java

@ -0,0 +1,122 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import org.springframework.data.annotation.CreatedDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Bing on 2022/1/7.
 * 手表睡眠数据
 */
@Entity
@Table(name="base_sleep_x1device")
public class BaseSleepX1device extends UuidIdentityEntity {
    private String patient;
    private String deviceSn;
    private String sleepTime; //睡眠时长 分钟
    private String deepSleep; //深睡时长 分钟
    private String lightSleep; //浅睡时长 分钟
    private String awakeTime; // 清醒时长 分钟
    private Date createTime; // 开始时间
    private Date endTime;   //结束时间
    private Integer intervalTime; //固定30分钟
    private Integer total; // 检测次数
    private Integer del;  //是否有效 1有效 0无效
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    public String getSleepTime() {
        return sleepTime;
    }
    public void setSleepTime(String sleepTime) {
        this.sleepTime = sleepTime;
    }
    public String getDeepSleep() {
        return deepSleep;
    }
    public void setDeepSleep(String deepSleep) {
        this.deepSleep = deepSleep;
    }
    public String getLightSleep() {
        return lightSleep;
    }
    public void setLightSleep(String lightSleep) {
        this.lightSleep = lightSleep;
    }
    public String getAwakeTime() {
        return awakeTime;
    }
    public void setAwakeTime(String awakeTime) {
        this.awakeTime = awakeTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "end_time")
    public Date getEndTime() {
        return endTime;
    }
    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }
    public Integer getIntervalTime() {
        return intervalTime;
    }
    public void setIntervalTime(Integer intervalTime) {
        this.intervalTime = intervalTime;
    }
    public Integer getTotal() {
        return total;
    }
    public void setTotal(Integer total) {
        this.total = total;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 4 - 0
common/common-rest-model/pom.xml

@ -60,5 +60,9 @@
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
    </dependencies>
</project>

+ 153 - 0
common/common-web/src/main/resources/logback-spring.xml-bak

@ -0,0 +1,153 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- EHR全局异常日志处理配置,包含每个微服务的默认日志配置,
如果有其他日志处理需求,请拷贝此文件,并按照以下说明(73行)进行配置 -->
<configuration scan="true">
    <springProperty scope="context" name="appName" source="spring.application.name" />
	<property name="log_home" value="/Users/Mewtwo/ideaSpace/log/wlyy-logs/${appName}" />
    <property name="max_history" value="30"/>
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    <!-- 彩色日志格式 -->
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr([${appName}]){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />
    <!-- 文件日志格式 -->
    <property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} [${appName}] %-5level --- [%thread] - %logger{36}: %msg%n" />
    <!-- Standard output -->
	<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>${CONSOLE_LOG_PATTERN}</pattern>
			<charset class="java.nio.charset.Charset">UTF-8</charset>
		</encoder>
	</appender>
    <!-- Api Log Start -->
<!-- 先注释调,不生成日志文件,只在控制台生成
   <appender name="ApiInfoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log_home}/api/info/%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>${max_history}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset class="java.nio.charset.Charset">UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>OFF</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <appender name="ApiWarnFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log_home}/api/warn/%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>${max_history}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset class="java.nio.charset.Charset">UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>OFF</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <appender name="ApiErrorFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log_home}/api/error/%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>${max_history}</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset class="java.nio.charset.Charset">UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>OFF</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>-->
    <!-- Api Log End -->
    <!-- Business Log Start -->
<!--    <appender name="BusinessInfoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!--        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!--            <fileNamePattern>${log_home}/business/info/%d{yyyy-MM-dd}.log</fileNamePattern>-->
<!--            <maxHistory>${max_history}</maxHistory>-->
<!--        </rollingPolicy>-->
<!--        <encoder>-->
<!--            <pattern>${FILE_LOG_PATTERN}</pattern>-->
<!--            <charset class="java.nio.charset.Charset">UTF-8</charset>-->
<!--        </encoder>-->
<!--        <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
<!--            <level>OFF</level>-->
<!--            <onMatch>ACCEPT</onMatch>-->
<!--            <onMismatch>DENY</onMismatch>-->
<!--        </filter>-->
<!--    </appender>-->
<!--    <appender name="BusinessWarnFile" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!--        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!--            <fileNamePattern>${log_home}/business/warn/%d{yyyy-MM-dd}.log</fileNamePattern>-->
<!--            <maxHistory>${max_history}</maxHistory>-->
<!--        </rollingPolicy>-->
<!--        <encoder>-->
<!--            <pattern>${FILE_LOG_PATTERN}</pattern>-->
<!--            <charset class="java.nio.charset.Charset">UTF-8</charset>-->
<!--        </encoder>-->
<!--        <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
<!--            <level>OFF</level>-->
<!--            <onMatch>ACCEPT</onMatch>-->
<!--            <onMismatch>DENY</onMismatch>-->
<!--        </filter>-->
<!--    </appender>-->
<!--    <appender name="BusinessErrorFile" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!--        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!--            <fileNamePattern>${log_home}/business/error/%d{yyyy-MM-dd}.log</fileNamePattern>-->
<!--            <maxHistory>${max_history}</maxHistory>-->
<!--        </rollingPolicy>-->
<!--        <encoder>-->
<!--            <pattern>${FILE_LOG_PATTERN}</pattern>-->
<!--            <charset class="java.nio.charset.Charset">UTF-8</charset>-->
<!--        </encoder>-->
<!--        <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
<!--            <level>OFF</level>-->
<!--            <onMatch>ACCEPT</onMatch>-->
<!--            <onMismatch>DENY</onMismatch>-->
<!--        </filter>-->
<!--    </appender>-->
    <!-- Business Log End -->
    <!-- 如果微服务纳入全局异常处理,请勿修改以上代码,有新的日志处理请在以下追加!!! -->
    <!-- Other Log Start -->
    <!-- Other Log End -->
    <!-- 针对接口调用出错日志(单独记录) -->
<!--    <logger name="com.yihu.jw.web.handler.GlobalExceptionHandler" level="OFF" additivity="false">-->
<!--        <appender-ref ref="console" />-->
<!--        <appender-ref ref="ApiInfoFile" />-->
<!--        <appender-ref ref="ApiWarnFile" />-->
<!--        <appender-ref ref="ApiErrorFile" />-->
<!--    </logger>-->
    <!-- 业务日志 -->
<!--    <logger name="com.yihu.jw">-->
<!--        <appender-ref ref="BusinessInfoFile" />-->
<!--        <appender-ref ref="BusinessWarnFile" />-->
<!--        <appender-ref ref="BusinessErrorFile" />-->
<!--    </logger>-->
    <!-- 基础日志 -->
	<root level="INFO">
        <appender-ref ref="console" />
	</root>
</configuration>

+ 8 - 3
server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java

@ -652,7 +652,7 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
     * @param loginType
     * @param id
     */
    public void updateInfo(String clientId,String padImei,String loginType,String id,BaseLoginLogDO baseLoginLogDO){
    public void updateInfo(String clientId,String clientType,String padImei,String loginType,String id,BaseLoginLogDO baseLoginLogDO){
        int isPateint = isPatient(loginType);
        if(StringUtils.isNotBlank(padImei)){
            try {
@ -663,16 +663,21 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
                e.printStackTrace();
            }
        }
        if(StringUtils.isNotBlank(clientId)&&isPateint<3){
        if(StringUtils.isNotBlank(clientId)&&StringUtils.isNotBlank(clientType)&&isPateint<3){
            try {
                List<GetuiClientDO> list = baseGetuiClientDao.findByUser(id,isPateint,clientId);
                List<GetuiClientDO> list = baseGetuiClientDao.findByUser(id,isPateint,clientType);
                if(list.size() == 0){
                    GetuiClientDO getuiClientDO = new GetuiClientDO();
                    getuiClientDO.setClientId(clientId);
                    getuiClientDO.setType(isPateint);
                    getuiClientDO.setClientType(clientType);
                    getuiClientDO.setUser(id);
                    getuiClientDO.setCreateTime(new Date());
                    baseGetuiClientDao.save(getuiClientDO);
                }else{
                    GetuiClientDO getuiClientDO = list.get(0);
                    getuiClientDO.setClientId(clientId);
                    baseGetuiClientDao.save(getuiClientDO);
                }
            }catch (Exception e){
                e.printStackTrace();

+ 5 - 2
server/svr-authentication/src/main/java/com/yihu/jw/security/dao/patient/BaseGetuiClientDao.java

@ -17,6 +17,9 @@ import java.util.List;
 */
public interface BaseGetuiClientDao extends PagingAndSortingRepository<GetuiClientDO, String>, JpaSpecificationExecutor<GetuiClientDO> {
    @Query("from GetuiClientDO p where p.user = ?1 and p.type=?2 and p.clientId=?3")
    List<GetuiClientDO> findByUser(String user, Integer type,String clientId);
    @Query("from GetuiClientDO p where p.user = ?1 and p.type=?2 and p.clientId=?3 and p.clientType=?4")
    List<GetuiClientDO> findByUser(String user, Integer type,String clientId,String clientType);
    @Query("from GetuiClientDO p where p.user = ?1 and p.type=?2 and p.clientType=?3")
    List<GetuiClientDO> findByUser(String user, Integer type,String clientType);
}

+ 2 - 1
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java

@ -384,9 +384,10 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        //个推 clientId
        String clientId = parameters.get("getuiClientId");
        String getuiClientType = parameters.get("getuiClientType");
        String padImei = parameters.get("padImei");
        //客户端类型 app,wx,pad,pc
        userDetailsService.updateInfo(clientId,padImei,loginType,wlyyUserSimple.getId(),baseLoginLogDO);
        userDetailsService.updateInfo(clientId,getuiClientType,padImei,loginType,wlyyUserSimple.getId(),baseLoginLogDO);
        return getResponse(wlyyUserSimple);
    }

+ 55 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/filter/XssAndHttpServletRequestWrapper.java

@ -0,0 +1,55 @@
package com.yihu.jw.base.filter;
import com.yihu.jw.util.XssUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * Created by yeshijie on 2020/8/27.
 */
public class XssAndHttpServletRequestWrapper extends HttpServletRequestWrapper {
    HttpServletRequest request;
    public XssAndHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        // System.out.println("name:" + name + "," + value);
        if (value != null) {
            // 转换Html
            value = XssUtil.cleanXss(value);
        }
        return value;
    }
    @Override
    public String getHeader(String name) {
        return XssUtil.cleanXss(super.getHeader(name));
    }
    @Override
    public String getQueryString() {
        return XssUtil.cleanXss(super.getQueryString());
    }
    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = XssUtil.cleanXss(values[i]);
        }
        return encodedValues;
    }
}

+ 25 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/filter/XssFiter.java

@ -0,0 +1,25 @@
package com.yihu.jw.base.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
 * Created by yeshijie on 2020/8/27.
 */
public class XssFiter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        XssAndHttpServletRequestWrapper xssRequestWrapper = new XssAndHttpServletRequestWrapper(req);
        chain.doFilter(xssRequestWrapper, response);
    }
    public void destroy() {
    }
}

+ 8 - 5
svr/svr-cloud-care/pom.xml

@ -188,6 +188,11 @@
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>shield</artifactId>
            <version>2.4.6</version>
        </dependency>
        <!-- xlsx  依赖这个包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
@ -238,13 +243,11 @@
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- 个推v2sdk -->
        <dependency>
            <groupId>com.getui.push</groupId>
            <artifactId>restful-sdk</artifactId>
            <version>1.0.0.1</version>
            <groupId>com.yihu.jw</groupId>
            <artifactId>push-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>im-service</artifactId>

+ 28 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/PatientConsultEndpoint.java

@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.service.consult.ConsultService;
import com.yihu.jw.care.service.message.BaseServiceNewsService;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
@ -38,8 +39,10 @@ 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.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;
@ -107,6 +110,31 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
	@Autowired
	private BaseServiceNewsService serviceNewsService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private MessageUtil messageUtil;
	@PostMapping(value = "sendGetuiMessage")
	@ApiOperation(value = "im推送个推消息")
	public Envelop sendGetuiMessage(String sessionId,String type,String senderName,String senderId,String targetId){
		try {
			String body = "收到来自"+senderName+"的一条消息,请关注并及时处理。";
			String peerName = null;
			String sql = "SELECT name from im_internet_hospital.sessions WHERE id = '"+sessionId+"'";
			List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
			if(list!=null&&list.size()>0){
				peerName = URLEncoder.encode(list.get(0).get("name").toString(), "UTF-8");
			}
			String url = "/chatroom/index?type="+type+"&peerId=&peerName="+peerName+"&sessionId="+sessionId;
			messageUtil.sendDoctorGetuiMessage(targetId,"4",url,"im消息",body);
			return Envelop.getSuccess("请求成功");
		}catch (Exception e){
			e.printStackTrace();
			return Envelop.getError("请求失败");
		}
	}
	@GetMapping(value = "findLastOnlineConsult")
	@ApiOperation(value = "获取居民该机构的最近一次在线咨询")

+ 12 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/message/DoctorMessageEndpoint.java

@ -40,6 +40,18 @@ public class DoctorMessageEndpoint extends EnvelopRestEndpoint {
        }
    }
    @GetMapping(value = "unreadMessageNum")
    @ApiOperation("未读消息数量")
    public ObjEnvelop unreadMessageNum(@ApiParam(name = "doctor", required = true, value = "doctor")
                                   @RequestParam(value = "doctor", required = true) String doctor){
        try {
            return ObjEnvelop.getSuccess("查询成功",0);
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @PostMapping(value = "newOrgNotice")
    @ApiOperation("创建机构通知消息")
    @ObserverRequired

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/security/SecurityMonitoringOrderEndpoint.java

@ -331,7 +331,7 @@ public class SecurityMonitoringOrderEndpoint extends EnvelopRestEndpoint {
                                @ApiParam(name = "topicItem", value = "专题code,关联security_topic_dict字典", required = false)
                                @RequestParam(value = "topicItem",required = false,defaultValue = "preventLost") String topicItem) {
        try {
            return ObjEnvelop.getSuccess( "查询成功", securityMonitoringOrderService.patientMonitoringInfo(patient,topicItem,true));
            return ObjEnvelop.getSuccess( "查询成功", securityMonitoringOrderService.patientMonitoringInfo(patient,topicItem,null,true));
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }

+ 155 - 78
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/DetectionPlatformEndpoint.java

@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.service.security.SecurityMonitoringOrderService;
import com.yihu.jw.care.service.statistics.DetectionPlatformService;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.web.Envelop;
@ -37,12 +38,14 @@ public class DetectionPlatformEndpoint extends EnvelopRestEndpoint {
    private DetectionPlatformService platformService;
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private SecurityMonitoringOrderService securityMonitoringOrderService;
    @ApiOperation("环境信息")
    @RequestMapping(value = "envMessage", method = RequestMethod.GET)
    public ObjEnvelop envMessage(@ApiParam(name = "patientId", value = "居民id", defaultValue = "1")
                             @RequestParam(value = "patientId", required = true) String patientId){
                                 @RequestParam(value = "patientId", required = true) String patientId) {
        try {
            return success(patientDeviceService.envMessage(patientId));
        } catch (Exception ex) {
@ -54,11 +57,11 @@ public class DetectionPlatformEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "getHealthMonitoringListNew")
    @ApiOperation(value = "体征监测/安防监护")
    public PageEnvelop getHealthMonitoringListNew(
            @ApiParam(name="page",value = "page") @RequestParam(required = true) int page,
            @ApiParam(name="size",value = "size") @RequestParam(required = true) int size,
            @ApiParam(name="type",value = "type=1(健康监测)   type=2(安防检测)   type=3(设备异常)") @RequestParam(required = true) int type) {
            @ApiParam(name = "page", value = "page") @RequestParam(required = true) int page,
            @ApiParam(name = "size", value = "size") @RequestParam(required = true) int size,
            @ApiParam(name = "type", value = "type=1(健康监测)   type=2(安防检测)   type=3(设备异常)") @RequestParam(required = true) int type) {
        try {
            return platformService.getHealthMonitoringListNew(page,size,type);
            return platformService.getHealthMonitoringListNew(page, size, type);
        } catch (Exception e) {
            return failedPageEnvelopException2(e);
        }
@ -66,153 +69,195 @@ public class DetectionPlatformEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "getDeviceCompany")
    @ApiOperation(value = "设备入驻")
    public ObjEnvelop getDeviceCompany(){
    public ObjEnvelop getDeviceCompany() {
        try {
            JSONObject o = platformService.getDeviceComapny();
            return success(o);
        }catch (Exception e){
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @GetMapping(value = "getRealTimeData")
    @ApiOperation(value = "实时数据")
    public ObjEnvelop getRealTimeData(){
    public ObjEnvelop getRealTimeData() {
        try {
            JSONObject o = platformService.getRealTimeData();
            return success(o);
        }catch (Exception e){
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @GetMapping(value = "getDeviceType")
    @ApiOperation(value = "设备类型")
    public ListEnvelop getDeviceType(){
    public ListEnvelop getDeviceType() {
        try {
            return success("查询成功",200,platformService.getDeviceType());
        }catch (Exception e){
            return success("查询成功", 200, platformService.getDeviceType());
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @GetMapping(value = "getDeviceByCondition")
    @ApiOperation(value = "地图展示,根据不同的条件展示不同的数据")
    public ListEnvelop<Object> getDeviceByCondition(@ApiParam(name="categoryCode",value = "categoryCode") @RequestParam(required = false) String categoryCode,
                                                    @ApiParam(name="patient",value = "patient") @RequestParam(required = false) String patient){
    public ListEnvelop<Object> getDeviceByCondition(@ApiParam(name = "categoryCode", value = "categoryCode") @RequestParam(required = false) String categoryCode,
                                                    @ApiParam(name = "patient", value = "patient") @RequestParam(required = false) String patient) {
        try {
            JSONArray object = platformService.getDeviceByCondition(categoryCode,patient);
            return success("查询成功",200,object);
        }catch (Exception e){
            JSONArray object = platformService.getDeviceByCondition(categoryCode, patient);
            return success("查询成功", 200, object);
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @GetMapping("getOrderListWarning")
    @ApiOperation(value = "物联网大屏预警工单列表坐标获取")
    public ListEnvelop getOrderListWarning(){
    public ListEnvelop getOrderListWarning() {
        try {
            return ListEnvelop.getSuccess("success",platformService.getOrderListWarning());
        }catch (Exception e){
            return ListEnvelop.getSuccess("success", platformService.getOrderListWarning());
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @GetMapping(value = "getDeviceInfo")
    @ApiOperation(value = "地图展示,根据设备sn码查询详情")
    public ObjEnvelop getDeviceInfo(            @ApiParam(name="deviceSn",value = "deviceSn") @RequestParam(required = true) String deviceSn){
    public ObjEnvelop getDeviceInfo(@ApiParam(name = "deviceSn", value = "deviceSn") @RequestParam(required = true) String deviceSn) {
        try {
            JSONObject object = platformService.getDeviceInfo(deviceSn);
            return success("查询成功",200,object);
        }catch (Exception e){
            return success("查询成功", 200, object);
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @GetMapping(value = "nightRecordList")
    @ApiOperation(value = "根据设备sn码查询起夜记录")
    public ListEnvelop nightRecordList(            @ApiParam(name="deviceSn",value = "deviceSn") @RequestParam(required = true) String deviceSn){
    public ListEnvelop nightRecordList(@ApiParam(name = "deviceSn", value = "deviceSn") @RequestParam(required = true) String deviceSn) {
        try {
            return success("查询成功",200, platformService.nightRecordList(deviceSn));
        }catch (Exception e){
            return success("查询成功", 200, platformService.nightRecordList(deviceSn));
        } catch (Exception e) {
            return failedListEnvelopException(e);
        }
    }
    @ApiOperation("获取设备详情信息")
    @RequestMapping(value = "getPatientDeviceDetail",method = RequestMethod.GET)
    public Envelop getPatientDeviceDetail(@ApiParam(name="patient")
                                         @RequestParam(value = "patient")String patient,
                                          @ApiParam(name="deviceSN")
                                         @RequestParam(value = "deviceSN")String deviceSn,
                                          @ApiParam(name="day",value = "yyyy-mm-dd")
                                         @RequestParam(value = "day",required = false)String day){
    @RequestMapping(value = "getPatientDeviceDetail", method = RequestMethod.GET)
    public Envelop getPatientDeviceDetail(@ApiParam(name = "patient")
                                          @RequestParam(value = "patient") String patient,
                                          @ApiParam(name = "deviceSN")
                                          @RequestParam(value = "deviceSN") String deviceSn,
                                          @ApiParam(name = "day", value = "yyyy-mm-dd")
                                          @RequestParam(value = "day", required = false) String day) {
        try {
            org.json.JSONObject result = patientDeviceService.getPatientDeviceDetail(patient,deviceSn,day);
            if (result.getInt(ResponseContant.resultFlag)==ResponseContant.success){
            org.json.JSONObject result = patientDeviceService.getPatientDeviceDetail(patient, deviceSn, day);
            if (result.getInt(ResponseContant.resultFlag) == ResponseContant.success) {
                return success(JSON.parseObject(result.getString(ResponseContant.resultMsg)));
            }else {
            } else {
                return success(result.getString(ResponseContant.resultMsg), -1);
            }
        }catch (Exception e){
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @ApiOperation("获取设备详情数据 --设备可多人绑定查询数据时与patient无关")
    @GetMapping(value = "getPatientDeviceData")
    public Envelop getPatientDeviceData(@ApiParam(name="patient")
                                       @RequestParam(value = "patient")String patient,
                                       @ApiParam(name="deviceSN")
                                       @RequestParam(value = "deviceSN")String deviceSn,
                                       @ApiParam(name="type",value = "0全部 1日常监护 2预警记录(工单列表)")
                                       @RequestParam(value = "type",required = false)String type,
                                       @ApiParam(name="page")
                                       @RequestParam(value = "page")Integer page,
                                       @ApiParam(name="pageSize")
                                       @RequestParam(value = "pageSize")Integer pageSize){
        try {
            org.json.JSONObject result = patientDeviceService.getPatientDeviceData(patient,type,deviceSn,page,pageSize);
            if (result.getInt(ResponseContant.resultFlag)==ResponseContant.success){
    public Envelop getPatientDeviceData(@ApiParam(name = "patient")
                                        @RequestParam(value = "patient") String patient,
                                        @ApiParam(name = "deviceSN")
                                        @RequestParam(value = "deviceSN") String deviceSn,
                                        @ApiParam(name = "type", value = "0全部 1日常监护 2预警记录(工单列表)")
                                        @RequestParam(value = "type", required = false) String type,
                                        @ApiParam(name = "page")
                                        @RequestParam(value = "page") Integer page,
                                        @ApiParam(name = "pageSize")
                                        @RequestParam(value = "pageSize") Integer pageSize) {
        try {
            org.json.JSONObject result = patientDeviceService.getPatientDeviceData(patient, type, deviceSn, page, pageSize);
            if (result.getInt(ResponseContant.resultFlag) == ResponseContant.success) {
                return success(JSON.parseObject(result.getString(ResponseContant.resultMsg)));
            }else {
            } else {
                return success(result.getString(ResponseContant.resultMsg), -1);
            }
        }catch (Exception e){
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @ApiOperation("获取睡眠带睡眠报告")
    @RequestMapping(value ="getSleepReport",method = RequestMethod.GET)
    public ObjEnvelop getSleepReport(@ApiParam(name="patient")@RequestParam(value = "patient",required = false)String patient,
                                     @ApiParam(name="deviceSn")@RequestParam(value = "deviceSn",required = false)String deviceSn,
                                     @ApiParam(name="day")@RequestParam(value = "day",required = false)String day){
    @RequestMapping(value = "getSleepReport", method = RequestMethod.GET)
    public ObjEnvelop getSleepReport(@ApiParam(name = "patient") @RequestParam(value = "patient", required = false) String patient,
                                     @ApiParam(name = "deviceSn") @RequestParam(value = "deviceSn", required = false) String deviceSn,
                                     @ApiParam(name = "day") @RequestParam(value = "day", required = false) String day) {
        try {
            if (StringUtils.isBlank(patient) && StringUtils.isBlank(deviceSn)) {
                return ObjEnvelop.getError("请求参数");
            }
            org.json.JSONObject result = patientDeviceService.getSleepReport(patient, deviceSn, day);
            if (ResponseContant.success == result.getInt(ResponseContant.resultFlag)) {
                return ObjEnvelop.getSuccess("获取成功", result.get(ResponseContant.resultMsg));
            } else {
                return ObjEnvelop.getError(result.getString(ResponseContant.resultMsg));
            }
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @ApiOperation("获取患者步数数据")
    @RequestMapping(value = "getPatientStep", method = RequestMethod.GET)
    public ObjEnvelop getPatientStep(@ApiParam(name = "patient") @RequestParam(value = "patient", required = false) String patient,
                                     @ApiParam(name = "deviceSn") @RequestParam(value = "deviceSn", required = false) String deviceSn,
                                     @ApiParam(name = "day") @RequestParam(value = "day", required = false) String day) {
        try {
            if (StringUtils.isBlank(patient)&&StringUtils.isBlank(deviceSn)){
            if (StringUtils.isBlank(patient) && StringUtils.isBlank(deviceSn)) {
                return ObjEnvelop.getError("请求参数");
            }
            org.json.JSONObject result = patientDeviceService.getSleepReport(patient,deviceSn,day);
            if (ResponseContant.success==result.getInt(ResponseContant.resultFlag)){
                return ObjEnvelop.getSuccess("获取成功",result.get(ResponseContant.resultMsg));
            }else {
            org.json.JSONObject result = patientDeviceService.getPatientStep(patient, deviceSn, day);
            if (ResponseContant.success == result.getInt(ResponseContant.resultFlag)) {
                return ObjEnvelop.getSuccess("获取成功", result.get(ResponseContant.resultMsg));
            } else {
                return ObjEnvelop.getError(result.getString(ResponseContant.resultMsg));
            }
        }catch (Exception e){
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @ApiOperation("获取患者手表X1睡吧数据")
    @RequestMapping(value = "getX1SleepInfo", method = RequestMethod.GET)
    public ObjEnvelop getX1SleepInfo(@ApiParam(name = "patient") @RequestParam(value = "patient", required = false) String patient,
                                     @ApiParam(name = "deviceSn") @RequestParam(value = "deviceSn", required = false) String deviceSn,
                                     @ApiParam(name = "day") @RequestParam(value = "day", required = false) String day) {
        try {
            if (StringUtils.isBlank(patient) && StringUtils.isBlank(deviceSn)) {
                return ObjEnvelop.getError("请求参数");
            }
            org.json.JSONObject result = patientDeviceService.getX1SleepInfo(patient, deviceSn, day);
            if (ResponseContant.success == result.getInt(ResponseContant.resultFlag)) {
                return ObjEnvelop.getSuccess("获取成功", result.get(ResponseContant.resultMsg));
            } else {
                return ObjEnvelop.getError(result.getString(ResponseContant.resultMsg));
            }
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @ApiOperation("获取烟雾/燃气浓度列表")
    @RequestMapping(value ="getSmokeOrGasList",method = RequestMethod.GET)
    public ListEnvelop getSmokeOrGasList(@ApiParam(name="deviceSn")@RequestParam(value = "deviceSn",required = true)String deviceSn,
                                         @ApiParam(name="day",value = "yyyy-MM-dd")@RequestParam(value = "day",required = false)String day){
    @RequestMapping(value = "getSmokeOrGasList", method = RequestMethod.GET)
    public ListEnvelop getSmokeOrGasList(@ApiParam(name = "deviceSn") @RequestParam(value = "deviceSn", required = true) String deviceSn,
                                         @ApiParam(name = "day", value = "yyyy-MM-dd") @RequestParam(value = "day", required = false) String day) {
        try {
            return ListEnvelop.getSuccess("获取成功",patientDeviceService.getSmokeOrGasList(deviceSn,day));
        }catch (Exception e){
            return ListEnvelop.getSuccess("获取成功", patientDeviceService.getSmokeOrGasList(deviceSn, day));
        } catch (Exception e) {
            return failedListEnvelopException2(e);
        }
    }
@ -220,32 +265,64 @@ public class DetectionPlatformEndpoint extends EnvelopRestEndpoint {
    /********************v1.1.0**************************/
    @GetMapping(value = "getGiveEarlyWarning")
    @ApiOperation(value = "物联网检测大屏,预警部分")
    public ObjEnvelop getGiveEarlyWarning(){
    public ObjEnvelop getGiveEarlyWarning() {
        try {
            return success("查询成功",200, platformService.getDistributionOfWarningTypes());
        }catch (Exception e){
            return success("查询成功", 200, platformService.getDistributionOfWarningTypes());
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @GetMapping(value = "getServiceSituation")
    @ApiOperation(value = "物联网检测大屏,服务情况")
    public ObjEnvelop getServiceSituation(){
    public ObjEnvelop getServiceSituation() {
        try {
            return success("查询成功",200, platformService.getServiceSituation());
        }catch (Exception e){
            return success("查询成功", 200, platformService.getServiceSituation());
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @GetMapping(value = "deviceAndService")
        @ApiOperation(value = "物联网检测大屏,设备种类     安防服务")
    public ObjEnvelop deviceAndService(){
    @ApiOperation(value = "物联网检测大屏,设备种类    安防服务")
    public ObjEnvelop deviceAndService() {
        try {
            return success("查询成功",200, platformService.deviceAndService());
        }catch (Exception e){
            return success("查询成功", 200, platformService.deviceAndService());
        } catch (Exception e) {
            return failedObjEnvelopException(e);
        }
    }
    @ApiOperation("助老员端获取日常监护居民")
    @GetMapping(value = "findMonitorPatientsByDoctor")
    @ResponseBody
    public ObjEnvelop findMonitorPatientsByDoctor(
            @ApiParam(name = "topicItem", value = "专题code,关联security_topic_dict字典,actionTrack行动轨迹,sos紧急预警", required = true)
            @RequestParam(value = "topicItem", required = true, defaultValue = "preventLost") String topicItem,
            @ApiParam(name = "day", value = "day", required = false)
            @RequestParam(value = "day", required = false) String day,
            @ApiParam(name = "page")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize")
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @ApiParam(name = "detail", value = "是否返回专题详情0否 1是")
            @RequestParam(value = "detail", required = false, defaultValue = "0") Integer detail) {
        try {
            return ObjEnvelop.getSuccess("查询成功", securityMonitoringOrderService.findMonitorPatientsByDoctors(topicItem, day, page, pageSize, detail));
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @ApiOperation("助老员端获取日常监护居民")
    @GetMapping(value = "findSignOlder")
    @ResponseBody
    public ObjEnvelop findSignOlder() {
        try {
            return ObjEnvelop.getSuccess("查询成功", platformService.findSignOlder());
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
}

+ 123 - 48
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/OpenStatisticsEndpoint.java

@ -53,7 +53,7 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    public ListEnvelop executeESSQL1(
            @RequestParam(required = true) String sql) {
        try {
            return success(elasticsearchUtil.excute(sql, SaveModel.class,null,null));
            return success(elasticsearchUtil.excute(sql, SaveModel.class, null, null));
        } catch (Exception e) {
            return failedListEnvelopException2(e);
        }
@ -82,6 +82,55 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
        }
    }
    @GetMapping(value = "patientAnalysis")
    @ApiOperation(value = "居民分析")
    public ObjEnvelop patientAnalysis(
                                      @RequestParam(required = true) String endDate,
                                      @RequestParam(required = true) String area,
                                      @RequestParam(required = true) int level,
                                      @ApiParam(name = "index", value = "42幼儿,37老人", defaultValue = "") @RequestParam(required = true) String index) {
        try {
            JSONObject result = statisticsService.patientAnalysisDP(endDate, area, level, index);
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "patientTypeTotalAnalysis")
    @ApiOperation(value = "老人幼儿类型统计分析")
    public ObjEnvelop patientTypeTotalAnalysis(
            @RequestParam(required = false) String endDate,
            @ApiParam(name = "index", value = "42幼儿,37老人", defaultValue = "") @RequestParam(required = true) String index) {
        try {
            JSONObject result = statisticsService.combinedTotal(index,endDate);
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "curveTotal")
    @ApiOperation(value = "曲线图")
    public ObjEnvelop curveTotal(@RequestParam(required = true) String day,
                                 @ApiParam(name = "type", value = "39-老人-生活照料-服务工单数 44-老人-生活照料-代预约 3-幼儿活动报名 41-紧急呼叫  43-老人安放监护 2-公艺课程播放  1-活动浏览次数 28-新生儿-在线咨询总数 32-新生儿-在线咨询总数  35-新生儿-上门辅导-服务工单数")
                                 @RequestParam(required = true) String type,
                                 @RequestParam(required = true) String area,
                                 @RequestParam(required = true) int level,
                                 @RequestParam(required = false) String timeLevel,
                                 @RequestParam(required = false) String interval,
                                 @RequestParam(required = false) String lowLevel
    ) {
        try {
            JSONObject result = statisticsService.curveTotal(day, type, area, level, timeLevel, interval, lowLevel);
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "serviceResources")
    @ApiOperation(value = "服务资源v0.7.0")
    public ObjEnvelop ServiceResources() {
@ -107,9 +156,9 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "getAllDynamics")
    @ApiOperation(value = "综合动态v0.7.0")
    public PageEnvelop getAllDynamics(
            @RequestParam(required = true) Integer page,@RequestParam(required = true) Integer size) {
            @RequestParam(required = true) Integer page, @RequestParam(required = true) Integer size) {
        try {
            return statisticsService.getAllDynamics(page,size);
            return statisticsService.getAllDynamics(page, size);
        } catch (Exception e) {
            return failedPageEnvelopException2(e);
        }
@ -118,9 +167,9 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "serviceRankingAnalysis")
    @ApiOperation(value = "服务排名分析")
    public ListEnvelop serviceRankingAnalysis(
            @RequestParam(required = true) String endDate,@RequestParam(required = true) String orgType) {
            @RequestParam(required = true) String endDate, @RequestParam(required = true) String orgType) {
        try {
            return success(statisticsService.serviceRankingAnalysis(endDate,orgType));
            return success(statisticsService.serviceRankingAnalysis(endDate, orgType));
        } catch (Exception e) {
            return failedListEnvelopException2(e);
        }
@ -129,9 +178,9 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "fingLoginLog")
    @ApiOperation(value = "获取登录记录")
    public PageEnvelop fingLoginLog(
            @RequestParam(required = true) Integer page,@RequestParam(required = true) Integer size) {
            @RequestParam(required = true) Integer page, @RequestParam(required = true) Integer size) {
        try {
            return statisticsService.fingLoginLog(page,size);
            return statisticsService.fingLoginLog(page, size);
        } catch (Exception e) {
            return failedPageEnvelopException2(e);
        }
@ -162,60 +211,60 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "findUserByType")
    @ApiOperation(value = "人员实时动态搜索")
    public Envelop findUserByType(@ApiParam(name = "type", value = "类型:1幼儿,2老人,3助老员,4医生。不传返回四个类型的数据")
                                    @RequestParam(value = "type", required = false)String type,
                                    @ApiParam(name = "name", value = "姓名")
                                    @RequestParam(value = "name", required = false)String name,
                                    @ApiParam(name = "residentialArea", value = "居住小区")
                                    @RequestParam(value = "residentialArea", required = false)String residentialArea,
                                    @ApiParam(name = "page", value = "第几页")
                                        @RequestParam(value = "page", required = false)Integer page,
                                    @ApiParam(name = "size", value = "页面大小")
                                        @RequestParam(value = "size", required = false)Integer size){
        try{
            return success("修改成功",patientService.findUserByType(type, name, residentialArea, page, size));
        }catch (Exception e){
                                  @RequestParam(value = "type", required = false) String type,
                                  @ApiParam(name = "name", value = "姓名")
                                  @RequestParam(value = "name", required = false) String name,
                                  @ApiParam(name = "residentialArea", value = "居住小区")
                                  @RequestParam(value = "residentialArea", required = false) String residentialArea,
                                  @ApiParam(name = "page", value = "第几页")
                                  @RequestParam(value = "page", required = false) Integer page,
                                  @ApiParam(name = "size", value = "页面大小")
                                  @RequestParam(value = "size", required = false) Integer size) {
        try {
            return success("修改成功", patientService.findUserByType(type, name, residentialArea, page, size));
        } catch (Exception e) {
            return failedException2(e);
        }
    }
    @GetMapping(value = "doctorInfo")
    @ApiOperation(value = "获取医生详情")
    public ObjEnvelop doctorInfo (
    public ObjEnvelop doctorInfo(
            @ApiParam(name = "doctorId", value = "医生id", required = true)
            @RequestParam(value = "doctorId",required = true) String doctorId) throws Exception {
        try{
            return ObjEnvelop.getSuccess("查询成功",doctorService.doctorSimpleInfo(doctorId));
        }catch (Exception e){
            @RequestParam(value = "doctorId", required = true) String doctorId) throws Exception {
        try {
            return ObjEnvelop.getSuccess("查询成功", doctorService.doctorSimpleInfo(doctorId));
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "getDoctorOrderList")
    @ApiOperation("获取医生生活照料列表")
    public ObjEnvelop getDoctorOrderList(@ApiParam(name="doctor",value = "医生id",required = true)
                                      @RequestParam(value = "doctor")String doctor,
                                      @ApiParam(name="page",value="page")
                                      @RequestParam(name = "page")Integer page,
                                      @ApiParam(name="size",value="size")
                                      @RequestParam(name = "size")Integer size){
    public ObjEnvelop getDoctorOrderList(@ApiParam(name = "doctor", value = "医生id", required = true)
                                         @RequestParam(value = "doctor") String doctor,
                                         @ApiParam(name = "page", value = "page")
                                         @RequestParam(name = "page") Integer page,
                                         @ApiParam(name = "size", value = "size")
                                         @RequestParam(name = "size") Integer size) {
        try {
            return ObjEnvelop.getSuccess("查询成功",lifeCareOrderService.getDoctorOrderList(doctor,page,size));
        }catch (Exception e){
            return ObjEnvelop.getSuccess("查询成功", lifeCareOrderService.getDoctorOrderList(doctor, page, size));
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "getEmergencyAssistanceList")
    @ApiOperation(value = "紧急救助列表")
    public PageEnvelop getEmergencyAssistanceList(@ApiParam(name="doctor",value = "医生id",required = true)
                                                     @RequestParam(value = "doctor")String doctor,
                                                 @ApiParam(name="page",value = "page")
                                                 @RequestParam(value = "page") Integer page,
                                                 @ApiParam(name="size",value = "size")
                                                 @RequestParam(value = "size") Integer size){
    public PageEnvelop getEmergencyAssistanceList(@ApiParam(name = "doctor", value = "医生id", required = true)
                                                  @RequestParam(value = "doctor") String doctor,
                                                  @ApiParam(name = "page", value = "page")
                                                  @RequestParam(value = "page") Integer page,
                                                  @ApiParam(name = "size", value = "size")
                                                  @RequestParam(value = "size") Integer size) {
        try {
            return emergencyAssistanceService.getEmergencyAssistanceList(page,size,doctor);
        }catch (Exception e){
            return emergencyAssistanceService.getEmergencyAssistanceList(page, size, doctor);
        } catch (Exception e) {
            return failedPageEnvelopException2(e);
        }
    }
@ -225,7 +274,7 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    public ObjEnvelop statisticsOrderServer(
            @RequestParam(required = true) String endDate) {
        try {
            JSONObject result = statisticsService.statisticsOrderServer("46,48",endDate,2,"4");
            JSONObject result = statisticsService.statisticsOrderServer("46,48", endDate, 2, "4");
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
@ -249,7 +298,7 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    public ObjEnvelop statisticsOlderAge(
            @RequestParam(required = true) String endDate) {
        try {
            JSONObject result = statisticsService.statisticsOrderServer("50",endDate,2,"2");
            JSONObject result = statisticsService.statisticsOrderServer("50", endDate, 2, "2");
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
@ -261,18 +310,44 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
    public ListEnvelop searchBySql(
            @RequestParam(required = true) String sql) {
        try {
            return ListEnvelop.getSuccess("查询成功",statisticsService.searchBySql(sql));
            return ListEnvelop.getSuccess("查询成功", statisticsService.searchBySql(sql));
        } catch (Exception e) {
            return failedListEnvelopException2(e);
        }
    }
    @RequestMapping(value="esDataModify",method = RequestMethod.GET)
    public ObjEnvelop esDataModify(@RequestParam(required = true) String sql,@RequestParam(required = true) String jsonStr){
    @RequestMapping(value = "esDataModify", method = RequestMethod.GET)
    public ObjEnvelop esDataModify(@RequestParam(required = true) String sql, @RequestParam(required = true) String jsonStr) {
        try {
            return ObjEnvelop.getSuccess("success", statisticsService.esDataModify(sql, jsonStr));
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @ApiOperation(value = "新生儿回复")
    @RequestMapping(value = "newBornReply",method = RequestMethod.GET)
    public ObjEnvelop newBornReply(
            @RequestParam(required = true) String endDate){
        try {
            return ObjEnvelop.getSuccess("success",statisticsService.esDataModify(sql,jsonStr));
        }catch (Exception e){
           return failedObjEnvelopException2(e);
            return ObjEnvelop.getSuccess("success",statisticsService.newBornReply(endDate));
        } catch (Exception e) {
            e.printStackTrace();
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "doorCoachAnalysis")
    @ApiOperation(value = "上门辅导分析")
    public ObjEnvelop doorCoachAnalysis(
            @RequestParam(required = true) String endDate,
            @RequestParam(required = true) String area,
            @RequestParam(required = true) int level) {
        try {
            JSONObject result = statisticsService.doorCoachAnalysis(endDate, area, level);
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/third/platForm/PatientInfoPlatFormEndpoint.java

@ -225,7 +225,7 @@ public class PatientInfoPlatFormEndpoint extends EnvelopRestEndpoint {
                                     @ApiParam(name = "topicItem", value = "专题code,关联security_topic_dict字典", required = false)
                                     @RequestParam(value = "topicItem",required = false) String topicItem){
        try {
            return baseController.write (200,"查询成功","data",securityMonitoringOrderService.patientMonitoringInfo(patient,topicItem,true));
            return baseController.write (200,"查询成功","data",securityMonitoringOrderService.patientMonitoringInfo(patient,topicItem,null,true));
        }catch (Exception e){
            return baseController.errorResult(e);
        }

+ 13 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/activity/ChildActivityRegistrationService.java

@ -14,8 +14,14 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
 * Created by yeshijie on 2021/10/16.
@ -114,7 +120,13 @@ public class ChildActivityRegistrationService {
     */
    @Transactional
    public void activityClick(Integer type){
        String sql = " UPDATE base_child_activity_click SET num = num+1 where type="+type;
        //取当前时间
        Date nowdate=new Date();
        //转换时间格式
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp timestamp = Timestamp.valueOf(simpleDate.format(nowdate));
        //String sql = " UPDATE base_child_activity_click SET num = num+1 where type="+type;
        String sql = " INSERT INTO base_activity_click VALUES ('"+UUID.randomUUID().toString().replace("-","")+"',"+type+",'"+timestamp+"')";
        jdbcTemplate.execute(sql);
    }
}

+ 6 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/assistance/EmergencyAssistanceService.java

@ -295,6 +295,8 @@ public class EmergencyAssistanceService extends BaseJpaService<EmergencyAssistan
                    messageUtil.sendTXYSJson("1099807",doctorDO.getMobile(),assistanceDO.getPatientName(),"紧急呼叫");
                }
            }catch (Exception e){}
            String body = "您好,"+assistanceDO.getPatientName()+"居民发起紧急呼叫,请关注并及时处理。";
            messageUtil.sendDoctorGetuiMessage(doctorDO.getId(),"2","/sos/index?tabActive=1","紧急呼叫",body);
            imUtill.sendMDTSocketMessageToDoctor(doctorDO.getId(),message.toString());
        }
        //pc管理端端推送消息
@ -1155,11 +1157,11 @@ public class EmergencyAssistanceService extends BaseJpaService<EmergencyAssistan
     */
    public PageEnvelop getEmergencyAssistanceList(Integer page, Integer size,String doctor){
        page = page>0?page-1:0;
        String sql = " select '20' as OrderType,ord.id,ord.doctor,ord.status,ord.patient,ord.patient_name as name,p.name as doctorName,'紧急呼叫' as serve_desc,DATE_FORMAT(ord.create_time,'%Y-%m-%d %H:%i:%S') create_time" +
                " from base_emergency_assistance_order ord INNER JOIN base_doctor p on ord.doctor = p.id where ord.doctor='"+doctor+"'" ;
        String sql = " select '20' as OrderType,ord.id,ord.doctor,ord.status,ord.patient,ord.patient_name as name,pat.sex,p.name as doctorName,'紧急呼叫' as serve_desc,DATE_FORMAT(ord.create_time,'%Y-%m-%d %H:%i:%S') create_time" +
                " from base_emergency_assistance_order ord INNER JOIN base_doctor p on ord.doctor = p.id INNER JOIN base_patient pat on pat.id = ord.patient where ord.doctor='"+doctor+"'" ;
        sql +="UNION " +
                "select  '22' as 'OrderType',ord.id,ord.doctor,ord.status,ord.patient,ord.patient_name as name,p.name as doctorName,ord.serve_desc,DATE_FORMAT(ord.create_time,'%Y-%m-%d %H:%i:%S') create_time " +
                "from base_security_monitoring_order ord INNER JOIN base_doctor p on ord.doctor = p.id  where ord.doctor='"+doctor+"'" ;
                "select  '22' as 'OrderType',ord.id,ord.doctor,ord.status,ord.patient,ord.patient_name as name,pat.sex,p.name as doctorName,ord.serve_desc,DATE_FORMAT(ord.create_time,'%Y-%m-%d %H:%i:%S') create_time " +
                "from base_security_monitoring_order ord INNER JOIN base_doctor p on ord.doctor = p.id INNER JOIN base_patient pat on pat.id = ord.patient  where ord.doctor='"+doctor+"'" ;
        String countSql = "select count(id) from ("+sql+")A ";
        long count = jdbcTemplate.queryForObject(countSql,long.class);
        sql +=" order by create_time desc limit "+page*size+","+size;

+ 5 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/consult/ConsultService.java

@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.consult.BaseYunxingChannelDao;
import com.yihu.jw.care.util.EntranceUtil;
import com.yihu.jw.care.util.MessageUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
@ -32,6 +33,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
@ -76,6 +78,8 @@ public class ConsultService {
    private EntranceUtil entranceUtil;
    @Autowired
    private BaseYunxingChannelDao yunxingChannelDao;
    @Autowired
    private MessageUtil messageUtil;
    /**
     * 保存云信channelId
@ -625,6 +629,7 @@ public class ConsultService {
        }
        // 保存医生咨询信息
        // 添加咨询转发记录
        // 添加医生咨询日志

+ 53 - 15
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java

@ -108,7 +108,7 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
    private static final String gxy = "HP0093";
    //健康问题 糖尿病
    private static final String tnb = "HP0047";
    Map<Integer, String> relations = new HashMap<>();
    @Value("${es.index.Statistics}")
    private String esIndex;
    @Autowired
@ -132,20 +132,6 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
    @Autowired
    private PatientSafeAreaConfirmDao patientSafeAreaConfirmDao;
    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
        relations.put(8, "免疫关联");
    }
    /**
     * 获取烟雾 燃气浓度
     * @param patient
@ -1189,6 +1175,58 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        return result;
    }
    public JSONObject getPatientStep(String patient,String deviceSn,String day){
        JSONObject result = new JSONObject();
        String sql = " select * from base_patient_step where 1=1 ";
        if (StringUtils.isNotBlank(patient)){
            sql +=" and patient='"+patient+"'";
        }
        if (StringUtils.isNotBlank(deviceSn)){
            sql += " and device_sn='"+deviceSn+"' ";
        }
        if (StringUtils.isNotBlank(day)){
            sql +=" and create_time>='"+day+" 00:00:00' and create_time<'"+day+" 23:59:59' ";
        }else   {
            sql +=" order by create_time desc ";
        }
        sql +=" limit 1 ";
        List<BasePatientStepDo> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(BasePatientStepDo.class));
        if (list.size()>0){
            result.put(ResponseContant.resultFlag,ResponseContant.success);
            result.put(ResponseContant.resultMsg,list.get(0));
        }else {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"无步数数据!");
        }
        return result;
    }
    public JSONObject getX1SleepInfo(String patient,String deviceSn,String day){
        JSONObject result = new JSONObject();
        String sql = " select * from base_sleep_x1device where 1=1 ";
        if (StringUtils.isNotBlank(patient)){
            sql +=" and patient='"+patient+"'";
        }
        if (StringUtils.isNotBlank(deviceSn)){
            sql += " and device_sn='"+deviceSn+"' ";
        }
        if (StringUtils.isNotBlank(day)){
            sql +=" and create_time>='"+day+" 00:00:00' and create_time<'"+day+" 23:59:59' ";
        }else   {
            sql +=" order by create_time desc ";
        }
        sql +=" limit 1 ";
        List<BaseSleepX1device> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(BaseSleepX1device.class));
        if (list.size()>0){
            result.put(ResponseContant.resultFlag,ResponseContant.success);
            result.put(ResponseContant.resultMsg,list.get(0));
        }else {
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"无睡眠数据!");
        }
        return result;
    }
    /**
     * 烟感、气感设备浓度列表获取
     */

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/doctor/CareDoctorService.java

@ -95,7 +95,7 @@ public class CareDoctorService extends BaseJpaService<BaseDoctorDO, BaseDoctorDa
        Integer signNum = jdbcTemplate.queryForObject(sql1,Integer.class);
        String sqlLife= "SELECT COUNT(*) from base_life_care_order where `status` = 2";
        String sqlEmergency= "SELECT COUNT(*) from base_emergency_assistance_order where `status` = 0";
        String sqlSecurity= "SELECT COUNT(*) from base_security_monitoring_order where `status` = 7 ";
        String sqlSecurity= "SELECT COUNT(*) from base_security_monitoring_order where `status` = 0 ";
        String filter = " and doctor = '"+doctorId+"'";
        Integer lifeCare = jdbcTemplate.queryForObject(sqlLife+filter,Integer.class);
        Integer emergency = jdbcTemplate.queryForObject(sqlEmergency+filter,Integer.class);

+ 1015 - 803
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java

@ -47,6 +47,7 @@ import com.yihu.jw.util.common.LatitudeUtils;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.EntityUtils;
import com.yihu.mysql.query.BaseJpaService;
import jdk.nashorn.internal.runtime.FindProperty;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -141,7 +142,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
    private Logger logger = LoggerFactory.getLogger(SecurityMonitoringOrderService.class);
    public JSONObject createOrder(String jsonData,Integer orderSource,String warnStr) throws Exception {
    public JSONObject createOrder(String jsonData, Integer orderSource, String warnStr) throws Exception {
        logger.info("创建安防工单jsonData参数:" + jsonData);
        JSONObject result = new JSONObject();
@ -168,9 +169,9 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        //V1.4 同一类型的安防工单 距离上次发起小于6小时不可重复发起
        String sql = " select count(id) from base_security_monitoring_order where `status`=1  " +
                "  and TIMESTAMPDIFF(HOUR,create_time,NOW())<=6 " +
                " and patient='"+orderDO.getPatient()+"' and serve_desc ='"+orderDO.getServeDesc()+"' ";
        Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
        if (count>0){
                " and patient='" + orderDO.getPatient() + "' and serve_desc ='" + orderDO.getServeDesc() + "' ";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        if (count > 0) {
            result.put("resultFlag", 0);
            String failMsg = "居民六小时内已存在该预警类型工单,无法重复发起";
            result.put("resultMsg", failMsg);
@ -186,7 +187,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        orderDO.setOrderInfo("0");
        orderDO.setOrderSource(orderSource);
        if(StringUtils.isEmpty(orderDO.getPatient())){
        if (StringUtils.isEmpty(orderDO.getPatient())) {
            result.put("resultFlag", 0);
            String failMsg = "当前服务对象code为空,请联系管理员检查参数!patient = " + orderDO.getPatient();
            result.put("resultMsg", failMsg);
@ -195,7 +196,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        }
        BasePatientDO patientDO = basePatientDao.findById(orderDO.getPatient());
        if (patientDO==null){
        if (patientDO == null) {
            result.put("resultFlag", 0);
            String failMsg = "当前服务对象未建档";
            result.put("resultMsg", failMsg);
@ -204,11 +205,11 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        }
        //签约防走失服务包
        sql ="SELECT i.code,r.team_code,pack.org_code,pack.org_name from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i,base_service_package pack    \n" +
        sql = "SELECT i.code,r.team_code,pack.org_code,pack.org_name from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i,base_service_package pack    \n" +
                "where  sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id and r.service_package_id = pack.id  and i.del = 1 and sr.`status`=1 \n" +
                "and  sr.patient  = '"+orderDO.getPatient()+"' and i.code='preventLost' ";
        List<Map<String,Object>> items = jdbcTemplate.queryForList(sql);
        if (items.size()==0) {
                "and  sr.patient  = '" + orderDO.getPatient() + "' and i.code='preventLost' ";
        List<Map<String, Object>> items = jdbcTemplate.queryForList(sql);
        if (items.size() == 0) {
            result.put("resultFlag", 0);
            String failMsg = "当前服务对象未签约防走失服务,请签约后再发起预警!";
            result.put("resultMsg", failMsg);
@ -228,12 +229,12 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
//            logger.error(failMsg);
//            return result;
//        }
        Map<String,Object> mapTmp = items.get(0);
        List<BaseDoctorDO> doctorDOS = baseTeamMemberDao.findAllMembersByLevel(mapTmp.get("team_code").toString(),2);
        if (doctorDOS.size()==0){
        Map<String, Object> mapTmp = items.get(0);
        List<BaseDoctorDO> doctorDOS = baseTeamMemberDao.findAllMembersByLevel(mapTmp.get("team_code").toString(), 2);
        if (doctorDOS.size() == 0) {
            String failMsg = "安防警报服务项服务医生为空,不可发起救助";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
@ -243,94 +244,98 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        orderDO.setServiceStatus("2");
        this.save(orderDO);
        //创建im会话  安防警报咨询的sessionid  为居民code+(wlyy_consult_team表consult)+20
        JSONObject IMObj = consultTeamService.addSecurityMoConsult(orderDO.getId(),orderDO.getPatient(),null,null,orderDO.getServeDesc());
        String sessionId=orderDO.getPatient()+"_"+ IMObj.getJSONObject("resultMsg").getString("consult") + "_22";
        JSONObject IMObj = consultTeamService.addSecurityMoConsult(orderDO.getId(), orderDO.getPatient(), null, null, orderDO.getServeDesc());
        String sessionId = orderDO.getPatient() + "_" + IMObj.getJSONObject("resultMsg").getString("consult") + "_22";
        orderDO.setSessionId(sessionId);
        if (StringUtils.isNotBlank(orderDO.getServeDesc())){
        if (StringUtils.isNotBlank(orderDO.getServeDesc())) {
            ConsultTeamDo consultTeam = consultTeamDao.queryByRelationCode(orderDO.getId());
            if (consultTeam!=null){
                imUtil.sendTopicIM(orderDO.getPatient(),patientDO.getName(),consultTeam.getConsult(),"1",orderDO.getServeDesc(),null);
            if (consultTeam != null) {
                imUtil.sendTopicIM(orderDO.getPatient(), patientDO.getName(), consultTeam.getConsult(), "1", orderDO.getServeDesc(), null);
            }
        }
        //推送socket给医生  推送紧急预警
        JSONObject message = new JSONObject();
        String latLon = orderDO.getServeLat()+","+orderDO.getServeLon();
        message.put("latLon",latLon);
        message.put("session_id",sessionId);
        message.put("sender_name",orderDO.getPatientName());
        message.put("content_notice",orderDO.getPatientName()+" "+warnStr+"!");
        message.put("sender_code",orderDO.getPatient());
        message.put("OrderType",22);
        message.put("OrderStatus","new");
        message.put("order_id",orderDO.getId());
        message.put("content_type",40);
        message.put("serverDesc",orderDO.getServeDesc());
        message.put("categoryCode","");
        message.put("orgType","");
        message.put("contactStatus","");
        message.put("residentialArea",patientDO.getResidentialArea());
        if (null!=orderDO.getDeviceSn()){
        String latLon = orderDO.getServeLat() + "," + orderDO.getServeLon();
        message.put("latLon", latLon);
        message.put("session_id", sessionId);
        message.put("sender_name", orderDO.getPatientName());
        message.put("content_notice", orderDO.getPatientName() + " " + warnStr + "!");
        message.put("sender_code", orderDO.getPatient());
        message.put("OrderType", 22);
        message.put("OrderStatus", "new");
        message.put("order_id", orderDO.getId());
        message.put("content_type", 40);
        message.put("serverDesc", orderDO.getServeDesc());
        message.put("categoryCode", "");
        message.put("orgType", "");
        message.put("contactStatus", "");
        message.put("residentialArea", patientDO.getResidentialArea());
        if (null != orderDO.getDeviceSn()) {
            String device_sn = orderDO.getDeviceSn();
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)){
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)) {
                DeviceDetail deviceDetail = deviceDetailDao.findBySn(device_sn);
                if (null!=deviceDetail){
                    message.put("contactStatus",deviceDetail.getContactStatus());
                    message.put("categoryCode",deviceDetail.getCategoryCode());
                if (null != deviceDetail) {
                    message.put("contactStatus", deviceDetail.getContactStatus());
                    message.put("categoryCode", deviceDetail.getCategoryCode());
                }
            }
        }
        String orgCode = orderDO.getHospital();
        BaseOrgDO orgDO = orgDao.findByCode(orgCode);
        if (null!=orgDO){
            message.put("orgType",orgDO.getType());
        if (null != orgDO) {
            message.put("orgType", orgDO.getType());
        }
        for (BaseDoctorDO doctorDO:doctorDOS){
        for (BaseDoctorDO doctorDO : doctorDOS) {
            try {
                if (StringUtils.isNotBlank(doctorDO.getMobile())){
                    messageUtil.sendTXYSJson("1141719",doctorDO.getMobile(),orderDO.getPatientName(),orderDO.getServeDesc());
                if (StringUtils.isNotBlank(doctorDO.getMobile())) {
                    messageUtil.sendTXYSJson("1141719", doctorDO.getMobile(), orderDO.getPatientName(), orderDO.getServeDesc());
                }
            }catch (Exception e){}
            imUtil.sendMDTSocketMessageToDoctor(doctorDO.getId(),message.toString());
            } catch (Exception e) {
            }
            String body = "您好," + orderDO.getPatientName() + "居民" + orderDO.getServeDesc() + ",请关注并及时处理。";
            messageUtil.sendDoctorGetuiMessage(doctorDO.getId(), "1", "/securityMonitoring/index", "安防紧急预警", body);
            imUtil.sendMDTSocketMessageToDoctor(doctorDO.getId(), message.toString());
        }
        //pc管理端端推送消息
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage",message.toString());
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage", message.toString());
        result.put("resultFlag", 1);
        result.put("resultMsg",orderDO);
        result.put("resultMsg", orderDO);
        return result;
    }
    public List<Map<String , Object>> getElectronicFence(String patient){
        String sql = " select safe_area_gz safeAreaGz from wlyy_patient_safe_area where patient = '"+patient+"' ";
    public List<Map<String, Object>> getElectronicFence(String patient) {
        String sql = " select safe_area_gz safeAreaGz from wlyy_patient_safe_area where patient = '" + patient + "' ";
        return jdbcTemplate.queryForList(sql);
    }
    public List<Map<String , Object>> getActionTrack(String deviceSn,String day){
        String sql = "SELECT * FROM base_yxdevice_index WHERE sn = '"+deviceSn+"' AND lon != 0 AND lat != 0  and create_time like '"+day+"%' ORDER BY create_time DESC LIMIT 0,20";
    public List<Map<String, Object>> getActionTrack(String deviceSn, String day) {
        String sql = "SELECT * FROM base_yxdevice_index WHERE sn = '" + deviceSn + "' AND lon != 0 AND lat != 0  and create_time like '" + day + "%' ORDER BY create_time DESC LIMIT 0,20";
        return jdbcTemplate.queryForList(sql);
    }
    public List<Map<String,Object>>getNewList(String deviceSn,String day){
        if (StringUtils.isBlank(day)){
    public List<Map<String, Object>> getNewList(String deviceSn, String day) {
        if (StringUtils.isBlank(day)) {
            day = DateUtil.getStringDateShort();
        }
        String sql = "SELECT * FROM base_yxdevice_index WHERE sn = '"+deviceSn+"' AND create_time LIKE '"+day+"%' AND lon != 0 AND lat != 0 ORDER BY create_time DESC limit 1";
        String sql = "SELECT * FROM base_yxdevice_index WHERE sn = '" + deviceSn + "' AND create_time LIKE '" + day + "%' AND lon != 0 AND lat != 0 ORDER BY create_time DESC limit 1";
        return jdbcTemplate.queryForList(sql);
    }
    public List<Map<String , Object>> getPatientLatLon(String deviceSn){
        String sql = "SELECT p.lat_lon FROM base_patient p,wlyy_patient_device pd WHERE pd.del = 0 AND pd.device_sn = '"+deviceSn+"' AND pd.`user` = p.id AND p.del = 1 limit 1";
    public List<Map<String, Object>> getPatientLatLon(String deviceSn) {
        String sql = "SELECT p.lat_lon FROM base_patient p,wlyy_patient_device pd WHERE pd.del = 0 AND pd.device_sn = '" + deviceSn + "' AND pd.`user` = p.id AND p.del = 1 limit 1";
        return jdbcTemplate.queryForList(sql);
    }
    public JSONObject getSecurityOrderDetail(String orderID,String doctor){
    public JSONObject getSecurityOrderDetail(String orderID, String doctor) {
        JSONObject result = new JSONObject();
        EmergencyOrderVO emergencyOrderVO = new EmergencyOrderVO();
        SecurityMonitoringOrderDO orderDO = securityMonitoringOrderDao.findOne(orderID);
        if (orderDO==null){
        if (orderDO == null) {
            String failMsg = "工单不存在!";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
@ -339,13 +344,21 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        }
        emergencyOrderVO.setId(orderDO.getId());
        BasePatientDO patientDO = basePatientDao.findById(orderDO.getPatient());
        Integer statustemp = Integer.valueOf(orderDO.getStatus()+"");
        Integer statustemp = Integer.valueOf(orderDO.getStatus() + "");
        String statusName = "";
        switch (statustemp){
            case -2:statusName="误警报";break;
            case -1:statusName="已取消";break;
            case 0:statusName="已完成";break;
            case 1:statusName="预警中";break;
        switch (statustemp) {
            case -2:
                statusName = "误警报";
                break;
            case -1:
                statusName = "已取消";
                break;
            case 0:
                statusName = "已完成";
                break;
            case 1:
                statusName = "预警中";
                break;
        }
        emergencyOrderVO.setStatusName(statusName);
        emergencyOrderVO.setOrderId(orderID);
@ -359,247 +372,244 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        emergencyOrderVO.setSex(patientDO.getSex());
        emergencyOrderVO.setTopicItem(orderDO.getTopicItem());
        emergencyOrderVO.setOrderType(22);
        if (StringUtils.isNotBlank(orderDO.getSceneImg())){
        if (StringUtils.isNotBlank(orderDO.getSceneImg())) {
            emergencyOrderVO.setSceneImg(orderDO.getSceneImg());
        }
        List<BaseEmergencyWarnLogDO> logDOS = logDao.findByOrderIdOrderByCreateTimeDesc(orderDO.getId());
        for (BaseEmergencyWarnLogDO tmp:logDOS){
            tmp.setTimeInfo(DateUtil.getDifferentTimeInfo(new Date(),tmp.getCreateTime(),0));
        for (BaseEmergencyWarnLogDO tmp : logDOS) {
            tmp.setTimeInfo(DateUtil.getDifferentTimeInfo(new Date(), tmp.getCreateTime(), 0));
        }
        if (logDOS.size()==0&&1==emergencyOrderVO.getStatus()){//未响应
            emergencyOrderVO.setOverTimeNotResponse(DateUtil.getDifferentTimeInfo1(new Date(),orderDO.getCreateTime()));
        if (logDOS.size() == 0 && 1 == emergencyOrderVO.getStatus()) {//未响应
            emergencyOrderVO.setOverTimeNotResponse(DateUtil.getDifferentTimeInfo1(new Date(), orderDO.getCreateTime()));
        }
        emergencyOrderVO.setOrderLogInfo(logDOS);
        List<PatientSosContactsDO> contactsDOS = contactsService.getPatientSosContacts(orderDO.getPatient());
        emergencyOrderVO.setSosContacts(contactsDOS);
        List<Map<String,Object>> securityDevices = patientDeviceService.patientEmeDeviceList(orderDO.getPatient());
        List<Map<String, Object>> securityDevices = patientDeviceService.patientEmeDeviceList(orderDO.getPatient());
        emergencyOrderVO.setSecurityDevices(securityDevices);
        if(StringUtils.isNotBlank(patientDO.getIdcard())){
            emergencyOrderVO.setAge((IdCardUtil.getAgeForIdcard(patientDO.getIdcard()))+"");
        if (StringUtils.isNotBlank(patientDO.getIdcard())) {
            emergencyOrderVO.setAge((IdCardUtil.getAgeForIdcard(patientDO.getIdcard())) + "");
        }
        emergencyOrderVO.setLiveAddress(patientDO.getAddress());
        emergencyOrderVO.setOrderSource(orderDO.getOrderSource());
        if(orderDO.getStatus()==-2){//误报警
        if (orderDO.getStatus() == -2) {//误报警
            emergencyOrderVO.setUpdateUserName(orderDO.getUpdateUserName());
            emergencyOrderVO.setUpdateUser(orderDO.getUpdateUser());
            emergencyOrderVO.setUpdateTime(orderDO.getUpdateTime());
            emergencyOrderVO.setEmergencyCancel(orderDO.getEmergencyCancel());
        }
        emergencyOrderVO.setUpdateTime(orderDO.getUpdateTime());
        if (orderDO.getStatus()==-1){//已取消
            if (orderDO.getCancelTime()!=null){
        if (orderDO.getStatus() == -1) {//已取消
            if (orderDO.getCancelTime() != null) {
                emergencyOrderVO.setUpdateTime(orderDO.getCancelTime());
            }
            else {
            } else {
                emergencyOrderVO.setUpdateTime(orderDO.getUpdateTime());
            }
        }
        //小结
        Integer conclusionStatus = Integer.valueOf(orderDO.getConclusionStatus()==null?"0":(orderDO.getConclusionStatus()+""));
        if (conclusionStatus==2){
        Integer conclusionStatus = Integer.valueOf(orderDO.getConclusionStatus() == null ? "0" : (orderDO.getConclusionStatus() + ""));
        if (conclusionStatus == 2) {
            EmergencyWarnConclusionDO conclusionDO = emergencyWarnConclusionDao.findByOrderId(orderDO.getId());
            if (conclusionDO!=null){
                conclusionDO.setReasonName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_REASON,String.valueOf(conclusionDO.getEmergencyReason())));
                conclusionDO.setTreatmentStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_TREATMENT_STATUS,String.valueOf(conclusionDO.getEmergencyTreatmentStatus())));
            if (conclusionDO != null) {
                conclusionDO.setReasonName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_REASON, String.valueOf(conclusionDO.getEmergencyReason())));
                conclusionDO.setTreatmentStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_TREATMENT_STATUS, String.valueOf(conclusionDO.getEmergencyTreatmentStatus())));
                emergencyOrderVO.setEmergencyWarnConclusionDO(conclusionDO);
            }
        }
        //附加信息 电子围栏状态
        if (2==orderDO.getOrderSource()||8==orderDO.getOrderSource()){//手表/拐杖
            Map<String,Object> map = new HashMap<>();
            map.put("inFenceStatus",false);
            map.put("inFenceName","疑似超出安全区域");
        if (2 == orderDO.getOrderSource() || 8 == orderDO.getOrderSource()) {//手表/拐杖
            Map<String, Object> map = new HashMap<>();
            map.put("inFenceStatus", false);
            map.put("inFenceName", "疑似超出安全区域");
            emergencyOrderVO.setInformation(map);
        }
        if(4==orderDO.getOrderSource()){//监控器
            List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(orderDO.getPatient(),"12");
            if (devicePatientDeviceDos.size()==0){
            }else {
        if (4 == orderDO.getOrderSource()) {//监控器
            List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(orderDO.getPatient(), "12");
            if (devicePatientDeviceDos.size() == 0) {
            } else {
                try {
                    JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(orderDO.getPatient(),devicePatientDeviceDos.get(0).getDeviceSn(),1,null);
                    Map<String,Object> map = new HashMap<>();
                    map.put("monitorInfoStatus",monitorUrl.getIntValue(ResponseContant.resultFlag));
                    map.put("patientAddress",devicePatientDeviceDos.get(0).getSosAddress());
                    if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail){
                        map.put("monitorInfo",monitorUrl.getString(ResponseContant.resultMsg));
                    }
                    else {
                        map.put("monitorInfo",monitorUrl.getJSONObject(ResponseContant.resultMsg));
                    JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(orderDO.getPatient(), devicePatientDeviceDos.get(0).getDeviceSn(), 1, null);
                    Map<String, Object> map = new HashMap<>();
                    map.put("monitorInfoStatus", monitorUrl.getIntValue(ResponseContant.resultFlag));
                    map.put("patientAddress", devicePatientDeviceDos.get(0).getSosAddress());
                    if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                        map.put("monitorInfo", monitorUrl.getString(ResponseContant.resultMsg));
                    } else {
                        map.put("monitorInfo", monitorUrl.getJSONObject(ResponseContant.resultMsg));
                    }
                    emergencyOrderVO.setInformation(map);
                }catch (Exception e){
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (5==orderDO.getOrderSource()){//睡眠带工单
        if (5 == orderDO.getOrderSource()) {//睡眠带工单
            try {
                JSONObject monitorInfo = JSONObject.parseObject(orderDO.getWarnInfo());
                List<BaseSleepPlan> sleepPlans = sleepPlanDao.findByPatient(patientDO.getId());
                if(null==monitorInfo){
                if (null == monitorInfo) {
                    monitorInfo = new JSONObject();
                }
                if (sleepPlans.size()>0){
                if (sleepPlans.size() > 0) {
                    BaseSleepPlan sleepPlan = sleepPlans.get(0);
                    String endTime = DateUtil.getNextMin(sleepPlan.getGetUpTime(),-1);
                    monitorInfo.put("sleepPlan",true);
                    monitorInfo.put("getUpTime",sleepPlan.getGetUpTime());
                    monitorInfo.put("siestaTime",sleepPlan.getNapTime());
                    monitorInfo.put("nightRestTime",sleepPlan.getNightRestTime());
                    monitorInfo.put("nightRecordTime",sleepPlan.getNightRestTime()+"-隔日"+endTime);
                }else {
                    monitorInfo.put("sleepPlan",false);
                    String endTime = DateUtil.getNextMin(sleepPlan.getGetUpTime(), -1);
                    monitorInfo.put("sleepPlan", true);
                    monitorInfo.put("getUpTime", sleepPlan.getGetUpTime());
                    monitorInfo.put("siestaTime", sleepPlan.getNapTime());
                    monitorInfo.put("nightRestTime", sleepPlan.getNightRestTime());
                    monitorInfo.put("nightRecordTime", sleepPlan.getNightRestTime() + "-隔日" + endTime);
                } else {
                    monitorInfo.put("sleepPlan", false);
                }
                monitorInfo = patientSignTopicInfo(monitorInfo,orderDO.getPatient(),"preventFall",null,true);
                monitorInfo = patientSignTopicInfo(monitorInfo, orderDO.getPatient(), "preventFall", null, true);
                emergencyOrderVO.setInformation(monitorInfo);
            }catch (Exception e){
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (6==orderDO.getOrderSource()){//气感工单
        if (6 == orderDO.getOrderSource()) {//气感工单
            try {
                JSONObject monitorInfo = JSONObject.parseObject(orderDO.getWarnInfo());
                monitorInfo = patientSignTopicInfo(monitorInfo,orderDO.getPatient(),"preventFall",null,true);
                monitorInfo = patientSignTopicInfo(monitorInfo, orderDO.getPatient(), "preventFall", null, true);
                emergencyOrderVO.setInformation(monitorInfo);
            }catch (Exception e){
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (7==orderDO.getOrderSource()){//烟感工单
        if (7 == orderDO.getOrderSource()) {//烟感工单
            try {
                JSONObject monitorInfo = JSONObject.parseObject(orderDO.getWarnInfo());
                monitorInfo = patientSignTopicInfo(monitorInfo,orderDO.getPatient(),"preventFall",null,true);
                monitorInfo = patientSignTopicInfo(monitorInfo, orderDO.getPatient(), "preventFall", null, true);
                emergencyOrderVO.setInformation(monitorInfo);
            }catch (Exception e){
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //通知对象
        List<Map<String,Object>> noticePersons = new ArrayList<>();
        JSONArray familyArr =  familyMemberService.getPatientMembers(orderDO.getPatient(),null,null,null,"3");
        for (int i=0;i<familyArr.size();i++){
        List<Map<String, Object>> noticePersons = new ArrayList<>();
        JSONArray familyArr = familyMemberService.getPatientMembers(orderDO.getPatient(), null, null, null, "3");
        for (int i = 0; i < familyArr.size(); i++) {
            String patientId = familyArr.getJSONObject(i).getString("id");
            BasePatientDO patientDO1 = basePatientDao.findById(patientId);
            Map<String,Object> noticeObj = new HashMap<>();
            noticeObj.put("type","0");
            noticeObj.put("typeName","家属");
            noticeObj.put("id",patientDO1.getId());
            noticeObj.put("name",patientDO1.getName());
            noticeObj.put("photo",patientDO1.getPhoto());
            noticeObj.put("mobile",patientDO1.getMobile());
            List<Map<String,Object>> arr = new ArrayList<>();
            Map<String,Object> tmp = new HashMap<>();
            tmp.put("name","系统预警");
            tmp.put("status",0);
            tmp.put("statusName","未读");
            SystemMessageDO messageDO = systemMessageDao.findByRelationCodeAndReceiver(orderDO.getId(),patientId);
            if (messageDO != null){
                if (StringUtils.isNotBlank(messageDO.getIsRead())){
                    tmp.put("status",Integer.parseInt(messageDO.getIsRead()));
                    if (Integer.parseInt(messageDO.getIsRead())==1){
                        tmp.put("statusName","已读");
            Map<String, Object> noticeObj = new HashMap<>();
            noticeObj.put("type", "0");
            noticeObj.put("typeName", "家属");
            noticeObj.put("id", patientDO1.getId());
            noticeObj.put("name", patientDO1.getName());
            noticeObj.put("photo", patientDO1.getPhoto());
            noticeObj.put("mobile", patientDO1.getMobile());
            List<Map<String, Object>> arr = new ArrayList<>();
            Map<String, Object> tmp = new HashMap<>();
            tmp.put("name", "系统预警");
            tmp.put("status", 0);
            tmp.put("statusName", "未读");
            SystemMessageDO messageDO = systemMessageDao.findByRelationCodeAndReceiver(orderDO.getId(), patientId);
            if (messageDO != null) {
                if (StringUtils.isNotBlank(messageDO.getIsRead())) {
                    tmp.put("status", Integer.parseInt(messageDO.getIsRead()));
                    if (Integer.parseInt(messageDO.getIsRead()) == 1) {
                        tmp.put("statusName", "已读");
                    }
                }
            }
            arr.add(tmp);
            noticeObj.put("response",arr);
            noticeObj.put("response", arr);
            noticePersons.add(noticeObj);
        }
        //医生信息
        String sql ="SELECT i.code,r.team_code,pack.org_code,pack.org_name from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i,base_service_package pack  \n" +
        String sql = "SELECT i.code,r.team_code,pack.org_code,pack.org_name from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i,base_service_package pack  \n" +
                "where  sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id and r.service_package_id = pack.id  and i.del = 1 and sr.`status`=1 \n" +
                "and  sr.patient  = '"+orderDO.getPatient()+"' and i.code='preventLost' ";
        List<Map<String,Object>> items = jdbcTemplate.queryForList(sql);
        if (items.size()>0){
            Map<String,Object> mapTmp = items.get(0);
            List<BaseDoctorDO> doctorDOS = baseTeamMemberDao.findAllMembersByLevel(mapTmp.get("team_code").toString(),2);
                "and  sr.patient  = '" + orderDO.getPatient() + "' and i.code='preventLost' ";
        List<Map<String, Object>> items = jdbcTemplate.queryForList(sql);
        if (items.size() > 0) {
            Map<String, Object> mapTmp = items.get(0);
            List<BaseDoctorDO> doctorDOS = baseTeamMemberDao.findAllMembersByLevel(mapTmp.get("team_code").toString(), 2);
            JSONArray otherDoctorDistance = new JSONArray();
            JSONObject otherDoctorDistanceObj = new JSONObject();
            for(BaseDoctorDO doc:doctorDOS){
                Map<String,Object> noticeObj = new HashMap<>();
                noticeObj.put("type","1");
                noticeObj.put("typeName","社工");
                noticeObj.put("id",doc.getId());
                noticeObj.put("name",doc.getName());
                noticeObj.put("photo",doc.getPhoto());
                noticeObj.put("mobile",doc.getMobile());
                List<Map<String,Object>> arr = new ArrayList<>();
                Map<String,Object> tmp = new HashMap<>();
                tmp.put("name","系统预警");
                tmp.put("status",0);
                tmp.put("statusName","未响应");
                if (emergencyWarnDoctorResponseDao.findByDoctorAndOrderId(doc.getId(),orderDO.getId())!=null){
                    tmp.put("status",1);
                    tmp.put("statusName","已响应");
            for (BaseDoctorDO doc : doctorDOS) {
                Map<String, Object> noticeObj = new HashMap<>();
                noticeObj.put("type", "1");
                noticeObj.put("typeName", "社工");
                noticeObj.put("id", doc.getId());
                noticeObj.put("name", doc.getName());
                noticeObj.put("photo", doc.getPhoto());
                noticeObj.put("mobile", doc.getMobile());
                List<Map<String, Object>> arr = new ArrayList<>();
                Map<String, Object> tmp = new HashMap<>();
                tmp.put("name", "系统预警");
                tmp.put("status", 0);
                tmp.put("statusName", "未响应");
                if (emergencyWarnDoctorResponseDao.findByDoctorAndOrderId(doc.getId(), orderDO.getId()) != null) {
                    tmp.put("status", 1);
                    tmp.put("statusName", "已响应");
                }
                arr.add(tmp);
                noticeObj.put("response",arr);
                noticeObj.put("response", arr);
                noticePersons.add(noticeObj);
                if (StringUtils.isBlank(doc.getDoctorLat()) || StringUtils.isBlank(doc.getDoctorLon())) {
                    List<BaseDoctorHospitalDO> doctorHospitalDOS = baseDoctorHospitalDao.findByDoctorCode(doc.getId());
                    if (doctorHospitalDOS.size()>0){
                    if (doctorHospitalDOS.size() > 0) {
                        BaseDoctorHospitalDO hospitalDO = doctorHospitalDOS.get(0);
                        BaseOrgDO orgDO = orgDao.findByCode(hospitalDO.getOrgCode());
                        doc.setDoctorLocateAddress(orgDO.getAddress());
                        doc.setDoctorLat(orgDO.getLatitude());
                        doc.setDoctorLon(orgDO.getLongitude());
                    }else {
                    } else {
                        continue;
                    }
                }
                //double distanceTmp = countDistance.getDistance(Double.parseDouble(orderDO.getServeLat()),Double.parseDouble(orderDO.getServeLon()),Double.parseDouble(doc.getDoctorLat()),Double.parseDouble(doc.getDoctorLon()));
                otherDoctorDistanceObj = new JSONObject();
                otherDoctorDistanceObj.put("doctor",doc.getId());
                otherDoctorDistanceObj.put("doctorName",doc.getName());
                otherDoctorDistanceObj.put("doctorAddress",doc.getDoctorLocateAddress());
                otherDoctorDistanceObj.put("doctorLon",doc.getDoctorLon());
                otherDoctorDistanceObj.put("doctorLat",doc.getDoctorLat());
                otherDoctorDistanceObj.put("distance",null);//两点距离
                otherDoctorDistanceObj.put("doctor", doc.getId());
                otherDoctorDistanceObj.put("doctorName", doc.getName());
                otherDoctorDistanceObj.put("doctorAddress", doc.getDoctorLocateAddress());
                otherDoctorDistanceObj.put("doctorLon", doc.getDoctorLon());
                otherDoctorDistanceObj.put("doctorLat", doc.getDoctorLat());
                otherDoctorDistanceObj.put("distance", null);//两点距离
                otherDoctorDistance.add(otherDoctorDistanceObj);
            }
            emergencyOrderVO.setOtherDoctorDistance(otherDoctorDistance.toJSONString());
        }
        emergencyOrderVO.setNoticePersons(noticePersons);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONStringWithDateFormat(emergencyOrderVO,"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue));
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONStringWithDateFormat(emergencyOrderVO, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue));
        //获取咨询
        ConsultDo consult = consultDao.queryByRelationCode(orderID);
        if (null != consult) {
            String sessionId = orderDO.getPatient() + "_" + consult.getId() + "_" + consult.getType();
            jsonObject.put("sessionId",sessionId);
            if (1==orderDO.getStatus()&&StringUtils.isNotBlank(doctor)){//查询未读数量
            jsonObject.put("sessionId", sessionId);
            if (1 == orderDO.getStatus() && StringUtils.isNotBlank(doctor)) {//查询未读数量
                try {
                    Integer count = imUtil.UserSessionsUnreadMessageCount(sessionId,doctor);
                    jsonObject.put("UnRead",count);
                }catch (Exception e){
                    jsonObject.put("sessionId",sessionId);
                    jsonObject.put("UnRead",0);
                    Integer count = imUtil.UserSessionsUnreadMessageCount(sessionId, doctor);
                    jsonObject.put("UnRead", count);
                } catch (Exception e) {
                    jsonObject.put("sessionId", sessionId);
                    jsonObject.put("UnRead", 0);
                }
            }
        }
        else {
            jsonObject.put("sessionId",null);
            jsonObject.put("UnRead",0);
        } else {
            jsonObject.put("sessionId", null);
            jsonObject.put("UnRead", 0);
        }
        result.put("resultFlag", 1);
        result.put("resultMsg",jsonObject);
        result.put("resultMsg", jsonObject);
        return result;
    }
    public JSONObject errorWarning(String orderId,Integer emergencyCancel,String doctor){
    public JSONObject errorWarning(String orderId, Integer emergencyCancel, String doctor) {
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO orderDO = securityMonitoringOrderDao.findOne(orderId);
        if (orderDO==null){
        if (orderDO == null) {
            String failMsg = "工单不存在!";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
@ -613,60 +623,60 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        orderDO.setUpdateUserName(doctorDO.getName());
        orderDO.setUpdateUser(doctorDO.getId());
        orderDO.setEmergencyCancel(emergencyCancel);
        if (!consultTeamService.finishConsult(orderDO.getId(),orderDO.getPatient(),doctor,2)){
        if (!consultTeamService.finishConsult(orderDO.getId(), orderDO.getPatient(), doctor, 2)) {
            String failMsg = "修改失败:咨询未能结束";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        securityMonitoringOrderDao.save(orderDO);
        //完成工单向pc管理端发送消息
        JSONObject message = new JSONObject();
        String latLon = orderDO.getServeLat()+","+orderDO.getServeLon();
        message.put("latLon",latLon);
        message.put("session_id",orderDO.getSessionId());
        message.put("sender_name",orderDO.getPatientName());
        message.put("content_notice","完成安防服务工单");
        message.put("sender_code",orderDO.getPatient());
        message.put("OrderType",22);
        message.put("OrderStatus","finish");
        message.put("order_id",orderDO.getId());
        message.put("content_type",40);
        message.put("serverDesc",orderDO.getServeDesc());
        message.put("categoryCode","");
        message.put("orgType","");
        message.put("contactStatus","");
        message.put("residentialArea","");//结束时该字段无意义
        if (null!=orderDO.getDeviceSn()){
        String latLon = orderDO.getServeLat() + "," + orderDO.getServeLon();
        message.put("latLon", latLon);
        message.put("session_id", orderDO.getSessionId());
        message.put("sender_name", orderDO.getPatientName());
        message.put("content_notice", "完成安防服务工单");
        message.put("sender_code", orderDO.getPatient());
        message.put("OrderType", 22);
        message.put("OrderStatus", "finish");
        message.put("order_id", orderDO.getId());
        message.put("content_type", 40);
        message.put("serverDesc", orderDO.getServeDesc());
        message.put("categoryCode", "");
        message.put("orgType", "");
        message.put("contactStatus", "");
        message.put("residentialArea", "");//结束时该字段无意义
        if (null != orderDO.getDeviceSn()) {
            String device_sn = orderDO.getDeviceSn();
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)){
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)) {
                DeviceDetail deviceDetail = deviceDetailDao.findBySn(device_sn);
                if (null!=deviceDetail){
                    message.put("contactStatus",deviceDetail.getContactStatus());
                    message.put("categoryCode",deviceDetail.getCategoryCode());
                if (null != deviceDetail) {
                    message.put("contactStatus", deviceDetail.getContactStatus());
                    message.put("categoryCode", deviceDetail.getCategoryCode());
                }
            }
        }
        String orgCode = orderDO.getHospital();
        BaseOrgDO orgDO = orgDao.findByCode(orgCode);
        if (null!=orgDO){
            message.put("orgType",orgDO.getType());
        if (null != orgDO) {
            message.put("orgType", orgDO.getType());
        }
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage",message.toString());
        result = getSecurityOrderDetail(orderId,null);
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage", message.toString());
        result = getSecurityOrderDetail(orderId, null);
        return result;
    }
    public PageEnvelop getSecurityOrderList(String doctor, String serverDoctor, String patientName, String patient, String status,
                                            String svrDesc,String topicItem, Integer page, Integer pageSize,Integer dailyMonitor){
                                            String svrDesc, String topicItem, Integer page, Integer pageSize, Integer dailyMonitor) {
        JSONArray result = new JSONArray();
        //服务权限
        if(doctorServicePermissionsService.isPermission(doctor,10)==0){
            return PageEnvelop.getSuccessListWithPage("success",result,page,pageSize,0L);
        if (doctorServicePermissionsService.isPermission(doctor, 10) == 0) {
            return PageEnvelop.getSuccessListWithPage("success", result, page, pageSize, 0L);
        }
        String sqlCount = "select count(ord.id) from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
@ -676,167 +686,178 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                "ord.doctor_name,ord.update_user,ord.update_user_name,ord.patient_phone,ord.conclusion_status from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
                "where 1=1 ";
        if (1==dailyMonitor){//医生日常监护居民安防工单列表查询
            if (StringUtils.isBlank(topicItem)||StringUtils.isBlank(doctor)){
        if (1 == dailyMonitor) {//医生日常监护居民安防工单列表查询
            if (StringUtils.isBlank(topicItem) || StringUtils.isBlank(doctor)) {
                return new PageEnvelop();
            }
            String categoryCode ="";
            switch (topicItem){
            String categoryCode = "";
            switch (topicItem) {
                case "preventLost":
                    categoryCode="'4'";
                    categoryCode = "'4'";
                    break;
                case "preventFall":
                    categoryCode="'12'";
                    categoryCode = "'12'";
                    break;
                case "preventFire":
                    categoryCode="'15'";
                    categoryCode = "'15'";
                    break;
                case "preventGasLeakage":
                    categoryCode="'14'";
                    categoryCode = "'14'";
                    break;
                case "preventOutOfBed":
                    categoryCode="'13'";
                    categoryCode = "'13'";
                    break;
            }
            if (StringUtils.isNotBlank(doctor)){//日常监护医生必传
            if (StringUtils.isNotBlank(doctor)) {//日常监护医生必传
                fliter += " and EXISTS( SELECT DISTINCT p.id,p.name,p.residential_area residentialArea,p.photo,p.idcard,p.mobile, " +
                        " p.openid,p.sex,p.pad_imei padImei " +
                        " from base_patient p , base_service_package_sign_record sr,base_service_package_record r,base_team_member m  " +
                        " WHERE p.id = sr.patient and sr.status=1 and m.team_code = r.team_code and sr.id=r.sign_id  " +
                        " and m.doctor_code = '"+doctor+"' and m.del = '1' ) ";
                        " and m.doctor_code = '" + doctor + "' and m.del = '1' ) ";
                fliter +=" and EXISTS (select 1 from wlyy_patient_device pd INNER JOIN dm_device dd on pd.device_id = dd.id  " +
                        " where  pd.user = p.id and pd.del=0 and pd.category_code in ("+categoryCode+") and FIND_IN_SET('"+topicItem+"',dd.service_topic)) ";
                fliter += " and EXISTS (select 1 from wlyy_patient_device pd INNER JOIN dm_device dd on pd.device_id = dd.id  " +
                        " where  pd.user = p.id and pd.del=0 and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItem + "',dd.service_topic)) ";
                if ("preventLost".equals(topicItem)){//有绑定围栏的居民
                if ("preventLost".equals(topicItem)) {//有绑定围栏的居民
                    fliter += " and EXISTS (select 1 from wlyy_patient_safe_area sf where sf.patient = p.id and sf.del=1 and sf.manage_status=1) ";
                }
            }
        }else {
            if (StringUtils.isNotBlank(doctor)){
                fliter+=" and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i ," +
        } else {
            if (StringUtils.isNotBlank(doctor)) {
                fliter += " and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i ," +
                        "base_team_member m " +
                        "where ord.patient = CONVERT(sr.patient USING utf8) and  sr.id = r.sign_id and sr.status=1 and " +
                        " r.service_package_id = i.service_package_id and  m.team_code = r.team_code  and i.del = 1 and sr.`status`=1  and m.doctor_code = '"+doctor+"' and m.del = '1') ";
                        " r.service_package_id = i.service_package_id and  m.team_code = r.team_code  and i.del = 1 and sr.`status`=1  and m.doctor_code = '" + doctor + "' and m.del = '1') ";
            }
        }
        if (StringUtils.isNotBlank(serverDoctor)){
            fliter +=" and ord.doctor = '"+serverDoctor+"' ";
        if (StringUtils.isNotBlank(serverDoctor)) {
            fliter += " and ord.doctor = '" + serverDoctor + "' ";
        }
        if (StringUtils.isNotBlank(patientName)){
            fliter+=" and (ord.patient_name like '%"+patientName+"%' or p.idcard='"+patientName+"')  ";
        if (StringUtils.isNotBlank(patientName)) {
            fliter += " and (ord.patient_name like '%" + patientName + "%' or p.idcard='" + patientName + "')  ";
        }
        if (StringUtils.isNotBlank(patient)){
            fliter+=" and ord.patient='"+patient+"' ";
        if (StringUtils.isNotBlank(patient)) {
            fliter += " and ord.patient='" + patient + "' ";
        }
        if (StringUtils.isNotBlank(status)){
            fliter+=" and ord.status='"+Integer.parseInt(status)+"' ";
        if (StringUtils.isNotBlank(status)) {
            fliter += " and ord.status='" + Integer.parseInt(status) + "' ";
        }
        if (StringUtils.isNotBlank(svrDesc)){
            fliter+=" and ord.serve_desc='"+svrDesc+"' ";
        if (StringUtils.isNotBlank(svrDesc)) {
            fliter += " and ord.serve_desc='" + svrDesc + "' ";
        }
        if (StringUtils.isNotBlank(topicItem)){
            fliter+=" and ord.topic_item='"+topicItem+"' ";
        if (StringUtils.isNotBlank(topicItem)) {
            fliter += " and ord.topic_item='" + topicItem + "' ";
        }
        Long count = jdbcTemplate.queryForObject(sqlCount+fliter,Long.class);
        fliter+=" order by ord.create_time desc limit " + (page*pageSize) + "," + pageSize;
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql+fliter);
        Long count = jdbcTemplate.queryForObject(sqlCount + fliter, Long.class);
        fliter += " order by ord.create_time desc limit " + (page * pageSize) + "," + pageSize;
        List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql + fliter);
        for (Map<String,Object>one:sqlResult){
        for (Map<String, Object> one : sqlResult) {
            JSONObject tmp = new JSONObject();
            tmp.put("patientCode",one.get("patientCode"));
            tmp.put("patientName",one.get("name"));
            tmp.put("sex",one.get("sex"));
            tmp.put("photo",one.get("photo"));
            tmp.put("idcard",one.get("idcard"));
            tmp.put("number",one.get("number"));
            tmp.put("id",one.get("orderId"));
            tmp.put("serveDesc",one.get("serve_desc"));
            Date date = (Date)one.get("create_time");
            tmp.put("patientCode", one.get("patientCode"));
            tmp.put("patientName", one.get("name"));
            tmp.put("sex", one.get("sex"));
            tmp.put("photo", one.get("photo"));
            tmp.put("idcard", one.get("idcard"));
            tmp.put("number", one.get("number"));
            tmp.put("id", one.get("orderId"));
            tmp.put("serveDesc", one.get("serve_desc"));
            Date date = (Date) one.get("create_time");
            tmp.put("createTime", DateUtil.dateToStrLong(date));
            tmp.put("status",one.get("status"));
            tmp.put("doctor",one.get("doctor"));
            tmp.put("doctorName",one.get("doctor_name"));
            tmp.put("patientPhone",one.get("patient_phone"));
            tmp.put("conclusionStatus",one.get("conclusion_status"));
            Integer conclusionStatus = Integer.valueOf(one.get("conclusion_status")==null?"0":(one.get("conclusion_status")+""));
            tmp.put("status", one.get("status"));
            tmp.put("doctor", one.get("doctor"));
            tmp.put("doctorName", one.get("doctor_name"));
            tmp.put("patientPhone", one.get("patient_phone"));
            tmp.put("conclusionStatus", one.get("conclusion_status"));
            Integer conclusionStatus = Integer.valueOf(one.get("conclusion_status") == null ? "0" : (one.get("conclusion_status") + ""));
            String conclusionStatusName = "";
            switch (conclusionStatus){
                case 1:conclusionStatusName="待补录";break;
                case 2:conclusionStatusName="已登记";break;
            switch (conclusionStatus) {
                case 1:
                    conclusionStatusName = "待补录";
                    break;
                case 2:
                    conclusionStatusName = "已登记";
                    break;
            }
            tmp.put("conclusionStatusName",conclusionStatusName);
            Integer statustemp = Integer.valueOf(one.get("status")+"");
            if (-2==statustemp||-1==statustemp){
                tmp.put("doctor",one.get("update_user"));
                tmp.put("doctorName",one.get("update_user_name"));
            tmp.put("conclusionStatusName", conclusionStatusName);
            Integer statustemp = Integer.valueOf(one.get("status") + "");
            if (-2 == statustemp || -1 == statustemp) {
                tmp.put("doctor", one.get("update_user"));
                tmp.put("doctorName", one.get("update_user_name"));
            }
            String statusName = "";
            switch (statustemp){
                case -2:statusName="误警报";break;
                case -1:statusName="已取消";break;
                case 0:statusName="已完成";break;
                case 1:statusName="预警中";break;
            switch (statustemp) {
                case -2:
                    statusName = "误警报";
                    break;
                case -1:
                    statusName = "已取消";
                    break;
                case 0:
                    statusName = "已完成";
                    break;
                case 1:
                    statusName = "预警中";
                    break;
            }
            tmp.put("statusName",statusName);
            Integer age  = IdCardUtil.getAgeForIdcard(tmp.getString("idcard"));
            tmp.put("age",age);
            tmp.put("statusName", statusName);
            Integer age = IdCardUtil.getAgeForIdcard(tmp.getString("idcard"));
            tmp.put("age", age);
            //患者设备
            List<DevicePatientDevice> devices = patientDeviceDao.findAllByUser(tmp.get("patientCode").toString());
            if (devices.size()>0){
                tmp.put("deviceFlag","1");
            }
            else {
                tmp.put("deviceFlag","0");
            if (devices.size() > 0) {
                tmp.put("deviceFlag", "1");
            } else {
                tmp.put("deviceFlag", "0");
            }
            result.add(tmp);
        }
        return PageEnvelop.getSuccessListWithPage("success",result,page,pageSize,count);
        return PageEnvelop.getSuccessListWithPage("success", result, page, pageSize, count);
    }
    public JSONObject getSecurityTab(String patient,String doctor,String status,String svrDesc,String topicItem,Integer dailyMonitor){
    public JSONObject getSecurityTab(String patient, String doctor, String status, String svrDesc, String topicItem, Integer dailyMonitor) {
        JSONObject result = new JSONObject();
        result.put("status_-2",0);//误报警
        result.put("status_-1",0);//已取消
        result.put("status_0",0);//已完成
        result.put("status_1",0);//预警中
        result.put("status_all",0);//
        result.put("svr_all",0);//
        result.put("status_-2", 0);//误报警
        result.put("status_-1", 0);//已取消
        result.put("status_0", 0);//已完成
        result.put("status_1", 0);//预警中
        result.put("status_all", 0);//
        result.put("svr_all", 0);//
        Map<String,String> serverTmp = new HashMap<>();
        Map<String, String> serverTmp = new HashMap<>();
        String sql = " select py_code,dict_value from wlyy_hospital_sys_dict where dict_name='security_server_dict' ";
        List<Map<String,Object>> servers = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> server:servers){
            result.put("svr_"+server.get("py_code").toString(),0);
            serverTmp.put(server.get("dict_value").toString(),server.get("py_code").toString());
        List<Map<String, Object>> servers = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> server : servers) {
            result.put("svr_" + server.get("py_code").toString(), 0);
            serverTmp.put(server.get("dict_value").toString(), server.get("py_code").toString());
        }
        sql = "select ord.status,ord.serve_desc,count(ord.id) count from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
                "where 1=1 ";
        String fliter = "  ";
        if (1==dailyMonitor){//医生日常监护居民安防工单列表查询
            if (StringUtils.isBlank(topicItem)||StringUtils.isBlank(doctor)){
        if (1 == dailyMonitor) {//医生日常监护居民安防工单列表查询
            if (StringUtils.isBlank(topicItem) || StringUtils.isBlank(doctor)) {
                return result;
            }
            String categoryCode ="";
            switch (topicItem){
            String categoryCode = "";
            switch (topicItem) {
                case "preventLost":
                    categoryCode="'4'";
                    categoryCode = "'4'";
                    break;
                case "preventFall":
                    categoryCode="'12'";
                    categoryCode = "'12'";
                    break;
                case "preventFire":
                    categoryCode="'15'";
                    categoryCode = "'15'";
                    break;
                case "preventGasLeakage":
                    categoryCode="'14'";
                    categoryCode = "'14'";
                    break;
                case "preventOutOfBed":
                    categoryCode="'13'";
                    categoryCode = "'13'";
                    break;
            }
            if (StringUtils.isNotBlank(doctor)) {//日常监护医生必传
@ -853,59 +874,58 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                    fliter += " and EXISTS (select 1 from wlyy_patient_safe_area sf where sf.patient = p.id and sf.del=1 and sf.manage_status=1) ";
                }
            }
        }else {
            if (StringUtils.isNotBlank(doctor)){
                fliter+=" and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i ," +
        } else {
            if (StringUtils.isNotBlank(doctor)) {
                fliter += " and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i ," +
                        "base_team_member m " +
                        "where ord.patient = CONVERT(sr.patient USING utf8) and  sr.id = r.sign_id and sr.status=1 and " +
                        " r.service_package_id = i.service_package_id and  m.team_code = r.team_code  and i.del = 1 and sr.`status`=1  and m.doctor_code = '"+doctor+"' and m.del = '1') ";
                        " r.service_package_id = i.service_package_id and  m.team_code = r.team_code  and i.del = 1 and sr.`status`=1  and m.doctor_code = '" + doctor + "' and m.del = '1') ";
            }
        }
        if (StringUtils.isNotBlank(patient)){
            fliter+=" and ord.patient='"+patient+"' ";
        if (StringUtils.isNotBlank(patient)) {
            fliter += " and ord.patient='" + patient + "' ";
        }
        if (StringUtils.isNotBlank(status)){
            fliter+=" and ord.status='"+Integer.parseInt(status)+"' ";
        if (StringUtils.isNotBlank(status)) {
            fliter += " and ord.status='" + Integer.parseInt(status) + "' ";
        }
        if (StringUtils.isNotBlank(svrDesc)){
            fliter+=" and ord.serve_desc='"+svrDesc+"' ";
        if (StringUtils.isNotBlank(svrDesc)) {
            fliter += " and ord.serve_desc='" + svrDesc + "' ";
        }
        if (StringUtils.isNotBlank(topicItem)){
            fliter+=" and ord.topic_item='"+topicItem+"' ";
        if (StringUtils.isNotBlank(topicItem)) {
            fliter += " and ord.topic_item='" + topicItem + "' ";
        }
        fliter+=" group by ord.status,ord.serve_desc ";
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql+fliter);
        fliter += " group by ord.status,ord.serve_desc ";
        List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql + fliter);
        String pyCode = "";
        for (Map<String,Object> map:sqlResult){
            result.put("status_"+map.get("status"),result.getInteger("status_"+map.get("status"))+Integer.parseInt(map.get("count").toString()));
            pyCode =  serverTmp.get(map.get("serve_desc"))==null?null:serverTmp.get(map.get("serve_desc")).toString();
            if (StringUtils.isNotBlank(pyCode)){
                result.put("svr_"+pyCode,result.getInteger("svr_"+pyCode)+Integer.parseInt(map.get("count").toString()));
                result.put("status_all",result.getInteger("status_all")+Integer.parseInt(map.get("count").toString()));
                result.put("svr_all",result.getInteger("svr_all")+Integer.parseInt(map.get("count").toString()));
        for (Map<String, Object> map : sqlResult) {
            result.put("status_" + map.get("status"), result.getInteger("status_" + map.get("status")) + Integer.parseInt(map.get("count").toString()));
            pyCode = serverTmp.get(map.get("serve_desc")) == null ? null : serverTmp.get(map.get("serve_desc")).toString();
            if (StringUtils.isNotBlank(pyCode)) {
                result.put("svr_" + pyCode, result.getInteger("svr_" + pyCode) + Integer.parseInt(map.get("count").toString()));
                result.put("status_all", result.getInteger("status_all") + Integer.parseInt(map.get("count").toString()));
                result.put("svr_all", result.getInteger("svr_all") + Integer.parseInt(map.get("count").toString()));
            }
        }
        return result;
    }
    public List<Map<String,Object>> getSecurityOrderUnCompleteList(String doctor){
        List<Map<String,Object>> result = new ArrayList<>();
    public List<Map<String, Object>> getSecurityOrderUnCompleteList(String doctor) {
        List<Map<String, Object>> result = new ArrayList<>();
        String sql = " select p.id patientCode,p.name,p.sex,p.idcard,p.photo,ord.id orderId,ord.number,ord.serve_desc,DATE_FORMAT(ord.create_time,'%Y-%m-%d %H:%i:%S') create_time,ord.`status`,ord.doctor," +
                "ord.doctor_name,ord.patient_phone,ord.conclusion_status from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
                "where ord.status <>-1 and ord.status<>0  ";
        sql+= "and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i ," +
        sql += "and  EXISTS ( SELECT 1 from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i ," +
                "base_team_member m " +
                "where ord.patient = CONVERT(sr.patient USING utf8) and  sr.id = r.sign_id and sr.status=1 and " +
                " r.service_package_id = i.service_package_id and  m.team_code = r.team_code  and i.del = 1 and sr.`status`=1  and i.code='preventLost' and m.doctor_code = '"+doctor+"' and m.del = '1') ";
        sql +=" order by ord.create_time asc ";
        result= jdbcTemplate.queryForList(sql);
        for (Map<String,Object> map:result){
            if (map.get("idcard")==null){
                map.put("age",null);
            }
            else{
                Integer age  = IdCardUtil.getAgeForIdcard(map.get("idcard").toString());
                map.put("age",age);
                " r.service_package_id = i.service_package_id and  m.team_code = r.team_code  and i.del = 1 and sr.`status`=1  and i.code='preventLost' and m.doctor_code = '" + doctor + "' and m.del = '1') ";
        sql += " order by ord.create_time asc ";
        result = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : result) {
            if (map.get("idcard") == null) {
                map.put("age", null);
            } else {
                Integer age = IdCardUtil.getAgeForIdcard(map.get("idcard").toString());
                map.put("age", age);
            }
        }
@ -913,9 +933,9 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
    }
    /**
     * 系统更新医生工单状态
     *
     * @param doctor
     * @param dispatchOrderStatus
     */
@ -937,7 +957,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        doctorStatusDao.save(doctorSwitch);
    }
    public SecurityMonitoringOrderDO acceptOrder1(String orderId,String doctor) throws Exception{
    public SecurityMonitoringOrderDO acceptOrder1(String orderId, String doctor) throws Exception {
        SecurityMonitoringOrderDO doorServiceOrder = securityMonitoringOrderDao.findOne(orderId);
        if (null == doorServiceOrder) {
            throw new Exception("该工单不存在");
@ -948,9 +968,9 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        securityMonitoringOrderDao.save(doorServiceOrder);
        systemMessageDao.orderMessageDelByType(doorServiceOrder.getDoctor(),orderId,"607");
        systemMessageDao.orderMessageDelByType(doorServiceOrder.getDoctor(), orderId, "607");
        if(doorServiceOrder.getType() == null|| doorServiceOrder.getType() != 3) {
        if (doorServiceOrder.getType() == null || doorServiceOrder.getType() != 3) {
//            //获取咨询
//            ConsultTeam consultTeam = consultTeamDao.queryByRelationCode(orderId);
@ -976,10 +996,11 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
    /**
     * 接单
     *
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject acceptOrder(String orderId,String doctor) throws Exception {
    public JSONObject acceptOrder(String orderId, String doctor) throws Exception {
//        JSONObject result = new JSONObject();
//        SecurityMonitoringOrderDO doorServiceOrderDO = securityMonitoringOrderDao.findOne(orderId);
//        if(null == doorServiceOrderDO){
@ -1062,21 +1083,22 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        //  待接单消息设为已操作, 434 医生接单-- 王五接受了服务工单12345678
//        messageUtil.createMessage("医生接单","634",doorServiceOrder.getPatient(),doorServiceOrder.getPatientName(),
//                doorServiceOrder.getId(), doorServiceOrder.getDoctor(),doorServiceOrder.getDoctorName() ,null, doorServiceOrder.getDoctorName() + "接受了服务工单"+ doorServiceOrder.getNumber());
        return getSecurityOrderDetail(orderId,null);
        return getSecurityOrderDetail(orderId, null);
    }
    /**
     * 取消工单
     *
     * @param orderId
     * @param reason
     * @return
     */
    public JSONObject cancelOrder(String orderId,int type,String reason,String doctor){
    public JSONObject cancelOrder(String orderId, int type, String reason, String doctor) {
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO orderDO = securityMonitoringOrderDao.findOne(orderId);
        if(null == orderDO){
            String failMsg = "【取消工单】该工单不存在" ;
        if (null == orderDO) {
            String failMsg = "【取消工单】该工单不存在";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
@ -1084,24 +1106,24 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        }
        //接单前可取消工单
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        if (doctorDO==null){
        if (doctorDO == null) {
            String failMsg = "【取消工单】操作医生不存在";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        if(orderDO.getStatus() == SecurityMonitoringOrderDO.Status.complete.getType()){
        if (orderDO.getStatus() == SecurityMonitoringOrderDO.Status.complete.getType()) {
            String failMsg = "当前工单已结束";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            logger.error(failMsg);
            return result;
        }
        if (!consultTeamService.finishConsult(orderDO.getId(),orderDO.getPatient(),orderDO.getPatient(),1)){
        if (!consultTeamService.finishConsult(orderDO.getId(), orderDO.getPatient(), orderDO.getPatient(), 1)) {
            String failMsg = "咨询结束失败 无法取消工单";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
@ -1113,8 +1135,8 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        orderDO.setStatus(SecurityMonitoringOrderDO.Status.cancel.getType());
        this.save(orderDO);
       if(type == SecurityMonitoringOrderDO.CancelType.patient.getType()){                   //居民取消,消息列表也应该不显示
           messageUtil.updateSecurityMonitoringOrderMessage(orderDO,new String[]{"602","603"},"patientCancel");
        if (type == SecurityMonitoringOrderDO.CancelType.patient.getType()) {                   //居民取消,消息列表也应该不显示
            messageUtil.updateSecurityMonitoringOrderMessage(orderDO, new String[]{"602", "603"}, "patientCancel");
        }
        //保存取消记录
@ -1128,40 +1150,40 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        //完成工单向pc管理端发送消息
        JSONObject message = new JSONObject();
        String latLon = orderDO.getServeLat()+","+orderDO.getServeLon();
        message.put("latLon",latLon);
        message.put("session_id",orderDO.getSessionId());
        message.put("sender_name",orderDO.getPatientName());
        message.put("content_notice","完成安防服务工单");
        message.put("sender_code",orderDO.getPatient());
        message.put("OrderType",22);
        message.put("OrderStatus","finish");
        message.put("order_id",orderDO.getId());
        message.put("content_type",40);
        message.put("serverDesc",orderDO.getServeDesc());
        message.put("categoryCode","");
        message.put("orgType","");
        message.put("contactStatus","");
        message.put("residentialArea","");
        if (null!=orderDO.getDeviceSn()){
        String latLon = orderDO.getServeLat() + "," + orderDO.getServeLon();
        message.put("latLon", latLon);
        message.put("session_id", orderDO.getSessionId());
        message.put("sender_name", orderDO.getPatientName());
        message.put("content_notice", "完成安防服务工单");
        message.put("sender_code", orderDO.getPatient());
        message.put("OrderType", 22);
        message.put("OrderStatus", "finish");
        message.put("order_id", orderDO.getId());
        message.put("content_type", 40);
        message.put("serverDesc", orderDO.getServeDesc());
        message.put("categoryCode", "");
        message.put("orgType", "");
        message.put("contactStatus", "");
        message.put("residentialArea", "");
        if (null != orderDO.getDeviceSn()) {
            String device_sn = orderDO.getDeviceSn();
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)){
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)) {
                DeviceDetail deviceDetail = deviceDetailDao.findBySn(device_sn);
                if (null!=deviceDetail){
                    message.put("contactStatus",deviceDetail.getContactStatus());
                    message.put("categoryCode",deviceDetail.getCategoryCode());
                if (null != deviceDetail) {
                    message.put("contactStatus", deviceDetail.getContactStatus());
                    message.put("categoryCode", deviceDetail.getCategoryCode());
                }
            }
        }
        String orgCode = orderDO.getHospital();
        BaseOrgDO orgDO = orgDao.findByCode(orgCode);
        if (null!=orgDO){
            message.put("orgType",orgDO.getType());
        if (null != orgDO) {
            message.put("orgType", orgDO.getType());
        }
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage",message.toString());
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage", message.toString());
//        Consult consult = consultDao.queryByRelationCode(orderId);
//        // 发送微信模板消息,通知居民工单已取消(smyyyqx-上门预约已取消)
//
@ -1181,12 +1203,13 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
//        }
//        pushMsgTask.putWxMsg(tokenUtils.getAccessToken(), 30, patient.getOpenid(), patient.getName(), json);
        result = getSecurityOrderDetail(orderId,null);
        result = getSecurityOrderDetail(orderId, null);
        return result;
    }
    /**
     * 签到保存
     *
     * @param orderId
     * @param signTime
     * @param signWay
@ -1195,7 +1218,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
     * @return
     */
    public JSONObject signIn(String orderId, String signTime, Integer signWay, String signLocation,
                                         String signImg, String twoDimensionalCode,String doctorId) throws Exception {
                             String signImg, String twoDimensionalCode, String doctorId) throws Exception {
       /* SecurityMonitoringOrderDO doorServiceOrder = securityMonitoringOrderDao.findOne(orderId);
        doorServiceOrder.setDoctorSignTime(DateUtil.strToDate(signTime));
        doorServiceOrder.setDoctorSignWay(signWay);
@ -1223,11 +1246,12 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
            return getSecurityOrderDetail(orderId);
        }*/
        return getSecurityOrderDetail(orderId,null);
        return getSecurityOrderDetail(orderId, null);
    }
    /**
     * 根据接单医生code获取最近一次服务orderId
     *
     * @param doctor
     * @return
     */
@ -1239,31 +1263,32 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
    /**
     * 编辑保存服务工单小结
     *
     * @return
     * @throws Exception
     */
    public JSONObject updateDoorConclusion(Integer emergency_reason,Integer treatment_status,String orderId,String conclusion,String conclusion_img,String doctor) throws Exception {
    public JSONObject updateDoorConclusion(Integer emergency_reason, Integer treatment_status, String orderId, String conclusion, String conclusion_img, String doctor) throws Exception {
        JSONObject result = new JSONObject();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        if (StringUtils.isNotBlank(doctor)){
        if (StringUtils.isNotBlank(doctor)) {
            BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
            if (doctorDO!=null){
            if (doctorDO != null) {
                one.setDoctor(doctor);
                one.setDoctorName(doctorDO.getName());
                one.setUpdateUser(doctor);
                one.setUpdateUserName(doctorDO.getName());
            }
        }
        if (one==null){
            String failMsg = "工单不存在" ;
        if (one == null) {
            String failMsg = "工单不存在";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            return result;
        }
        EmergencyWarnConclusionDO doorConclusion =  emergencyWarnConclusionDao.findByOrderId(orderId);
        if (doorConclusion==null){
        EmergencyWarnConclusionDO doorConclusion = emergencyWarnConclusionDao.findByOrderId(orderId);
        if (doorConclusion == null) {
            doorConclusion = new EmergencyWarnConclusionDO();
            doorConclusion.setOrderId(orderId);
            doorConclusion.setPatient(one.getPatient());
@ -1286,7 +1311,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
            doorConclusion.setCreateUser(one.getDoctor());
            doorConclusion.setCreateUserName(null != doctorVO ? doctorVO.getName() : null);
        }
        if (!consultTeamService.finishConsult(one.getId(),one.getPatient(),one.getPatient(),1)){
        if (!consultTeamService.finishConsult(one.getId(), one.getPatient(), one.getPatient(), 1)) {
            String failMsg = "咨询结束失败 无法结束工单";
            throw new Exception(failMsg);
        }
@ -1297,66 +1322,67 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        //完成工单向pc管理端发送消息
        JSONObject message = new JSONObject();
        String latLon = one.getServeLat()+","+one.getServeLon();
        message.put("latLon",latLon);
        message.put("session_id",one.getSessionId());
        message.put("sender_name",one.getPatientName());
        message.put("content_notice","完成安防服务工单");
        message.put("sender_code",one.getPatient());
        message.put("OrderType",22);
        message.put("OrderStatus","finish");
        message.put("order_id",one.getId());
        message.put("content_type",40);
        message.put("serverDesc",one.getServeDesc());
        message.put("categoryCode","");
        message.put("orgType","");
        message.put("contactStatus","");
        message.put("residentialArea","");
        if (null!=one.getDeviceSn()){
        String latLon = one.getServeLat() + "," + one.getServeLon();
        message.put("latLon", latLon);
        message.put("session_id", one.getSessionId());
        message.put("sender_name", one.getPatientName());
        message.put("content_notice", "完成安防服务工单");
        message.put("sender_code", one.getPatient());
        message.put("OrderType", 22);
        message.put("OrderStatus", "finish");
        message.put("order_id", one.getId());
        message.put("content_type", 40);
        message.put("serverDesc", one.getServeDesc());
        message.put("categoryCode", "");
        message.put("orgType", "");
        message.put("contactStatus", "");
        message.put("residentialArea", "");
        if (null != one.getDeviceSn()) {
            String device_sn = one.getDeviceSn();
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)){
            if (org.apache.commons.lang.StringUtils.isNotBlank(device_sn)) {
                DeviceDetail deviceDetail = deviceDetailDao.findBySn(device_sn);
                if (null!=deviceDetail){
                    message.put("contactStatus",deviceDetail.getContactStatus());
                    message.put("categoryCode",deviceDetail.getCategoryCode());
                if (null != deviceDetail) {
                    message.put("contactStatus", deviceDetail.getContactStatus());
                    message.put("categoryCode", deviceDetail.getCategoryCode());
                }
            }
        }
        String orgCode = one.getHospital();
        BaseOrgDO orgDO = orgDao.findByCode(orgCode);
        if (null!=orgDO){
            message.put("orgType",orgDO.getType());
        if (null != orgDO) {
            message.put("orgType", orgDO.getType());
        }
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage",message.toString());
        return getSecurityOrderDetail(orderId,null);
        imUtil.sendPcManageMessageToPc("cloudCare_pcManage", message.toString());
        return getSecurityOrderDetail(orderId, null);
    }
    /**
     * 跳过登记服务小结
     *
     * @param orderId
     */
    public JSONObject cancelConclusion(String orderId,String doctor) throws Exception {
    public JSONObject cancelConclusion(String orderId, String doctor) throws Exception {
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        if (StringUtils.isNotBlank(doctor)){
        if (StringUtils.isNotBlank(doctor)) {
            BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
            if (doctorDO!=null){
            if (doctorDO != null) {
                one.setDoctor(doctor);
                one.setDoctorName(doctorDO.getName());
                one.setUpdateUser(doctor);
                one.setUpdateUserName(doctorDO.getName());
            }
        }
        if (one==null){
            String failMsg = "工单不存在" ;
        if (one == null) {
            String failMsg = "工单不存在";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            return result;
        }
        if (!consultTeamService.finishConsult(one.getId(),one.getPatient(),one.getPatient(),1)){
        if (!consultTeamService.finishConsult(one.getId(), one.getPatient(), one.getPatient(), 1)) {
            String failMsg = "咨询结束失败 无法结束工单";
            throw new Exception(failMsg);
        }
@ -1364,44 +1390,46 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        one.setUpdateTime(new Date());
        securityMonitoringOrderDao.save(one);
        return getSecurityOrderDetail(orderId,null);
        return getSecurityOrderDetail(orderId, null);
    }
    /**
     * 统计居民已经服务的次数
     *
     * @param patient
     * @return
     */
    public Integer countPatientDoorTimes(String patient){
    public Integer countPatientDoorTimes(String patient) {
        Integer count = 0;
        String sql = "SELECT count(o.id) as count FROM base_security_monitoring_order o  where  o.patient = '" + patient + "' and status>3 ";
        count = jdbcTemplate.queryForObject(sql,Integer.class);
        count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }
    /**
     * 根据orderId获取工单服务小结
     *
     * @param orderId
     * @return
     */
    public EmergencyWarnConclusionDO getDoorConclusion(String orderId){
    public EmergencyWarnConclusionDO getDoorConclusion(String orderId) {
        EmergencyWarnConclusionDO doorConclusion = emergencyWarnConclusionDao.findByOrderId(orderId);
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        if (doorConclusion==null&&one!=null) {
        if (doorConclusion == null && one != null) {
            doorConclusion = new EmergencyWarnConclusionDO();
            doorConclusion.setOrderId(one.getId());
            doorConclusion.setPatient(one.getPatient());
            doorConclusion.setPatientName(one.getPatientName());
            doorConclusion.setDoctor(one.getDoctor());
            doorConclusion.setDoctorName(one.getDoctorName());
        }else {
            doorConclusion.setReasonName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_REASON,String.valueOf(doorConclusion.getEmergencyReason())));
            doorConclusion.setTreatmentStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_TREATMENT_STATUS,String.valueOf(doorConclusion.getEmergencyTreatmentStatus())));
        } else {
            doorConclusion.setReasonName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_REASON, String.valueOf(doorConclusion.getEmergencyReason())));
            doorConclusion.setTreatmentStatusName(dictService.fingByNameAndCode(ConstantUtil.DICT_EMERGENCY_TREATMENT_STATUS, String.valueOf(doorConclusion.getEmergencyTreatmentStatus())));
        }
        return doorConclusion;
    }
    public JSONObject saveOrderFinishBydoctor(String orderId ,String finishImg) throws Exception {
    public JSONObject saveOrderFinishBydoctor(String orderId, String finishImg) throws Exception {
//        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
//        one.setDoctorConfirmFinishImg(finishImg);
//        one.setStatus(SecurityMonitoringOrderDO.Status.complete.getType());
@ -1419,11 +1447,12 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
//        // 发送微信通知  待付款
//        BasePatientDO patient = basePatientDao.findById(one.getPatient());
        return getSecurityOrderDetail(orderId,null);
        return getSecurityOrderDetail(orderId, null);
    }
    /**
     * 根据id获取服务工单信息
     *
     * @param id
     * @return
     */
@ -1435,7 +1464,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        BasePatientDO patient = basePatientDao.findById(doorServiceOrder.getPatient());
        if (patient != null) {
            String sex = IdCardUtil.getSexForIdcard_new(patient.getIdcard());
            int age = IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday());
            int age = IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(), patient.getBirthday());
            doorServiceOrder.setSex("1".equals(sex) ? "男" : "2".equals(sex) ? "女" : "未知");
            doorServiceOrder.setAge(age);
            doorServiceOrder.setPhoto(patient.getPhoto());
@ -1455,261 +1484,261 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        return doorServiceOrder;
    }
    public List<Map<String,Object>> getSecurityServerDoctor(String patient,String topicItem){
    public List<Map<String, Object>> getSecurityServerDoctor(String patient, String topicItem) {
        //获取患者签约防走失服务的团队
        String sql="SELECT DISTINCT r.team_code from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i  \n" +
        String sql = "SELECT DISTINCT r.team_code from base_service_package_sign_record sr,base_service_package_record r, base_service_package_item i  \n" +
                "where  sr.id = r.sign_id and sr.status=1 and r.service_package_id = i.service_package_id   and i.del = 1 and sr.`status`=1 \n" +
                "and  sr.patient  = '"+patient+"' and i.code='"+topicItem+"'";
        List<String> teams = jdbcTemplate.queryForList(sql,String.class);
        List<Map<String,Object>> result = new ArrayList<>();
        if (teams.size()==0){
                "and  sr.patient  = '" + patient + "' and i.code='" + topicItem + "'";
        List<String> teams = jdbcTemplate.queryForList(sql, String.class);
        List<Map<String, Object>> result = new ArrayList<>();
        if (teams.size() == 0) {
            return new ArrayList<>();
        }else {
            for (String team:teams){
        } else {
            for (String team : teams) {
                sql = "select DISTINCT doc.id doctor,doc.name as doctorName,CONCAT(doc.`name`,\n" +
                        "CASE WHEN doc.doctor_level=1 THEN '(社区医生)' ELSE '(社工)' END) as name,doc.photo,doc.mobile from base_team_member mem " +
                        "INNER JOIN base_doctor doc on mem.doctor_code = doc.id and mem.del=1 and mem.team_code='"+team+"'";
                List<Map<String,Object>>tmp = jdbcTemplate.queryForList(sql);
                        "INNER JOIN base_doctor doc on mem.doctor_code = doc.id and mem.del=1 and mem.team_code='" + team + "'";
                List<Map<String, Object>> tmp = jdbcTemplate.queryForList(sql);
                result.addAll(tmp);
            }
        }
        return result;
    }
    public JSONObject patientMonitoringInfo(String patient,String topicItem,boolean video){
    public JSONObject patientMonitoringInfo(String patient, String topicItem,String deviceSn,boolean video) {
        JSONObject result = new JSONObject();
        result.put("location",null);
        result.put("fences",null);
        result.put("gasLeakage",null);
        result.put("fire",null);
        result.put("fall",null);
        result.put("sleep",null);
        result.put("sleepOrderInfo",null);//最近工单
        result.put("deviceSn",null);
        result.put("emeAssistance",false);
        result.put("monitorInfo",null);
        result.put("location", null);
        result.put("fences", null);
        result.put("gasLeakage", null);
        result.put("fire", null);
        result.put("fall", null);
        result.put("sleep", null);
        result.put("sleepOrderInfo", null);//最近工单
        result.put("deviceSn", deviceSn);
        result.put("emeAssistance", false);
        result.put("monitorInfo", null);
        String sql = " select dict.code,count(ord.id) total from base_system_dict_entry dict LEFT JOIN base_security_monitoring_order ord " +
                " on dict.code = ord.topic_item COLLATE utf8_unicode_ci and ord.status="+SecurityMonitoringOrderDO.Status.apply.getType()+" where dict.dict_code='service_item' " +
                "and dict.remark='security' and ord.patient='"+patient+"' GROUP BY dict.code ";
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql);
        for (Map<String,Object>tmp:sqlResult){
            switch (tmp.get("code").toString()){
                " on dict.code = ord.topic_item COLLATE utf8_unicode_ci and ord.status=" + SecurityMonitoringOrderDO.Status.apply.getType() + " where dict.dict_code='service_item' " +
                "and dict.remark='security' and ord.patient='" + patient + "' GROUP BY dict.code ";
        List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> tmp : sqlResult) {
            switch (tmp.get("code").toString()) {
                case "preventGasLeakage":
                   Integer count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("gasLeakage",true);
                    }else {
                        result.put("gasLeakage",false);
                    Integer count = Integer.parseInt(tmp.get("total").toString());
                    if (count > 0) {
                        result.put("gasLeakage", true);
                    } else {
                        result.put("gasLeakage", false);
                    }
                    break;
                case "preventFire":
                    count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("fire",true);
                    }else {
                        result.put("fire",false);
                    if (count > 0) {
                        result.put("fire", true);
                    } else {
                        result.put("fire", false);
                    }
                    break;
                case "preventFall":
                    count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("fall",true);
                    }else {
                        result.put("fall",false);
                    if (count > 0) {
                        result.put("fall", true);
                    } else {
                        result.put("fall", false);
                    }
                    break;
                case "preventOutOfBed":
                    count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("sleep",true);
                    if (count > 0) {
                        result.put("sleep", true);
                        sql = " select serve_desc from base_security_monitoring_order where topic_item='preventOutOfBed' " +
                                "and patient='"+patient+"' and `status`=1 order by create_time desc limit 1 ";
                        List<String> serveDesces = jdbcTemplate.queryForList(sql,String.class);
                        if (serveDesces.size()>0){
                            result.put("sleepOrderInfo",serveDesces.get(0));
                                "and patient='" + patient + "' and `status`=1 order by create_time desc limit 1 ";
                        List<String> serveDesces = jdbcTemplate.queryForList(sql, String.class);
                        if (serveDesces.size() > 0) {
                            result.put("sleepOrderInfo", serveDesces.get(0));
                        }
                    }else {
                        result.put("sleep",false);
                    } else {
                        result.put("sleep", false);
                    }
                    break;
            }
        }
        sql = " select count(id) from base_emergency_assistance_order  where patient='"+patient+"' and status="+ EmergencyAssistanceDO.Status.apply.getType();
        Integer counnt = jdbcTemplate.queryForObject(sql,Integer.class);
        if (counnt>0){
            result.put("emeAssistance",true);
        sql = " select count(id) from base_emergency_assistance_order  where patient='" + patient + "' and status=" + EmergencyAssistanceDO.Status.apply.getType();
        Integer counnt = jdbcTemplate.queryForObject(sql, Integer.class);
        if (counnt > 0) {
            result.put("emeAssistance", true);
        }
        result = patientSignTopicInfo(result,patient,topicItem,null,true);
        result = patientSignTopicInfo(result, patient, topicItem, deviceSn, true);
        return result;
    }
    /**
     *老人家属首页实时监护信息
     * 老人家属首页实时监护信息
     * 居家状态取手表 无手表缺省
     * 监控
     */
    public JSONObject patientMonitoringInfo2(String patient){
    public JSONObject patientMonitoringInfo2(String patient) {
        JSONObject result = new JSONObject();
        result.put("atHome",null);// 居家状态
        result.put("location",null);
        result.put("fences",null);
        result.put("gasLeakage",null);
        result.put("fire",null);
        result.put("fall",null);
        result.put("sleep",null);
        result.put("sleepOrderInfo",null);//最近工单
        result.put("deviceSn",null);
        result.put("emeAssistance",false);
        result.put("monitorInfo",null);
        result.put("atHome", null);// 居家状态
        result.put("location", null);
        result.put("fences", null);
        result.put("gasLeakage", null);
        result.put("fire", null);
        result.put("fall", null);
        result.put("sleep", null);
        result.put("sleepOrderInfo", null);//最近工单
        result.put("deviceSn", null);
        result.put("emeAssistance", false);
        result.put("monitorInfo", null);
        String sql = " select dict.code,count(ord.id) total from base_system_dict_entry dict LEFT JOIN base_security_monitoring_order ord " +
                " on dict.code = ord.topic_item COLLATE utf8_unicode_ci and ord.status="+SecurityMonitoringOrderDO.Status.apply.getType()+" where dict.dict_code='service_item' " +
                "and dict.remark='security' and ord.patient='"+patient+"' GROUP BY dict.code ";
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql);
        for (Map<String,Object>tmp:sqlResult){
            switch (tmp.get("code").toString()){
                " on dict.code = ord.topic_item COLLATE utf8_unicode_ci and ord.status=" + SecurityMonitoringOrderDO.Status.apply.getType() + " where dict.dict_code='service_item' " +
                "and dict.remark='security' and ord.patient='" + patient + "' GROUP BY dict.code ";
        List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> tmp : sqlResult) {
            switch (tmp.get("code").toString()) {
                case "preventGasLeakage":
                    Integer count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("gasLeakage",true);
                    }else {
                        result.put("gasLeakage",false);
                    if (count > 0) {
                        result.put("gasLeakage", true);
                    } else {
                        result.put("gasLeakage", false);
                    }
                    break;
                case "preventFire":
                    count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("fire",true);
                    }else {
                        result.put("fire",false);
                    if (count > 0) {
                        result.put("fire", true);
                    } else {
                        result.put("fire", false);
                    }
                    break;
                case "preventFall":
                    count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("fall",true);
                    }else {
                        result.put("fall",false);
                    if (count > 0) {
                        result.put("fall", true);
                    } else {
                        result.put("fall", false);
                    }
                    break;
                case "preventOutOfBed":
                    count = Integer.parseInt(tmp.get("total").toString());
                    if (count>0){
                        result.put("sleep",true);
                    if (count > 0) {
                        result.put("sleep", true);
                        sql = " select serve_desc from base_security_monitoring_order where topic_item='preventOutOfBed' " +
                                "and patient='"+patient+"' and `status`=1 order by create_time desc limit 1 ";
                        List<String> serveDesces = jdbcTemplate.queryForList(sql,String.class);
                        if (serveDesces.size()>0){
                            result.put("sleepOrderInfo",serveDesces.get(0));
                                "and patient='" + patient + "' and `status`=1 order by create_time desc limit 1 ";
                        List<String> serveDesces = jdbcTemplate.queryForList(sql, String.class);
                        if (serveDesces.size() > 0) {
                            result.put("sleepOrderInfo", serveDesces.get(0));
                        }
                    }else {
                        result.put("sleep",false);
                    } else {
                        result.put("sleep", false);
                    }
                    break;
            }
        }
        sql = " select count(id) from base_emergency_assistance_order  where patient='"+patient+"' and status="+ EmergencyAssistanceDO.Status.apply.getType();
        Integer counnt = jdbcTemplate.queryForObject(sql,Integer.class);
        if (counnt>0){
            result.put("emeAssistance",true);
        sql = " select count(id) from base_emergency_assistance_order  where patient='" + patient + "' and status=" + EmergencyAssistanceDO.Status.apply.getType();
        Integer counnt = jdbcTemplate.queryForObject(sql, Integer.class);
        if (counnt > 0) {
            result.put("emeAssistance", true);
        }
        List<DevicePatientDevice> devices4 = patientDeviceDao.findByUserAndCategoryCode(patient,"4");//手表
        if (devices4.size()>0){
            result =  patientSignTopicInfo(result,patient,"preventLost",devices4.get(0).getDeviceSn(),true);
        List<DevicePatientDevice> devices4 = patientDeviceDao.findByUserAndCategoryCode(patient, "4");//手表
        if (devices4.size() > 0) {
            result = patientSignTopicInfo(result, patient, "preventLost", devices4.get(0).getDeviceSn(), true);
        }
        patientSignTopicInfo(result,patient,"preventFall",null,true);
        patientSignTopicInfo(result, patient, "preventFall", null, true);
        return result;
    }
    public void preventLost(JSONObject result,String patient,String deviceSn){
    public void preventLost(JSONObject result, String patient, String deviceSn) {
        //手表与拐杖同时绑定时优先手表,围栏状态其中一个超出围栏即为超出围栏
        try {
            Integer categoryCode=0;//未指定设备
            Integer categoryCode = 0;//未指定设备
            List<DevicePatientDevice> devicePatientDeviceDos = new ArrayList<>();
            List<DevicePatientDevice> devicePatientDeviceDos2 = new ArrayList<>();
            if (StringUtils.isNotBlank(deviceSn)){//查看指定设备详情
            if (StringUtils.isNotBlank(deviceSn)) {//查看指定设备详情
                List<DevicePatientDevice> devices = patientDeviceDao.findByDeviceSn(deviceSn);
                if (devices.size()>0){
                   String categoryCodeTmp = devices.get(0).getCategoryCode();
                    categoryCode = StringUtils.isBlank(categoryCodeTmp)?-1:Integer.parseInt(categoryCodeTmp);
                    if (4==categoryCode){
                if (devices.size() > 0) {
                    String categoryCodeTmp = devices.get(0).getCategoryCode();
                    categoryCode = StringUtils.isBlank(categoryCodeTmp) ? -1 : Integer.parseInt(categoryCodeTmp);
                    if (4 == categoryCode) {
                        devicePatientDeviceDos = devices;
                    }
                    if (16==categoryCode){
                    if (16 == categoryCode) {
                        devicePatientDeviceDos2 = devices;
                    }
                }
            }else {//未指定设备
                devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"4");//手表
                devicePatientDeviceDos2 = patientDeviceDao.findByUserAndCategoryCode(patient,"16");//拐杖
            } else {//未指定设备
                devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient, "4");//手表
                devicePatientDeviceDos2 = patientDeviceDao.findByUserAndCategoryCode(patient, "16");//拐杖
            }
            if (devicePatientDeviceDos.size()>0&&(4==categoryCode||0==categoryCode)){//手表
            if (devicePatientDeviceDos.size() > 0 && (4 == categoryCode || 0 == categoryCode)) {//手表
                DevicePatientDevice device = devicePatientDeviceDos.get(0);
                result.put("deviceSn",device.getDeviceSn());
                JSONObject response= patientDeviceService.getAqgDeviceInfo2(device.getDeviceSn());
                if (response!=null){
                result.put("deviceSn", device.getDeviceSn());
                JSONObject response = patientDeviceService.getAqgDeviceInfo2(device.getDeviceSn());
                if (response != null) {
                    //定位信息
                    if (response.containsKey("last_location")&&response.get("last_location")!=null){
                    if (response.containsKey("last_location") && response.get("last_location") != null) {
                        JSONObject locationTmp = response.getJSONObject("last_location");
                        Double lon = locationTmp.getJSONArray("coordinates").getDouble(0);
                        Double lat = locationTmp.getJSONArray("coordinates").getDouble(1);
                        if (!response.getBoolean("online")){//设备离线 取居民表定位
                            result.put("X1online",false);
                        }else {
                            result.put("X1online",true);
                        if (!response.getBoolean("online")) {//设备离线 取居民表定位
                            result.put("X1online", false);
                        } else {
                            result.put("X1online", true);
                        }
                        JSONObject tmp = gpsUtil.gcj02_To_Bd09(lat,lon);
                        tmp.put("city",response.getString("last_city"));
                        tmp.put("province",response.getString("last_province"));
                        tmp.put("address",response.getString("last_address"));
                        result.put("location",tmp);
                        JSONObject tmp = gpsUtil.gcj02_To_Bd09(lat, lon);
                        tmp.put("city", response.getString("last_city"));
                        tmp.put("province", response.getString("last_province"));
                        tmp.put("address", response.getString("last_address"));
                        result.put("location", tmp);
                        BasePatientDO patientDO = basePatientDao.findById(patient);
                        if (null != patientDO){
                            if (StringUtils.isNotBlank(patientDO.getHomeLatLon())){
                        if (null != patientDO) {
                            if (StringUtils.isNotBlank(patientDO.getHomeLatLon())) {
                                String homeLatLon = patientDO.getHomeLatLon();
                                double homeLat = Double.parseDouble( homeLatLon.split(",")[0]);
                                double homeLon = Double.parseDouble( homeLatLon.split(",")[1]);
                                double homeDistance =  countDistance.getDistance(result.getJSONObject("location").getDouble("lat"),result.getJSONObject("location").getDouble("lon"),
                                       homeLat,homeLon);
                                if (homeDistance>50*1000){
                                    result.put("atHome",false);
                                }else {
                                    result.put("atHome",true);
                                double homeLat = Double.parseDouble(homeLatLon.split(",")[0]);
                                double homeLon = Double.parseDouble(homeLatLon.split(",")[1]);
                                double homeDistance = countDistance.getDistance(result.getJSONObject("location").getDouble("lat"), result.getJSONObject("location").getDouble("lon"),
                                        homeLat, homeLon);
                                if (homeDistance > 50 * 1000) {
                                    result.put("atHome", false);
                                } else {
                                    result.put("atHome", true);
                                }
                            }
                        }
                    }
                    //围栏信息
                    if (response.containsKey("fences")&&response.get("fences")!=null){
                    if (response.containsKey("fences") && response.get("fences") != null) {
                        JSONArray fencesArr = response.getJSONArray("fences");
                        JSONArray fencesEnables = new JSONArray();
                        for (int i=0;i<fencesArr.size();i++){
                        for (int i = 0; i < fencesArr.size(); i++) {
                            JSONObject tmp = fencesArr.getJSONObject(i);
                            if (tmp.getBooleanValue("enable")){//围栏生效
                            if (tmp.getBooleanValue("enable")) {//围栏生效
                                JSONObject fenceTmp = new JSONObject();
                                fenceTmp.put("fenceNO",tmp.getInteger("seqid").toString());
                                fenceTmp.put("name",tmp.getString("name"));
                                fenceTmp.put("fenceNO", tmp.getInteger("seqid").toString());
                                fenceTmp.put("name", tmp.getString("name"));
                                JSONArray fenceLocationTmp = tmp.getJSONObject("safe_area").getJSONArray("coordinates").getJSONArray(0);
                                JSONArray fenceLocation = new JSONArray();
                                for (int j=0;j<fenceLocationTmp.size();j++){
                                for (int j = 0; j < fenceLocationTmp.size(); j++) {
                                    Double lon = fenceLocationTmp.getJSONArray(j).getDouble(0);
                                    Double lat = fenceLocationTmp.getJSONArray(j).getDouble(1);
                                    JSONObject positionTmp = gpsUtil.gcj02_To_Bd09(lat,lon);
                                    JSONObject positionTmp = gpsUtil.gcj02_To_Bd09(lat, lon);
                                    fenceLocation.add(positionTmp);
                                }
                                fenceTmp.put("location",fenceLocation);
                                fenceTmp.put("inFenceStatus",countDistance.isInPolygon(result.getJSONObject("location").getDouble("lon"),result.getJSONObject("location").getDouble("lat"),fenceLocation));
                                fenceTmp.put("location", fenceLocation);
                                fenceTmp.put("inFenceStatus", countDistance.isInPolygon(result.getJSONObject("location").getDouble("lon"), result.getJSONObject("location").getDouble("lat"), fenceLocation));
                                fencesEnables.add(fenceTmp);
                            }
                        }
                        if (fencesEnables.size()>0){
                            result.put("fences",fencesEnables);
                        if (fencesEnables.size() > 0) {
                            result.put("fences", fencesEnables);
                        }
                    }
                }
            }
            if (devicePatientDeviceDos2.size()>0&&(16==categoryCode||0==categoryCode)) {//拐杖
            if (devicePatientDeviceDos2.size() > 0 && (16 == categoryCode || 0 == categoryCode)) {//拐杖
                DevicePatientDevice deviceDO = devicePatientDeviceDos2.get(0);
                double dulat = 0l;
                double dulon = 0l;
@ -1738,8 +1767,8 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                }
                if (!(dulat == 0.0 && dulon == 0.0)) {
                    List<PatientSafeAreaDO> safeAreaDOS = safeAreaDao.findByPatient(deviceDO.getUser());
                    String safeArea=null;
                    if (safeAreaDOS.size()>0){
                    String safeArea = null;
                    if (safeAreaDOS.size() > 0) {
                        safeArea = safeAreaDOS.get(0).getSafeAreaGz();
                    }
                    JSONArray fenceLocation = new JSONArray();
@ -1755,7 +1784,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                            positionTmp.put("lon", areaLon);
                            fenceLocation.add(positionTmp);
                        }
                        if (devicePatientDeviceDos2.size() > 0 && 0 == categoryCode && devicePatientDeviceDos2.size()>0) {
                        if (devicePatientDeviceDos2.size() > 0 && 0 == categoryCode && devicePatientDeviceDos2.size() > 0) {
                            JSONObject obj = result.getJSONArray("fences").getJSONObject(0);
                            if (obj.getBooleanValue("inFenceStatus")) {
                                if (!countDistance.isInPolygon(dulon, dulat, fenceLocation)) {
@ -1766,87 +1795,86 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                                    obj.put("lat", dulat);
                                }
                            }
                        }
                        else if(devicePatientDeviceDos2.size() > 0) {//指定拐杖设备
                        } else if (devicePatientDeviceDos2.size() > 0) {//指定拐杖设备
                            if (StringUtils.isNotBlank(safeArea)) {
                                result.put("deviceSn", deviceDO.getDeviceSn());
                                JSONObject location = new JSONObject();
                                location.put("address",address);
                                location.put("province","");
                                location.put("city","");
                                location.put("lon",dulon);
                                location.put("lat",dulat);
                                result.put("location",location);
                                location.put("address", address);
                                location.put("province", "");
                                location.put("city", "");
                                location.put("lon", dulon);
                                location.put("lat", dulat);
                                result.put("location", location);
                                JSONArray fences = new JSONArray();
                                JSONObject fence = new JSONObject();
                                fence.put("fenceNO","1");
                                fence.put("name","安全区域1");
                                fence.put("fenceNO", "1");
                                fence.put("name", "安全区域1");
                                fence.put("inFenceStatus", countDistance.isInPolygon(dulon, dulat, fenceLocation));
                                fence.put("location", fenceLocation);
                                fences.add(fence);
                                result.put("fences",fences);
                                result.put("fences", fences);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            result.put("location",null);
            result.put("location", null);
        }
    }
    public void preventOutOfBed(JSONObject result,String patient,boolean video,String dayTime){
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"13");
        if (devicePatientDeviceDos.size()==0){}
        else {
    public void preventOutOfBed(JSONObject result, String patient, boolean video, String dayTime) {
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient, "13");
        if (devicePatientDeviceDos.size() == 0) {
        } else {
            DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
            JSONObject deviceInfo =  patientDeviceService.getSleepDeviceInfo(deviceDo.getDeviceSn());
            if(deviceInfo.getBooleanValue("success")){
                result.put("patientAddress",deviceDo.getSosAddress());
            JSONObject deviceInfo = patientDeviceService.getSleepDeviceInfo(deviceDo.getDeviceSn());
            if (deviceInfo.getBooleanValue("success")) {
                result.put("patientAddress", deviceDo.getSosAddress());
                JSONArray objInfo = deviceInfo.getJSONArray("objs");
                if (objInfo.size()>0){
                    result.put("sleepStatus",true);
                if (objInfo.size() > 0) {
                    result.put("sleepStatus", true);
                    JSONObject tmp = objInfo.getJSONObject(0);
                    JSONObject sleepInfo = new JSONObject();
                    if (StringUtils.isBlank(dayTime)){
                        dayTime = getSleepMonitoringDay(new Date(),patient);
                    if (StringUtils.isBlank(dayTime)) {
                        dayTime = getSleepMonitoringDay(new Date(), patient);
                    }
                    List<BaseSleepPlanDetail> planDetails = sleepPlanDetailDao.findByPatientAndDay(patient,dayTime);
                    List<BaseSleepPlanDetail> planDetails = sleepPlanDetailDao.findByPatientAndDay(patient, dayTime);
                    BaseSleepPlanDetail planDetail = new BaseSleepPlanDetail();
                    if (planDetails.size()>0){
                        planDetail =  planDetails.get(0);
                        List<BaseSleepNightRecord> sleepNightRecordList = nightRecordDao.findByPatientAndDayOrderByCreateTimeDesc(patient,dayTime);
                    if (planDetails.size() > 0) {
                        planDetail = planDetails.get(0);
                        List<BaseSleepNightRecord> sleepNightRecordList = nightRecordDao.findByPatientAndDayOrderByCreateTimeDesc(patient, dayTime);
                        planDetail.setSleepNightRecordList(sleepNightRecordList);
                    }
                    String jsonStr = JSON.toJSONStringWithDateFormat(planDetail, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
                    sleepInfo = JSONObject.parseObject(jsonStr);
                    sleepInfo.put("day",dayTime);
                    sleepInfo.put("day", dayTime);
                    List<BaseSleepPlan> sleepPlans = sleepPlanDao.findByPatient(patient);
                    if (sleepPlans.size()>0){
                    if (sleepPlans.size() > 0) {
                        BaseSleepPlan sleepPlan = sleepPlans.get(0);
                        String endTime = DateUtil.getNextMin(sleepPlan.getGetUpTime(),-1);
                        sleepInfo.put("sleepPlan",true);
                        sleepInfo.put("getUpTime",sleepPlan.getGetUpTime());
                        sleepInfo.put("siestaTime",sleepPlan.getNapTime());
                        sleepInfo.put("nightRestTime",sleepPlan.getNightRestTime());
                        sleepInfo.put("nightRecordTime",sleepPlan.getNightRestTime()+"-隔日"+endTime);
                    }else {
                        sleepInfo.put("sleepPlan",false);
                        String endTime = DateUtil.getNextMin(sleepPlan.getGetUpTime(), -1);
                        sleepInfo.put("sleepPlan", true);
                        sleepInfo.put("getUpTime", sleepPlan.getGetUpTime());
                        sleepInfo.put("siestaTime", sleepPlan.getNapTime());
                        sleepInfo.put("nightRestTime", sleepPlan.getNightRestTime());
                        sleepInfo.put("nightRecordTime", sleepPlan.getNightRestTime() + "-隔日" + endTime);
                    } else {
                        sleepInfo.put("sleepPlan", false);
                    }
                    sleepInfo.put("online",tmp.getBooleanValue("online"));
                    if(tmp.getBooleanValue("onbed")){
                        sleepInfo.put("bedStatus",1);
                        sleepInfo.put("heartRate",tmp.getString("heartrate"));
                        sleepInfo.put("breath",tmp.getString("breathrate"));
                    }else {
                        sleepInfo.put("bedStatus",0);
                        sleepInfo.put("heartRate",null);
                        sleepInfo.put("breath",null);
                    sleepInfo.put("online", tmp.getBooleanValue("online"));
                    if (tmp.getBooleanValue("onbed")) {
                        sleepInfo.put("bedStatus", 1);
                        sleepInfo.put("heartRate", tmp.getString("heartrate"));
                        sleepInfo.put("breath", tmp.getString("breathrate"));
                    } else {
                        sleepInfo.put("bedStatus", 0);
                        sleepInfo.put("heartRate", null);
                        sleepInfo.put("breath", null);
                    }
                    BasePatientOutBed outBed = outBedDao.findByPatientAndDeviceSnAndStatus(patient,deviceDo.getDeviceSn(),0);
                    if (null!=outBed){
                    BasePatientOutBed outBed = outBedDao.findByPatientAndDeviceSnAndStatus(patient, deviceDo.getDeviceSn(), 0);
                    if (null != outBed) {
                        String outBedTime = "";
                        Date date = new Date();
                        long millisecondsDiff = date.getTime() - outBed.getCreateTime().getTime();
@ -1856,131 +1884,129 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                        if (hoursDiff > 0L) {
                            outBedTime += String.format("%d小时", hoursDiff);
                        }
                        if (minuteFieldDiff>0){
                            outBedTime +=String.format("%d分钟", minuteFieldDiff);
                        if (minuteFieldDiff > 0) {
                            outBedTime += String.format("%d分钟", minuteFieldDiff);
                        }
                        sleepInfo.put("outBedTimeCrzq",outBed.getCreateTime());
                        sleepInfo.put("outBedTime",outBedTime);
                    }else {
                        sleepInfo.put("outBedTime","无");
                        sleepInfo.put("outBedTimeCrzq", outBed.getCreateTime());
                        sleepInfo.put("outBedTime", outBedTime);
                    } else {
                        sleepInfo.put("outBedTime", "无");
                    }
                    result.put("sleepInfo",sleepInfo);
                    result.put("sleepInfo", sleepInfo);
                }
            }else {
                result.put("sleepStatus",false);
                result.put("sleepInfo","获取睡眠带数据失败");
            } else {
                result.put("sleepStatus", false);
                result.put("sleepInfo", "获取睡眠带数据失败");
            }
        }
        if (video){
        if (video) {
            monitorInfo(result, patient);
        }
    }
    public void preventFire(JSONObject result,String patient,String deviceSn,boolean video){
    public void preventFire(JSONObject result, String patient, String deviceSn, boolean video) {
        String sql = "SELECT r.value from wlyy_patient_device pd,base_device_health_index r " +
                "WHERE pd.device_sn = r.device_sn  ";
        if (StringUtils.isNotBlank(patient)){
            sql+=" and pd.`user` = '"+patient+"' ";
        if (StringUtils.isNotBlank(patient)) {
            sql += " and pd.`user` = '" + patient + "' ";
        }
        if (StringUtils.isNotBlank(deviceSn)){
            sql+=" and  r.device_sn = '"+deviceSn+"' ";
        if (StringUtils.isNotBlank(deviceSn)) {
            sql += " and  r.device_sn = '" + deviceSn + "' ";
        }
        sql += " and pd.category_code='15' ORDER BY r.create_time desc LIMIT 1";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql);
        if(list1.size()==0){
            result.put("smoke","-1");
        }else{
            result.put("smoke",list1.get(0).get("value"));
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql);
        if (list1.size() == 0) {
            result.put("smoke", "-1");
        } else {
            result.put("smoke", list1.get(0).get("value"));
        }
        result.put("smokeOrderNum",getOrder(patient,"preventFire"));
        if (video){
        result.put("smokeOrderNum", getOrder(patient, "preventFire"));
        if (video) {
            monitorInfo(result, patient);
        }
    }
    public Integer getOrder(String patient,String topicItem){
    public Integer getOrder(String patient, String topicItem) {
        String sql = "select count(1) from base_security_monitoring_order " +
                "WHERE patient = '"+patient+"' and `status` = 1 and topic_item = '"+topicItem+"'";
        Integer num = jdbcTemplate.queryForObject(sql,Integer.class);
                "WHERE patient = '" + patient + "' and `status` = 1 and topic_item = '" + topicItem + "'";
        Integer num = jdbcTemplate.queryForObject(sql, Integer.class);
        return num;
    }
    public void preventGasLeakage(JSONObject result,String patient,boolean video){
    public void preventGasLeakage(JSONObject result, String patient, boolean video) {
        String sql = "SELECT r.value from wlyy_patient_device pd,base_device_health_index r " +
                "WHERE pd.device_sn = r.device_sn and pd.`user` = '"+patient+"' ";
                "WHERE pd.device_sn = r.device_sn and pd.`user` = '" + patient + "' ";
        sql += " and pd.category_code='14' ORDER BY r.create_time desc LIMIT 1";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql);
        if(list1.size()==0){
            result.put("methane","-1");
        }else{
            result.put("methane",list1.get(0).get("value"));
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql);
        if (list1.size() == 0) {
            result.put("methane", "-1");
        } else {
            result.put("methane", list1.get(0).get("value"));
        }
        result.put("methaneOrderNum",getOrder(patient,"preventGasLeakage"));
        if (video){
        result.put("methaneOrderNum", getOrder(patient, "preventGasLeakage"));
        if (video) {
            monitorInfo(result, patient);
        }
    }
    public void monitorInfo(JSONObject result,String patient){
    public void monitorInfo(JSONObject result, String patient) {
        //监控
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient,"12");
        if (devicePatientDeviceDos.size()==0){
        List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByUserAndCategoryCode(patient, "12");
        if (devicePatientDeviceDos.size() == 0) {
            return;
        }
        try {
            DevicePatientDevice deviceDo = devicePatientDeviceDos.get(0);
            JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(patient,deviceDo.getDeviceSn(),1,null);
            result.put("monitorInfoStatus",monitorUrl.getIntValue(ResponseContant.resultFlag));
            result.put("patientAddress",deviceDo.getSosAddress());
            if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail){
                result.put("monitorInfo",monitorUrl.getString(ResponseContant.resultMsg));
            }
            else {
                result.put("monitorInfo",monitorUrl.getJSONObject(ResponseContant.resultMsg));
            JSONObject monitorUrl = ysDeviceServicel.getDeviceLiveAddress(patient, deviceDo.getDeviceSn(), 1, null);
            result.put("monitorInfoStatus", monitorUrl.getIntValue(ResponseContant.resultFlag));
            result.put("patientAddress", deviceDo.getSosAddress());
            if (monitorUrl.getIntValue(ResponseContant.resultFlag) == ResponseContant.fail) {
                result.put("monitorInfo", monitorUrl.getString(ResponseContant.resultMsg));
            } else {
                result.put("monitorInfo", monitorUrl.getJSONObject(ResponseContant.resultMsg));
            }
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public JSONObject patientSignTopicInfo(JSONObject result,String patient,String topicItem,String deviceSn,boolean video){
        if (null==result){
    public JSONObject patientSignTopicInfo(JSONObject result, String patient, String topicItem, String deviceSn, boolean video) {
        if (null == result) {
            result = new JSONObject();
        }
        if ("preventLost".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventLost(result, patient,deviceSn);
        if ("preventLost".equals(topicItem) || StringUtils.isBlank(topicItem)) {
            preventLost(result, patient, deviceSn);
        }
        if ("preventFall".equals(topicItem)||StringUtils.isBlank(topicItem)){
        if ("preventFall".equals(topicItem) || StringUtils.isBlank(topicItem)) {
            monitorInfo(result, patient);
        }
        if ("preventOutOfBed".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventOutOfBed(result, patient,true,null);
        if ("preventOutOfBed".equals(topicItem) || StringUtils.isBlank(topicItem)) {
            preventOutOfBed(result, patient, true, null);
        }
        if ("preventFire".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventFire(result, patient,null,video);
        if ("preventFire".equals(topicItem) || StringUtils.isBlank(topicItem)) {
            preventFire(result, patient, null, video);
        }
        if ("preventGasLeakage".equals(topicItem)||StringUtils.isBlank(topicItem)){
            preventGasLeakage(result, patient,video);
        if ("preventGasLeakage".equals(topicItem) || StringUtils.isBlank(topicItem)) {
            preventGasLeakage(result, patient, video);
        }
        return result;
    }
    public JSONObject updateDoctorLocation(String doctor,String orderId,String doctorAddress,String doctorLat,String doctorLon){
    public JSONObject updateDoctorLocation(String doctor, String orderId, String doctorAddress, String doctorLat, String doctorLon) {
        JSONObject result = new JSONObject();
        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
        if (doctorDO==null){
        if (doctorDO == null) {
            String failMsg = "当前医生不存在";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        else {
        } else {
            doctorDO.setDoctorLocateAddress(doctorAddress);
            doctorDO.setDoctorLat(doctorLat);
            doctorDO.setDoctorLon(doctorLon);
@ -1990,44 +2016,43 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        return result;
    }
    public JSONObject updatePatientLocation(String patient,String patientAddress,String patientLat,String patientLon){
    public JSONObject updatePatientLocation(String patient, String patientAddress, String patientLat, String patientLon) {
        JSONObject result = new JSONObject();
        BasePatientDO patientDO = basePatientDao.findById(patient);
        if (patientDO==null){
        if (patientDO == null) {
            String failMsg = "患者不存在";
            result.put(ResponseContant.resultFlag, ResponseContant.fail);
            result.put(ResponseContant.resultMsg,failMsg);
            result.put(ResponseContant.resultMsg, failMsg);
            return result;
        }
        patientDO.setLatLon(patientLat+","+patientLon);
        patientDO.setLatLon(patientLat + "," + patientLon);
        basePatientDao.save(patientDO);
        List<SecurityMonitoringOrderDO> monitoringOrderDO = securityMonitoringOrderDao.findByPatientAndStatus(patient,1);
        if (monitoringOrderDO.size()>0){
            for (SecurityMonitoringOrderDO tmp:monitoringOrderDO){
        List<SecurityMonitoringOrderDO> monitoringOrderDO = securityMonitoringOrderDao.findByPatientAndStatus(patient, 1);
        if (monitoringOrderDO.size() > 0) {
            for (SecurityMonitoringOrderDO tmp : monitoringOrderDO) {
                tmp.setServeAddress(patientAddress);
                tmp.setServeLat(patientLat);
                tmp.setServeLon(patientLon);
                securityMonitoringOrderDao.save(monitoringOrderDO);
            }
            result.put(ResponseContant.resultFlag, ResponseContant.success);
        }
        else {
        } else {
            result.put(ResponseContant.resultFlag, ResponseContant.success);
            result.put(ResponseContant.resultMsg,null);
            result.put(ResponseContant.resultMsg, null);
        }
        return result;
    }
    public JSONObject responseOrder(String orderId,String doctor){
    public JSONObject responseOrder(String orderId, String doctor) {
        JSONObject result = new JSONObject();
        SecurityMonitoringOrderDO one = securityMonitoringOrderDao.findOne(orderId);
        if (one==null){
            String failMsg = "工单不存在" ;
        if (one == null) {
            String failMsg = "工单不存在";
            result.put("resultFlag", 0);
            result.put("resultMsg", failMsg);
            return result;
        }
        if (emergencyWarnDoctorResponseDao.findByDoctorAndOrderId(doctor,orderId)==null){
        if (emergencyWarnDoctorResponseDao.findByDoctorAndOrderId(doctor, orderId) == null) {
            EmergencyWarnDoctorResponseDO responseDO = new EmergencyWarnDoctorResponseDO();
            responseDO.setOrderId(orderId);
            responseDO.setDoctor(doctor);
@ -2035,14 +2060,14 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
            emergencyWarnDoctorResponseDao.save(responseDO);
            BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);
            if (null!=doctorDO){
            if (null != doctorDO) {
                BaseEmergencyWarnLogDO logDO = new BaseEmergencyWarnLogDO();
                logDO.setUserCode(doctor);
                logDO.setUserName(doctorDO.getName());
                logDO.setOrderId(orderId);
                logDO.setUserType(2);
                logDO.setCreateTime(new Date());
                logDO.setContent("社工"+doctorDO.getName()+"前往定位");
                logDO.setContent("社工" + doctorDO.getName() + "前往定位");
                logDao.save(logDO);
            }
        }
@ -2053,70 +2078,70 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
    }
    /**
     *获取居民睡眠计划
     * 获取居民睡眠计划
     */
    public BaseSleepPlan getPatientSleepPlan(String patient){
    public BaseSleepPlan getPatientSleepPlan(String patient) {
        List<BaseSleepPlan> list = sleepPlanDao.findByPatient(patient);
        if (list.size()>0){
        if (list.size() > 0) {
            return list.get(0);
        }else {
        } else {
            return null;
        }
    }
    /**
     *获取居民睡眠监护列表
     * 获取居民睡眠监护列表
     */
    public JSONObject getPatientSleepDetainList(String patient,String begin,String end,Integer page,Integer pageSize){
        page=page>0?page-1:0;
    public JSONObject getPatientSleepDetainList(String patient, String begin, String end, Integer page, Integer pageSize) {
        page = page > 0 ? page - 1 : 0;
        PageRequest pageRequest = new PageRequest(page, pageSize);
        if (StringUtils.isBlank(end)){
        if (StringUtils.isBlank(end)) {
            end = begin;
        }
        JSONArray array = new JSONArray();
        Page<BaseSleepPlanDetail> list = sleepPlanDetailDao.findByListByPage(patient,begin,end,pageRequest);
        Page<BaseSleepPlanDetail> list = sleepPlanDetailDao.findByListByPage(patient, begin, end, pageRequest);
        List<BaseSleepPlan> sleepPlans = sleepPlanDao.findByPatient(patient);
        BaseSleepPlan sleepPlan=null;
        if (sleepPlans.size()>0){
        BaseSleepPlan sleepPlan = null;
        if (sleepPlans.size() > 0) {
            sleepPlan = sleepPlans.get(0);
        }
        for (BaseSleepPlanDetail tmp:list){
            List<BaseSleepNightRecord> records = nightRecordDao.findByPatientAndDayOrderByCreateTimeDesc(patient,tmp.getDay());
        for (BaseSleepPlanDetail tmp : list) {
            List<BaseSleepNightRecord> records = nightRecordDao.findByPatientAndDayOrderByCreateTimeDesc(patient, tmp.getDay());
            tmp.setSleepNightRecordList(records);
            String str = JSON.toJSONStringWithDateFormat(tmp, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
            JSONObject jsonObject = JSONObject.parseObject(str);
            if (null==sleepPlan){
                jsonObject.put("sleepPlan",false);
            }else {
                jsonObject.put("sleepPlan",true);
                String endTime = DateUtil.getNextMin(sleepPlan.getGetUpTime(),-1);
                jsonObject.put("getUpTime",sleepPlan.getGetUpTime());
                jsonObject.put("siestaTime",sleepPlan.getNapTime());
                jsonObject.put("nightRestTime",sleepPlan.getNightRestTime());
                jsonObject.put("nightRecordTime",sleepPlan.getNightRestTime()+"-隔日"+endTime);
            if (null == sleepPlan) {
                jsonObject.put("sleepPlan", false);
            } else {
                jsonObject.put("sleepPlan", true);
                String endTime = DateUtil.getNextMin(sleepPlan.getGetUpTime(), -1);
                jsonObject.put("getUpTime", sleepPlan.getGetUpTime());
                jsonObject.put("siestaTime", sleepPlan.getNapTime());
                jsonObject.put("nightRestTime", sleepPlan.getNightRestTime());
                jsonObject.put("nightRecordTime", sleepPlan.getNightRestTime() + "-隔日" + endTime);
                array.add(jsonObject);
            }
        }
        JSONObject result = (JSONObject) JSONObject.toJSON(list);
        result.put("content",array);
        result.put("content", array);
        return result;
    }
    /**
     *获取居民起夜记录
     * 获取居民起夜记录
     */
    public List<BaseSleepNightRecord> getPatientSleepNightRecord(String patient, String day){
    public List<BaseSleepNightRecord> getPatientSleepNightRecord(String patient, String day) {
        List<BaseSleepNightRecord> records = nightRecordDao.findByPatientAndDayOrderByCreateTimeDesc(patient,day);
        List<BaseSleepNightRecord> records = nightRecordDao.findByPatientAndDayOrderByCreateTimeDesc(patient, day);
        return records;
    }
    private String getRandomIntStr(){
    private String getRandomIntStr() {
        Random rand = new Random();
        int i = rand.nextInt(); //int范围类的随机数
        i = rand.nextInt(100); //生成0-100以内的随机数
        i = (int)(Math.random() * 100000000); //0-100以内的随机数,用Matn.random()方式
        i = (int) (Math.random() * 100000000); //0-100以内的随机数,用Matn.random()方式
        return String.valueOf(i);
    }
@ -2126,98 +2151,242 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        one.setUpdateUserName(one.getDoctorName());
    }
    private String getSleepMonitoringDay(Date date,String patient){
    private String getSleepMonitoringDay(Date date, String patient) {
        List<BaseSleepPlan> sleepPlans = sleepPlanDao.findByPatient(patient);
        if (sleepPlans.size()>0){
        if (sleepPlans.size() > 0) {
            BaseSleepPlan sleepPlan = sleepPlans.get(0);
            String bedUpStr = sleepPlans.get(0).getGetUpTime();
            Date bedUp = DateUtil.strToDate(DateUtil.getStringDateShort()+" "+bedUpStr+":00");// 起床时间 起床前一小时内算为起床
            if (date.before(bedUp)&&bedUp.getTime()-date.getTime()>1000*1*3600){
                bedUp = DateUtil.getNextDay1(bedUp,-1);
            Date bedUp = DateUtil.strToDate(DateUtil.getStringDateShort() + " " + bedUpStr + ":00");// 起床时间 起床前一小时内算为起床
            if (date.before(bedUp) && bedUp.getTime() - date.getTime() > 1000 * 1 * 3600) {
                bedUp = DateUtil.getNextDay1(bedUp, -1);
            }
            String dayTime = DateUtil.dateToStr(bedUp,DateUtil.YYYY_MM_DD);//监测日期
            String dayTime = DateUtil.dateToStr(bedUp, DateUtil.YYYY_MM_DD);//监测日期
            return dayTime;
        }else {
        } else {
            return null;
        }
    }
    public JSONObject findMonitorPatientsByDoctor(String doctor,String topicItem,String day,Integer page,Integer pageSize,Integer detail){
    public JSONObject findMonitorPatientsByDoctor(String doctor, String topicItem, String day, Integer page, Integer pageSize, Integer detail) {
        JSONObject result = new JSONObject();
        String sql = " SELECT DISTINCT p.id,p.name,p.residential_area residentialArea,p.photo,p.idcard,p.mobile, " +
                " p.openid,p.sex,p.pad_imei padImei " +
                " from base_patient p , base_service_package_sign_record sr,base_service_package_record r,base_team_member m  " +
                " WHERE p.id = sr.patient and sr.status=1 and m.team_code = r.team_code and sr.id=r.sign_id  " +
                " and m.doctor_code = '"+doctor+"' and m.del = '1' ";
                " and m.doctor_code = '" + doctor + "' and m.del = '1' ";
        String fliter = "";
        String categoryCode ="";
        String categoryCode = "";
        String topicItemTmp = topicItem;
        switch (topicItem){
        switch (topicItem) {
            case "actionTrack":
                categoryCode="'4'";
                topicItemTmp="preventLost";
                categoryCode = "'4'";
                topicItemTmp = "preventLost";
                break;
            case "preventLost":
                categoryCode="'4'";
                categoryCode = "'4'";
                break;
            case "preventFall":
                categoryCode="'12'";
                categoryCode = "'12'";
                break;
            case "preventFire":
                categoryCode="'15'";
                categoryCode = "'15'";
                break;
            case "preventGasLeakage":
                categoryCode="'14'";
                categoryCode = "'14'";
                break;
            case "preventOutOfBed":
                categoryCode="'13'";
                categoryCode = "'13'";
                break;
        }
        fliter =" and EXISTS (select 1 from wlyy_patient_device pd INNER JOIN dm_device dd on pd.device_id = dd.id  " +
                    " where  pd.user = sr.patient and pd.del=0 and pd.category_code in ("+categoryCode+") and FIND_IN_SET('"+topicItemTmp+"',dd.service_topic)) ";
        fliter = " and EXISTS (select 1 from wlyy_patient_device pd INNER JOIN dm_device dd on pd.device_id = dd.id  " +
                " where  pd.user = sr.patient and pd.del=0 and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItemTmp + "',dd.service_topic)) ";
        if ("preventLost".equals(topicItem)){//有绑定围栏的居民
        if ("preventLost".equals(topicItem)) {//有绑定围栏的居民
            fliter += " and EXISTS (select 1 from wlyy_patient_safe_area sf where sf.patient = p.id and sf.del=1 and sf.manage_status=1) ";
        }
        List<Map<String,Object>> list =  jdbcTemplate.queryForList(sql+fliter);
        result.put("total",list.size());
        if (1 == detail){//获取详情
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql + fliter);
        result.put("total", list.size());
        if (1 == detail) {//获取详情
            JSONArray monitorInfos = new JSONArray();
            page = page>0?page-1:0;
            page = page > 0 ? page - 1 : 0;
            Integer totalPage = 0;
            if(list.size()%pageSize==0){
                totalPage =list.size()/pageSize;
            }else{
                totalPage = list.size()/pageSize+1;
            if (list.size() % pageSize == 0) {
                totalPage = list.size() / pageSize;
            } else {
                totalPage = list.size() / pageSize + 1;
            }
            Integer currentIndexFrom = page*pageSize;
            Integer currentIndexEnd = page*pageSize+pageSize;
            result.put("totalPage",totalPage);
            result.put("currentPage",page+1);
            for (int i=currentIndexFrom;i<list.size()&&i<currentIndexEnd;i++){
                Map<String,Object> patientTmp = list.get(i);
            Integer currentIndexFrom = page * pageSize;
            Integer currentIndexEnd = page * pageSize + pageSize;
            result.put("totalPage", totalPage);
            result.put("currentPage", page + 1);
            for (int i = currentIndexFrom; i < list.size() && i < currentIndexEnd; i++) {
                Map<String, Object> patientTmp = list.get(i);
                com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
                String deviceSn ="";
                String deviceSn = "";
                List<String> deviceSns = jdbcTemplate.queryForList("select pd.device_sn from wlyy_patient_device pd INNER JOIN dm_device dd " +
                        " on pd.device_id = dd.id where  pd.user = '"+patientTmp.get("id").toString()+"' and pd.del=0  and pd.category_code in ("+categoryCode+") and FIND_IN_SET('"+topicItemTmp+"',dd.service_topic)",String.class);
                if (deviceSns.size()>0){
                        " on pd.device_id = dd.id where  pd.user = '" + patientTmp.get("id").toString() + "' and pd.del=0  and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItemTmp + "',dd.service_topic)", String.class);
                if (deviceSns.size() > 0) {
                    deviceSn = deviceSns.get(0);
                }
                if (deviceSns.size()>0){
                object.put("deviceSn", deviceSn);
                switch (topicItem) {
                    case "actionTrack":
                        JSONArray locations = JSON.parseArray(JSON.toJSONString(patientDeviceService.getX1Locations(deviceSn, day), SerializerFeature.WriteMapNullValue));
                        object.put("routes", locations);
                        //获取手表定位
                        JSONObject response = patientDeviceService.getAqgDeviceInfo2(deviceSn);
                        if (response != null) {
                            //定位信息
                            if (response.containsKey("last_location") && response.get("last_location") != null) {
                                JSONObject locationTmp = response.getJSONObject("last_location");
                                Double lon = locationTmp.getJSONArray("coordinates").getDouble(0);
                                Double lat = locationTmp.getJSONArray("coordinates").getDouble(1);
                                if (!response.getBoolean("online")) {//设备离线 取居民表定位
                                    object.put("X1online", false);
                                } else {
                                    object.put("X1online", true);
                                }
                                JSONObject tmp = gpsUtil.gcj02_To_Bd09(lat, lon);
                                tmp.put("city", response.getString("last_city"));
                                tmp.put("province", response.getString("last_province"));
                                tmp.put("address", response.getString("last_address"));
                                object.put("location", tmp);
                            }
                        }
                        break;
                    default:
                        object = patientMonitoringInfo(patientTmp.get("id").toString(), topicItem,deviceSn, false);
                        break;
                }
                object.put("patientInfo", patientTmp);
                object.put("deviceSn", deviceSn);
                monitorInfos.add(object);
            }
            result.put("topicInfo", monitorInfos);
        } else {
            JSONArray monitorInfos = new JSONArray();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> patientTmp = list.get(i);
                String deviceSn = "";
                List<String> deviceSns = jdbcTemplate.queryForList("select pd.device_sn from wlyy_patient_device pd INNER JOIN dm_device dd " +
                        " on pd.device_id = dd.id where  pd.user = '" + patientTmp.get("id").toString() + "' and pd.del=0  and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItem + "',dd.service_topic)", String.class);
                if (deviceSns.size() > 0) {
                    deviceSn = deviceSns.get(0);
                }
                object.put("deviceCode",deviceSn);
                JSONObject object = patientMonitoringInfo(patientTmp.get("id").toString(), "null", null,false);
                object.put("deviceSn", deviceSn);
                object.put("patientInfo", patientTmp);
                monitorInfos.add(object);
            }
            result.put("topicInfo", monitorInfos);
        }
        return result;
    }
    public JSONObject findMonitorPatientsByDoctors(String topicItem, String day, Integer page, Integer pageSize, Integer detail) {
        JSONObject result = new JSONObject();
                switch (topicItem){
        String sql = " SELECT DISTINCT p.id,p.name,p.residential_area residentialArea,p.photo,p.idcard,p.mobile, " +
                " p.openid,p.sex,p.pad_imei padImei,p.home_lat_lon homeLatLon,p.lat_lon latLon " +
                " from base_patient p , base_service_package_sign_record sr,base_service_package_record r,base_team_member m  " +
                " WHERE p.id = sr.patient and sr.status=1 and m.team_code = r.team_code and sr.id=r.sign_id  " +
                " and m.del = '1' ";
        String fliter = "";
        String categoryCode = "";
        String topicItemTmp = topicItem;
        switch (topicItem) {
            case "actionTrack":
                categoryCode = "'4'";
                topicItemTmp = "preventLost";
                break;
            case "preventLost":
                categoryCode = "'4'";
                break;
            case "preventFall":
                categoryCode = "'12'";
                break;
            case "preventFire":
                categoryCode = "'15'";
                break;
            case "preventGasLeakage":
                categoryCode = "'14'";
                break;
            case "preventOutOfBed":
                categoryCode = "'13'";
                break;
            case "emergencyAssistance":
                categoryCode = "'7','4'";
                break;
        }
        if ("emergencyAssistance".equals(topicItem)) {
            fliter = "";
        } else {
            fliter = " and EXISTS (select 1 from wlyy_patient_device pd INNER JOIN dm_device dd on pd.device_id = dd.id  " +
                    " where  pd.user = sr.patient and pd.del=0 and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItemTmp + "',dd.service_topic)) ";
        }
        if ("preventLost".equals(topicItem)) {//有绑定围栏的居民
            fliter += " and EXISTS (select 1 from wlyy_patient_safe_area sf where sf.patient = p.id and sf.del=1 and sf.manage_status=1) ";
        }
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql + fliter);
        result.put("total", list.size());
        if (1 == detail) {//获取详情
            JSONArray monitorInfos = new JSONArray();
            page = page > 0 ? page - 1 : 0;
            Integer totalPage = 0;
            if (list.size() % pageSize == 0) {
                totalPage = list.size() / pageSize;
            } else {
                totalPage = list.size() / pageSize + 1;
            }
            Integer currentIndexFrom = page * pageSize;
            Integer currentIndexEnd = page * pageSize + pageSize;
            result.put("totalPage", totalPage);
            result.put("currentPage", page + 1);
            for (int i = currentIndexFrom; i < list.size() && i < currentIndexEnd; i++) {
                Map<String, Object> patientTmp = list.get(i);
                com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
                String deviceSn = "";
                if ("emergencyAssistance".equals(topicItem)){
                    sql = "select pd.device_sn,dd.category_code from wlyy_patient_device pd INNER JOIN dm_device dd " +
                    " on pd.device_id = dd.id where  pd.user = '" + patientTmp.get("id").toString() + "' and pd.del=0  and pd.category_code in (" + categoryCode + ")";
                    List<Map<String,Object>> deviceSns = jdbcTemplate.queryForList(sql);
                    if (deviceSns.size() > 0) {
                        boolean findFlag = false;
                        for (Map<String,Object> tmp:deviceSns){
                            if("4".equals(tmp.get("category_code").toString())){
                                deviceSn = tmp.get("device_sn").toString();
                                findFlag=true;
                            }
                        }
                        if (!findFlag){
                            deviceSn = deviceSns.get(0).get("device_sn").toString();
                        }
                    }
                    object.put("deviceSn", deviceSn);
                }else {
                    sql = "select pd.device_sn from wlyy_patient_device pd INNER JOIN dm_device dd " +
                    " on pd.device_id = dd.id where  pd.user = '" + patientTmp.get("id").toString() + "' and pd.del=0  and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItemTmp + "',dd.service_topic)";
                    List<String> deviceSns = jdbcTemplate.queryForList(sql, String.class);
                    if (deviceSns.size() > 0) {
                        deviceSn = deviceSns.get(0);
                    }
                    object.put("deviceSn", deviceSn);
                }
                switch (topicItem) {
                    case "actionTrack":
                        JSONArray locations = JSON.parseArray(JSON.toJSONString(patientDeviceService.getX1Locations(deviceSn, day), SerializerFeature.WriteMapNullValue));
                        object.put("routes", locations);
                        //获取手表定位
                        JSONObject response= patientDeviceService.getAqgDeviceInfo2(deviceSn);
                        if (response!=null) {
                        JSONObject response = patientDeviceService.getAqgDeviceInfo2(deviceSn);
                        if (response != null) {
                            //定位信息
                            if (response.containsKey("last_location") && response.get("last_location") != null) {
                                JSONObject locationTmp = response.getJSONObject("last_location");
@ -2236,32 +2405,75 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
                            }
                        }
                        break;
                    case "emergencyAssistance":
                        String id = (String) list.get(i).get("id");
                        String residentialArea = (String) list.get(i).get("residentialArea");
                        String SoSDeviceSql = "SELECT id  FROM base_emergency_assistance_order WHERE `status` = '1' AND patient = '" + id + "'";
                        List<Map<String, Object>> listMapsOrder = jdbcTemplate.queryForList(SoSDeviceSql);
                        JSONObject tmp = new JSONObject();
                        if (listMapsOrder.size() > 0) {
                            for (Map<String, Object> stringObjectMap : listMapsOrder) {
                                tmp.put("orderId", stringObjectMap.get("id"));
                            }
                            tmp.put("eCall", 1);
                        } else {
                            tmp.put("eCall", 0);
                            tmp.put("orderId", "");
                        }
                        BasePatientDO patientDO = basePatientDao.findById(id);
                        if (null != patientDO) {
                            if (StringUtils.isNotBlank(patientDO.getLatLon())) {
                                String[] latLon = patientDO.getLatLon().toString().split(",");
                                if (StringUtils.isNotBlank(patientDO.getHomeLatLon())) {
                                    String homeLatLon = patientDO.getHomeLatLon();
                                    double homeLat = Double.parseDouble(homeLatLon.split(",")[0]);
                                    double homeLon = Double.parseDouble(homeLatLon.split(",")[1]);
                                    double homeDistance = countDistance.getDistance(Double.parseDouble(latLon[0]), Double.parseDouble(latLon[1]),
                                            homeLat, homeLon);
                                    if (homeDistance > 50 * 1000) {
                                        tmp.put("atHome", false);
                                    } else {
                                        tmp.put("atHome", true);
                                    }
                                } else {
                                    tmp.put("atHome", null);
                                }
                                String locationAddress = LatitudeUtils.getLocationAddress(latLon[0], latLon[1]);
                                tmp.put("address", locationAddress);
                            } else {
                                tmp.put("atHome", null);
                                tmp.put("address", "");
                            }
                        }
                        object.put("info", tmp);
                        break;
                    default:
                        object = patientMonitoringInfo(patientTmp.get("id").toString(),topicItem,false);
                        object = patientMonitoringInfo(patientTmp.get("id").toString(), topicItem, deviceSn,false);
                        break;
                }
                object.put("patientInfo",patientTmp);
                object.put("patientInfo", patientTmp);
                object.put("deviceSn", deviceSn);
                monitorInfos.add(object);
            }
            result.put("topicInfo",monitorInfos);
        }else {
            result.put("topicInfo", monitorInfos);
        } else {
            JSONArray monitorInfos = new JSONArray();
            for (int i=0;i<list.size();i++){
                Map<String,Object> patientTmp = list.get(i);
                String deviceSn ="";
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> patientTmp = list.get(i);
                String deviceSn = "";
                List<String> deviceSns = jdbcTemplate.queryForList("select pd.device_sn from wlyy_patient_device pd INNER JOIN dm_device dd " +
                        " on pd.device_id = dd.id where  pd.user = '"+patientTmp.get("id").toString()+"' and pd.del=0  and pd.category_code in ("+categoryCode+") and FIND_IN_SET('"+topicItem+"',dd.service_topic)",String.class);
                if (deviceSns.size()>0){
                        " on pd.device_id = dd.id where  pd.user = '" + patientTmp.get("id").toString() + "' and pd.del=0  and pd.category_code in (" + categoryCode + ") and FIND_IN_SET('" + topicItem + "',dd.service_topic)", String.class);
                if (deviceSns.size() > 0) {
                    deviceSn = deviceSns.get(0);
                }
                JSONObject object  = patientMonitoringInfo(patientTmp.get("id").toString(),"null",false);
                object.put("deviceSn",deviceSn);
                object.put("patientInfo",patientTmp);
                JSONObject object = patientMonitoringInfo(patientTmp.get("id").toString(), "null", null,false);
                object.put("deviceSn", deviceSn);
                object.put("patientInfo", patientTmp);
                monitorInfos.add(object);
            }
            result.put("topicInfo",monitorInfos);
            result.put("topicInfo", monitorInfos);
        }
        return result;
    }
}

+ 68 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/DetectionPlatformService.java

@ -5,7 +5,9 @@ import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.xs.datatypes.ByteList;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.service.device.DeviceService;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.service.sign.ServicePackageService;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
@ -16,6 +18,7 @@ import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import io.swagger.models.auth.In;
@ -29,10 +32,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
/***
@ -60,6 +60,11 @@ public class DetectionPlatformService  {
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private BaseOrgDao orgDao;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ServicePackageService servicePackageService;
    /**
     * 体征监测 安防监护
@ -528,4 +533,63 @@ public class DetectionPlatformService  {
        return object;
    }
    public List<Map<String,Object >> findSignOlder(){
        String sql=  "SELECT p.id,p.name,p.photo,p.idcard,CAST(IFNULL(p.birthday,'') AS char ) birthday,p.residential_area residentialArea,p.sex, " +
                " p.ykt_id yktId, case 1 WHEN p.openid is not null then 1 WHEN p.on_line = '1' then 1 ELSE 0 end as online,IFNULL(p.sign_status,0) signStatus "+
                " from base_service_package_sign_record sr,base_patient p,base_service_package_record r,base_team_member m " +
                "WHERE sr.status=1 and sr.patient = p.id and m.team_code = r.team_code and sr.id=r.sign_id " +
                " and m.del = '1' and  p.del = '1' " +
                " GROUP BY p.id,p.name,p.photo,p.idcard,p.birthday,p.residential_area,p.sex,p.ykt_id,online,signStatus" +
                " ORDER BY online desc,p.ykt_id desc,signStatus desc ";
        /*String sql=  "SELECT p.id,p.name,p.photo,p.idcard,CAST(IFNULL(p.birthday,'') AS char ) birthday,p.residential_area residentialArea,p.sex, " +
                " p.ykt_id yktId, case 1 WHEN p.openid is not null then 1 WHEN p.on_line = '1' then 1 ELSE 0 end as online,IFNULL(p.sign_status,0) signStatus "+
                " from base_service_package_sign_record sr,base_patient p,base_service_package_record r,base_team_member m " +
                "WHERE sr.status=1 and sr.patient = p.id and m.team_code = r.team_code and sr.id=r.sign_id " +
                "and m.doctor_code = '"+doctorId+"' and m.del = '1' and  p.del = '1' " +
                " GROUP BY p.id,p.name,p.photo,p.idcard,p.birthday,p.residential_area,p.sex,p.ykt_id,online,signStatus" +
                " ORDER BY online desc,p.ykt_id desc,signStatus desc ";*/
//        String sql = "SELECT DISTINCT p.id,p.name,p.photo,p.idcard,p.mobile,p.openid,p.sex,p.pad_imei padImei,p.residential_area residentialArea  " +
//                " from base_service_package_sign_record sr,base_patient p,base_service_package_record r,base_team_member m " +
//                "WHERE sr.status=1 and sr.patient = p.id and m.team_code = r.team_code and sr.id=r.sign_id " +
//                "and m.doctor_code = '"+doctorId+"' and m.del = '1' ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        String sqlLife= "SELECT COUNT(*) from base_life_care_order ";
        String sqlEmergency= "SELECT COUNT(*) from base_emergency_assistance_order ";
        String sqlSecurity= "SELECT COUNT(*) from base_security_monitoring_order  ";
        String sqlDevice = "SELECT pd.category_code deviceFlag, IFNULL(d.contact_status,0) status from wlyy_patient_device pd,wlyy_devices d";
        for (Map<String,Object> map : list){
            String paientId = map.get("id").toString();
            String idcard = map.get("idcard").toString();
            map.put("age", IdCardUtil.getAgeForIdcard(idcard));
            //签约医生标识
            List<Map<String,Object>> doctorList = servicePackageService.getServerDoctorAll(map.get("id").toString(),"0","1");
            List<Map<String,Object>> helperList = servicePackageService.getServerDoctorAll(map.get("id").toString(),"0","2");
            map.put("helper", helperList.size()>0?1:0);
            map.put("doctor", doctorList.size()>0?1:0);
            String filterDevice = " WHERE pd.device_sn = d.device_code and pd.user = '"+paientId+"' ORDER BY deviceFlag,status desc";
            List<Map<String,Object>> deviceList = jdbcTemplate.queryForList(sqlDevice+filterDevice);
            Iterator it = deviceList.listIterator();
            Map<Object,Object> deviceMap = new HashedMap();
            while (it.hasNext()){
                Map<String,Object> tmp = (Map<String,Object>)it.next();
                if(deviceMap.containsKey(tmp.get("deviceFlag"))){
                    it.remove();
                }else{
                    deviceMap.put(tmp.get("deviceFlag"),tmp.get("deviceFlag"));
                }
            }
            String filter = " where patient = '"+paientId+"'";
            Integer lifeCare = jdbcTemplate.queryForObject(sqlLife+filter,Integer.class);
            Integer emergency = jdbcTemplate.queryForObject(sqlEmergency+filter,Integer.class);
            Integer security = jdbcTemplate.queryForObject(sqlSecurity+filter,Integer.class);
            map.put("lifeCare",lifeCare);
            map.put("emergency",emergency);
            map.put("security",security);
            map.put("devices",deviceList);
        }
        return list;
    }
}

+ 960 - 599
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsService.java

@ -43,13 +43,16 @@ import org.springframework.transaction.annotation.Transactional;
import javax.persistence.Transient;
import javax.persistence.criteria.CriteriaBuilder;
import java.awt.print.Pageable;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
 *
 * Created by yeshijie on 2021/4/7.
 */
@Service
@ -98,70 +101,223 @@ public class StatisticsService {
    /**
     * 统计总数
     *
     * @param endDate
     * @return
     * @throws Exception
     */
    public JSONObject statisticsTotalAmount(String endDate) throws Exception {
        JSONObject res = new JSONObject();
        // 28 新生儿-在线咨询总数
        // 31 老人-在线咨询总数
        // 35 新生儿-上门辅导-服务工单数
        // 37 老人-能力评估
        // 39 老人-生活照料-服务工单数
        // 44 老人-生活照料-代预约
        // 54 新生儿-上门辅导-工单发起数
        String index = "28,31,35,37,39,44,54";
        String[] indexes = index.split(",");
        for(String ind:indexes){
        for (String ind : indexes) {
            //总量
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, defalutArea, defalutLevel, ind, SaveModel.timeLevel_DDL);
            res.put("index_"+ind,saveModel.getResult2().longValue());
            res.put("index_" + ind, saveModel.getResult2().longValue());
        }
        //41紧急预警43安防要与实时一样,查sql
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_org' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        String filter="";
        String filter2="";
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        String filter = "";
        String filter2 = "";
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " and hospital not in ('"+orgCodes+"') ";
            filter2 = " and org_code not in ('"+orgCodes+"') ";
        }
        String emergencyCallSql = "SELECT COUNT(1) FROM base_emergency_assistance_order WHERE status >= 0 "+filter2;
        Integer emergencyCallNum = jdbcTemplate.queryForObject(emergencyCallSql,Integer.class);
        String securityMonitoringSql = "SELECT COUNT(1) FROM base_security_monitoring_order where 1=1 "+filter;
        Integer securityMonitoringNum = jdbcTemplate.queryForObject(securityMonitoringSql,Integer.class);
        res.put("index_"+41,emergencyCallNum);
        res.put("index_"+43,securityMonitoringNum);
            orgCodes = orgCodes.replaceAll(",", "','");
            filter = " and hospital not in ('" + orgCodes + "') ";
            filter2 = " and org_code not in ('" + orgCodes + "') ";
        }
        String emergencyCallSql = "SELECT COUNT(1) FROM base_emergency_assistance_order WHERE status >= 0 " + filter2;
        Integer emergencyCallNum = jdbcTemplate.queryForObject(emergencyCallSql, Integer.class);
        String securityMonitoringSql = "SELECT COUNT(1) FROM base_security_monitoring_order where 1=1 " + filter;
        Integer securityMonitoringNum = jdbcTemplate.queryForObject(securityMonitoringSql, Integer.class);
        /*//男 女 性别总数
        String sexCountSql = "SELECT COUNT(*) ss, CASE p.sex WHEN 1 THEN '男' WHEN 2 THEN '女' END AS sex " +
                "FROM wlyy_patient_label lab " +
                "INNER JOIN base_patient p ON p.id = lab.patient AND lab.label_type = '3' AND lab.patient NOT IN ('null') GROUP BY p.sex";
        List<Map<String, Object>> sexCountMap = jdbcTemplate.queryForList(sexCountSql);
        res.put("sexCount",sexCountMap);*/
        //老人-紧急预警
        res.put("index_" + 41, emergencyCallNum);
        //老人 安放监护
        res.put("index_" + 43, securityMonitoringNum);
        //评估类型
        res.put("capacityAssessment",capacityAssessment(endDate,defalutArea,defalutLevel));
        res.put("patientLabelStatistic",statisticsOrderServer("47",endDate,2,"2"));
        res.put("capacityAssessment", cloudCareForTheElderly(endDate, defalutArea, defalutLevel));
        //居民健康标签纬度
        res.put("patientLabelStatistic", statisticsOrderServer("47", endDate, 2, "2"));
        // 1.4.2 大屏新增活动浏览数、公益课程播放数、活动报名数
        // activity-1   活动浏览次数
        // activity-2   公艺课程播放
        String sql = " select type,num from base_child_activity_click where type in(1,2)";
        List<Map<String,Object>> lists = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> tmp:lists){
        List<Map<String, Object>> lists = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> tmp : lists) {
            Integer num = Integer.parseInt(tmp.get("num").toString());
            res.put("activity_"+tmp.get("type").toString(),num);
            res.put("activity_" + tmp.get("type").toString(), num);
        }
        //activity-3 幼儿活动报名-总数
        sql = " select count(id) as total from base_child_activity_registration ";
        Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
        res.put("activity_3",count);
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        res.put("activity_3", count);
        return res;
    }
    /*曲线*/
    public JSONObject curveTotal(String day, String type, String area, int level, String timeLevel, String interval, String lowLevel) throws Exception {
        JSONObject res = new JSONObject();
        StringBuffer sqlbuff = new StringBuffer();
        List<Map<String, Object>> listMaps = null;
        if ("".equals(day)) {
            day = "30";
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, -Integer.parseInt(day));
        java.sql.Date date = new java.sql.Date(cal.getTime().getTime());
        /*---------sql----------*/
        // 3 幼儿活动
        if ("3".equals(type)) {
            sqlbuff.append("SELECT count(id) amount,DATE_FORMAT(create_time,'%Y-%m-%d') as `range` FROM base_child_activity_registration WHERE DATE_SUB(CURDATE(), INTERVAL " + day + " DAY) <= date(create_time) GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d') ORDER BY create_time");
            listMaps = jdbcTemplate.queryForList(String.valueOf(sqlbuff));
            res.put("count", listMaps);
        }
        //41 老人-紧急呼叫
        if ("41".equals(type)) {
            sqlbuff.append("SELECT COUNT(id) amount,DATE_FORMAT(create_time,'%Y-%m-%d') AS `range` FROM base_emergency_assistance_order WHERE DATE_SUB(CURDATE(), INTERVAL " + day + " DAY) <= DATE(create_time) AND status >= 0 GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d') ORDER BY create_time");
            listMaps = jdbcTemplate.queryForList(String.valueOf(sqlbuff));
            res.put("count", listMaps);
        }
        //43 老人 安放监护
        if ("43".equals(type)) {
            sqlbuff.append("SELECT COUNT(id) amount,DATE_FORMAT(create_time,'%Y-%m-%d') AS `range` FROM base_security_monitoring_order WHERE DATE_SUB(CURDATE(), INTERVAL " + day + " DAY) <= DATE(create_time) AND status >= 0 GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d') ORDER BY create_time");
            listMaps = jdbcTemplate.queryForList(String.valueOf(sqlbuff));
            res.put("count", listMaps);
        }
        // 1   活动浏览次数
        if ("1".equals(type)) {
            sqlbuff.append("SELECT COUNT(id) amount,DATE_FORMAT(create_time,'%Y-%m-%d') AS `range` FROM base_activity_click WHERE DATE_SUB(CURDATE(), INTERVAL " + day + " DAY) <= DATE(create_time) AND activity_type = 1 GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d') ORDER BY create_time");
            listMaps = jdbcTemplate.queryForList(String.valueOf(sqlbuff));
            res.put("count", listMaps);
        }
        // 2 公艺课程播放
        if ("2".equals(type)) {
            sqlbuff.append("SELECT COUNT(id) amount,DATE_FORMAT(create_time,'%Y-%m-%d') AS `range` FROM base_activity_click WHERE DATE_SUB(CURDATE(), INTERVAL " + day + " DAY) <= DATE(create_time) AND activity_type = 2 GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d') ORDER BY create_time");
            listMaps = jdbcTemplate.queryForList(String.valueOf(sqlbuff));
            res.put("count", listMaps);
        }
        /*----------es-----------*/
        // 39 老人-生活照料-服务工单数
        // 44 老人-生活照料-代预约
        // 28 新生儿-在线咨询总数
        // 32 新生儿-在线咨询总数
        // 35 新生儿-上门辅导-服务工单数
        // 54 新生儿-上门辅导-工单数发起数
        if ("".equals(interval)) {
            interval = "1";
        }
        if ("".equals(timeLevel)) {
            timeLevel = "1";
        }
        if (!"3".equals(type) && !"41".equals(type) && !"43".equals(type) && !"1".equals(type) && !"2".equals(type)) {
            JSONArray esResoult = addLine(String.valueOf(date), LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), area, level, type, timeLevel, interval, lowLevel);
            List<Map> maps = JSONObject.parseArray(esResoult.toJSONString(), Map.class);
            res.put("count", maps);
        }
        return res;
    }
    public JSONObject serviceResources(){
    /*综合总数*/
    public JSONObject combinedTotal(String type, String endDate) throws Exception {
        JSONObject res = new JSONObject();
        String index = "";
        //es
        // 39 老人-生活照料-服务工单数
        // 44 老人-生活照料-代预约
        // 28 新生儿-在线咨询总数
        // 35 新生儿-上门辅导-服务工单数
        // 29 新生儿-在线咨询未回复数
        // 54 新生儿-上门辅导-工单数发起数
        //sql
        // activity-3 幼儿活动
        // activity-1   活动浏览次数
        // activity-2   公艺课程播放
        //41 老人-紧急呼叫
        //43 老人 安放监护
        //type   幼儿42    37老人
        if ("37".equals(type)) {
            index = "39,44";
            String[] indexes = index.split(",");
            for (String ind : indexes) {
                //总量
                SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, defalutArea, defalutLevel, ind, SaveModel.timeLevel_DDL);
                res.put("index_" + ind, saveModel.getResult2().longValue());
            }
            String emergencyCallSql = "SELECT COUNT(1) FROM base_emergency_assistance_order WHERE status >= 0 ";
            Integer emergencyCallNum = jdbcTemplate.queryForObject(emergencyCallSql, Integer.class);
            String securityMonitoringSql = "SELECT COUNT(1) FROM base_security_monitoring_order where 1=1 ";
            Integer securityMonitoringNum = jdbcTemplate.queryForObject(securityMonitoringSql, Integer.class);
            res.put("index_41", emergencyCallNum);
            res.put("index_43", securityMonitoringNum);
        } else {
            index = "28,35,54,29";
            String[] indexes = index.split(",");
            for (String ind : indexes) {
                //总量
                SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, defalutArea, defalutLevel, ind, SaveModel.timeLevel_DDL);
                res.put("index_" + ind, saveModel.getResult2().longValue());
            }
            // activity-1   活动浏览次数
            // activity-2   公艺课程播放
            String sql = " select type,num from base_child_activity_click where type in(1,2)";
            List<Map<String, Object>> lists = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> tmp : lists) {
                Integer num = Integer.parseInt(tmp.get("num").toString());
                res.put("activity_" + tmp.get("type").toString(), num);
            }
            /*幼儿活动报名 总数*/
            String sqlActivity = " select count(id) as total from base_child_activity_registration ";
            Integer count = jdbcTemplate.queryForObject(sqlActivity, Integer.class);
            res.put("activity_3", count);
        }
        return res;
    }
    public JSONObject serviceResources() {
        String orgFilter = "";
        String sqlOrg = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_org' ";
        List<Map<String,Object>> listOrg =  jdbcTemplate.queryForList(sqlOrg);
        if(listOrg.size()>0){
        List<Map<String, Object>> listOrg = jdbcTemplate.queryForList(sqlOrg);
        if (listOrg.size() > 0) {
            String orgCodes = String.valueOf(listOrg.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            orgFilter = " and code not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            orgFilter = " and code not in ('" + orgCodes + "')";
        }
        JSONObject res = new JSONObject();
        String medicalInstitutionSql = "SELECT COUNT(1) FROM base_org WHERE (type = 1 OR type = 2) AND del = 1 "+orgFilter;
        String elderlyCarServiceSql = "SELECT COUNT(1) FROM base_org WHERE type = 3 AND del = 1"+orgFilter;
        String childcareInstitutionsssSql = "SELECT COUNT(1) FROM base_org WHERE type = 4 AND del = 1"+orgFilter;
        String medicalInstitutionSql = "SELECT COUNT(1) FROM base_org WHERE (type = 1 OR type = 2) AND del = 1 " + orgFilter;
        String elderlyCarServiceSql = "SELECT COUNT(1) FROM base_org WHERE type = 3 AND del = 1" + orgFilter;
        String childcareInstitutionsssSql = "SELECT COUNT(1) FROM base_org WHERE type = 4 AND del = 1" + orgFilter;
        //助老员和教师注册人数
        Integer doctorNum = 0;
@ -171,31 +327,31 @@ public class StatisticsService {
                "and a.doctor_level is not null and h.org_code not in ( " +
                "SELECT dict_code from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_org'  " +
                ") GROUP BY a.doctor_level";
        List<Map<String,Object>> list2 = jdbcTemplate.queryForList(sql2);
        for(Map<String,Object> map:list2){
        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
        for (Map<String, Object> map : list2) {
            String archive_type = map.get("doctor_level").toString();
            Integer num = Integer.valueOf(map.get("c").toString());
            if("1".equals(archive_type)){
            if ("1".equals(archive_type)) {
                doctorNum = num;
                continue;
            }
            if("2".equals(archive_type)){
            if ("2".equals(archive_type)) {
                helperNum = num;
                continue;
            }
            if("3".equals(archive_type)){
            if ("3".equals(archive_type)) {
                teacherNum = num;
            }
        }
        Integer medicalInstitutionNum = jdbcTemplate.queryForObject(medicalInstitutionSql,Integer.class);
        Integer elderlyCarServiceNum = jdbcTemplate.queryForObject(elderlyCarServiceSql,Integer.class);
        Integer childcareInstitutionsssNum = jdbcTemplate.queryForObject(childcareInstitutionsssSql,Integer.class);
        res.put("medicalInstitutionNum",medicalInstitutionNum);             //医疗结构
        res.put("elderlyCarServiceNum",elderlyCarServiceNum);               //养老机构
        res.put("childcareInstitutionsssNum",childcareInstitutionsssNum);   //托育机构
        res.put("doctorNum",doctorNum);     //医生
        res.put("helperNum",helperNum);     //助老员
        res.put("teacherNum",teacherNum);   //教师
        Integer medicalInstitutionNum = jdbcTemplate.queryForObject(medicalInstitutionSql, Integer.class);
        Integer elderlyCarServiceNum = jdbcTemplate.queryForObject(elderlyCarServiceSql, Integer.class);
        Integer childcareInstitutionsssNum = jdbcTemplate.queryForObject(childcareInstitutionsssSql, Integer.class);
        res.put("medicalInstitutionNum", medicalInstitutionNum);             //医疗结构
        res.put("elderlyCarServiceNum", elderlyCarServiceNum);               //养老机构
        res.put("childcareInstitutionsssNum", childcareInstitutionsssNum);   //托育机构
        res.put("doctorNum", doctorNum);     //医生
        res.put("helperNum", helperNum);     //助老员
        res.put("teacherNum", teacherNum);   //教师
        return res;
    }
@ -205,11 +361,11 @@ public class StatisticsService {
        String filter = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " and id not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            filter = " and id not in ('" + orgCodes + "')";
        }
        Integer olderTotal = 0;
@ -218,158 +374,159 @@ public class StatisticsService {
        sql1 += filter;
        sql1 += " GROUP BY archive_type";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql1);
        for(Map<String,Object> map:list1){
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
        for (Map<String, Object> map : list1) {
            String archive_type = map.get("archive_type").toString();
            Integer num = Integer.valueOf(map.get("c").toString());
            if("1".equals(archive_type)){
            if ("1".equals(archive_type)) {
                olderTotal = num;
                continue;
            }
            if("2".equals(archive_type)){
            if ("2".equals(archive_type)) {
                childTotal = num;
            }
        }
        String healthEquipmentSql = "SELECT COUNT(1) FROM wlyy_patient_device WHERE del = 0 AND (category_code = 1 OR category_code = 2)";
        Integer healthEquipmentNum = jdbcTemplate.queryForObject(healthEquipmentSql,Integer.class);
        Integer healthEquipmentNum = jdbcTemplate.queryForObject(healthEquipmentSql, Integer.class);
        String securityEquipmentSql = "SELECT COUNT(1) FROM wlyy_patient_device WHERE del = 0 AND category_code > 2";
        Integer securityEquipmentNum = jdbcTemplate.queryForObject(securityEquipmentSql,Integer.class);
        Integer securityEquipmentNum = jdbcTemplate.queryForObject(securityEquipmentSql, Integer.class);
        sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_org' ";
        listtmp =  jdbcTemplate.queryForList(sqltmp);
        filter="";
        String filter2="";
        if(listtmp.size()>0){
        listtmp = jdbcTemplate.queryForList(sqltmp);
        filter = "";
        String filter2 = "";
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " and hospital not in ('"+orgCodes+"') ";
            filter2 = " and org_code not in ('"+orgCodes+"') ";
        }
        String emergencyCallSql = "SELECT COUNT(1) FROM base_emergency_assistance_order WHERE status >= 0"+filter2;
        Integer emergencyCallNum = jdbcTemplate.queryForObject(emergencyCallSql,Integer.class);
        String securityMonitoringSql = "SELECT COUNT(1) FROM base_security_monitoring_order where 1=1 "+filter;
        Integer securityMonitoringNum = jdbcTemplate.queryForObject(securityMonitoringSql,Integer.class);
        res.put("olderTotal",olderTotal);   //老人注册人数
        res.put("childTotal",childTotal);   //儿童注册人数
        res.put("healthEquipmentNum",healthEquipmentNum);   //健康设备
        res.put("securityEquipmentNum",securityEquipmentNum);   //安防设备
        res.put("emergencyCallNum",emergencyCallNum);   //紧急呼叫的次数
        res.put("securityMonitoringNum",securityMonitoringNum);   //安防监护触发工单的次数
        return  res;
            orgCodes = orgCodes.replaceAll(",", "','");
            filter = " and hospital not in ('" + orgCodes + "') ";
            filter2 = " and org_code not in ('" + orgCodes + "') ";
        }
        String emergencyCallSql = "SELECT COUNT(1) FROM base_emergency_assistance_order WHERE status >= 0" + filter2;
        Integer emergencyCallNum = jdbcTemplate.queryForObject(emergencyCallSql, Integer.class);
        String securityMonitoringSql = "SELECT COUNT(1) FROM base_security_monitoring_order where 1=1 " + filter;
        Integer securityMonitoringNum = jdbcTemplate.queryForObject(securityMonitoringSql, Integer.class);
        res.put("olderTotal", olderTotal);   //老人注册人数
        res.put("childTotal", childTotal);   //儿童注册人数
        res.put("healthEquipmentNum", healthEquipmentNum);   //健康设备
        res.put("securityEquipmentNum", securityEquipmentNum);   //安防设备
        res.put("emergencyCallNum", emergencyCallNum);   //紧急呼叫的次数
        res.put("securityMonitoringNum", securityMonitoringNum);   //安防监护触发工单的次数
        return res;
    }
    public PageEnvelop getAllDynamics(Integer page,Integer size){
    public PageEnvelop getAllDynamics(Integer page, Integer size) {
        List result = new ArrayList<>();
        Date date = DateUtil.getPreDays(new Date(),-7);
        Date date = DateUtil.getPreDays(new Date(), -7);
        String dateStr = DateUtil.dateToStrLong(date);
        String filter =" ";
        String filter = " ";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' " +
                "  or dict_name = 'jkzl_user' or dict_name = 'jkzl_helper'  or dict_name = 'jkzl_teacher' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            if (StringUtils.isNotBlank(orgCodes)){
                orgCodes = orgCodes.replaceAll(",","','");
                filter = " and user_id not in ('"+orgCodes+"')";
            if (StringUtils.isNotBlank(orgCodes)) {
                orgCodes = orgCodes.replaceAll(",", "','");
                filter = " and user_id not in ('" + orgCodes + "')";
            }
        }
        String sql = "select * from base_login_log where create_time>='"+dateStr+"' "+filter+" order by create_time desc limit "+ (page-1)*size+","+size;
        String sqlCount = "select count(id) from base_login_log where create_time>='"+dateStr+"' "+filter;
        Long count = jdbcTemplate.queryForObject(sqlCount,Long.class);
        List<BaseLoginLogDO> loginLogDOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(BaseLoginLogDO.class));
        for (BaseLoginLogDO log:loginLogDOs) {
        String sql = "select * from base_login_log where create_time>='" + dateStr + "' " + filter + " order by create_time desc limit " + (page - 1) * size + "," + size;
        String sqlCount = "select count(id) from base_login_log where create_time>='" + dateStr + "' " + filter;
        Long count = jdbcTemplate.queryForObject(sqlCount, Long.class);
        List<BaseLoginLogDO> loginLogDOs = jdbcTemplate.query(sql, new BeanPropertyRowMapper(BaseLoginLogDO.class));
        for (BaseLoginLogDO log : loginLogDOs) {
            JSONObject object = new JSONObject();
            object.put("patient",log.getUserId());
            if("1".equals(log.getLoginType())){
            object.put("patient", log.getUserId());
            if ("1".equals(log.getLoginType())) {
                //user
                object.put("onLineFlag", 0);
                object.put("archiveType","0");
            }else if("2".equals(log.getLoginType())){
                object.put("archiveType", "0");
            } else if ("2".equals(log.getLoginType())) {
                //docotr
                Integer onLineFlag =0;
                Integer onLineFlag = 0;
                BaseDoctorDO doctorDO = doctorDao.findOne(log.getUserId());
                if(doctorDO!=null&&"1".equals(doctorDO.getOnline())){
                    onLineFlag=1;
                if (doctorDO != null && "1".equals(doctorDO.getOnline())) {
                    onLineFlag = 1;
                }
                object.put("onLineFlag", onLineFlag);
                object.put("archiveType","0");
            }else{
                object.put("archiveType", "0");
            } else {
                //居民
                BasePatientDO patient = patientDao.findById(log.getUserId());
                if (patient != null){
                    Integer onLineFlag =0;
                    if (patient.getArchiveType() == null){
                if (patient != null) {
                    Integer onLineFlag = 0;
                    if (patient.getArchiveType() == null) {
                        continue;
                    }
                    switch (patient.getArchiveType().toString()){
                    switch (patient.getArchiveType().toString()) {
                        case "1":
                            //老人
                            if(StringUtils.isNotBlank(patient.getOpenid())||"1".equals(patient.getOnline())){
                                onLineFlag=1;
                            if (StringUtils.isNotBlank(patient.getOpenid()) || "1".equals(patient.getOnline())) {
                                onLineFlag = 1;
                            }
                            break;
                        case "2":
                            //新生儿
                            if(StringUtils.isNotBlank(patient.getOpenid())){
                                onLineFlag=1;
                            if (StringUtils.isNotBlank(patient.getOpenid())) {
                                onLineFlag = 1;
                            }
                            break;
                    }
                    object.put("archiveType",patient.getArchiveType());
                    object.put("residentialArea",patient.getResidentialArea());
                    object.put("archiveType", patient.getArchiveType());
                    object.put("residentialArea", patient.getResidentialArea());
                    object.put("onLineFlag", onLineFlag);
                }
            }
            object.put("name",log.getName());
            object.put("createTime", DateUtil.dateToStrLong(log.getCreateTime()) );
            object.put("name", log.getName());
            object.put("createTime", DateUtil.dateToStrLong(log.getCreateTime()));
            object.put("clientType", log.getClientType());
            result.add(object);
        }
        return PageEnvelop.getSuccessListWithPage("查询成功",result,page,size,count);
        return PageEnvelop.getSuccessListWithPage("查询成功", result, page, size, count);
    }
    /**
     * 服务排名分析
     *
     * @param endDate
     * @param orgType
     */
    public List<NumVo> serviceRankingAnalysis(String endDate, String orgType) throws Exception {
        String index = "28,35";
        if("3".equals(orgType)){
        if ("3".equals(orgType)) {
            index = "31,39,44";
        }
        String[] indexes = index.split(",");
        Map<String,NumVo> map = new HashedMap();
        for(String ind:indexes){
        Map<String, NumVo> map = new HashedMap();
        for (String ind : indexes) {
            //总量
            List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(endDate, endDate, defalutArea, defalutLevel, ind, SaveModel.timeLevel_DDL,null,SaveModel.OrgLevel);
            for (SaveModel saveModel:saveModels){
            List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(endDate, endDate, defalutArea, defalutLevel, ind, SaveModel.timeLevel_DDL, null, SaveModel.OrgLevel);
            for (SaveModel saveModel : saveModels) {
                String orgCode = saveModel.getHospital();
                if(StringUtils.isBlank(orgCode)){
                if (StringUtils.isBlank(orgCode)) {
                    continue;
                }
                if(map.containsKey(orgCode)){
                if (map.containsKey(orgCode)) {
                    NumVo numVo = map.get(orgCode);
                    Long num = saveModel.getResult2().longValue()+numVo.getNum();
                    Long num = saveModel.getResult2().longValue() + numVo.getNum();
                    numVo.setNum(num);
                }else{
                } else {
                    NumVo numVo = new NumVo();
                    numVo.setCode(orgCode);
                    numVo.setName(saveModel.getHospitalName());
                    numVo.setNum(saveModel.getResult2().longValue());
                    map.put(orgCode,numVo);
                    map.put(orgCode, numVo);
                }
            }
        }
        List<NumVo> list = new ArrayList<>();
        for (String key:map.keySet()){
        for (String key : map.keySet()) {
            list.add(map.get(key));
        }
        list=list.stream().sorted(Comparator.comparing(NumVo::getNum).reversed()).collect(Collectors.toList());
        list = list.stream().sorted(Comparator.comparing(NumVo::getNum).reversed()).collect(Collectors.toList());
        return list;
    }
@ -377,83 +534,85 @@ public class StatisticsService {
    /**
     * 大屏实时数据 半小时刷新一次只能查数据库
     */
    public JSONObject realTimeData() throws Exception{
    public JSONObject realTimeData() throws Exception {
        JSONObject json = new JSONObject();
        //幼儿数
        String sql = "SELECT COUNT(DISTINCT patient) from base_doctor_patient_tmp WHERE del = 1 ";
        Integer childNum = jdbcTemplate.queryForObject(sql,Integer.class);
        json.put("childNum",childNum);
        Integer childNum = jdbcTemplate.queryForObject(sql, Integer.class);
        json.put("childNum", childNum);
        //幼儿 服务次数
        String startDate = DateUtil.getNowYear()+"-01-01 00:00:00";
        String startDate = DateUtil.getNowYear() + "-01-01 00:00:00";
        String endDate = DateUtil.getStringDate();
        String sql28 = "SELECT COUNT(o.consult) FROM wlyy_consult_team o WHERE o.type = 23 and o.czrq >='"+startDate+"' ";
        String sql35 = "SELECT COUNT(o.patient) FROM base_door_coach_order o WHERE o.`status`=6  and o.update_time>='"+startDate+"' ";
        Integer num28 = jdbcTemplate.queryForObject(sql28,Integer.class);
        Integer num35 = jdbcTemplate.queryForObject(sql35,Integer.class);
        Integer childServiceNum = num28+num35;
        json.put("childServiceNum",childServiceNum);
        String sql28 = "SELECT COUNT(o.consult) FROM wlyy_consult_team o WHERE o.type = 23 and o.czrq >='" + startDate + "' ";
        String sql35 = "SELECT COUNT(o.patient) FROM base_door_coach_order o WHERE o.`status`=6  and o.update_time>='" + startDate + "' ";
        Integer num28 = jdbcTemplate.queryForObject(sql28, Integer.class);
        Integer num35 = jdbcTemplate.queryForObject(sql35, Integer.class);
        Integer childServiceNum = num28 + num35;
        json.put("childServiceNum", childServiceNum);
        //老人 服务次数
        String sql31 = "SELECT COUNT(o.consult) FROM wlyy_consult_team o WHERE o.type = 24 and o.czrq >='"+startDate+"' ";
        String sql39 = "SELECT COUNT(o.patient) FROM base_life_care_order o WHERE o.`status`=2 and o.update_time>='"+startDate+"' ";
        String sql44 = "SELECT COUNT(o.id) FROM base_life_care_order o WHERE o.`status`>0 and o.type = 3 and o.update_time>='"+startDate+"' ";
        Integer num31 = jdbcTemplate.queryForObject(sql31,Integer.class);
        Integer num39 = jdbcTemplate.queryForObject(sql39,Integer.class);
        Integer num44 = jdbcTemplate.queryForObject(sql44,Integer.class);
        String sql31 = "SELECT COUNT(o.consult) FROM wlyy_consult_team o WHERE o.type = 24 and o.czrq >='" + startDate + "' ";
        String sql39 = "SELECT COUNT(o.patient) FROM base_life_care_order o WHERE o.`status`=2 and o.update_time>='" + startDate + "' ";
        String sql44 = "SELECT COUNT(o.id) FROM base_life_care_order o WHERE o.`status`>0 and o.type = 3 and o.update_time>='" + startDate + "' ";
        Integer num31 = jdbcTemplate.queryForObject(sql31, Integer.class);
        Integer num39 = jdbcTemplate.queryForObject(sql39, Integer.class);
        Integer num44 = jdbcTemplate.queryForObject(sql44, Integer.class);
        Integer olderServiceNum = num31 + num39 + num44;
        json.put("olderServiceNum",olderServiceNum);
        json.put("olderServiceNum", olderServiceNum);
        String signSql = " SELECT COUNT(sr.id) " +
                " FROM " +
                "  base_service_package_sign_record sr " +
                " WHERE " +
                "  sr.STATUS = 1 ";
        //当前签约老人数
        Integer signNum = jdbcTemplate.queryForObject(signSql,Integer.class);
        json.put("signNum",signNum);
        Integer signNum = jdbcTemplate.queryForObject(signSql, Integer.class);
        json.put("signNum", signNum);
        return json;
    }
    /**
     * 获取登录记录
     *
     * @param page
     * @param size
     * @return
     */
    public PageEnvelop fingLoginLog(Integer page,Integer size){
    public PageEnvelop fingLoginLog(Integer page, Integer size) {
        List<String> result = new ArrayList<>();
        Date date = DateUtil.getPreDays(new Date(),-7);
        Date date = DateUtil.getPreDays(new Date(), -7);
        String dateStr = DateUtil.dateToStrLong(date);
        String sql = "select * from base_login_log where create_time>='"+dateStr+"'  order by create_time desc limit "+ (page-1)*size+","+size;
        String sqlCount = "select count(id) from base_login_log where create_time>='"+dateStr+"' ";
        Long count = jdbcTemplate.queryForObject(sqlCount,Long.class);
        List<BaseLoginLogDO> loginLogDOs = jdbcTemplate.query(sql,new BeanPropertyRowMapper(BaseLoginLogDO.class));
        for (BaseLoginLogDO log:loginLogDOs) {
        String sql = "select * from base_login_log where create_time>='" + dateStr + "'  order by create_time desc limit " + (page - 1) * size + "," + size;
        String sqlCount = "select count(id) from base_login_log where create_time>='" + dateStr + "' ";
        Long count = jdbcTemplate.queryForObject(sqlCount, Long.class);
        List<BaseLoginLogDO> loginLogDOs = jdbcTemplate.query(sql, new BeanPropertyRowMapper(BaseLoginLogDO.class));
        for (BaseLoginLogDO log : loginLogDOs) {
            String content = log.getName() + "登录云照护平台 登录终端:" + getClientName(log.getClientType())
                    + " " + DateUtil.dateToStrLong(log.getCreateTime());
            result.add(content);
        }
        return PageEnvelop.getSuccessListWithPage("查询成功",result,page,size,count);
        return PageEnvelop.getSuccessListWithPage("查询成功", result, page, size, count);
    }
    /**
     * app,wx,pad,pc
     *
     * @param clientType
     * @return
     */
    private String getClientName(String clientType){
        if(StringUtils.isBlank(clientType)){
    private String getClientName(String clientType) {
        if (StringUtils.isBlank(clientType)) {
            return "";
        }
        if("app".equals(clientType)){
        if ("app".equals(clientType)) {
            return "APP";
        }
        if("wx".equals(clientType)){
        if ("wx".equals(clientType)) {
            return "微信公众号";
        }
        if("pad".equals(clientType)){
        if ("pad".equals(clientType)) {
            return "多媒体平板";
        }
        if("pc".equals(clientType)){
        if ("pc".equals(clientType)) {
            return "电脑脑端";
        }
        return "";
@ -462,7 +621,7 @@ public class StatisticsService {
    /**
     * 平台人员实时统计
     */
    public JSONObject platformPeople(){
    public JSONObject platformPeople() {
        JSONObject result = new JSONObject();
        Integer olderTotal = 0;
        Integer childTotal = 0;
@ -481,21 +640,21 @@ public class StatisticsService {
        //儿童注册人数
        String childFilter = "";
        String sqlChildtmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older'  ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqlChildtmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqlChildtmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            childFilter = " and id not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            childFilter = " and id not in ('" + orgCodes + "')";
        }
        String sqlchild = "SELECT COUNT(*) c,case 1 WHEN openid is not null then 1 WHEN a.on_line = '1' then 1 ELSE 0 end as online from base_patient a WHERE archive_type = 2" +
                " and del='1' "+childFilter+" GROUP BY online";
        List<Map<String,Object>> listChild = jdbcTemplate.queryForList(sqlchild);
        for(Map<String,Object> map:listChild){
                " and del='1' " + childFilter + " GROUP BY online";
        List<Map<String, Object>> listChild = jdbcTemplate.queryForList(sqlchild);
        for (Map<String, Object> map : listChild) {
            Integer num = Integer.valueOf(map.get("c").toString());
            Integer online = Integer.valueOf(map.get("online").toString());
            if(online == 1){
            if (online == 1) {
                childOn += num;
            }else{
            } else {
                childOff += num;
            }
        }
@ -503,99 +662,100 @@ public class StatisticsService {
        //老人
        String oldFilter = "";
        String sqlOldtmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listOldtmp =  jdbcTemplate.queryForList(sqlOldtmp);
        if(listOldtmp.size()>0){
        List<Map<String, Object>> listOldtmp = jdbcTemplate.queryForList(sqlOldtmp);
        if (listOldtmp.size() > 0) {
            String orgCodes = String.valueOf(listOldtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            oldFilter = " and a.id not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            oldFilter = " and a.id not in ('" + orgCodes + "')";
        }
        String sql1 = "SELECT COUNT(*) c,case 1 WHEN openid is not null then 1 WHEN a.on_line = '1' then 1 ELSE 0 end as online from base_patient a WHERE archive_type = 1" +
                " and del='1' "+oldFilter+" GROUP BY online";
        List<Map<String,Object>> list1 = jdbcTemplate.queryForList(sql1);
        for(Map<String,Object> map:list1){
                " and del='1' " + oldFilter + " GROUP BY online";
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList(sql1);
        for (Map<String, Object> map : list1) {
            Integer num = Integer.valueOf(map.get("c").toString());
            Integer online = Integer.valueOf(map.get("online").toString());
            if(online == 1){
            if (online == 1) {
                olderOn += num;
            }else{
            } else {
                olderOff += num;
            }
        }
        olderTotal = olderOff+olderOn;
        childTotal = childOff+childOn;
        olderTotal = olderOff + olderOn;
        childTotal = childOff + childOn;
        //助老员和教师注册人数
        String sql2 = "SELECT COUNT(a.id) c,a.doctor_level,IFNULL(a.on_line,0) online from base_doctor a,base_doctor_hospital h where a.id=h.doctor_code and a.del = '1' and h.del = '1' " +
                "and a.doctor_level is not null and h.org_code not in ( " +
                "SELECT dict_code from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_org'  " +
                ") GROUP BY a.doctor_level,on_line";
        List<Map<String,Object>> list2 = jdbcTemplate.queryForList(sql2);
        for(Map<String,Object> map:list2){
        List<Map<String, Object>> list2 = jdbcTemplate.queryForList(sql2);
        for (Map<String, Object> map : list2) {
            String archive_type = map.get("doctor_level").toString();
            Integer num = Integer.valueOf(map.get("c").toString());
            Integer online = Integer.valueOf(map.get("online").toString());
            if("2".equals(archive_type)){
                if(online == 1){
            if ("2".equals(archive_type)) {
                if (online == 1) {
                    helperOn += num;
                }else{
                } else {
                    helperOff += num;
                }
                continue;
            }
            if("3".equals(archive_type)){
                if(online == 1){
            if ("3".equals(archive_type)) {
                if (online == 1) {
                    teacherOn += num;
                }else{
                } else {
                    teacherOff += num;
                }
            }
        }
        helperTotal = helperOff+helperOn;
        teacherTotal = teacherOff+teacherOn;
        helperTotal = helperOff + helperOn;
        teacherTotal = teacherOff + teacherOn;
        //helper 助老员,teacher 教师,child 幼儿,olderWx 老人公众号,olderPad 老人平板
        result.put("olderTotal",olderTotal);
        result.put("childTotal",childTotal);
        result.put("helperTotal",helperTotal);
        result.put("teacherTotal",teacherTotal);
        result.put("helperOn",helperOn);
        result.put("teacherOn",teacherOn);
        result.put("childOn",childOn);
        result.put("olderOn",olderOn);
        result.put("childOff",childOff);
        result.put("helperOff",helperOff);
        result.put("teacherOff",teacherOff);
        result.put("olderOff",olderOff);
        result.put("olderTotal", olderTotal);
        result.put("childTotal", childTotal);
        result.put("helperTotal", helperTotal);
        result.put("teacherTotal", teacherTotal);
        result.put("helperOn", helperOn);
        result.put("teacherOn", teacherOn);
        result.put("childOn", childOn);
        result.put("olderOn", olderOn);
        result.put("childOff", childOff);
        result.put("helperOff", helperOff);
        result.put("teacherOff", teacherOff);
        result.put("olderOff", olderOff);
        return result;
    }
    /**
     * 统计总数
     *
     * @param endDate
     * @param area
     * @param level 2 市  3区  4医院 5、科室 6医生
     * @param level   2 市  3区  4医院 5、科室 6医生
     * @param index
     * @param type
     * @return
     * @throws Exception
     */
    public JSONObject statisticsTotalAmount( String endDate, String area, int level, String index, String type) throws Exception {
    public JSONObject statisticsTotalAmount(String endDate, String area, int level, String index, String type) throws Exception {
        JSONObject res = new JSONObject();
        String[] indexes = index.split(",");
        String areaLevel = null;
        for(String ind:indexes){
        for (String ind : indexes) {
            //总量
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, ind, SaveModel.timeLevel_DDL,areaLevel);
            res.put("index_"+ind+"_total",saveModel.getResult2().longValue());
            if(StringUtils.isNotBlank(type)){
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, ind, SaveModel.timeLevel_DDL, areaLevel);
            res.put("index_" + ind + "_total", saveModel.getResult2().longValue());
            if (StringUtils.isNotBlank(type)) {
                //周/月 增量
                String start = statisticsUtilService.calStart(endDate,type);
                SaveModel saveModelAdd = elasticsearchUtil.findOneDateQuotaLevel0(start, endDate, area, level, ind, SaveModel.timeLevel_ZL,areaLevel);
                String start = statisticsUtilService.calStart(endDate, type);
                SaveModel saveModelAdd = elasticsearchUtil.findOneDateQuotaLevel0(start, endDate, area, level, ind, SaveModel.timeLevel_ZL, areaLevel);
                res.put("index_"+ind+"_add",saveModelAdd.getResult2().longValue());
                res.put("index_" + ind + "_add", saveModelAdd.getResult2().longValue());
            }
        }
@ -606,12 +766,12 @@ public class StatisticsService {
     * 咨询分析
     * type 1幼儿 2老人
     */
    public JSONObject consultAnalysis(String endDate, String area, int level, String type) throws Exception{
    public JSONObject consultAnalysis(String endDate, String area, int level, String type) throws Exception {
        JSONObject res = new JSONObject();
        String totalIndex = "28";
        String noReplyIndex = "29";
        String inTimeIndex = "30";
        if("2".equals(type)){
        if ("2".equals(type)) {
            totalIndex = "31";
            noReplyIndex = "32";
            inTimeIndex = "33";
@ -622,11 +782,11 @@ public class StatisticsService {
        SaveModel saveModel2 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, noReplyIndex, SaveModel.timeLevel_DDL);
        //及时回复数
        SaveModel saveModel3 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, inTimeIndex, SaveModel.timeLevel_DDL);
        res.put("total",saveModel1.getResult2().longValue());
        res.put("noReply",saveModel2.getResult2().longValue());
        res.put("inTime",saveModel3.getResult2().longValue());
        res.put("noReplyRate",statisticsUtilService.getTwoRange(saveModel2.getResult2(),saveModel1.getResult2()));
        res.put("inTimeRate",statisticsUtilService.getTwoRange(saveModel3.getResult2(),saveModel1.getResult2()));
        res.put("total", saveModel1.getResult2().longValue());
        res.put("noReply", saveModel2.getResult2().longValue());
        res.put("inTime", saveModel3.getResult2().longValue());
        res.put("noReplyRate", statisticsUtilService.getTwoRange(saveModel2.getResult2(), saveModel1.getResult2()));
        res.put("inTimeRate", statisticsUtilService.getTwoRange(saveModel3.getResult2(), saveModel1.getResult2()));
        return res;
    }
@ -635,7 +795,7 @@ public class StatisticsService {
    /**
     * 上门辅导分析
     */
    public JSONObject doorCoachAnalysis(String endDate, String area, int level) throws Exception{
    public JSONObject doorCoachAnalysis(String endDate, String area, int level) throws Exception {
        JSONObject res = new JSONObject();
        String totalIndex = "34";
        String noReplyIndex = "35";
@ -646,22 +806,22 @@ public class StatisticsService {
        SaveModel saveModel2 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, noReplyIndex, SaveModel.timeLevel_DDL);
        //服务费用
        SaveModel saveModel3 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, inTimeIndex, SaveModel.timeLevel_DDL);
        res.put("patientNum",saveModel1.getResult2().longValue());
        res.put("orderNum",saveModel2.getResult2().longValue());
        res.put("fee",saveModel3.getResult1());
        res.put("patientNum", saveModel1.getResult2().longValue());
        res.put("orderNum", saveModel2.getResult2().longValue());
        res.put("fee", saveModel3.getResult1());
        //服务项目分析
        JSONArray jsonArray = new JSONArray();
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate,endDate,area,level,inTimeIndex,SaveModel.timeLevel_DDL,null,null);
        for(int i=0;(i<list.size()&&i<5);i++){
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate, endDate, area, level, inTimeIndex, SaveModel.timeLevel_DDL, null, null);
        for (int i = 0; (i < list.size() && i < 5); i++) {
            SaveModel saveModel = list.get(i);
            JSONObject json = new JSONObject();
            json.put("num",saveModel.getResult2().longValue());
            json.put("code",saveModel.getSlaveKey1());
            json.put("name",saveModel.getSlaveKey1Name());
            json.put("num", saveModel.getResult2().longValue());
            json.put("code", saveModel.getSlaveKey1());
            json.put("name", saveModel.getSlaveKey1Name());
            jsonArray.add(json);
        }
        res.put("items",jsonArray);
        res.put("items", jsonArray);
        return res;
    }
@ -669,16 +829,16 @@ public class StatisticsService {
    /**
     * 上门辅导服务项目
     */
    public JSONArray doorCoachItems(String endDate, String area, int level) throws Exception{
    public JSONArray doorCoachItems(String endDate, String area, int level) throws Exception {
        //服务项目分析
        JSONArray jsonArray = new JSONArray();
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate,endDate,area,level,"36",SaveModel.timeLevel_DDL,null,null);
        for(int i=0;i<list.size();i++){
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate, endDate, area, level, "36", SaveModel.timeLevel_DDL, null, null);
        for (int i = 0; i < list.size(); i++) {
            SaveModel saveModel = list.get(i);
            JSONObject json = new JSONObject();
            json.put("num",saveModel.getResult2().longValue());
            json.put("code",saveModel.getSlaveKey1());
            json.put("name",saveModel.getSlaveKey1Name());
            json.put("num", saveModel.getResult2().longValue());
            json.put("code", saveModel.getSlaveKey1());
            json.put("name", saveModel.getSlaveKey1Name());
            jsonArray.add(json);
        }
        return jsonArray;
@ -687,8 +847,8 @@ public class StatisticsService {
    /**
     * 通用增量趋势接口
     */
    public JSONArray addLine(String startDate,String endDate, String area, int level,String index,String timeLevel,String interval,String lowLevel)throws Exception{
        List<SaveModel> list = elasticsearchUtil.findDateQuotaLevel0(startDate,endDate,area,level,index,timeLevel,interval,lowLevel);
    public JSONArray addLine(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {
        List<SaveModel> list = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, timeLevel, interval, lowLevel);
        JSONArray result = new JSONArray();
        for (SaveModel saveModel : list) {
            JSONObject range = new JSONObject();
@ -696,120 +856,119 @@ public class StatisticsService {
            range.put("amount", saveModel.getResult2());
            result.add(range);
        }
        return result;
    }
    /**
     * 居民分析
     */
    public JSONObject patientAnalysis(String endDate, String area, int level,String index) throws Exception{
    public JSONObject patientAnalysis(String endDate, String area, int level, String index) throws Exception {
        JSONObject res = new JSONObject();
        String areaLevel = "6";
        if("42".equals(index)){
        if ("42".equals(index)) {
            areaLevel = "4";
            //新生儿
            //是否入学
            List<SaveModel> statusList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL,null,null,areaLevel);
            List<SaveModel> statusList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, null, null, areaLevel);
            JSONArray statusArray = new JSONArray();
            for(int i=0;i<statusList.size();i++){
            for (int i = 0; i < statusList.size(); i++) {
                SaveModel saveModel = statusList.get(i);
                JSONObject json = new JSONObject();
                json.put("num",saveModel.getResult2().longValue());
                json.put("code",saveModel.getSlaveKey1());
                json.put("name",saveModel.getSlaveKey1Name());
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                statusArray.add(json);
            }
            res.put("statusList",statusArray);
        }else{
            res.put("statusList", statusArray);
        } else {
            //老人
            //能力评估 从签约时服务标签取
            res.put("levelList",capacityAssessment(null,null,null));
            res.put("levelList", capacityAssessment(null, null, null));
            //居民健康标签
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate,endDate,area,level,"47",SaveModel.timeLevel_DDL,null,null,"2");
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "47", SaveModel.timeLevel_DDL, null, null, "2");
            JSONArray labelArr = new JSONArray();
            Long total = 0l;
            for(int i=0;i<list.size();i++){
            for (int i = 0; i < list.size(); i++) {
                SaveModel saveModel = list.get(i);
                JSONObject json = new JSONObject();
                if (saveModel.getResult2().longValue()==0&&StringUtils.isBlank(saveModel.getSlaveKey1())){
                if (saveModel.getResult2().longValue() == 0 && StringUtils.isBlank(saveModel.getSlaveKey1())) {
                    continue;
                }
                if ("0".equals(saveModel.getSlaveKey1())){//去除60岁以下老人
                if ("0".equals(saveModel.getSlaveKey1())) {//去除60岁以下老人
                    continue;
                }
                json.put("num",saveModel.getResult2().longValue());
                json.put("code",saveModel.getSlaveKey1());
                json.put("name",saveModel.getSlaveKey1Name());
                total+=saveModel.getResult2().longValue();
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                total += saveModel.getResult2().longValue();
                labelArr.add(json);
            }
            JSONObject arrTmp = new JSONObject();
            arrTmp.put("patientLabelTotal",total);
            arrTmp.put("patientLabelList",labelArr);
            res.put("patientLabelStatistic",arrTmp);
            arrTmp.put("patientLabelTotal", total);
            arrTmp.put("patientLabelList", labelArr);
            res.put("patientLabelStatistic", arrTmp);
            //年龄分布 50
//            ageList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "50", SaveModel.timeLevel_DDL,null,null,"2");
            List<SaveModel>  ageList = elasticsearchUtil.findDateAllQuotaLevel1(endDate,endDate,area,level,"50",SaveModel.timeLevel_DDL,null,null,"2");
            List<SaveModel> ageList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "50", SaveModel.timeLevel_DDL, null, null, "2");
            JSONArray ageArray = new JSONArray();
            for(int i=0;i<ageList.size();i++){
            for (int i = 0; i < ageList.size(); i++) {
                SaveModel saveModel = ageList.get(i);
                if ("0".equals(saveModel.getSlaveKey1())){//去除60岁以下老人
                if ("0".equals(saveModel.getSlaveKey1())) {//去除60岁以下老人
                    continue;
                }
                JSONObject json = new JSONObject();
                json.put("num",saveModel.getResult2().longValue());
                json.put("code",saveModel.getSlaveKey1());
                json.put("name",saveModel.getSlaveKey1Name());
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                ageArray.add(json);
            }
            res.put("ageList",ageArray);
            res.put("ageList", ageArray);
            //居住小区分布
            String filter = "";
            String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
            List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
            if(listtmp.size()>0){
            List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
            if (listtmp.size() > 0) {
                String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
                orgCodes = orgCodes.replaceAll(",","','");
                filter = " not in ('"+orgCodes+"')";
                orgCodes = orgCodes.replaceAll(",", "','");
                filter = " not in ('" + orgCodes + "')";
            }
            String  sql = "select count(id) total,residential_area residentialArea  from base_patient where del=1 and id "+filter+"  and archive_type=1 " +
            String sql = "select count(id) total,residential_area residentialArea  from base_patient where del=1 and id " + filter + "  and archive_type=1 " +
                    "GROUP BY residential_area ORDER BY total desc";
            List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            Iterator<Map<String, Object>> iterator = result.iterator();
            Map<String, Object> tmp = new HashMap<>();
            while (iterator.hasNext()){
            while (iterator.hasNext()) {
                tmp = iterator.next();
                if (null==tmp.get("residentialArea")){
                if (null == tmp.get("residentialArea")) {
                    iterator.remove();
                    break;
                }
            }
            result.add(tmp);
            res.put("residentialArea",result);
            res.put("residentialArea", result);
        }
        //性别分析
        String archiType="";
        if("42".equals(index)){
            archiType="2";
        String archiType = "";
        if ("42".equals(index)) {
            archiType = "2";
        }
        if("37".equals(index)){
            archiType="1";
        if ("37".equals(index)) {
            archiType = "1";
        }
        List<SaveModel> sexList = elasticsearchUtil.findDateQuotaLevel2ByKeyGroup(endDate, endDate,defalutArea, level, "51",SaveModel.timeLevel_DDL,null,archiType,null,null,"2","1");
        List<SaveModel> sexList = elasticsearchUtil.findDateQuotaLevel2ByKeyGroup(endDate, endDate, defalutArea, level, "51", SaveModel.timeLevel_DDL, null, archiType, null, null, "2", "1");
        JSONArray sexArray = new JSONArray();
        for(int i=0;i<sexList.size();i++){
        for (int i = 0; i < sexList.size(); i++) {
            SaveModel saveModel = sexList.get(i);
            JSONObject json = new JSONObject();
            json.put("num",saveModel.getResult2().longValue());
            json.put("code",saveModel.getSlaveKey1());
            json.put("name",saveModel.getSlaveKey1Name());
            json.put("num", saveModel.getResult2().longValue());
            json.put("code", saveModel.getSlaveKey1());
            json.put("name", saveModel.getSlaveKey1Name());
            sexArray.add(json);
        }
        res.put("sexList",sexArray);
        res.put("sexList", sexArray);
        return res;
    }
@ -817,7 +976,7 @@ public class StatisticsService {
    /**
     * 生活照料分析
     */
    public JSONObject lifeCareAnalysis(String endDate, String area, int level) throws Exception{
    public JSONObject lifeCareAnalysis(String endDate, String area, int level) throws Exception {
        JSONObject res = new JSONObject();
        String totalIndex = "38";
        String noReplyIndex = "39";
@ -828,22 +987,22 @@ public class StatisticsService {
        SaveModel saveModel2 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, noReplyIndex, SaveModel.timeLevel_DDL);
        //服务费用
        SaveModel saveModel3 = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, inTimeIndex, SaveModel.timeLevel_DDL);
        res.put("patientNum",saveModel1.getResult2().longValue());
        res.put("orderNum",saveModel2.getResult2().longValue());
        res.put("fee",saveModel3.getResult1());
        res.put("patientNum", saveModel1.getResult2().longValue());
        res.put("orderNum", saveModel2.getResult2().longValue());
        res.put("fee", saveModel3.getResult1());
        //服务项目分析
        JSONArray jsonArray = new JSONArray();
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate,endDate,area,level,inTimeIndex,SaveModel.timeLevel_DDL,null,null);
        for(int i=0;(i<list.size()&&i<5);i++){
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate, endDate, area, level, inTimeIndex, SaveModel.timeLevel_DDL, null, null);
        for (int i = 0; (i < list.size() && i < 5); i++) {
            SaveModel saveModel = list.get(i);
            JSONObject json = new JSONObject();
            json.put("num",saveModel.getResult2().longValue());
            json.put("code",saveModel.getSlaveKey1());
            json.put("name",saveModel.getSlaveKey1Name());
            json.put("num", saveModel.getResult2().longValue());
            json.put("code", saveModel.getSlaveKey1());
            json.put("name", saveModel.getSlaveKey1Name());
            jsonArray.add(json);
        }
        res.put("items",jsonArray);
        res.put("items", jsonArray);
        return res;
    }
@ -851,16 +1010,16 @@ public class StatisticsService {
    /**
     * 生活照料服务项目
     */
    public JSONArray lifeCareItems(String endDate, String area, int level) throws Exception{
    public JSONArray lifeCareItems(String endDate, String area, int level) throws Exception {
        //服务项目分析
        JSONArray jsonArray = new JSONArray();
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate,endDate,area,level,"40",SaveModel.timeLevel_DDL,null,null);
        for(int i=0;i<list.size();i++){
        List<SaveModel> list = statisticsUtilService.findDateAllQuotaLevel1Sort(endDate, endDate, area, level, "40", SaveModel.timeLevel_DDL, null, null);
        for (int i = 0; i < list.size(); i++) {
            SaveModel saveModel = list.get(i);
            JSONObject json = new JSONObject();
            json.put("num",saveModel.getResult2().longValue());
            json.put("code",saveModel.getSlaveKey1());
            json.put("name",saveModel.getSlaveKey1Name());
            json.put("num", saveModel.getResult2().longValue());
            json.put("code", saveModel.getSlaveKey1());
            json.put("name", saveModel.getSlaveKey1Name());
            jsonArray.add(json);
        }
        return jsonArray;
@ -870,48 +1029,50 @@ public class StatisticsService {
    /**
     * 能力评估评估类型
     */
    public JSONArray capacityAssessment(String endDate, String area, Integer level) throws Exception{
    public JSONArray capacityAssessment(String endDate, String area, Integer level) throws Exception {
        //评估类型
        String filter = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            if (StringUtils.isNotBlank(orgCodes)){
                orgCodes = orgCodes.replaceAll(",","','");
                filter = " and lab.patient not in ('"+orgCodes+"')";
            if (StringUtils.isNotBlank(orgCodes)) {
                orgCodes = orgCodes.replaceAll(",", "','");
                filter = " and lab.patient not in ('" + orgCodes + "')";
            }
        }
        JSONArray jsonArray = new JSONArray();
        String sql = " select dict.dict_code,dict_value,count(DISTINCT A.patient) total from wlyy_hospital_sys_dict dict \n" +
                " LEFT JOIN (select distinct lab.patient,lab.label_code from  wlyy_patient_label lab  INNER JOIN base_patient p on p.id = lab.patient AND  lab.label_type='1' " +
                  filter+"   \n" +
                filter + "   \n" +
                ")A on dict.dict_code = A.label_code " +
                "where  dict.dict_name='service_type'  and  dict.dict_code is not null and dict_code<>5  \n" +
                "where  dict.dict_name='service_type'  and  dict.dict_code is not null and dict_code <> 5  \n" +
                " GROUP BY dict.dict_code; ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        String older = " select count(distinct lab.patient) from  wlyy_patient_label lab  INNER JOIN base_patient p on p.id = lab.patient AND  lab.label_type='1' "+filter;
        Integer count = jdbcTemplate.queryForObject(older,Integer.class);
        String older = " select count(distinct lab.patient) from  wlyy_patient_label lab  INNER JOIN base_patient p on p.id = lab.patient AND  lab.label_type='1' " + filter;
        Integer count = jdbcTemplate.queryForObject(older, Integer.class);
        for(Map<String,Object> map:list){
        for (Map<String, Object> map : list) {
            JSONObject json = new JSONObject();
            DecimalFormat df = new DecimalFormat("0.00");
            json.put("rate", df.format((Integer.parseInt(map.get("total").toString())*1.00) / count * 100));
            json.put("rate", df.format((Integer.parseInt(map.get("total").toString()) * 1.00) / count * 100));
            json.put("num", map.get("total"));
            json.put("code",map.get("dict_code").toString());
            json.put("name",map.get("dict_value").toString());
            json.put("code", map.get("dict_code").toString());
            json.put("name", map.get("dict_value").toString());
            jsonArray.add(json);
        }
        return jsonArray;
    }
        /**
         * 统计首页头部数据
         * @param area
         * @param startDate
         * @param endDate
         */
    public JSONObject indexTopNum(String area,String startDate,String endDate,Integer level){
    /**
     * 统计首页头部数据
     *
     * @param area
     * @param startDate
     * @param endDate
     */
    public JSONObject indexTopNum(String area, String startDate, String endDate, Integer level) {
        JSONObject re = new JSONObject();
        String signSql = " SELECT COUNT(sr.id) " +
                " FROM " +
@ -927,98 +1088,100 @@ public class StatisticsService {
        String capacitySql = "select count(sr.id) from base_capacity_assessment_record sr, " +
                "   base_org o " +
                " WHERE " +
                " sr.org_code = o.code" ;
                " sr.org_code = o.code";
        String filters = "";
        if(ConstantUtil.cityLevel.equals(level)){
            filters = " and o.city_code = '"+area+"'";
        }else if(ConstantUtil.townLevel.equals(level)){
            filters = " and o.town_code = '"+area+"'";
        }else if(ConstantUtil.orgLevel.equals(level)){
            filters = " and o.code = '"+area+"'";
        if (ConstantUtil.cityLevel.equals(level)) {
            filters = " and o.city_code = '" + area + "'";
        } else if (ConstantUtil.townLevel.equals(level)) {
            filters = " and o.town_code = '" + area + "'";
        } else if (ConstantUtil.orgLevel.equals(level)) {
            filters = " and o.code = '" + area + "'";
        }
        if(StringUtils.isNotBlank(startDate)){
            filters += " and sr.create_time >='"+startDate+"'";
        if (StringUtils.isNotBlank(startDate)) {
            filters += " and sr.create_time >='" + startDate + "'";
        }
        if(StringUtils.isNotBlank(endDate)){
            filters += " and sr.create_time <='"+endDate+"'";
        if (StringUtils.isNotBlank(endDate)) {
            filters += " and sr.create_time <='" + endDate + "'";
        }
        //签约数 能力评估
        Integer signNum = jdbcTemplate.queryForObject(signSql+filters,Integer.class);
        Integer capacityNum = jdbcTemplate.queryForObject(capacitySql+filters,Integer.class);
        re.put("signNum",signNum);
        re.put("capacityNum",capacityNum);
        Integer signNum = jdbcTemplate.queryForObject(signSql + filters, Integer.class);
        Integer capacityNum = jdbcTemplate.queryForObject(capacitySql + filters, Integer.class);
        re.put("signNum", signNum);
        re.put("capacityNum", capacityNum);
        return re;
    }
    /**
     * 首页 养护服务
     *
     * @param area
     * @param startDate
     * @param endDate
     * @param level
     * @param type 类型:1本周,2本月
     * @param type      类型:1本周,2本月
     */
    public JSONObject indexMaintenanceServices(String area,String startDate,String endDate,Integer level,int type){
    public JSONObject indexMaintenanceServices(String area, String startDate, String endDate, Integer level, int type) {
        JSONObject re = new JSONObject();
        String sql = "select count(sr.id) from base_life_care_order sr, " +
                "   base_org o " +
                " WHERE " +
                " sr.hospital = o.code" ;
                " sr.hospital = o.code";
        if(ConstantUtil.cityLevel.equals(level)){
            sql += " and o.city_code = '"+area+"'";
        }else if(ConstantUtil.townLevel.equals(level)){
            sql += " and o.town_code = '"+area+"'";
        }else if(ConstantUtil.orgLevel.equals(level)){
            sql += " and o.code = '"+area+"'";
        if (ConstantUtil.cityLevel.equals(level)) {
            sql += " and o.city_code = '" + area + "'";
        } else if (ConstantUtil.townLevel.equals(level)) {
            sql += " and o.town_code = '" + area + "'";
        } else if (ConstantUtil.orgLevel.equals(level)) {
            sql += " and o.code = '" + area + "'";
        }
        String filters = "";
        String timefilters = "";
        if(StringUtils.isNotBlank(startDate)){
            filters += " and sr.create_time >='"+startDate+"'";
        if (StringUtils.isNotBlank(startDate)) {
            filters += " and sr.create_time >='" + startDate + "'";
        }
        if(StringUtils.isNotBlank(endDate)){
            filters += " and sr.create_time <='"+endDate+"'";
        if (StringUtils.isNotBlank(endDate)) {
            filters += " and sr.create_time <='" + endDate + "'";
        }
        String start = calStart(endDate,type);
        timefilters += " and sr.create_time >='"+start+"'";
        timefilters += " and sr.create_time <='"+endDate+"'";
        String start = calStart(endDate, type);
        timefilters += " and sr.create_time >='" + start + "'";
        timefilters += " and sr.create_time <='" + endDate + "'";
        //生活照料
        Integer lifeCareNum = jdbcTemplate.queryForObject(sql+filters,Integer.class);
        Integer lifeCareNumAdd = jdbcTemplate.queryForObject(sql+timefilters,Integer.class);
        re.put("lifeCareNum",lifeCareNum);
        re.put("lifeCareNumAdd",lifeCareNumAdd);
        Integer lifeCareNum = jdbcTemplate.queryForObject(sql + filters, Integer.class);
        Integer lifeCareNumAdd = jdbcTemplate.queryForObject(sql + timefilters, Integer.class);
        re.put("lifeCareNum", lifeCareNum);
        re.put("lifeCareNumAdd", lifeCareNumAdd);
        return re;
    }
    /**
     * 统计安防、生活
     * 误报警率完成率 完成率
     *
     * @param endDate
     * @return
     */
    public JSONObject statisticsOrderResponse(String endDate){
    public JSONObject statisticsOrderResponse(String endDate) {
        JSONObject res = new JSONObject();
        try {
            //安防总数
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate,endDate,defalutArea,2,"46","2","4");
            res.put("index_"+46+"_total",saveModel.getResult2().longValue());
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, defalutArea, 2, "46", "2", "4");
            res.put("index_" + 46 + "_total", saveModel.getResult2().longValue());
            //安防响应 误报警+完成
            saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,defalutArea,2,"46","2","-2","4");
            saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate, defalutArea, 2, "46", "2", "-2", "4");
            long finish = saveModel.getResult2().longValue();
            saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,defalutArea,2,"46","2","0","4");
            saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate, defalutArea, 2, "46", "2", "0", "4");
            finish += saveModel.getResult2().longValue();
            res.put("index_"+46+"_finish",finish);
            res.put("index_" + 46 + "_finish", finish);
            //安防误报警
            saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,defalutArea,2,"46","2","-2","4");
            res.put("index_"+46+"_error",saveModel.getResult2().longValue());
            saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate, defalutArea, 2, "46", "2", "-2", "4");
            res.put("index_" + 46 + "_error", saveModel.getResult2().longValue());
            //生活总数
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate,endDate,defalutArea,2,"49","2","4");
            res.put("index_"+49+"_total",saveModel.getResult2().longValue());
            saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, defalutArea, 2, "49", "2", "4");
            res.put("index_" + 49 + "_total", saveModel.getResult2().longValue());
            //生活完成
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(endDate,endDate,defalutArea,2,"49","2","2","4");
            res.put("index_"+49+"_finish",saveModel.getResult2().longValue());
            saveModel = elasticsearchUtil.findOneDateQuotaLevel1(endDate, endDate, defalutArea, 2, "49", "2", "2", "4");
            res.put("index_" + 49 + "_finish", saveModel.getResult2().longValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
@ -1027,196 +1190,198 @@ public class StatisticsService {
    /**
     * 根据指标 level arealevel统计
     *
     * @param endDate
     * @return
     * @throws Exception
     */
    public JSONObject statisticsOrderServer(String index,String endDate,Integer level,String areaLevel) throws Exception {
    public JSONObject statisticsOrderServer(String index, String endDate, Integer level, String areaLevel) throws Exception {
        JSONObject res = new JSONObject();
        String[] indexes = index.split(",");
        for(String ind:indexes){
        for (String ind : indexes) {
            JSONArray jsonArray = new JSONArray();
            long total = 0l;
            //总量
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate,endDate,defalutArea,level,ind,SaveModel.timeLevel_DDL,null,null,areaLevel);
            for(int i=0;i<list.size();i++){
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, defalutArea, level, ind, SaveModel.timeLevel_DDL, null, null, areaLevel);
            for (int i = 0; i < list.size(); i++) {
                SaveModel saveModel = list.get(i);
                JSONObject json = new JSONObject();
                if (saveModel.getResult2().longValue()==0&&StringUtils.isBlank(saveModel.getSlaveKey1())){
                if (saveModel.getResult2().longValue() == 0 && StringUtils.isBlank(saveModel.getSlaveKey1())) {
                    continue;
                }
                if ("0".equals(saveModel.getSlaveKey1())){//去除60岁以下老人
                if ("0".equals(saveModel.getSlaveKey1())) {//去除60岁以下老人
                    continue;
                }
                json.put("num",saveModel.getResult2().longValue());
                json.put("code",saveModel.getSlaveKey1());
                json.put("name",saveModel.getSlaveKey1Name());
                total+=saveModel.getResult2().longValue();
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                total += saveModel.getResult2().longValue();
                jsonArray.add(json);
            }
            res.put("index_"+ind+"_total",total);
            res.put("index_"+ind,jsonArray);
            res.put("index_" + ind + "_total", total);
            res.put("index_" + ind, jsonArray);
        }
        return res;
    }
    /**
     * 管理端首页老人接入情况
     *
     * @return
     */
    public JSONObject olderBindingDeviceStatus(String area){
    public JSONObject olderBindingDeviceStatus(String area) {
        JSONObject result = new JSONObject();
        String filter = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            filter = " not in ('" + orgCodes + "')";
        }
        String sql =" select count(id) from base_patient  where del=1 and archive_type=1 and id "+filter;
        Integer olderCount  = jdbcTemplate.queryForObject(sql,Integer.class);
        String sql = " select count(id) from base_patient  where del=1 and archive_type=1 and id " + filter;
        Integer olderCount = jdbcTemplate.queryForObject(sql, Integer.class);
        sql = " select count(DISTINCT p.id) from base_patient p INNER JOIN wlyy_patient_device pd on p.id = pd.user and p.archive_type=1 and pd.del=0 where p.del=1 and p.id "+filter;
        Integer bindingCount  = jdbcTemplate.queryForObject(sql,Integer.class);
        result.put("olderCount",olderCount);
        result.put("bindingCount",bindingCount);
        result.put("range",commonUtil.getRange(bindingCount,olderCount));
        sql = " select count(DISTINCT p.id) from base_patient p INNER JOIN wlyy_patient_device pd on p.id = pd.user and p.archive_type=1 and pd.del=0 where p.del=1 and p.id " + filter;
        Integer bindingCount = jdbcTemplate.queryForObject(sql, Integer.class);
        result.put("olderCount", olderCount);
        result.put("bindingCount", bindingCount);
        result.put("range", commonUtil.getRange(bindingCount, olderCount));
        return result;
    }
    /**
     * 管理端安防监护新增分析
     */
    public JSONObject statisticsSecurityOlder( String endDate, String area, int level, String type) throws Exception {
    public JSONObject statisticsSecurityOlder(String endDate, String area, int level, String type) throws Exception {
        JSONObject res = new JSONObject();
        String areaLevel = "4";
            areaLevel="4";
        SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, "46", SaveModel.timeLevel_DDL,areaLevel);
        res.put("index_"+46+"_total",saveModel.getResult2().longValue());
        if(StringUtils.isNotBlank(type)){
        areaLevel = "4";
        SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, "46", SaveModel.timeLevel_DDL, areaLevel);
        res.put("index_" + 46 + "_total", saveModel.getResult2().longValue());
        if (StringUtils.isNotBlank(type)) {
            //周/月 增量
            String start = statisticsUtilService.calStart(endDate,type);
            SaveModel saveModelAdd = elasticsearchUtil.findOneDateQuotaLevel0(start, endDate, area, level, "46", SaveModel.timeLevel_ZL,areaLevel);
            res.put("index_"+46+"_add",saveModelAdd.getResult2().longValue());
            String start = statisticsUtilService.calStart(endDate, type);
            SaveModel saveModelAdd = elasticsearchUtil.findOneDateQuotaLevel0(start, endDate, area, level, "46", SaveModel.timeLevel_ZL, areaLevel);
            res.put("index_" + 46 + "_add", saveModelAdd.getResult2().longValue());
        }
        JSONArray addDetail = new JSONArray();
        if(StringUtils.isNotBlank(type)){
        if (StringUtils.isNotBlank(type)) {
            //周/月 增量
            String start = statisticsUtilService.calStart(endDate,type);
            String start = statisticsUtilService.calStart(endDate, type);
            List<SaveModel> saveModelAdds = elasticsearchUtil.findDateQuotaLevelList(start,endDate, area,level, "46", SaveModel.timeLevel_ZL, "3",null,null,null);
            for (SaveModel saveModelTmp:saveModelAdds){
            List<SaveModel> saveModelAdds = elasticsearchUtil.findDateQuotaLevelList(start, endDate, area, level, "46", SaveModel.timeLevel_ZL, "3", null, null, null);
            for (SaveModel saveModelTmp : saveModelAdds) {
                JSONObject json = new JSONObject();
                SaveModel saveMode2 = elasticsearchUtil.findOneDateQuotaLevels(endDate,endDate, area,level, "46", SaveModel.timeLevel_DDL, "3",null,null,saveModelTmp.getSlaveKey3());
                json.put("total",saveMode2.getResult2().longValue());
                json.put("num",saveModelTmp.getResult2().longValue());
                json.put("code",saveModelTmp.getSlaveKey3());
                json.put("name",saveModelTmp.getSlaveKey3Name());
                SaveModel saveMode2 = elasticsearchUtil.findOneDateQuotaLevels(endDate, endDate, area, level, "46", SaveModel.timeLevel_DDL, "3", null, null, saveModelTmp.getSlaveKey3());
                json.put("total", saveMode2.getResult2().longValue());
                json.put("num", saveModelTmp.getResult2().longValue());
                json.put("code", saveModelTmp.getSlaveKey3());
                json.put("name", saveModelTmp.getSlaveKey3Name());
                addDetail.add(json);
            }
        }
        res.put("index_add_detail",addDetail);
        res.put("index_add_detail", addDetail);
        return res;
    }
    public  JSONObject deviceGrantAndService(){
    public JSONObject deviceGrantAndService() {
        JSONObject result = new JSONObject();
        String filter = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            filter = " not in ('" + orgCodes + "')";
        }
        String sql =" select count(DISTINCT device_code) from wlyy_devices ";
        Integer deviceTotal  = jdbcTemplate.queryForObject(sql,Integer.class);
        String sql = " select count(DISTINCT device_code) from wlyy_devices ";
        Integer deviceTotal = jdbcTemplate.queryForObject(sql, Integer.class);
        sql = " select count(DISTINCT wd.device_code) from wlyy_devices wd INNER JOIN wlyy_patient_device pd " +
                " ON pd.device_sn = wd.device_code AND pd.del=0 and pd.user "+filter;
        Integer bindingCount  = jdbcTemplate.queryForObject(sql,Integer.class);
                " ON pd.device_sn = wd.device_code AND pd.del=0 and pd.user " + filter;
        Integer bindingCount = jdbcTemplate.queryForObject(sql, Integer.class);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deviceTotal",deviceTotal);
        jsonObject.put("bindingCount",bindingCount);
        jsonObject.put("range",commonUtil.getRange(bindingCount,deviceTotal));
        result.put("deviceGrant",jsonObject);
        sql =" SELECT sde.`value`,COUNT(d.id) count,GROUP_CONCAT(DISTINCT d.category_code SEPARATOR ',') AS category_code," +
        jsonObject.put("deviceTotal", deviceTotal);
        jsonObject.put("bindingCount", bindingCount);
        jsonObject.put("range", commonUtil.getRange(bindingCount, deviceTotal));
        result.put("deviceGrant", jsonObject);
        sql = " SELECT sde.`value`,COUNT(d.id) count,GROUP_CONCAT(DISTINCT d.category_code SEPARATOR ',') AS category_code," +
                " GROUP_CONCAT(DISTINCT d.model SEPARATOR ',') AS model FROM base_system_dict_entry sde LEFT JOIN dm_device d " +
                " ON FIND_IN_SET(sde.`code`,d.service_topic) WHERE sde.remark = 'security' GROUP BY sde.`value` ";
        List<Map<String,Object>> deviceService = jdbcTemplate.queryForList(sql);
        result.put("deviceService",deviceService);
        List<Map<String, Object>> deviceService = jdbcTemplate.queryForList(sql);
        result.put("deviceService", deviceService);
        return result;
    }
    public PageEnvelop getAllDeviceLostMessage(String area,Integer page,Integer size){
        page = page>0?page-1:0;
        String sql ="select GROUP_CONCAT(id) id,type,title,sender,sender_name senderName,\n" +
    public PageEnvelop getAllDeviceLostMessage(String area, Integer page, Integer size) {
        page = page > 0 ? page - 1 : 0;
        String sql = "select GROUP_CONCAT(id) id,type,title,sender,sender_name senderName,\n" +
                "receiver,receiver_name receiverName,relation_code relationCode,\n" +
                "data,is_read isRead,create_time createTime,sender_photo\n" +
                "from base_system_message where type=43 and del=1 GROUP BY relation_code order by createTime desc ";
        Long count = jdbcTemplate.queryForObject(" select count(id) from ("+sql+")A ",Long.class);
        sql +=" limit "+page*size+","+size ;
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        Long count = jdbcTemplate.queryForObject(" select count(id) from (" + sql + ")A ", Long.class);
        sql += " limit " + page * size + "," + size;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return PageEnvelop.getSuccessListWithPage("查询成功",list,page++,size,count);
        return PageEnvelop.getSuccessListWithPage("查询成功", list, page++, size, count);
    }
    @Transactional
    public void delMessageRead(String msgId){
        if (StringUtils.isNotBlank(msgId)){
    public void delMessageRead(String msgId) {
        if (StringUtils.isNotBlank(msgId)) {
            String[] ids = msgId.split(",");
            if (ids.length>0){
            if (ids.length > 0) {
                systemMessageDao.delMessage(ids);
            }
        }
    }
    public JSONObject deviceUsingInfo(String area){
    public JSONObject deviceUsingInfo(String area) {
        String filter = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " not in ('"+orgCodes+"')";
            orgCodes = orgCodes.replaceAll(",", "','");
            filter = " not in ('" + orgCodes + "')";
        }
        JSONObject result = new JSONObject();
        String sql = "SELECT COUNT(DISTINCT device_sn) FROM wlyy_patient_device WHERE del = 0 and user "+filter;
        Integer use = jdbcTemplate.queryForObject(sql,Integer.class);
        String sql = "SELECT COUNT(DISTINCT device_sn) FROM wlyy_patient_device WHERE del = 0 and user " + filter;
        Integer use = jdbcTemplate.queryForObject(sql, Integer.class);
        sql = "SELECT COUNT(DISTINCT device_code) FROM wlyy_devices ";
        Integer total = jdbcTemplate.queryForObject(sql,Integer.class);
        result.put("use",use);//使用中
        result.put("putOnFile",total);//采购
        result.put("stock",total-use);//库存
        Integer total = jdbcTemplate.queryForObject(sql, Integer.class);
        result.put("use", use);//使用中
        result.put("putOnFile", total);//采购
        result.put("stock", total - use);//库存
        sql = "SELECT DISTINCT count(wd.device_code) FROM wlyy_devices wd INNER JOIN wlyy_patient_device pd on " +
                "wd.device_code =pd.device_sn  WHERE contact_status = 0 and pd.user "+filter;//contact_status = 0   失联
        Integer lost = jdbcTemplate.queryForObject(sql,Integer.class);
                "wd.device_code =pd.device_sn  WHERE contact_status = 0 and pd.user " + filter;//contact_status = 0   失联
        Integer lost = jdbcTemplate.queryForObject(sql, Integer.class);
        //物联率 失联率
        result.put("deviceAll",total);//物联率分母总数 设备总数(包括库存)
        result.put("lost",lost);//失联数
        result.put("notLost",use);//物联数  被人绑定了就是物联
        result.put("deviceAll2",use);//失联数分母总数  发出的设备数
        result.put("iotRange",commonUtil.getRange(use,total));
        result.put("LostRange",commonUtil.getRange(lost,use));
        result.put("deviceAll", total);//物联率分母总数 设备总数(包括库存)
        result.put("lost", lost);//失联数
        result.put("notLost", use);//物联数  被人绑定了就是物联
        result.put("deviceAll2", use);//失联数分母总数  发出的设备数
        result.put("iotRange", commonUtil.getRange(use, total));
        result.put("LostRange", commonUtil.getRange(lost, use));
        return result;
    }
    public PageEnvelop getSecurityOrderList(String area,String status, String svrDesc,String topicItem, Integer page, Integer pageSize){
    public PageEnvelop getSecurityOrderList(String area, String status, String svrDesc, String topicItem, Integer page, Integer pageSize) {
        String testPatients = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            testPatients = " not in ('"+orgCodes+"') ";
            orgCodes = orgCodes.replaceAll(",", "','");
            testPatients = " not in ('" + orgCodes + "') ";
        }
        page = page>1?page-1:0;
        page = page > 1 ? page - 1 : 0;
        JSONArray result = new JSONArray();
        String sqlCount = "select count(ord.id) from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
@ -1225,189 +1390,200 @@ public class StatisticsService {
        String sql = " select p.id patientCode,p.name,p.sex,p.photo,p.idcard,ord.id orderId,ord.number,ord.serve_desc,ord.create_time,ord.`status`,ord.doctor," +
                "ord.doctor_name,ord.update_user,ord.update_user_name,ord.patient_phone,ord.conclusion_status from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
                "where 1=1 ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(status)){
            fliter+=" and ord.status='"+Integer.parseInt(status)+"' ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(status)) {
            fliter += " and ord.status='" + Integer.parseInt(status) + "' ";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(svrDesc)){
            fliter+=" and ord.serve_desc='"+svrDesc+"' ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(svrDesc)) {
            fliter += " and ord.serve_desc='" + svrDesc + "' ";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(topicItem)){
            fliter+=" and ord.topic_item='"+topicItem+"' ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(topicItem)) {
            fliter += " and ord.topic_item='" + topicItem + "' ";
        }
        fliter +=" and ord.patient "+testPatients;
        Long count = jdbcTemplate.queryForObject(sqlCount+fliter,Long.class);
        fliter+=" order by ord.create_time desc limit " + (page*pageSize) + "," + pageSize;
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql+fliter);
        fliter += " and ord.patient " + testPatients;
        Long count = jdbcTemplate.queryForObject(sqlCount + fliter, Long.class);
        fliter += " order by ord.create_time desc limit " + (page * pageSize) + "," + pageSize;
        List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql + fliter);
        for (Map<String,Object>one:sqlResult){
        for (Map<String, Object> one : sqlResult) {
            JSONObject tmp = new JSONObject();
            tmp.put("patientCode",one.get("patientCode"));
            tmp.put("patientName",one.get("name"));
            tmp.put("sex",one.get("sex"));
            tmp.put("photo",one.get("photo"));
            tmp.put("idcard",one.get("idcard"));
            tmp.put("number",one.get("number"));
            tmp.put("id",one.get("orderId"));
            tmp.put("serveDesc",one.get("serve_desc"));
            Date date = (Date)one.get("create_time");
            tmp.put("patientCode", one.get("patientCode"));
            tmp.put("patientName", one.get("name"));
            tmp.put("sex", one.get("sex"));
            tmp.put("photo", one.get("photo"));
            tmp.put("idcard", one.get("idcard"));
            tmp.put("number", one.get("number"));
            tmp.put("id", one.get("orderId"));
            tmp.put("serveDesc", one.get("serve_desc"));
            Date date = (Date) one.get("create_time");
            tmp.put("createTime", DateUtil.dateToStrLong(date));
            tmp.put("status",one.get("status"));
            tmp.put("doctor",one.get("doctor"));
            tmp.put("doctorName",one.get("doctor_name"));
            tmp.put("patientPhone",one.get("patient_phone"));
            tmp.put("conclusionStatus",one.get("conclusion_status"));
            Integer conclusionStatus = Integer.valueOf(one.get("conclusion_status")==null?"0":(one.get("conclusion_status")+""));
            tmp.put("status", one.get("status"));
            tmp.put("doctor", one.get("doctor"));
            tmp.put("doctorName", one.get("doctor_name"));
            tmp.put("patientPhone", one.get("patient_phone"));
            tmp.put("conclusionStatus", one.get("conclusion_status"));
            Integer conclusionStatus = Integer.valueOf(one.get("conclusion_status") == null ? "0" : (one.get("conclusion_status") + ""));
            String conclusionStatusName = "";
            switch (conclusionStatus){
                case 1:conclusionStatusName="待补录";break;
                case 2:conclusionStatusName="已登记";break;
            switch (conclusionStatus) {
                case 1:
                    conclusionStatusName = "待补录";
                    break;
                case 2:
                    conclusionStatusName = "已登记";
                    break;
            }
            tmp.put("conclusionStatusName",conclusionStatusName);
            Integer statustemp = Integer.valueOf(one.get("status")+"");
            if (-2==statustemp||-1==statustemp){
                tmp.put("doctor",one.get("update_user"));
                tmp.put("doctorName",one.get("update_user_name"));
            tmp.put("conclusionStatusName", conclusionStatusName);
            Integer statustemp = Integer.valueOf(one.get("status") + "");
            if (-2 == statustemp || -1 == statustemp) {
                tmp.put("doctor", one.get("update_user"));
                tmp.put("doctorName", one.get("update_user_name"));
            }
            String statusName = "";
            switch (statustemp){
                case -2:statusName="误警报";break;
                case -1:statusName="已取消";break;
                case 0:statusName="已完成";break;
                case 1:statusName="预警中";break;
            switch (statustemp) {
                case -2:
                    statusName = "误警报";
                    break;
                case -1:
                    statusName = "已取消";
                    break;
                case 0:
                    statusName = "已完成";
                    break;
                case 1:
                    statusName = "预警中";
                    break;
            }
            tmp.put("statusName",statusName);
            Integer age  = IdCardUtil.getAgeForIdcard(tmp.getString("idcard"));
            tmp.put("age",age);
            tmp.put("statusName", statusName);
            Integer age = IdCardUtil.getAgeForIdcard(tmp.getString("idcard"));
            tmp.put("age", age);
            //患者设备
            List<DevicePatientDevice> devices = patientDeviceDao.findAllByUser(tmp.get("patientCode").toString());
            if (devices.size()>0){
                tmp.put("deviceFlag","1");
            }
            else {
                tmp.put("deviceFlag","0");
            if (devices.size() > 0) {
                tmp.put("deviceFlag", "1");
            } else {
                tmp.put("deviceFlag", "0");
            }
            result.add(tmp);
        }
        return PageEnvelop.getSuccessListWithPage("success",result,page,pageSize,count);
        return PageEnvelop.getSuccessListWithPage("success", result, page, pageSize, count);
    }
    public JSONObject getSecurityTab(String area,String status,String svrDesc,String topicItem){
    public JSONObject getSecurityTab(String area, String status, String svrDesc, String topicItem) {
        String testPatients = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String,Object>> listtmp =  jdbcTemplate.queryForList(sqltmp);
        if(listtmp.size()>0){
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            testPatients = " not in ('"+orgCodes+"') ";
            orgCodes = orgCodes.replaceAll(",", "','");
            testPatients = " not in ('" + orgCodes + "') ";
        }
        if (StringUtils.isNotBlank(area)){
        if (StringUtils.isNotBlank(area)) {
        }
        JSONObject result = new JSONObject();
        result.put("status_-2",0);//误报警
        result.put("status_-1",0);//已取消
        result.put("status_0",0);//已完成
        result.put("status_1",0);//预警中
        result.put("status_all",0);//
        result.put("svr_all",0);//
        result.put("status_-2", 0);//误报警
        result.put("status_-1", 0);//已取消
        result.put("status_0", 0);//已完成
        result.put("status_1", 0);//预警中
        result.put("status_all", 0);//
        result.put("svr_all", 0);//
        Map<String,String> serverTmp = new HashMap<>();
        Map<String, String> serverTmp = new HashMap<>();
        String sql = " select py_code,dict_value from wlyy_hospital_sys_dict where dict_name='security_server_dict' ";
        List<Map<String,Object>> servers = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> server:servers){
            result.put("svr_"+server.get("py_code").toString(),0);
            serverTmp.put(server.get("dict_value").toString(),server.get("py_code").toString());
        List<Map<String, Object>> servers = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> server : servers) {
            result.put("svr_" + server.get("py_code").toString(), 0);
            serverTmp.put(server.get("dict_value").toString(), server.get("py_code").toString());
        }
        sql = "select ord.status,ord.serve_desc,count(ord.id) count from base_security_monitoring_order ord INNER JOIN base_patient p on p.id = ord.patient " +
                "where 1=1 ";
        String fliter = "  ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(status)){
            fliter+=" and ord.status='"+Integer.parseInt(status)+"' ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(status)) {
            fliter += " and ord.status='" + Integer.parseInt(status) + "' ";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(svrDesc)){
            fliter+=" and ord.serve_desc='"+svrDesc+"' ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(svrDesc)) {
            fliter += " and ord.serve_desc='" + svrDesc + "' ";
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(topicItem)){
            fliter+=" and ord.topic_item='"+topicItem+"' ";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(topicItem)) {
            fliter += " and ord.topic_item='" + topicItem + "' ";
        }
        fliter +=" and ord.patient "+testPatients;
        fliter += " and ord.patient " + testPatients;
        fliter+=" group by ord.status,ord.serve_desc ";
        List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql+fliter);
        fliter += " group by ord.status,ord.serve_desc ";
        List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql + fliter);
        String pyCode = "";
        for (Map<String,Object> map:sqlResult){
            result.put("status_"+map.get("status"),result.getInteger("status_"+map.get("status"))+Integer.parseInt(map.get("count").toString()));
            pyCode =  serverTmp.get(map.get("serve_desc"))==null?null:serverTmp.get(map.get("serve_desc")).toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(pyCode)){
                result.put("svr_"+pyCode,result.getInteger("svr_"+pyCode)+Integer.parseInt(map.get("count").toString()));
                result.put("status_all",result.getInteger("status_all")+Integer.parseInt(map.get("count").toString()));
                result.put("svr_all",result.getInteger("svr_all")+Integer.parseInt(map.get("count").toString()));
        for (Map<String, Object> map : sqlResult) {
            result.put("status_" + map.get("status"), result.getInteger("status_" + map.get("status")) + Integer.parseInt(map.get("count").toString()));
            pyCode = serverTmp.get(map.get("serve_desc")) == null ? null : serverTmp.get(map.get("serve_desc")).toString();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(pyCode)) {
                result.put("svr_" + pyCode, result.getInteger("svr_" + pyCode) + Integer.parseInt(map.get("count").toString()));
                result.put("status_all", result.getInteger("status_all") + Integer.parseInt(map.get("count").toString()));
                result.put("svr_all", result.getInteger("svr_all") + Integer.parseInt(map.get("count").toString()));
            }
        }
        return result;
    }
    public JSONObject statisticsSecurityWarnInfo(String endDate,String area,Integer level,String index) throws Exception {
    public JSONObject statisticsSecurityWarnInfo(String endDate, String area, Integer level, String index) throws Exception {
        JSONObject res = new JSONObject();
        String[] indexes = index.split(",");
        for(String ind:indexes){
            String areaLevel="6";
            String sql = " select area_level from wlyy_job_config_new where id='"+ind+"' ";
            List<String> areaLevels = jdbcTemplate.queryForList(sql,String.class);
            if (areaLevels.size()>0){
        for (String ind : indexes) {
            String areaLevel = "6";
            String sql = " select area_level from wlyy_job_config_new where id='" + ind + "' ";
            List<String> areaLevels = jdbcTemplate.queryForList(sql, String.class);
            if (areaLevels.size() > 0) {
                areaLevel = areaLevels.get(0);
            }
            JSONArray jsonArray = new JSONArray();
            long total = 0l;
            //总量
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate,endDate,area,level,ind,SaveModel.timeLevel_DDL,null,null,areaLevel);
            for(int i=0;i<list.size();i++){
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, ind, SaveModel.timeLevel_DDL, null, null, areaLevel);
            for (int i = 0; i < list.size(); i++) {
                SaveModel saveModel = list.get(i);
                JSONObject json = new JSONObject();
                if (saveModel.getResult2().longValue()==0&&StringUtils.isBlank(saveModel.getSlaveKey1())){
                if (saveModel.getResult2().longValue() == 0 && StringUtils.isBlank(saveModel.getSlaveKey1())) {
                    continue;
                }
                if ("0".equals(saveModel.getSlaveKey1())){
                if ("0".equals(saveModel.getSlaveKey1())) {
                    continue;
                }
                json.put("num",saveModel.getResult2().longValue());
                json.put("code",saveModel.getSlaveKey1());
                json.put("name",saveModel.getSlaveKey1Name());
                total+=saveModel.getResult2().longValue();
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                total += saveModel.getResult2().longValue();
                jsonArray.add(json);
            }
            res.put("index_"+ind+"_total",total);
            res.put("index_"+ind,jsonArray);
            if("46".equals(ind)){
            res.put("index_" + ind + "_total", total);
            res.put("index_" + ind, jsonArray);
            if ("46".equals(ind)) {
                //安防响应 误报警+完成
                SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,area,level,"46","2","-2",areaLevel);
                SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate, area, level, "46", "2", "-2", areaLevel);
                long finish = saveModel.getResult2().longValue();
                saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,area,level,"46","2","0",areaLevel);
                saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate, area, level, "46", "2", "0", areaLevel);
                finish += saveModel.getResult2().longValue();
                res.put("index_"+46+"_finish",finish);
                res.put("index_" + 46 + "_finish", finish);
                //安防误报警
                saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,area,level,"46","2","-2",areaLevel);
                res.put("index_"+46+"_error",saveModel.getResult2().longValue());
                saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate, area, level, "46", "2", "-2", areaLevel);
                res.put("index_" + 46 + "_error", saveModel.getResult2().longValue());
            }
        }
        //误报警率分析
        return res;
    }
    public JSONArray statisticsSecurityTrend(String startDate,String endDate,String area,Integer level,String index) throws Exception {
    public JSONArray statisticsSecurityTrend(String startDate, String endDate, String area, Integer level, String index) throws Exception {
        //安防总数
        List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(startDate,endDate,area,level,index,SaveModel.timeLevel_DDL,SaveModel.interval_day,null);
        List<SaveModel> saveModels = elasticsearchUtil.findDateQuotaLevel0(startDate, endDate, area, level, index, SaveModel.timeLevel_DDL, SaveModel.interval_day, null);
        JSONArray jsonArray = new JSONArray();
        for (SaveModel tmp:saveModels){
        for (SaveModel tmp : saveModels) {
            JSONObject jsonTmp = new JSONObject();
            jsonTmp.put("count",tmp.getResult2().longValue());
            jsonTmp.put("timeDay",DateUtil.dateToStr(tmp.getQuotaDate(),DateUtil.YYYY_MM_DD));
            jsonTmp.put("time",DateUtil.dateToStr(tmp.getQuotaDate(),DateUtil.yyyy_MM_dd_HH_mm_ss));
            jsonTmp.put("count", tmp.getResult2().longValue());
            jsonTmp.put("timeDay", DateUtil.dateToStr(tmp.getQuotaDate(), DateUtil.YYYY_MM_DD));
            jsonTmp.put("time", DateUtil.dateToStr(tmp.getQuotaDate(), DateUtil.yyyy_MM_dd_HH_mm_ss));
            jsonArray.add(jsonTmp);
        }
        return jsonArray;
@ -1415,72 +1591,257 @@ public class StatisticsService {
    /**
     * 计算开始时间
     *
     * @param endDate
     * @param type 1周,2月
     * @param type    1周,2月
     * @return
     */
    public String calStart(String endDate,int type){
        if(StringUtils.isEmpty(endDate)){
    public String calStart(String endDate, int type) {
        if (StringUtils.isEmpty(endDate)) {
            return endDate;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(DateUtil.strToDate(endDate));
        if(1==type){
            if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
                cal.add(Calendar.DAY_OF_WEEK,-1);
        if (1 == type) {
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                cal.add(Calendar.DAY_OF_WEEK, -1);
            }
            cal.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
        }else{
            cal.set(Calendar.DAY_OF_MONTH,1);
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        } else {
            cal.set(Calendar.DAY_OF_MONTH, 1);
        }
        return DateUtil.dateToStrShort(cal.getTime());
    }
    public List searchBySql(String sql){
        if (sql.startsWith("select")||sql.startsWith("SELECT")){
    public List searchBySql(String sql) {
        if (sql.startsWith("select") || sql.startsWith("SELECT")) {
            return elasticsearchUtil.searchBySql(sql);
        }
        return null;
    }
    /**
     *
     * @param esSql
     * @param jsonStr 修改数据
     * @return
     */
    public boolean esDataModify(String esSql,String jsonStr) {
    public boolean esDataModify(String esSql, String jsonStr) {
        try {
            if (StringUtils.containsIgnoreCase(esSql,"limit")){
            if (StringUtils.containsIgnoreCase(esSql, "limit")) {
                return false;
            }
            Boolean flag=false;
            List<SaveModel> objs = elasticsearchUtil.excute(esSql,SaveModel.class,"","");
            List<Map<String,Object>> sourceMap = new ArrayList<>();
            int i=0;
            for (SaveModel tmp:objs){
            Boolean flag = false;
            List<SaveModel> objs = elasticsearchUtil.excute(esSql, SaveModel.class, "", "");
            List<Map<String, Object>> sourceMap = new ArrayList<>();
            int i = 0;
            for (SaveModel tmp : objs) {
                String jsonStr1 = JSON.toJSONString(tmp);
                Map<String,Object> tmpInfo = com.alibaba.fastjson.JSONObject.parseObject(jsonStr1,Map.class);
                if (StringUtils.isNotBlank(jsonStr)){
                    Map<String,Object> modifyInfo = com.alibaba.fastjson.JSONObject.parseObject(jsonStr,Map.class);
                    for (String key:modifyInfo.keySet()){
                Map<String, Object> tmpInfo = com.alibaba.fastjson.JSONObject.parseObject(jsonStr1, Map.class);
                if (StringUtils.isNotBlank(jsonStr)) {
                    Map<String, Object> modifyInfo = com.alibaba.fastjson.JSONObject.parseObject(jsonStr, Map.class);
                    for (String key : modifyInfo.keySet()) {
                        tmpInfo.put(key, modifyInfo.get(key));
                    }
                    sourceMap.add(tmpInfo);
                }
                i++;
            }
            if (i>0){
                flag = elasticSearchHelper.updateByMap(esIndex,esIndex,sourceMap);//修改
            if (i > 0) {
                flag = elasticSearchHelper.updateByMap(esIndex, esIndex, sourceMap);//修改
            }
            return flag;
        }
        catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /*大屏 老人云照护 病人分析 */
    public JSONObject patientAnalysisDP(String endDate, String area, int level, String index) throws Exception {
        JSONObject res = new JSONObject();
        String areaLevel = "6";
        if ("42".equals(index)) {
            areaLevel = "4";
            //新生儿
            //是否入学
            List<SaveModel> statusList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL, null, null, areaLevel);
            JSONArray statusArray = new JSONArray();
            for (int i = 0; i < statusList.size(); i++) {
                SaveModel saveModel = statusList.get(i);
                JSONObject json = new JSONObject();
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                statusArray.add(json);
            }
            res.put("statusList", statusArray);
        } else {
            //老人
            //能力评估 从签约时服务标签取
            res.put("levelList", cloudCareForTheElderly(null, null, null));
            //居民健康标签
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "47", SaveModel.timeLevel_DDL, null, null, "2");
            JSONArray labelArr = new JSONArray();
            Long total = 0l;
            for (int i = 0; i < list.size(); i++) {
                SaveModel saveModel = list.get(i);
                JSONObject json = new JSONObject();
                if (saveModel.getResult2().longValue() == 0 && StringUtils.isBlank(saveModel.getSlaveKey1())) {
                    continue;
                }
                if ("0".equals(saveModel.getSlaveKey1())) {//去除60岁以下老人
                    continue;
                }
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                total += saveModel.getResult2().longValue();
                labelArr.add(json);
            }
            JSONObject arrTmp = new JSONObject();
            arrTmp.put("patientLabelTotal", total);
            arrTmp.put("patientLabelList", labelArr);
            res.put("patientLabelStatistic", arrTmp);
            //年龄分布 50
//            ageList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "50", SaveModel.timeLevel_DDL,null,null,"2");
            List<SaveModel> ageList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "50", SaveModel.timeLevel_DDL, null, null, "2");
            JSONArray ageArray = new JSONArray();
            for (int i = 0; i < ageList.size(); i++) {
                SaveModel saveModel = ageList.get(i);
                if ("0".equals(saveModel.getSlaveKey1())) {//去除60岁以下老人
                    continue;
                }
                JSONObject json = new JSONObject();
                json.put("num", saveModel.getResult2().longValue());
                json.put("code", saveModel.getSlaveKey1());
                json.put("name", saveModel.getSlaveKey1Name());
                ageArray.add(json);
            }
            res.put("ageList", ageArray);
            //居住小区分布
            String filter = "";
            String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
            List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
            if (listtmp.size() > 0) {
                String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
                orgCodes = orgCodes.replaceAll(",", "','");
                filter = " not in ('" + orgCodes + "')";
            }
            String sql = "select count(id) total,residential_area residentialArea  from base_patient where del=1 and id " + filter + "  and archive_type=1 " +
                    "GROUP BY residential_area ORDER BY total desc";
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            Iterator<Map<String, Object>> iterator = result.iterator();
            Map<String, Object> tmp = new HashMap<>();
            while (iterator.hasNext()) {
                tmp = iterator.next();
                if (null == tmp.get("residentialArea")) {
                    iterator.remove();
                    break;
                }
            }
            result.add(tmp);
            res.put("residentialArea", result);
        }
        //性别分析
        String archiType = "";
        if ("42".equals(index)) {
            archiType = "2";
        }
        if ("37".equals(index)) {
            archiType = "1";
        }
        List<SaveModel> sexList = elasticsearchUtil.findDateQuotaLevel2ByKeyGroup(endDate, endDate, defalutArea, level, "51", SaveModel.timeLevel_DDL, null, archiType, null, null, "2", "1");
        JSONArray sexArray = new JSONArray();
        for (int i = 0; i < sexList.size(); i++) {
            SaveModel saveModel = sexList.get(i);
            JSONObject json = new JSONObject();
            json.put("num", saveModel.getResult2().longValue());
            json.put("code", saveModel.getSlaveKey1());
            json.put("name", saveModel.getSlaveKey1Name());
            sexArray.add(json);
        }
        res.put("sexList", sexArray);
        return res;
    }
    /*大屏 老人云照护 评估*/
    public JSONArray cloudCareForTheElderly(String endDate, String area, Integer level) throws Exception {
        //评估类型
        String filter = "";
        String sqltmp = "SELECT GROUP_CONCAT(dict_code) orgCodes from wlyy_hospital_sys_dict WHERE dict_name = 'jkzl_child' or dict_name = 'jkzl_older' ";
        List<Map<String, Object>> listtmp = jdbcTemplate.queryForList(sqltmp);
        if (listtmp.size() > 0) {
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            if (StringUtils.isNotBlank(orgCodes)) {
                orgCodes = orgCodes.replaceAll(",", "','");
                filter = " and lab.patient not in ('" + orgCodes + "')";
            }
        }
        JSONArray jsonArray = new JSONArray();
        String sql = " select dict.dict_code,dict_value,count(DISTINCT A.patient) total from wlyy_hospital_sys_dict dict \n" +
                " LEFT JOIN (select distinct lab.patient,lab.label_code from  wlyy_patient_label lab  INNER JOIN base_patient p on p.id = lab.patient AND  lab.label_type='3' " +
                filter + "   \n" +
                ")A on dict.dict_code = A.label_code " +
                "where  dict.dict_name='older_label'  and  dict.dict_code is not null and dict_code <= 7  \n" +
                " GROUP BY dict.dict_code; ";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        String older = " select count(distinct lab.patient) from  wlyy_patient_label lab  INNER JOIN base_patient p on p.id = lab.patient AND  lab.label_type='1' " + filter;
        Integer count = jdbcTemplate.queryForObject(older, Integer.class);
        for (Map<String, Object> map : list) {
            JSONObject json = new JSONObject();
            DecimalFormat df = new DecimalFormat("0.00");
            json.put("rate", df.format((Integer.parseInt(map.get("total").toString()) * 1.00) / count * 100));
            json.put("num", map.get("total"));
            json.put("code", map.get("dict_code").toString());
            json.put("name", map.get("dict_value").toString());
            jsonArray.add(json);
        }
        return jsonArray;
    }
    //新生儿 回复  为回复率  总咨询 及时回复率
    public JSONObject newBornReply(String endDate) throws Exception {
        JSONObject res = new JSONObject();
        String index = "28,29,30";
        String[] split = index.split(",");
        for (String ind : split) {
            long total = 0l;
            List<SaveModel> list = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, "330100", 2, ind, SaveModel.timeLevel_DDL, null, null, "2");
            for (int i = 0; i < list.size(); i++) {
                SaveModel saveModel = list.get(i);
                total+=saveModel.getResult2().longValue();
            }
            res.put("index_"+ind,total);
        }
        Long index_28 = (Long) res.get("index_28");
        Long index_29 = (Long) res.get("index_29");
        Long index_30 = (Long) res.get("index_30");
        DecimalFormat df=new DecimalFormat("0.00");
        if (index_28!=0){
            if (index_29!=0){
                res.put("noReply",df.format((float) index_29/index_28*100)+"%");
            }else {
                res.put("noReply","0.00%");
            }
            if (index_30!=0){
                res.put("reply",df.format((float) index_30/index_28*100 )+"%");
            }else {
                res.put("reply","0.00%");
            }
        }else{
            res.put("reply","0.00%");
            res.put("noReply","0.00%");
        }
        return res;
    }
    //新生儿上门辅导 类型
}

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/third/PatientInfoPlatFormService.java

@ -283,7 +283,7 @@ public class PatientInfoPlatFormService {
     * @return
     */
    public JSONObject getPatientMonitoringInfo(String patient){
        return securityMonitoringOrderService.patientMonitoringInfo(patient,null,true);
        return securityMonitoringOrderService.patientMonitoringInfo(patient,null,null,true);
    }
    /**

+ 37 - 6
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MessageUtil.java

@ -8,6 +8,7 @@ import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.care.common.GetuiClientDO;
import com.yihu.jw.entity.care.doorCoach.BaseDoorCoachOrderDO;
import com.yihu.jw.entity.care.lifeCare.LifeCareOrderDO;
import com.yihu.jw.entity.care.securitymonitoring.SecurityMonitoringOrderDO;
@ -15,6 +16,8 @@ import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.push.dao.GetuiClientDao;
import com.yihu.jw.push.service.GetuiService;
import com.yihu.jw.sms.service.TXYSmsService;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import com.yihu.jw.wechat.dao.WxAccessTokenDao;
@ -31,9 +34,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.*;
/**
 * Created by liub on 2020/12/28.
@ -67,8 +68,10 @@ public class MessageUtil {
    private BaseOrgDao orgDao;
    @Autowired
    private TXYSmsService txySmsService;
    //发送微信模板消息
    private  String sendMessageUrl = "http://172.16.100.37:8090/hospitalPortal-sms/sms/sendMessage";
    @Autowired
    private GetuiService getuiService;
    @Autowired
    private GetuiClientDao getuiClientDao;
    /**
     * 您好{1}有一条新的在线报名申请,请及时前往APP消息应用进行处理。
@ -82,6 +85,34 @@ public class MessageUtil {
        }
    }
    /**
     * 发送医生个推推送消息
     * type 1 安防紧急预警 2紧急呼叫 4im 5生日祝福
     */
    public void sendDoctorGetuiMessage(String doctorCode,String type,String url,String title,String body){
        try {
            List<GetuiClientDO> clientDOS = getuiClientDao.findByUser(doctorCode,2);
            JSONObject payload = new JSONObject();
            payload.put("title",title);
            payload.put("body",body);
            payload.put("url",url);
            JSONObject json = new JSONObject();
            json.put("title",title);
            json.put("body",body);
            json.put("url",url);
//        json.put("clickType","url");
            json.put("platform",getuiService.cloudCareDoctor);
            json.put("payload",payload.toString());
            for(GetuiClientDO clientDO:clientDOS){
                getuiService.push2(clientDO.getClientId(),Integer.valueOf(clientDO.getClientType()),json);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     *
     * @param wechatId
@ -117,7 +148,7 @@ public class MessageUtil {
                newConfig.setFirst(first);
            }
            if (StringUtils.isNoneBlank(url)){
               newConfig.setUrl(url);
                newConfig.setUrl(url);
            }
            if (StringUtils.isNoneBlank(remark)){
                newConfig.setRemark(remark);

+ 14 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BasePatientStepDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.BasePatientStepDo;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2021/12/22.
 */
public interface BasePatientStepDao extends PagingAndSortingRepository<BasePatientStepDo,Long>,
        JpaSpecificationExecutor<BasePatientStepDo> {
}

+ 12 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/dao/device/BaseSleepX1deviceDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.BaseSleepX1device;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Bing on 2022/1/7.
 */
public interface BaseSleepX1deviceDao extends PagingAndSortingRepository<BaseSleepX1device,String>,
        JpaSpecificationExecutor<BaseSleepX1device> {
}

+ 45 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceController.java

@ -393,6 +393,51 @@ public class DeviceController {
        }
    }
    @ApiOperation("爱牵挂-手表睡眠接收")
    @RequestMapping(value = "byX1Sleep",  method = {RequestMethod.POST,RequestMethod.GET})
    public String byX1Sleep(
            @ApiParam(name="imei",required = false,value="imei",defaultValue = "")
            @RequestParam(value = "imei",required = true) String imei,
            @ApiParam(name="time_begin",required = false,value="发生时间YYYY-MM-DD HH:mm:SS")
            @RequestParam(value = "time_begin",required = false) String time_begin,
            @ApiParam(name="time_end",required = false,value="结束时间YYYY-MM-DD HH:mm:SS")
            @RequestParam(value = "time_end",required = false) String time_end,
            @ApiParam(name="interval",required = false,value="固定30分钟,忽略,兼容其他设备的参数")
            @RequestParam(value = "interval",required = false) Integer interval,
            @ApiParam(name="total",required = false,value="检测次数, 忽略,兼容其他设备的参数")
            @RequestParam(value = "total",required = false) Integer total,
            @ApiParam(name="deep_sleep",required = false,value="深睡时长,单位小时,str(float)")
            @RequestParam(value = "deep_sleep",required = false) String deep_sleep,
            @ApiParam(name="light_sleep",required = false,value="浅睡时长,单位小时,str(float)")
            @RequestParam(value = "light_sleep",required = false)String light_sleep,
            @ApiParam(name="awake_time",required = false,value="清醒时长,单位小时,str(float)")
            @RequestParam(value = "awake_time",required = false)String awake_time,
            HttpServletRequest request) {
        try {
            String paraString = JSON.toJSONString(request.getParameterMap());
            deviceService.byX1Sleep(imei,time_begin,time_end,interval,total,deep_sleep,light_sleep,awake_time);
            logger.info("爱牵挂-手表睡眠接收,请求参数:"+paraString);
            dataPushLogUtil.savePushLog(imei,paraString,"手表睡眠接收");
            dataPushLogUtil.updContactStatus(imei,1,false);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"Device data incoming failure");
        }
    }
    @ApiOperation("设备步数接收")
    @RequestMapping(value = "stepsCreate",  method = {RequestMethod.POST,RequestMethod.GET})
    public String stepsCreate() {
        try {
            deviceService.stepsCreate();
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"Device data incoming failure");
        }
    }
    /*******************************************睡眠带end****************************************************************/
    /**
     * 返回接口处理结果

+ 92 - 4
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/DeviceService.java

@ -99,6 +99,10 @@ public class DeviceService {
    private DeviceDataPushLogUtil dataPushLogUtil;
    @Autowired
    private PatientSafeAreaDao safeAreaDao;
    @Autowired
    private BasePatientStepDao stepDao;
    @Autowired
    private BaseSleepX1deviceDao baseSleepX1deviceDao;
    /**
     * 获取爱牵挂管理员cookie
@ -551,7 +555,7 @@ public class DeviceService {
    }
    /**
     * 柏颐跌倒数据接收
     * 爱牵挂 X1手表跌倒数据接收
     * @param imei 15位设备唯一序号
     * @param time_begin 发生时间YYYY-MM-DD HH:mm:SS
     * @param city 城市
@ -561,10 +565,54 @@ public class DeviceService {
     * @param type 类型   0:Gps定位; 1:基站定位
     */
    @Async
    public void byFall(String imei,String time_begin,String city,String address,double lon,double lat,String type) {
    public void byFall(String imei,String time_begin,String city,String address,Double lon,Double lat,String type) {
        try {
            if(StringUtils.isNotBlank(imei)){
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 爱牵挂X1手表睡眠数据接收
     * @param imei
     * @param time_begin
     * @param time_end
     * @param interval
     * @param total
     * @param deep_sleep
     * @param light_sleep
     * @param awake_time
     */
    @Async
    public void byX1Sleep(String imei,String time_begin,String time_end,Integer interval,Integer total,String deep_sleep,String light_sleep,String awake_time) {
        try {
            if(StringUtils.isNotBlank(imei)){
                List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByDeviceSn(imei);
                if (devicePatientDeviceDos.size()>0){
                    Double deepSleep =Double.parseDouble(deep_sleep)*60 ;
                    Double lightSleep = Double.parseDouble(light_sleep)*60;
                    Double awakeTime = Double.parseDouble(awake_time)*60;
                    Double sleepTime = deepSleep+lightSleep+awakeTime;
                    BaseSleepX1device sleepX1device = new BaseSleepX1device();
                    sleepX1device.setDeviceSn(imei);
                    sleepX1device.setPatient(devicePatientDeviceDos.get(0).getUser());
                    sleepX1device.setDeepSleep(deepSleep.intValue()+"");
                    sleepX1device.setLightSleep(lightSleep.intValue()+"");
                    sleepX1device.setAwakeTime(awakeTime.intValue()+"");
                    sleepX1device.setSleepTime(sleepTime.intValue()+"");
                    sleepX1device.setIntervalTime(interval);
                    sleepX1device.setTotal(total);
                    sleepX1device.setCreateTime(DateUtil.strToDate(time_begin));
                    sleepX1device.setEndTime(DateUtil.strToDate(time_end));
                    baseSleepX1deviceDao.save(sleepX1device);
                }
            }
        } catch (Exception e) {
@ -582,9 +630,19 @@ public class DeviceService {
    public void bySteps(String imei,String time_begin,int value) {
        try {
            if(StringUtils.isNotBlank(imei)){
                List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByDeviceSn(imei);
                if (devicePatientDeviceDos.size()>0){
                    BasePatientStepDo basePatientStepDo = new BasePatientStepDo();
                    basePatientStepDo.setPatient(devicePatientDeviceDos.get(0).getUser());
                    basePatientStepDo.setDeviceSn(imei);
                    basePatientStepDo.setDel(1);
                    basePatientStepDo.setSteps(value+"");
                    Date createTime = DateUtil.strToDate(time_begin,DateUtil.yyyy_MM_dd_HH_mm_ss);
                    basePatientStepDo.setCreateTime(createTime);
                    basePatientStepDo.setDay(DateUtil.dateToStr(createTime,DateUtil.YYYY_MM_DD));
                    stepDao.save(basePatientStepDo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
@ -1006,4 +1064,34 @@ public class DeviceService {
        }
    }
    @Async
    public void stepsCreate(){
        String sql = " select data from device_data_push_log where api_name='爱牵挂设备步数数据接收' ORDER BY create_time asc ";
        List<String> steps = jdbcTemplate.queryForList(sql,String.class);
        List<BasePatientStepDo> list = new ArrayList<>();
        for(String step:steps)
        {
            try {
                JSONObject stepObj = JSONObject.parseObject(step);
                String imei = stepObj.getString("imei").replace("\"]","").replace("[\"","");
                String value = stepObj.getString("value").replace("\"]","").replace("[\"","");
                String time_begin = stepObj.getString("time_begin").replace("\"]","").replace("[\"","");
                if(StringUtils.isNotBlank(imei)){
                    List<DevicePatientDevice> devicePatientDeviceDos = patientDeviceDao.findByDeviceSn(imei);
                    if (devicePatientDeviceDos.size()>0){
                        BasePatientStepDo basePatientStepDo = new BasePatientStepDo();
                        basePatientStepDo.setPatient(devicePatientDeviceDos.get(0).getUser());
                        basePatientStepDo.setDeviceSn(imei);
                        basePatientStepDo.setDel(1);
                        basePatientStepDo.setSteps(value+"");
                        Date createTime = DateUtil.strToDate(time_begin,DateUtil.yyyy_MM_dd_HH_mm_ss);
                        basePatientStepDo.setCreateTime(createTime);
                        basePatientStepDo.setDay(DateUtil.dateToStr(createTime,DateUtil.YYYY_MM_DD));
                        list.add(basePatientStepDo);
                    }
                }
            }catch (Exception e){ }
        }
        stepDao.save(list);
    }
}

+ 5 - 1
svr/svr-cloud-job/pom.xml

@ -85,7 +85,11 @@
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>push-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>

+ 5 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/service/BirthdayReminderService.java

@ -43,11 +43,16 @@ public class BirthdayReminderService {
            try {
                String doctorName = map.get("name")+"";
                String mobile = map.get("mobile")+"";
                String doctorId =  map.get("id")+"";
                Integer c = Integer.valueOf(map.get("c")+"");
                if (c>0&&mobile.length()==11){
                    messageUtil.sendTXYSJson("1099809",mobile,doctorName,c+"");
                }
                if(c>0){
                    String body = "您好,今天有"+c+"位老人走访计划,请及时处理";
                    messageUtil.sendDoctorGetuiMessage(doctorId,"1","/solicitude/birthday","生日祝福提醒",body);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

+ 37 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/util/MessageUtil.java

@ -5,6 +5,9 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.care.common.GetuiClientDO;
import com.yihu.jw.push.dao.GetuiClientDao;
import com.yihu.jw.push.service.GetuiService;
import com.yihu.jw.sms.service.TXYSmsService;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
@ -18,6 +21,8 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.List;
/**
 * Created by Bing on 2021/5/29.
 */
@ -36,9 +41,41 @@ public class MessageUtil {
    @Value("${sendTXMessage.flag}")
    private Boolean sendTXMessageFlag;
    @Autowired
    private GetuiService getuiService;
    @Autowired
    private GetuiClientDao getuiClientDao;
    private static Logger logger = LoggerFactory.getLogger(MessageUtil.class);
    /**
     * 发送医生个推推送消息
     * type 1 安防紧急预警 2紧急呼叫 4im 5生日祝福
     */
    public void sendDoctorGetuiMessage(String doctorCode,String type,String url,String title,String body){
        try {
            List<GetuiClientDO> clientDOS = getuiClientDao.findByUser(doctorCode,2);
            JSONObject payload = new JSONObject();
            payload.put("title",title);
            payload.put("body",body);
            payload.put("url",url);
            JSONObject json = new JSONObject();
            json.put("title",title);
            json.put("body",body);
            json.put("url",url);
//        json.put("clickType","url");
            json.put("platform",getuiService.cloudCareDoctor);
            json.put("payload",payload.toString());
            for(GetuiClientDO clientDO:clientDOS){
                getuiService.push2(clientDO.getClientId(),Integer.valueOf(clientDO.getClientType()),json);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void putTemplateWxMessage(String wechatId, String templateName, String scene, String openId, String first
            ,String url, String remark, Integer type,JSONObject json,String ...keywords) {
        try {

+ 34 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/controller/TransforController.java

@ -370,6 +370,40 @@ public class TransforController {
        }
    }
    @ApiOperation("爱牵挂-手表睡眠接收")
    @RequestMapping(value = "byX1Sleep",  method = {RequestMethod.POST,RequestMethod.GET})
    public String byX1Sleep(
            @ApiParam(name="imei",required = false,value="imei",defaultValue = "")
            @RequestParam(value = "imei",required = true) String imei,
            @ApiParam(name="time_begin",required = false,value="发生时间YYYY-MM-DD HH:mm:SS")
            @RequestParam(value = "time_begin",required = false) String time_begin,
            @ApiParam(name="time_end",required = false,value="结束时间YYYY-MM-DD HH:mm:SS")
            @RequestParam(value = "time_end",required = false) String time_end,
            @ApiParam(name="interval",required = false,value="固定30分钟,忽略,兼容其他设备的参数")
            @RequestParam(value = "interval",required = false) Integer interval,
            @ApiParam(name="total",required = false,value="检测次数, 忽略,兼容其他设备的参数")
            @RequestParam(value = "total",required = false) Integer total,
            @ApiParam(name="deep_sleep",required = false,value="深睡时长,单位小时,str(float)")
            @RequestParam(value = "deep_sleep",required = false) String deep_sleep,
            @ApiParam(name="light_sleep",required = false,value="浅睡时长,单位小时,str(float)")
            @RequestParam(value = "light_sleep",required = false)String light_sleep,
            @ApiParam(name="awake_time",required = false,value="清醒时长,单位小时,str(float)")
            @RequestParam(value = "awake_time",required = false)String awake_time,
            HttpServletRequest request) {
        try {
            long startTime=System.currentTimeMillis();
            String paraString = JSON.toJSONString(request.getParameterMap());
            String url = RequestParamUtil.getParamUrl(request);
            String result = aqgService.aqgForward(url);
            long endTime=System.currentTimeMillis();
            logger.info("爱牵挂-手表睡眠接收,请求参数:"+paraString+" "+(endTime-startTime)+"ms; 响应:"+result);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"Device data incoming failure");
        }
    }
    /*******************************************睡眠带end****************************************************************/
    /**
     * 返回接口处理结果

+ 6 - 0
svr/svr-iot/pom.xml

@ -136,6 +136,12 @@
            <groupId>com.yihu</groupId>
            <artifactId>fastdfs-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>shield</artifactId>
            <version>2.4.6</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>

+ 333 - 0
svr/svr-iot/src/main/java/com/yihu/elasticsearch/ElasticSearchHelper.java

@ -0,0 +1,333 @@
package com.yihu.elasticsearch;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.expr.SQLQueryExpr;
import com.alibaba.druid.sql.parser.SQLExprParser;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.elasticsearch.ElasticSearchPool;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import org.apache.commons.collections.CollectionUtils;
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.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.*;
;
/**
 * Created by chenweida on 2017/6/2.
 */
@Component
@Scope("prototype")
public class ElasticSearchHelper {
    private Logger logger = LoggerFactory.getLogger(ElasticSearchHelper.class);
    @Autowired
    private ElasticSearchPool elasticSearchPool;
    private JestClient jestClient;
    @Value("${es.host}")
    private String esHost;
    @Autowired
    private ObjectMapper objectMapper;
    private static String[] curlCmds = new String[6];
    @PostConstruct
    public void init() {
        jestClient = elasticSearchPool.getJestClient();
        // curl命令格式
        String url = esHost.split(",")[0].replace("http://", "").concat("/_sql");
        curlCmds[0] = "curl";
        curlCmds[1] = url;
        curlCmds[2] = "-H";
        curlCmds[3] = "Content-Type: application/json";
        curlCmds[4] = "-d";
    }
    public <T> Boolean save(String index, String type, List<T> sources) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        sources.forEach((item) -> {
            Index indexObj = (new Index.Builder(item)).build();
            bulk.addAction(indexObj);
        });
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        this.logger.debug("save flag: " + br.isSucceeded());
        return br.isSucceeded();
    }
    public Boolean save (String index, String type, String source) throws IOException {
        Bulk.Builder bulk = new Bulk.Builder().defaultIndex(index).defaultType(type);
        Index indexObj = new Index.Builder(source).build();
        bulk.addAction(indexObj);
        BulkResult br = jestClient.execute(bulk.build());
        logger.debug("save flag: " + br.isSucceeded());
        return br.isSucceeded();
    }
    public Boolean save(String index, String type, String source,String errMsg) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        Index indexObj = (new Index.Builder(source)).build();
        bulk.addAction(indexObj);
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        if(!br.isSucceeded()){
            this.logger.error("save flag: " + br.isSucceeded());
            errMsg = br.getErrorMessage();
        }
        return br.isSucceeded();
    }
    public Boolean saveWithCustomId(String index, String type, String source, String idFieldString,StringBuilder errMsg) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        JSONObject jsonObject = (JSONObject)(JSONObject.parse(source));
        Index indexObj = ((Index.Builder)(new Index.Builder(source)).id(jsonObject.getString(idFieldString))).build();
        bulk.addAction(indexObj);
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        if(!br.isSucceeded()){
            errMsg.append(br.getJsonString());
            this.logger.error("save flag: " + br.isSucceeded() + "  " + errMsg.toString());
        }
        return br.isSucceeded();
    }
    public Boolean saveBulkWithCustomId(String index, String type, List<String> sources, String idFieldString) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        sources.forEach((item) -> {
            JSONObject jsonObject = (JSONObject)((JSONObject)JSONObject.parse(item));
            Index indexObj = ((Index.Builder)(new Index.Builder(item)).id(jsonObject.getString(idFieldString))).build();
            bulk.addAction(indexObj);
        });
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        this.logger.debug("save flag: " + br.isSucceeded());
        return br.isSucceeded();
    }
    public <T> Boolean update(String index, String type, List<T> sources) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        sources.forEach((item) -> {
            JSONObject jo = new JSONObject();
            jo.put("doc", item);
//            Update indexObj = ((io.searchbox.core.Update.Builder)((io.searchbox.core.Update.Builder)((Builder)(new Builder(jo.toString())).index(index)).type(type)).id((item).getId())).build();
//            bulk.addAction(indexObj);
        });
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        this.logger.debug("update flag: " + br.isSucceeded());
        return br.isSucceeded();
    }
    public Boolean updateByMap(String index, String type, List<Map<String, Object>> list) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        Iterator var10 = list.iterator();
        while(var10.hasNext()) {
            Map map = (Map)var10.next();
            JSONObject jo = new JSONObject();
            jo.put("doc", map);
            Update indexObj = ((Update.Builder)((Update.Builder)((Update.Builder)(new Update.Builder(jo.toString())).index(index)).type(type)).id(String.valueOf(map.get("id")))).build();
            bulk.addAction(indexObj);
        }
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        this.logger.debug("update flag: " + br.isSucceeded());
        return br.isSucceeded();
    }
    public boolean update(String index, String type, String _id, JSONObject source) throws IOException {
        JSONObject docSource = new JSONObject();
        docSource.put("doc", source);
        Update update = ((Update.Builder)((Update.Builder)((Update.Builder)(new Update.Builder(docSource)).index(index)).type(type)).id(_id)).build();
        JestResult jestResult = this.jestClient.execute(update);
        this.logger.debug("update info: " + jestResult.isSucceeded());
        return true;
    }
    public boolean delete(String index, String type, List<Map<String, Object>> datas) throws IOException {
        Bulk.Builder bulk = (new Bulk.Builder()).defaultIndex(index).defaultType(type);
        Iterator var5 = datas.iterator();
        while(var5.hasNext()) {
            Map map = (Map)var5.next();
            if (map.containsKey("id") && map.containsKey("_id")) {
                Delete indexObj = null;
                if (null != map.get("_id")) {
                    indexObj = (new Delete.Builder(map.get("_id").toString())).build();
                } else if (null != map.get("id")) {
                    indexObj = (new Delete.Builder(map.get("id").toString())).build();
                }
                bulk.addAction(indexObj);
            }
        }
        BulkResult br = (BulkResult)this.jestClient.execute(bulk.build());
        this.logger.debug("delete data count: " + datas.size());
        this.logger.debug("delete flag: " + br.isSucceeded());
        return br.isSucceeded();
    }
    public SearchResult search(String index, String type, String queryStr) throws IOException {
        Search search = ((Search.Builder)((Search.Builder)(new Search.Builder(queryStr)).addIndex(index)).addType(type)).build();
        SearchResult result = (SearchResult)this.jestClient.execute(search);
        this.logger.info("search data count: " + result.getTotal());
        return result;
    }
    public List<Map<String, Object>> executeSQL(String sql) throws Exception {
        List<Map<String, Object>> returnModels = new ArrayList();
        SQLExprParser parser = new ElasticSqlExprParser(sql);
        SQLExpr expr = parser.expr();
        SQLQueryExpr queryExpr = (SQLQueryExpr)expr;
//        SQLBinaryExpr queryExpr = (SQLBinaryExpr)expr;
        Select select = (new SqlParser()).parseSelect(queryExpr);
        AggregationQueryAction action = null;
        DefaultQueryAction queryAction = null;
        SqlElasticSearchRequestBuilder requestBuilder = null;
        if (select.isAgg) {
            action = new AggregationQueryAction(this.elasticSearchPool.getClient(), select);
            requestBuilder = action.explain();
        } else {
            Client client = this.elasticSearchPool.getClient();
            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 && sql.toUpperCase().indexOf("COUNT(") == -1) {
            queryResult = response.getHits();
        } else {
            queryResult = response.getAggregations();
        }
        ObjectResult temp = (new ObjectResultsExtractor(true, true, true)).extractResults(queryResult, true);
        List<String> heads = temp.getHeaders();
        temp.getLines().stream().forEach((one) -> {
            Map<String, Object> oneMap = new HashMap();
            for(int i = 0; i < one.size(); ++i) {
                Object value = one.get(i);
                String key = (String)heads.get(i);
                oneMap.put(key, value);
            }
            returnModels.add(oneMap);
        });
        return returnModels;
    }
    public Integer executeCountSQL(String sql) throws Exception {
        SQLQueryExpr queryExpr = new SQLQueryExpr();
        Select select = (new SqlParser()).parseSelect(queryExpr);
        SqlElasticSearchRequestBuilder requestBuilder;
        if (select.isAgg) {
            AggregationQueryAction action = new AggregationQueryAction(this.elasticSearchPool.getClient(), select);
            requestBuilder = action.explain();
        } else {
            Client client = this.elasticSearchPool.getClient();
            DefaultQueryAction queryAction = new DefaultQueryAction(client, select);
            requestBuilder = queryAction.explain();
        }
        SearchResponse response = (SearchResponse)requestBuilder.get();
        Object queryResult;
        if (sql.toUpperCase().indexOf("GROUP") == -1 && sql.toUpperCase().indexOf("SUM") == -1 && sql.toUpperCase().indexOf("COUNT(") == -1) {
            queryResult = response.getHits();
        } else {
            queryResult = response.getAggregations();
        }
        ObjectResult temp = (new ObjectResultsExtractor(true, true, true)).extractResults(queryResult, true);
        for(int j = 0; j < temp.getLines().size(); ++j) {
            List<Object> one = (List)temp.getLines().get(j);
            for(int i = 0; i < one.size(); ++i) {
                Object value = one.get(i);
                if (value instanceof Double) {
                    Double valueTemp = (Double)value;
                    DecimalFormat df = new DecimalFormat("######0");
                    return Integer.parseInt(df.format(valueTemp));
                }
            }
        }
        return 0;
    }
    /**
     * 使用curl方式执行 es-sql 查询操作
     * @param sql
     * @return
     */
    public List<JSONObject> execCurl(String sql){
        List<JSONObject> result = new ArrayList<>();
        curlCmds[5] = sql;
        ProcessBuilder process = new ProcessBuilder(curlCmds);
        Process p;
        StringBuilder builder = new StringBuilder();
        try {
            p = process.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }
        } catch (IOException e) {
            System.out.print("error");
            e.printStackTrace();
        }
        try {
            logger.info("request curlCmds:" + objectMapper.writeValueAsString(curlCmds));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String esResponse = builder.toString();
        logger.info("esResponse:" + esResponse);
        JSONObject esResObj = JSONObject.parseObject(esResponse);
        if(null != esResObj){
            if(null == (esResObj.get("error"))){
                if(esResObj.getJSONObject("_shards").getIntValue("total") > 0){
                    List resList = JSONObject.parseObject(esResponse).getJSONObject("hits").getJSONArray("hits");
                    if(!CollectionUtils.isEmpty(resList)){
                        resList.forEach(
                                one->{
                                    JSONObject oneHit = (JSONObject)one;
                                    result.add(oneHit.getJSONObject("_source"));
                                }
                        );
                    }
                }
            }
        }
        logger.info("execCurl result:"+result.toString());
        return result;
    }
}

+ 157 - 0
svr/svr-iot/src/main/java/com/yihu/elasticsearch/ElasticSearchPool.java

@ -0,0 +1,157 @@
package com.yihu.elasticsearch;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.ElasticSearchDruidDataSourceFactory;
import com.yihu.elasticsearch.config.ElasticSearchConfig;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.shield.ShieldPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
 * Pool - ES TransportClient 连接池
 * @author progr1mmer
 * @date Created on 2018/1/4.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ElasticSearchPool {
    private static JestClientFactory factory = null;
    private static volatile TransportClient transportClient;
    @Autowired
    private ElasticSearchConfig elasticSearchConfig;
    @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;
    @Value("${es.securityUser}")
    private String securityUser;
    @Value("${es.pwflag}")
    private String pwflag;
    @Value("${es.user}")
    private String user;
    @Value("${es.password}")
    private String password;
    /**
     * 1.TransportClient本身支持多线程的数据请求
     * 2.移除多个TransportClient的线程池支持,减少Socket链接
     * 3.基于多重检查的单例模式,兼顾安全和效率
     * 4.为提高效率,使用完毕后请勿进行 transportClient.close() 的关闭操作
     * @return
     */
    public TransportClient getClient() {
        try {
            //1需要加密初始化
            if("1".equals(pwflag)){
                initTranClientPw();
            }else {
                initTranClient();
            }
            return transportClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public JestClient getJestClient() {
        if (factory == null) {
            //初始化链接
            init();
        }
        return factory.getObject();
    }
    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)
                .defaultCredentials(user,password)
                .maxTotalConnection(50)// 最大链接
                .maxConnectionIdleTime(10, TimeUnit.MINUTES)//链接等待时间
                .connTimeout(60 * 1000*10)
                // .discoveryEnabled(true)
                .readTimeout(60 * 1000*10)//60秒
                .build();
        factory.setHttpClientConfig(httpClientConfig);//得到链接
    }
    private synchronized void initTranClientPw() throws Exception {
        if (transportClient == null) {
            String[] hosts = tHost.split(",");
            Settings settings = getSettings();
            transportClient = TransportClient.builder().addPlugin(ShieldPlugin.class).settings(settings).build();
            for (String oneHost : hosts) {
                String[] hostAndport = oneHost.split(":");
                transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAndport[0]), Integer.valueOf(hostAndport[1])));
            }
        }
    }
    /**
     * 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])));
            }
        }
    }
    private Settings getSettings() throws Exception {
        Settings.Builder settingBuilder = Settings.settingsBuilder();
        settingBuilder.put("cluster.name", clusterName);
        settingBuilder.put("shield.user", securityUser);
        settingBuilder.put("client.transport.sniff", false);
        settingBuilder.put("transport.address.list", tHost);
        return settingBuilder.build();
    }
    public DruidDataSource getDruidDataSource() throws Exception {
        Properties properties = new Properties();
        properties.put("url", "jdbc:elasticsearch://" + elasticSearchConfig.getClusterNodes() + "/");
        DruidDataSource druidDataSource = (DruidDataSource) ElasticSearchDruidDataSourceFactory
                .createDataSource(properties);
        druidDataSource.setInitialSize(1);
        return druidDataSource;
    }
}

+ 50 - 152
svr/svr-iot/src/main/java/com/yihu/iot/controller/common/FileUploadController.java

@ -1,179 +1,77 @@
/*package com.yihu.iot.controller.common;
package com.yihu.iot.controller.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.rm.iot.IotRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Base64;
*//**
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
 * 文件上传不在微服务中处理
 * @author yeshijie on 2017/12/7.
 *//*
 */
@RestController
@RequestMapping(IotRequestMapping.Common.file_upload)
@Api(tags = "文件上传相关操作", description = "文件上传相关操作")
public class FileUploadController extends EnvelopRestEndpoint {
    @Autowired
    private FastDFSUtil fastDFSHelper;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_stream_img)
    @ApiOperation(value = "文件流上传图片", notes = "文件流上传图片")
    public MixEnvelop<UploadVO, UploadVO> uploadImg(@ApiParam(value = "文件", required = true)
                                       @RequestParam(value = "file", required = true) MultipartFile file){
        try {
            // 得到文件的完整名称  xxx.txt
            String fullName = file.getOriginalFilename();
            if(StringUtils.isBlank(fullName)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            //得到文件类型
            String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
            if(StringUtils.isBlank(fileType)||!"jpg,jpeg,png".contains(fileType)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            long size = file.getSize();
            long max = 5*1024*1024;
            if(size>max){
                return MixEnvelop.getError("文件大小不超过5M",IotRequestMapping.api_iot_fail);
            }
            String fileName = fullName.substring(0, fullName.lastIndexOf("."));
            //上传到fastdfs
            ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
            //解析返回的objectNode
            UploadVO uploadVO = new UploadVO();
            uploadVO.setFileName(fileName);
            uploadVO.setFileType(fileType);
            uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
            uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_create, uploadVO);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/open/fileUpload")
    @ApiOperation("文件上传")
    public String handleFileUpload(@RequestParam("file") MultipartFile file
            ,@RequestParam("token") String token) {
        if (file.isEmpty()) {
            return "文件为空";
        }
    }
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_stream_attachment)
    @ApiOperation(value = "文件流上传附件", notes = "文件流上传附件")
    public MixEnvelop<UploadVO, UploadVO> uploadAttachment(@ApiParam(value = "文件", required = true)
                                       @RequestParam(value = "file", required = true) MultipartFile file){
        try {
            // 得到文件的完整名称  xxx.txt
            String fullName = file.getOriginalFilename();
            if(StringUtils.isBlank(fullName)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            //得到文件类型
            String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
            if(StringUtils.isBlank(fileType)||!"doc、docx、pdf、xls、xlsx、jpg、jpeg、png".contains(fileType)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            long size = file.getSize();
            long max = 5*1024*1024;
            if(size>max){
                return MixEnvelop.getError("文件大小不超过5M",IotRequestMapping.api_iot_fail);
            }
            String fileName = fullName.substring(0, fullName.lastIndexOf("."));
            //上传到fastdfs
            ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
            //解析返回的objectNode
            UploadVO uploadVO = new UploadVO();
            uploadVO.setFileName(fileName);
            uploadVO.setFileType(fileType);
            uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
            uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_create, uploadVO);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
        if(org.apache.commons.lang3.StringUtils.isBlank(token)){
            return "非法请求";
        }
        String sql = " select code from iot_system_dict where dict_name ='fileUpload_token'  ";
        List<String> urls = jdbcTemplate.queryForList(sql,String.class);
        if(urls.size()==0){
            return "非法请求";
        }
    }
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_stream)
    @ApiOperation(value = "文件流上传文件", notes = "文件流上传文件")
    public MixEnvelop<UploadVO, UploadVO> uploadStream(@ApiParam(value = "文件", required = true) @RequestParam(value = "file", required = true) MultipartFile file) {
        try {
            // 得到文件的完整名称  xxx.txt
            String fullName = file.getOriginalFilename();
            //得到文件类型
            String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
            String fileName = fullName.substring(0, fullName.lastIndexOf("."));
            //上传到fastdfs
            ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
            //解析返回的objectNode
            UploadVO uploadVO = new UploadVO();
            uploadVO.setFileName(fileName);
            uploadVO.setFileType(fileType);
            uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
            uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_create, uploadVO);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
        if(!token.equals(urls.get(0))){
            return "非法请求";
        }
    }
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_string)
    @ApiOperation(value = "base64上传图片",notes = "base64上传图片")
    public MixEnvelop<UploadVO, UploadVO> uploadImages(@ApiParam(name = "jsonData", value = "头像转化后的输入流") @RequestBody String jsonData) throws Exception {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为:" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为:" + suffixName);
        String filePath = "/data/";
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            if(jsonData == null){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_jsonData_is_null, ExceptionCode.common_error_params_code);
            }
            String date = URLDecoder.decode(jsonData,"UTF-8");
            String[] fileStreams = date.split(",");
            String is = URLDecoder.decode(fileStreams[1],"UTF-8").replace(" ","+");
            byte[] in = Base64.getDecoder().decode(is);
            String pictureName = fileStreams[0].substring(0,fileStreams[0].length()-1);
            String fileExtension = pictureName.substring(pictureName.lastIndexOf(".") + 1).toLowerCase();
            String description = null;
            if ((pictureName != null) && (pictureName.length() > 0)) {
                int dot = pictureName.lastIndexOf('.');
                if ((dot > -1) && (dot < (pictureName.length()))) {
                    description = pictureName.substring(0, dot);
                }
            }
            InputStream inputStream = new ByteArrayInputStream(in);
            ObjectNode objectNode = fastDFSHelper.upload(inputStream, "png", "");
            String groupName = objectNode.get("groupName").toString();
            String remoteFileName = objectNode.get("remoteFileName").toString();
            //解析返回的objectNode
            UploadVO uploadVO = new UploadVO();
            uploadVO.setFileName(remoteFileName);
            uploadVO.setFileType(groupName);
            uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
            uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            //返回文件路径
            return MixEnvelop.getSuccess(IotRequestMapping.FileUpload.message_success_upload, uploadVO);
        }catch (ApiException e){
            return MixEnvelop.getError(e.getMessage(), e.getErrorCode());
            file.transferTo(dest);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
}*/
}

+ 529 - 445
svr/svr-iot/src/main/java/com/yihu/iot/controller/monitorPlatform/MonitorPlatformController.java

@ -1,5 +1,6 @@
package com.yihu.iot.controller.monitorPlatform;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.iot.service.company.IotCompanyService;
@ -9,6 +10,7 @@ import com.yihu.iot.service.equipment.IotEqtDetailService;
import com.yihu.iot.service.monitorPlatform.CopdXeekDeviceService;
import com.yihu.iot.service.monitorPlatform.MonitorPlatformService;
import com.yihu.iot.service.product.IotProductBaseInfoService;
import com.yihu.jw.entity.care.message.BaseServiceNews;
import com.yihu.jw.entity.iot.device.IotPatientDeviceDO;
import com.yihu.jw.entity.iot.dict.IotSystemDictDO;
import com.yihu.jw.restmodel.iot.device.IotPatientDeviceVO;
@ -83,8 +85,8 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
            @RequestParam(value = "dictName", required = true) String dictName) throws Exception {
        try {
            List<IotSystemDictDO> doList = iotSystemDictService.getListByDictName(dictName);
            return MixEnvelop.getSuccessList(IotRequestMapping.Company.message_success_find_functions,doList);
        }catch (Exception e){
            return MixEnvelop.getSuccessList(IotRequestMapping.Company.message_success_find_functions, doList);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
@ -93,14 +95,14 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
    @GetMapping(value = IotRequestMapping.Product.findListByCategoryCode)
    @ApiOperation(value = "根据分类查找产品信息")
    public MixEnvelop<JSONObject, JSONObject> findListByCategoryCode(@ApiParam(name = "categoryCode", value = "分类code", defaultValue = "1")
                                                                     @RequestParam(value = "categoryCode", required = true)String categoryCode) {
                                                                     @RequestParam(value = "categoryCode", required = true) String categoryCode) {
        try {
            if(org.apache.commons.lang.StringUtils.isBlank(categoryCode)){
            if (org.apache.commons.lang.StringUtils.isBlank(categoryCode)) {
                return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, iotProductBaseInfoService.findListByCategoryCode());
            }else {
                return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, iotProductBaseInfoService.findListByCategoryCode("'"+categoryCode.replace(",","','")+"'"));
            } else {
                return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_find, iotProductBaseInfoService.findListByCategoryCode("'" + categoryCode.replace(",", "','") + "'"));
            }
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("操作失败");
        }
@ -114,335 +116,335 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
            @RequestParam(value = "parentCode", required = true) String parentCode) throws Exception {
        try {
            List<JSONObject> doList = null;
            if(StringUtils.isNoneBlank(parentCode)){
                doList = iotSystemDictService.getListByParentCode("'"+parentCode.replace(",","','")+"'");
            }else{
                doList= iotSystemDictService.getListByParentCode();
            if (StringUtils.isNoneBlank(parentCode)) {
                doList = iotSystemDictService.getListByParentCode("'" + parentCode.replace(",", "','") + "'");
            } else {
                doList = iotSystemDictService.getListByParentCode();
            }
            return MixEnvelop.getSuccessList(IotRequestMapping.Company.message_success_find_functions,doList);
        }catch (Exception e){
            return MixEnvelop.getSuccessList(IotRequestMapping.Company.message_success_find_functions, doList);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/areaDict",method = RequestMethod.GET)
    @RequestMapping(value = "/areaDict", method = RequestMethod.GET)
    @ApiOperation("地区字典")
    public MixEnvelop areaDict(){
    public MixEnvelop areaDict() {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.areaDict());
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.areaDict());
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/hospitalDict",method = RequestMethod.GET)
    @RequestMapping(value = "/hospitalDict", method = RequestMethod.GET)
    @ApiOperation("医院字典")
    public MixEnvelop hospitalDict(@ApiParam(name="town",value="地区",defaultValue = "")
                               @RequestParam(value="town",required = false) String town){
    public MixEnvelop hospitalDict(@ApiParam(name = "town", value = "地区", defaultValue = "")
                                   @RequestParam(value = "town", required = false) String town) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.hospitalDict(town));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.hospitalDict(town));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/smartDeviceDistribution",method = RequestMethod.GET)
    @RequestMapping(value = "/smartDeviceDistribution", method = RequestMethod.GET)
    @ApiOperation("智能设备发放")
    public MixEnvelop smartDeviceDistribution(@ApiParam(name="startTime",value="开始时间",defaultValue = "")
                                              @RequestParam(value="startTime",required = false) String startTime,
                                              @ApiParam(name="endTime",value="结束时间",defaultValue = "")
                                                  @RequestParam(value="endTime",required = false) String endTime,
                                              @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
                                                  @RequestParam(value="deviceType",required = false) String deviceType,
                                              @ApiParam(name="area",value="地区",defaultValue = "")
                                                  @RequestParam(value="area",required = false) String area,
                                              @ApiParam(name="hospital",value="机构",defaultValue = "")
                                                  @RequestParam(value="hospital",required = false) String hospital){
    public MixEnvelop smartDeviceDistribution(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
                                              @RequestParam(value = "startTime", required = false) String startTime,
                                              @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
                                              @RequestParam(value = "endTime", required = false) String endTime,
                                              @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
                                              @RequestParam(value = "deviceType", required = false) String deviceType,
                                              @ApiParam(name = "area", value = "地区", defaultValue = "")
                                              @RequestParam(value = "area", required = false) String area,
                                              @ApiParam(name = "hospital", value = "机构", defaultValue = "")
                                              @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.smartDeviceDistribution(startTime,endTime,deviceType,area,hospital));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.smartDeviceDistribution(startTime, endTime, deviceType, area, hospital));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/datafiltering",method = RequestMethod.GET)
    @RequestMapping(value = "/datafiltering", method = RequestMethod.GET)
    @ApiOperation("数据筛选")
    public MixEnvelop datafiltering(@ApiParam(name="name",value="设备sn码或居民姓名")
                                @RequestParam(value="name",required = false) String name){
    public MixEnvelop datafiltering(@ApiParam(name = "name", value = "设备sn码或居民姓名")
                                    @RequestParam(value = "name", required = false) String name) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.datafiltering(name));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.datafiltering(name));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/deviceUsageAnalysis",method = RequestMethod.GET)
    @RequestMapping(value = "/deviceUsageAnalysis", method = RequestMethod.GET)
    @ApiOperation("设备使用情况分析")
    public MixEnvelop deviceUsageAnalysis(@ApiParam(name="type",value="设备类型")
                                              @RequestParam(value="type",required = false) String type,
                                          @ApiParam(name="name",value="产品名称")
                                              @RequestParam(value="name",required = false) String name){
    public MixEnvelop deviceUsageAnalysis(@ApiParam(name = "type", value = "设备类型")
                                          @RequestParam(value = "type", required = false) String type,
                                          @ApiParam(name = "name", value = "产品名称")
                                          @RequestParam(value = "name", required = false) String name) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.deviceUsageAnalysis(type,name));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.deviceUsageAnalysis(type, name));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/warningInformationAlarm_new",method = RequestMethod.GET)
    @RequestMapping(value = "/warningInformationAlarm_new", method = RequestMethod.GET)
    @ApiOperation("预警信息警报")
    public MixEnvelop warningInformationAlarm_new(
            @ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
            @RequestParam(value="page",required = false) Integer page,
            @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
            @RequestParam(value="pageSize",required = false) Integer pageSize,
            @ApiParam(name="startTime",value="开始时间",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
            @RequestParam(value="deviceType",required = false) String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital,
            @ApiParam(name="deviceName",value = "设备名称(品牌)",required = false)
            @RequestParam(value = "deviceName",required = false,defaultValue = "")String deviceName){
            @ApiParam(name = "page", value = "第几页(默认第一页)", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize", value = "每页几行(默认10条记录)", defaultValue = "10")
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(name = "deviceName", value = "设备名称(品牌)", required = false)
            @RequestParam(value = "deviceName", required = false, defaultValue = "") String deviceName) {
        try {
            if(page==null){
            if (page == null) {
                page = 1;
            }
            if(pageSize==null){
            if (pageSize == null) {
                pageSize = 20;
            }
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.warningInformationAlarm_new(page,pageSize,startTime,endTime,deviceType,area,hospital,monitorPlatformService.getDeviceNameByRequestParam(deviceName)));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.warningInformationAlarm_new(page, pageSize, startTime, endTime, deviceType, area, hospital, monitorPlatformService.getDeviceNameByRequestParam(deviceName)));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/yellowAndRedRange",method = RequestMethod.GET)
    @RequestMapping(value = "/yellowAndRedRange", method = RequestMethod.GET)
    @ApiOperation("红标黄标率")
    public MixEnvelop yellowAndRedRange(
            @ApiParam(name="startTime",value="开始时间",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
            @RequestParam(value="deviceType",required = false) String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital){
            @ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.yellowAndRedRange(startTime,endTime,deviceType,area,hospital));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.yellowAndRedRange(startTime, endTime, deviceType, area, hospital));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/deviceUseData",method = RequestMethod.GET)
    @RequestMapping(value = "/deviceUseData", method = RequestMethod.GET)
    @ApiOperation("设备使用数据")
    public MixEnvelop deviceUseData(@ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
                                @RequestParam(value="page",required = false) Integer page,
                                @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
                                @RequestParam(value="pageSize",required = false) Integer pageSize,
                                @ApiParam(name="deviceSn",value="开始时间",defaultValue = "")
                                @RequestParam(value="deviceSn",required = false) String deviceSn){
    public MixEnvelop deviceUseData(@ApiParam(name = "page", value = "第几页(默认第一页)", defaultValue = "1")
                                    @RequestParam(value = "page", required = false) Integer page,
                                    @ApiParam(name = "pageSize", value = "每页几行(默认10条记录)", defaultValue = "10")
                                    @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                    @ApiParam(name = "deviceSn", value = "开始时间", defaultValue = "")
                                    @RequestParam(value = "deviceSn", required = false) String deviceSn) {
        try {
            if(page==null){
            if (page == null) {
                page = 1;
            }
            if(pageSize==null){
            if (pageSize == null) {
                pageSize = 10;
            }
            JSONObject jsonObject = monitorPlatformService.deviceUseData(page,pageSize,deviceSn);
            return MixEnvelop.getSuccess("查询成功",jsonObject.getJSONArray("list"),jsonObject.getInteger("total"));
        }catch (Exception e){
            JSONObject jsonObject = monitorPlatformService.deviceUseData(page, pageSize, deviceSn);
            return MixEnvelop.getSuccess("查询成功", jsonObject.getJSONArray("list"), jsonObject.getInteger("total"));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/deviceInfo",method = RequestMethod.GET)
    @RequestMapping(value = "/deviceInfo", method = RequestMethod.GET)
    @ApiOperation("设备信息")
    public MixEnvelop deviceInfo(@ApiParam(name="deviceSn",value="设备sn码")
                             @RequestParam(value="deviceSn",required = true) String deviceSn,
                             @ApiParam(name="patient",value="居民code")
                             @RequestParam(value="patient",required = true) String patient){
    public MixEnvelop deviceInfo(@ApiParam(name = "deviceSn", value = "设备sn码")
                                 @RequestParam(value = "deviceSn", required = true) String deviceSn,
                                 @ApiParam(name = "patient", value = "居民code")
                                 @RequestParam(value = "patient", required = true) String patient) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.deviceInfo(deviceSn,patient));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.deviceInfo(deviceSn, patient));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/deviceOverhaulList",method = RequestMethod.GET)
    @RequestMapping(value = "/deviceOverhaulList", method = RequestMethod.GET)
    @ApiOperation("质控情况")
    public MixEnvelop deviceOverhaulList(@ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
                                     @RequestParam(value="page",required = false) Integer page,
                                 @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
                                     @RequestParam(value="pageSize",required = false) Integer pageSize,
                                 @ApiParam(name="deviceSn",value="开始时间",defaultValue = "")
                                     @RequestParam(value="deviceSn",required = true) String deviceSn){
    public MixEnvelop deviceOverhaulList(@ApiParam(name = "page", value = "第几页(默认第一页)", defaultValue = "1")
                                         @RequestParam(value = "page", required = false) Integer page,
                                         @ApiParam(name = "pageSize", value = "每页几行(默认10条记录)", defaultValue = "10")
                                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                         @ApiParam(name = "deviceSn", value = "开始时间", defaultValue = "")
                                         @RequestParam(value = "deviceSn", required = true) String deviceSn) {
        try {
            if(page==null){
            if (page == null) {
                page = 1;
            }
            if(pageSize==null){
            if (pageSize == null) {
                pageSize = 10;
            }
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.deviceOverhaulList(page,pageSize,deviceSn),monitorPlatformService.deviceOverhaulListTotal(deviceSn));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.deviceOverhaulList(page, pageSize, deviceSn), monitorPlatformService.deviceOverhaulListTotal(deviceSn));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/residentUserType",method = RequestMethod.GET)
    @RequestMapping(value = "/residentUserType", method = RequestMethod.GET)
    @ApiOperation("入住情况")
    public MixEnvelop residentUserType(){
    public MixEnvelop residentUserType() {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.residentUserType());
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.residentUserType());
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/intefaceLogList",method = RequestMethod.GET)
    @RequestMapping(value = "/intefaceLogList", method = RequestMethod.GET)
    @ApiOperation("接口调用情况")
    public MixEnvelop intefaceLogList(@ApiParam(name="startTime",value="开始时间",defaultValue = "2019-01-01")
                                         @RequestParam(value="startTime",required = false) String startTime,
                                         @ApiParam(name="endTime",value="结束时间",defaultValue = "2020-06-01")
                                         @RequestParam(value="endTime",required = false) String endTime,
                                         @ApiParam(name="type",value="统计类型",defaultValue = "month")
                                         @RequestParam(value="type",required = true) String type){
    public MixEnvelop intefaceLogList(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "2019-01-01")
                                      @RequestParam(value = "startTime", required = false) String startTime,
                                      @ApiParam(name = "endTime", value = "结束时间", defaultValue = "2020-06-01")
                                      @RequestParam(value = "endTime", required = false) String endTime,
                                      @ApiParam(name = "type", value = "统计类型", defaultValue = "month")
                                      @RequestParam(value = "type", required = true) String type) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.intefaceLogList(startTime,endTime,type));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.intefaceLogList(startTime, endTime, type));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/totalRange",method = RequestMethod.GET)
    @RequestMapping(value = "/totalRange", method = RequestMethod.GET)
    @ApiOperation("85-发放率,96使用率,86绑定率,88指导率")
    public MixEnvelop totalRange(
            @ApiParam(name="startTime",value="开始时间",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
            @RequestParam(value="deviceType",required = false) String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital,
            @ApiParam(name="quotaCode",value="85-发放率,96使用率,86绑定率,88指导率",defaultValue = "")
            @RequestParam(value="quotaCode",required = true) String quotaCode){
            @ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(name = "quotaCode", value = "85-发放率,96使用率,86绑定率,88指导率", defaultValue = "")
            @RequestParam(value = "quotaCode", required = true) String quotaCode) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.totalRange(startTime,endTime,deviceType,area,hospital,quotaCode));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.totalRange(startTime, endTime, deviceType, area, hospital, quotaCode));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value="getTotalRange",method = RequestMethod.GET)
    @RequestMapping(value = "getTotalRange", method = RequestMethod.GET)
    @ApiOperation("96使用率,86绑定率,88指导率,慢病患者设备使用率,慢病患者设备覆盖率整合")
    public MixEnvelop getTotalRange(@ApiParam(name="startTime",value="开始时间yyyy-MM-dd",defaultValue = "")
                                        @RequestParam(value="startTime",required = false) String startTime,
                                    @ApiParam(name="endTime",value="结束时间",defaultValue = "")
                                        @RequestParam(value="endTime",required = false) String endTime,
                                    @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
                                        @RequestParam(value="deviceType",required = false) String deviceType,
                                    @ApiParam(name="area",value="地区",defaultValue = "")
                                        @RequestParam(value="area",required = false) String area,
                                    @ApiParam(name="hospital",value="机构",defaultValue = "")
                                        @RequestParam(value="hospital",required = false) String hospital){
    public MixEnvelop getTotalRange(@ApiParam(name = "startTime", value = "开始时间yyyy-MM-dd", defaultValue = "")
                                    @RequestParam(value = "startTime", required = false) String startTime,
                                    @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
                                    @RequestParam(value = "endTime", required = false) String endTime,
                                    @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
                                    @RequestParam(value = "deviceType", required = false) String deviceType,
                                    @ApiParam(name = "area", value = "地区", defaultValue = "")
                                    @RequestParam(value = "area", required = false) String area,
                                    @ApiParam(name = "hospital", value = "机构", defaultValue = "")
                                    @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.getTotalRange(startTime,endTime,deviceType,area,hospital));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.getTotalRange(startTime, endTime, deviceType, area, hospital));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/diseaseUseRange",method = RequestMethod.GET)
    @RequestMapping(value = "/diseaseUseRange", method = RequestMethod.GET)
    @ApiOperation("慢病患者设备使用率")
    public MixEnvelop diseaseUseRange(
            @ApiParam(name="startTime",value="开始时间",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
            @RequestParam(value="deviceType",required = false) String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital){
            @ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.diseaseUseRange(startTime,endTime,deviceType,area,hospital));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.diseaseUseRange(startTime, endTime, deviceType, area, hospital));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/diseaseRange",method = RequestMethod.GET)
    @RequestMapping(value = "/diseaseRange", method = RequestMethod.GET)
    @ApiOperation("慢病患者设备覆盖率")
    public MixEnvelop diseaseRange(
            @ApiParam(name="startTime",value="开始时间",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
            @RequestParam(value="deviceType",required = false) String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital){
            @ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.diseaseRange(startTime,endTime,deviceType,area,hospital));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.diseaseRange(startTime, endTime, deviceType, area, hospital));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/yellowOrRedRange",method = RequestMethod.GET)
    @RequestMapping(value = "/yellowOrRedRange", method = RequestMethod.GET)
    @ApiOperation("红标黄标率")
    public MixEnvelop yellowOrRedRange(
            @ApiParam(name="startTime",value="开始时间",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
            @RequestParam(value="deviceType",required = false) String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital,
            @ApiParam(name="diseaseCondition",value="红黄标 黄1,红2",defaultValue = "1")
            @RequestParam(value="diseaseCondition",required = true) Integer diseaseCondition){
            @ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
            @RequestParam(value = "deviceType", required = false) String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(name = "diseaseCondition", value = "红黄标 黄1,红2", defaultValue = "1")
            @RequestParam(value = "diseaseCondition", required = true) Integer diseaseCondition) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.yellowOrRedRange(startTime,endTime,deviceType,area,hospital,diseaseCondition));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.yellowOrRedRange(startTime, endTime, deviceType, area, hospital, diseaseCondition));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
@ -450,23 +452,23 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
    /*****************************************************************************************************/
    @RequestMapping(value = "/equipmentDistribution",method = RequestMethod.GET)
    @RequestMapping(value = "/equipmentDistribution", method = RequestMethod.GET)
    @ApiOperation("设备发放情况")
    public String equipmentDistribution(@ApiParam(name="startTime",value="开始时间",defaultValue = "")
                                            @RequestParam(value="startTime",required = false) String startTime,
                                        @ApiParam(name="endTime",value="结束时间",defaultValue = "")
                                            @RequestParam(value="endTime",required = false) String endTime,
                                        @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
                                            @RequestParam(value="deviceType",required = false) String deviceType,
                                        @ApiParam(name="area",value="地区",defaultValue = "")
                                            @RequestParam(value="area",required = false) String area,
                                        @ApiParam(name="hospital",value="机构",defaultValue = "")
                                            @RequestParam(value="hospital",required = false) String hospital){
    public String equipmentDistribution(@ApiParam(name = "startTime", value = "开始时间", defaultValue = "")
                                        @RequestParam(value = "startTime", required = false) String startTime,
                                        @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
                                        @RequestParam(value = "endTime", required = false) String endTime,
                                        @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
                                        @RequestParam(value = "deviceType", required = false) String deviceType,
                                        @ApiParam(name = "area", value = "地区", defaultValue = "")
                                        @RequestParam(value = "area", required = false) String area,
                                        @ApiParam(name = "hospital", value = "机构", defaultValue = "")
                                        @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return monitorPlatformService.equipmentDistribution(startTime,endTime,deviceType, area, hospital);
        }catch (Exception e){
            return monitorPlatformService.equipmentDistribution(startTime, endTime, deviceType, area, hospital);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
@ -474,191 +476,190 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
    @ApiOperation(value = "根据idCard查询设备地址", notes = "根据idCard查询设备地址")
    public MixEnvelop<LocationDataVO, LocationDataVO> findDeviceLocationsByIdCard(
            @ApiParam(name = "diseaseCondition", value = "病情:0绿标,1黄标,2红标,-1没有标注的居民", defaultValue = "")
            @RequestParam(value = "diseaseCondition",required = false) Integer diseaseCondition,
            @RequestParam(value = "diseaseCondition", required = false) Integer diseaseCondition,
            @ApiParam(name = "type", value = "1高血压 2糖尿病", defaultValue = "")
            @RequestParam(value = "type",required = false) String type,
            @ApiParam(name="deviceType",value="设备类型 对应设备字典库的DEVICE_TYPE值",required = true)
            @RequestParam(value="deviceType",required = true) String deviceType,
            @ApiParam(name="deviceName",value = "设备名称(品牌)",required = false)
            @RequestParam(value = "deviceName",required = false,defaultValue = " ")String deviceName,
            @ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
            @RequestParam(value="page",required = false) Integer page,
            @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
            @RequestParam(value="pageSize",required = false) Integer pageSize) {
            @RequestParam(value = "type", required = false) String type,
            @ApiParam(name = "deviceType", value = "设备类型 对应设备字典库的DEVICE_TYPE值", required = true)
            @RequestParam(value = "deviceType", required = true) String deviceType,
            @ApiParam(name = "deviceName", value = "设备名称(品牌)", required = false)
            @RequestParam(value = "deviceName", required = false, defaultValue = " ") String deviceName,
            @ApiParam(name = "page", value = "第几页(默认第一页)", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize", value = "每页几行(默认10条记录)", defaultValue = "10")
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        try {
            if(page==null){
            if (page == null) {
                page = 1;
            }
            if(pageSize==null){
            if (pageSize == null) {
                pageSize = 10;
            }
            return monitorPlatformService.findDeviceLocations(diseaseCondition,page,pageSize,type,deviceType,monitorPlatformService.getDeviceNameByRequestParam(deviceName));
            return monitorPlatformService.findDeviceLocations(diseaseCondition, page, pageSize, type, deviceType, monitorPlatformService.getDeviceNameByRequestParam(deviceName));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("操作失败");
        }
    }
    @RequestMapping(value = "/chronicDiseaseCount",method = RequestMethod.GET)
    @RequestMapping(value = "/chronicDiseaseCount", method = RequestMethod.GET)
    @ApiOperation("慢病患者情况-统计")
    public String chronicDiseaseCount(
            @ApiParam(name="type",value="类型(2糖尿病,1高血压)",defaultValue = "")
            @RequestParam(value="type",required = false) String type){
            @ApiParam(name = "type", value = "类型(2糖尿病,1高血压)", defaultValue = "")
            @RequestParam(value = "type", required = false) String type) {
        try {
            return monitorPlatformService.chronicDiseaseCount(type);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/searchPatient",method = RequestMethod.GET)
    @RequestMapping(value = "/searchPatient", method = RequestMethod.GET)
    @ApiOperation("居民 医生搜索")
    public String searchPatient(
            @ApiParam(name="name",value="姓名")
            @RequestParam(value="name",required = false) String name,
            @ApiParam(name="idcards",value="身份证(多个用逗号间隔)")
            @RequestParam(value="idcards",required = false) String idcards,
            @ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
            @RequestParam(value="page",required = false) Integer page,
            @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
            @RequestParam(value="pageSize",required = false) Integer pageSize){
            @ApiParam(name = "name", value = "姓名")
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "idcards", value = "身份证(多个用逗号间隔)")
            @RequestParam(value = "idcards", required = false) String idcards,
            @ApiParam(name = "page", value = "第几页(默认第一页)", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize", value = "每页几行(默认10条记录)", defaultValue = "10")
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        try {
            if(page==null){
            if (page == null) {
                page = 1;
            }
            if(pageSize==null){
            if (pageSize == null) {
                pageSize = 10;
            }
            return monitorPlatformService.searchPatient(name,page,pageSize,idcards);
        }catch (Exception e){
            return monitorPlatformService.searchPatient(name, page, pageSize, idcards);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/warningInformationAlarm",method = RequestMethod.GET)
    @RequestMapping(value = "/warningInformationAlarm", method = RequestMethod.GET)
    @ApiOperation("预警信息警报")
    public String warningInformationAlarm(
            @ApiParam(name="page",value="第几页(默认第一页)",defaultValue = "1")
            @RequestParam(value="page",required = false) Integer page,
            @ApiParam(name="pageSize",value="每页几行(默认10条记录)",defaultValue = "10")
            @RequestParam(value="pageSize",required = false) Integer pageSize){
            @ApiParam(name = "page", value = "第几页(默认第一页)", defaultValue = "1")
            @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(name = "pageSize", value = "每页几行(默认10条记录)", defaultValue = "10")
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        try {
            if(page==null){
            if (page == null) {
                page = 1;
            }
            if(pageSize==null){
            if (pageSize == null) {
                pageSize = 10;
            }
            return monitorPlatformService.warningInformationAlarm(page,pageSize);
        }catch (Exception e){
            return monitorPlatformService.warningInformationAlarm(page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/deviceBinding",method = RequestMethod.GET)
    @RequestMapping(value = "/deviceBinding", method = RequestMethod.GET)
    @ApiOperation("设备绑定情况")
    public String deviceBinding(
            @ApiParam(name="type",value="设备类型(1血糖仪,2血压计)",defaultValue = "")
            @RequestParam(value="type",required = false) String type){
            @ApiParam(name = "type", value = "设备类型(1血糖仪,2血压计)", defaultValue = "")
            @RequestParam(value = "type", required = false) String type) {
        try {
            return monitorPlatformService.deviceBinding(type);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/persionalInfo",method = RequestMethod.GET)
    @RequestMapping(value = "/persionalInfo", method = RequestMethod.GET)
    @ApiOperation("个人信息")
    public String persionalInfo(@ApiParam(name="patient",value="居民code",defaultValue = "")
                                @RequestParam(value="patient",required = true) String patient){
    public String persionalInfo(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                @RequestParam(value = "patient", required = true) String patient) {
        try {
            return monitorPlatformService.persionalInfo(patient);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/familyMember",method = RequestMethod.GET)
    @RequestMapping(value = "/familyMember", method = RequestMethod.GET)
    @ApiOperation("家人信息")
    public String familyMember(@ApiParam(name="patient",value="居民code",defaultValue = "")
                               @RequestParam(value="patient",required = true) String patient){
    public String familyMember(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                               @RequestParam(value = "patient", required = true) String patient) {
        try {
            return monitorPlatformService.familyMember(patient);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/healthDevice",method = RequestMethod.GET)
    @RequestMapping(value = "/healthDevice", method = RequestMethod.GET)
    @ApiOperation("健康设备")
    public String healthDevice(@ApiParam(name="patient",value="居民code",defaultValue = "")
                               @RequestParam(value="patient",required = true) String patient){
    public String healthDevice(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                               @RequestParam(value = "patient", required = true) String patient) {
        try {
            return monitorPlatformService.healthDevice(patient);
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "chart", method = RequestMethod.GET)
    @ApiOperation("根据患者标志获取健康指标(图表)")
    public String getHealthIndexChartByPatient(@ApiParam(name="patient",value="居民code",defaultValue = "")
                                               @RequestParam(value="patient",required = true) String patient,
    public String getHealthIndexChartByPatient(@ApiParam(name = "patient", value = "居民code", defaultValue = "")
                                               @RequestParam(value = "patient", required = true) String patient,
                                               @ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重,4腰围)", defaultValue = "1")
                                               @RequestParam(value = "type", required = true) Integer type,
                                               @ApiParam(name = "gi_type", value = "就餐类型0全部", defaultValue = "1")
                                               @RequestParam(value = "gi_type", required = false) Integer gi_type,
                                               @ApiParam(name="time",value="时间(一周,一月,半年)",defaultValue = "")
                                               @RequestParam(value="time",required = true) String time,
                                               @ApiParam(name = "time", value = "时间(一周,一月,半年)", defaultValue = "")
                                               @RequestParam(value = "time", required = true) String time,
                                               @ApiParam(name = "begin", value = "开始时间", defaultValue = "2017-05-22")
                                               @RequestParam(value = "begin", required = true) String begin,
                                               @ApiParam(name = "end", value = "结束时间", defaultValue = "2018-06-02")
                                               @RequestParam(value = "end", required = true) String end) {
        try {
            return monitorPlatformService.getHealthIndexChartByPatient(patient,type,gi_type,begin,end,time);
            return monitorPlatformService.getHealthIndexChartByPatient(patient, type, gi_type, begin, end, time);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "getXeekDeviceData",method = RequestMethod.GET)
    @RequestMapping(value = "getXeekDeviceData", method = RequestMethod.GET)
    @ApiOperation(value = "塞克设备数据获取")
    public ObjEnvelop getXeekDeviceData(@ApiParam(name="deviceSN",value = "设备sn码")
                                    @RequestParam(value = "deviceSN",required = false)String deviceSN,
                                    @ApiParam(name="reportType",value = "测试项目 1=吸气测试;2=呼气测试;6=MVV 测试;7=慢通气测试")
                                    @RequestParam(value = "reportType",required = false)String reportType,
                                    @ApiParam(name="patient",value = "patient")
                                    @RequestParam(value = "patient",required = false)String patient,
                                    @ApiParam(name="parameter",value = "数据指标 inCount,outCount")
                                    @RequestParam(value = "parameter",required = false)String parameter,
                                    @ApiParam(name="time",value = "7 30 90")
                                    @RequestParam(value = "time",required = false)String time,
                                    @ApiParam(name="begin",value = "开始时间 YYYY-MM-DD HH:MM:SS" ,defaultValue = "2021-04-14 00:00:00")
                                    @RequestParam(value = "begin")String begin,
                                    @ApiParam(name="end",value = "结束时间 YYYY-MM-DD HH:MM:SS" ,defaultValue = "2021-04-14 23:59:59" )
                                    @RequestParam(value = "end")String end)
    {
        if (StringUtils.isBlank(patient)&&StringUtils.isBlank(deviceSN)){
    public ObjEnvelop getXeekDeviceData(@ApiParam(name = "deviceSN", value = "设备sn码")
                                        @RequestParam(value = "deviceSN", required = false) String deviceSN,
                                        @ApiParam(name = "reportType", value = "测试项目 1=吸气测试;2=呼气测试;6=MVV 测试;7=慢通气测试")
                                        @RequestParam(value = "reportType", required = false) String reportType,
                                        @ApiParam(name = "patient", value = "patient")
                                        @RequestParam(value = "patient", required = false) String patient,
                                        @ApiParam(name = "parameter", value = "数据指标 inCount,outCount")
                                        @RequestParam(value = "parameter", required = false) String parameter,
                                        @ApiParam(name = "time", value = "7 30 90")
                                        @RequestParam(value = "time", required = false) String time,
                                        @ApiParam(name = "begin", value = "开始时间 YYYY-MM-DD HH:MM:SS", defaultValue = "2021-04-14 00:00:00")
                                        @RequestParam(value = "begin") String begin,
                                        @ApiParam(name = "end", value = "结束时间 YYYY-MM-DD HH:MM:SS", defaultValue = "2021-04-14 23:59:59")
                                        @RequestParam(value = "end") String end) {
        if (StringUtils.isBlank(patient) && StringUtils.isBlank(deviceSN)) {
            return ObjEnvelop.getError("参数错误");
        }
        try {
            return ObjEnvelop.getSuccess("查询成功",copdXeekDeviceService.getDeviceData(patient,deviceSN,reportType,parameter,time,begin,end));
        }catch (Exception e){
            return ObjEnvelop.getSuccess("查询成功", copdXeekDeviceService.getDeviceData(patient, deviceSN, reportType, parameter, time, begin, end));
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("查询失败"+e.getMessage());
            return ObjEnvelop.getError("查询失败" + e.getMessage());
        }
    }
@ -676,58 +677,59 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
            return monitorPlatformService.getAllEvent(patient, type, page, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    /**
     * 根据患者标志获取健康指标
     *
     * @param idcard 患者指标
     * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param type   健康指标类型(1血糖,2血压,3体重,4腰围)
     * @return 操作结果
     */
    @RequestMapping(value = "health_index/listByIdcard",method = RequestMethod.POST)
    @RequestMapping(value = "health_index/listByIdcard", method = RequestMethod.POST)
    @ApiOperation("根据患者标志获取健康指标")
    public String getHealthIndexByIdcard(@ApiParam(name="idcard",value="居民身份证",defaultValue = "P20160901001")
                                         @RequestParam(value="idcard",required = true) String idcard,
                                         @ApiParam(name="type",value="指标类型",defaultValue = "1")
                                         @RequestParam(value="type",required = true) int type,
                                         @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
                                         @RequestParam(value="begin",required = true) String begin,
                                         @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
                                         @RequestParam(value="end",required = true) String end,
                                         @ApiParam(name="page",value="第几页",defaultValue = "1")
                                         @RequestParam(value="page",required = true) int page,
                                         @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
                                         @RequestParam(value="pagesize",required = true) int pagesize,HttpServletRequest request) {
    public String getHealthIndexByIdcard(@ApiParam(name = "idcard", value = "居民身份证", defaultValue = "P20160901001")
                                         @RequestParam(value = "idcard", required = true) String idcard,
                                         @ApiParam(name = "type", value = "指标类型", defaultValue = "1")
                                         @RequestParam(value = "type", required = true) int type,
                                         @ApiParam(name = "begin", value = "开始时间", defaultValue = "2016-07-23 00:00:00")
                                         @RequestParam(value = "begin", required = true) String begin,
                                         @ApiParam(name = "end", value = "开始时间", defaultValue = "2016-08-23 00:00:00")
                                         @RequestParam(value = "end", required = true) String end,
                                         @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                         @RequestParam(value = "page", required = true) int page,
                                         @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                         @RequestParam(value = "pagesize", required = true) int pagesize, HttpServletRequest request) {
        try {
            return monitorPlatformService.getHealthIndexByIdcard(idcard, type, begin, end, page, pagesize,request);
            return monitorPlatformService.getHealthIndexByIdcard(idcard, type, begin, end, page, pagesize, request);
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    /**
     * 获取居民信息
     */
    @RequestMapping(value = "patientInfo",method = RequestMethod.GET)
    @RequestMapping(value = "patientInfo", method = RequestMethod.GET)
    @ApiOperation("获取居民信息")
    public String patientInfo(@ApiParam(name="idcard",value="居民身份证",defaultValue = "P20160901001")
                              @RequestParam(value="idcard",required = true) String idcard) {
    public String patientInfo(@ApiParam(name = "idcard", value = "居民身份证", defaultValue = "P20160901001")
                              @RequestParam(value = "idcard", required = true) String idcard) {
        try {
            return monitorPlatformService.patientInfo(idcard);
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1,"查询失败");
            return error(-1, "查询失败");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param code 结果码,成功为200
     * @param msg  结果提示信息
     * @return
     */
    public String error(int code, String msg) {
@ -748,69 +750,71 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
    @ApiOperation(value = "查询设备和数量")
    public Envelop getCountAndEquipment(
            @ApiParam(name = "startTime", value = "startTime", required = false)
            @RequestParam(value = "startTime", required = false)String startTime,
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "endTime", required = false)
            @RequestParam(value = "endTime", required = false)String endTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "area", value = "area", required = false)
            @RequestParam(value = "area", required = false)String area) throws Exception{
        JSONObject jsonObject =iotEqtDetailService.showJKXW(startTime,endTime,area);
            @RequestParam(value = "area", required = false) String area) throws Exception {
        JSONObject jsonObject = iotEqtDetailService.showJKXW(startTime, endTime, area);
        return success(jsonObject);
    }
    @GetMapping(value = IotRequestMapping.Common.getHospital)
    @ApiOperation(value = "查询医院")
    public Envelop getHospital(
            @ApiParam(name = "name", value = "name", required = false)
            @RequestParam(value = "name", required = false)String name,
            @RequestParam(value = "name", required = false) String name,
            @ApiParam(name = "code", value = "code", required = false)
            @RequestParam(value = "code", required = false)String code,
            @RequestParam(value = "code", required = false) String code,
            @ApiParam(name = "town", value = "town", required = false)
            @RequestParam(value = "town", required = false)String town,
            @RequestParam(value = "town", required = false) String town,
            @ApiParam(name = "city", value = "city", required = false)
            @RequestParam(value = "city", required = false)String city) throws Exception{
            @RequestParam(value = "city", required = false) String city) throws Exception {
        return success( iotEqtDetailService.getHosptital(name, code, town,city));
        return success(iotEqtDetailService.getHosptital(name, code, town, city));
    }
    @GetMapping(value = IotRequestMapping.Common.getNameAndCode)
    @ApiOperation(value = "查询idcard")
    public Envelop getByIdCard(
            @ApiParam(name = "idCard", value = "idCard", required = false)
            @RequestParam(value = "idCard", required = false)String idCard,
            @RequestParam(value = "idCard", required = false) String idCard,
            @ApiParam(name = "snCode", value = "snCode", required = false)
            @RequestParam(value = "snCode", required = false)String snCode) throws Exception{
            @RequestParam(value = "snCode", required = false) String snCode) throws Exception {
        return success( iotPatientDeviceService.getNameAndCode(idCard,snCode));
        return success(iotPatientDeviceService.getNameAndCode(idCard, snCode));
    }
    @GetMapping(value="/getEquipmentDetail")
    @GetMapping(value = "/getEquipmentDetail")
    @ApiOperation("健康小屋详情")
    public Envelop getEquipmentDetail(@RequestParam(value = "deviceSn",required = true)
                             @ApiParam(name="deviceSn",value ="设备SN码",required = true)String deviceSn){
    public Envelop getEquipmentDetail(@RequestParam(value = "deviceSn", required = true)
                                      @ApiParam(name = "deviceSn", value = "设备SN码", required = true) String deviceSn) {
        return success(monitorPlatformService.getEquipmentDetail(deviceSn));
    }
    @GetMapping(value ="/getBrandsAndManufacturer")
    @GetMapping(value = "/getBrandsAndManufacturer")
    @ApiOperation("设备品牌以及商家")
    public Envelop getBrandsAndManufacturer(){
    public Envelop getBrandsAndManufacturer() {
        return success(monitorPlatformService.getBrandsAndManufacturer());
    }
    @GetMapping(value="/getEquipmentStatistics")
    @GetMapping(value = "/getEquipmentStatistics")
    @ApiOperation("设备库存、使用数、总备案、失联率、物联率")
    public Envelop getEquipmentStatistics(@RequestParam(value = "deviceType",required = true,defaultValue = "1,2,5")
                                          @ApiParam(name="deviceType",value = "设备类型,1血糖仪,2血压计,5健康小屋",required = true) String deviceType,
                                          @RequestParam(value="deviceName",required = false,defaultValue = "")
                                          @ApiParam(name="deviceName",value = "设备名称(品牌)",required = false) String deviceName,
                                          @RequestParam(value = "showLevel",defaultValue = "0")
                                          @ApiParam(name="showLevel",value ="下转层次,默认0设备大类,1设备类型,2设备品牌") String showLevel){
    public Envelop getEquipmentStatistics(@RequestParam(value = "deviceType", required = true, defaultValue = "1,2,5,22")
                                          @ApiParam(name = "deviceType", value = "设备类型,1血糖仪,2血压计,5健康小屋,22智慧药房", required = true) String deviceType,
                                          @RequestParam(value = "deviceName", required = false, defaultValue = "")
                                          @ApiParam(name = "deviceName", value = "设备名称(品牌)", required = false) String deviceName,
                                          @RequestParam(value = "showLevel", defaultValue = "0")
                                          @ApiParam(name = "showLevel", value = "下转层次,默认0设备大类,1设备类型,2设备品牌") String showLevel) {
        return success(monitorPlatformService.getEquipmentStatistics(deviceType, monitorPlatformService.getDeviceNameByRequestParam(deviceName), showLevel));
    }
    @ApiOperation("大屏应用服务")
    @RequestMapping(value = "/getAppService" , method = RequestMethod.GET)
    @RequestMapping(value = "/getAppService", method = RequestMethod.GET)
    public Envelop getAppService() {
        try {
            return success(iotCompanyService.getAppService());
@ -821,8 +825,8 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
    }
    @ApiOperation("获取设备大类")
    @GetMapping(value ="/getDeviceTotalCategory")
    public Envelop getDeviceTotalCategory(){
    @GetMapping(value = "/getDeviceTotalCategory")
    public Envelop getDeviceTotalCategory() {
        try {
            return success(iotSystemDictService.getDeviceTotalCategory());
        } catch (Exception e) {
@ -830,143 +834,142 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/iotAndLostRange",method = RequestMethod.GET)
    @RequestMapping(value = "/iotAndLostRange", method = RequestMethod.GET)
    @ApiOperation("iot物联率 lost失联率")
    public MixEnvelop iotAndLostRange(
            @ApiParam(name="startTime",value="开始时间YYYY-MM-DD",defaultValue = "")
            @RequestParam(value="startTime",required = false) String startTime,
            @ApiParam(name="endTime",value="结束时间YYYY-MM-DD",defaultValue = "")
            @RequestParam(value="endTime",required = false) String endTime,
            @ApiParam(name="deviceType",value="设备类型",required = true)
            @RequestParam(value="deviceType",required = true,defaultValue = "1,2,5") String deviceType,
            @ApiParam(name="area",value="地区",defaultValue = "")
            @RequestParam(value="area",required = false) String area,
            @ApiParam(name="hospital",value="机构",defaultValue = "")
            @RequestParam(value="hospital",required = false) String hospital,
            @ApiParam(name="quotaCode",value="获取类型,1物联率 2失联率",required = true)
            @RequestParam(value="quotaCode",required = true) String quotaCode){
            @ApiParam(name = "startTime", value = "开始时间YYYY-MM-DD", defaultValue = "")
            @RequestParam(value = "startTime", required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间YYYY-MM-DD", defaultValue = "")
            @RequestParam(value = "endTime", required = false) String endTime,
            @ApiParam(name = "deviceType", value = "设备类型", required = true)
            @RequestParam(value = "deviceType", required = true, defaultValue = "1,2,5") String deviceType,
            @ApiParam(name = "area", value = "地区", defaultValue = "")
            @RequestParam(value = "area", required = false) String area,
            @ApiParam(name = "hospital", value = "机构", defaultValue = "")
            @RequestParam(value = "hospital", required = false) String hospital,
            @ApiParam(name = "quotaCode", value = "获取类型,1物联率 2失联率", required = true)
            @RequestParam(value = "quotaCode", required = true) String quotaCode) {
        try {
            return MixEnvelop.getSuccess("查询成功",monitorPlatformService.iotAndLostRange(startTime,endTime,deviceType,area,hospital,quotaCode));
        }catch (Exception e){
            return MixEnvelop.getSuccess("查询成功", monitorPlatformService.iotAndLostRange(startTime, endTime, deviceType, area, hospital, quotaCode));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @GetMapping(value="/getBrandsDetail")
    @GetMapping(value = "/getBrandsDetail")
    @ApiOperation("获取设备品牌列表")
    public Envelop getBrandsDetail(
            @ApiParam(name="deviceType",value ="设备类型",required = true)
            @RequestParam(value="deviceType",required = true,defaultValue = "1,2,5")String deviceType){
            @ApiParam(name = "deviceType", value = "设备类型", required = true)
            @RequestParam(value = "deviceType", required = true, defaultValue = "1,2,5,22") String deviceType) {
        return success(monitorPlatformService.getBrandsDetail(deviceType));
    }
    @RequestMapping(value="/getDeviceData", method = RequestMethod.GET)
    @RequestMapping(value = "/getDeviceData", method = RequestMethod.GET)
    @ApiOperation("物联网大屏实时动态设备")
    public Envelop getDeviceData(){
    public Envelop getDeviceData() {
        try {
            return success(monitorPlatformService.getDeviceData());
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "/getSearchTags",method = RequestMethod.GET)
    @RequestMapping(value = "/getSearchTags", method = RequestMethod.GET)
    @ApiOperation("快速搜索标签")
    public Envelop getSearchTags(){
    public Envelop getSearchTags() {
        try {
            return success(monitorPlatformService.getSearchTags());
        }
        catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value="getDeviceTotalCount",method = RequestMethod.GET)
    @RequestMapping(value = "getDeviceTotalCount", method = RequestMethod.GET)
    @ApiOperation("获取设备使用量、库存量、总备案")
    public Envelop getDeviceTotalCount(@ApiParam(name="startTime",value="开始时间yyyy-MM-dd",defaultValue = "")
                                           @RequestParam(value="startTime",required = false) String startTime,
                                       @ApiParam(name="endTime",value="结束时间",defaultValue = "")
                                       @RequestParam(value="endTime",required = false) String endTime,
                                       @ApiParam(name="deviceType",value="设备类型",defaultValue = "")
                                           @RequestParam(value="deviceType",required = false) String deviceType,
                                       @ApiParam(name="area",value="地区",defaultValue = "")
                                           @RequestParam(value="area",required = false) String area,
                                       @ApiParam(name="hospital",value="单位",defaultValue = "")
                                           @RequestParam(value="hospital",required = false) String hospital){
    public Envelop getDeviceTotalCount(@ApiParam(name = "startTime", value = "开始时间yyyy-MM-dd", defaultValue = "")
                                       @RequestParam(value = "startTime", required = false) String startTime,
                                       @ApiParam(name = "endTime", value = "结束时间", defaultValue = "")
                                       @RequestParam(value = "endTime", required = false) String endTime,
                                       @ApiParam(name = "deviceType", value = "设备类型", defaultValue = "")
                                       @RequestParam(value = "deviceType", required = false) String deviceType,
                                       @ApiParam(name = "area", value = "地区", defaultValue = "")
                                       @RequestParam(value = "area", required = false) String area,
                                       @ApiParam(name = "hospital", value = "单位", defaultValue = "")
                                       @RequestParam(value = "hospital", required = false) String hospital) {
        try {
            return success(monitorPlatformService.getDeviceTotalCount(startTime, endTime, deviceType, area,hospital));
        }
        catch (Exception e){
            return success(monitorPlatformService.getDeviceTotalCount(startTime, endTime, deviceType, area, hospital));
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    @RequestMapping(value = "savePatientDeviceLocation",method = RequestMethod.POST)
    public Envelop savePatientDeviceLocation(String categoryCode){
    @RequestMapping(value = "savePatientDeviceLocation", method = RequestMethod.POST)
    public Envelop savePatientDeviceLocation(String categoryCode) {
        try {
            return success(monitorPlatformService.savePatientDeviceLocation(categoryCode));
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("操作失败");
        }
    }
    @ApiOperation("获取运动记录")
    @RequestMapping(value = "getSportRecord",method = {RequestMethod.POST,RequestMethod.GET})
    @RequestMapping(value = "getSportRecord", method = {RequestMethod.POST, RequestMethod.GET})
    public Envelop getSportRecord(
            @ApiParam(name="patient",value="i健康居民code",defaultValue = "0fab4dd67e074e16ac86db6b6c15233e") @RequestParam(value = "patient", required = false)String patient,
            @ApiParam(name="date",value="开始日期,如2020-05-09",defaultValue = "2020-05-09") @RequestParam(value = "date", required = false)String date,
            @ApiParam(name="type",value="大屏选择项",defaultValue = "hear") @RequestParam(value = "type", required = false)String type,
            @ApiParam(name="day",value="周期",defaultValue = "7") @RequestParam(value = "day", required = false)Integer day
    ){
            @ApiParam(name = "patient", value = "i健康居民code", defaultValue = "0fab4dd67e074e16ac86db6b6c15233e") @RequestParam(value = "patient", required = false) String patient,
            @ApiParam(name = "date", value = "开始日期,如2020-05-09", defaultValue = "2020-05-09") @RequestParam(value = "date", required = false) String date,
            @ApiParam(name = "type", value = "大屏选择项", defaultValue = "hear") @RequestParam(value = "type", required = false) String type,
            @ApiParam(name = "day", value = "周期", defaultValue = "7") @RequestParam(value = "day", required = false) Integer day
    ) {
        try {
            JSONObject json = new JSONObject();
            String endDate = getNewDate(date,day);
            if (type.equals("hear") || type.equals("all")){
            String endDate = getNewDate(date, day);
            if (type.equals("hear") || type.equals("all")) {
                //心率
                List<Map<String,Object>> hearDo = monitorPlatformService.getHeartByPatient(patient,date,endDate);
                if (hearDo.size() > 0){
                    json.put("hear",hearDo);//心率
                }else {
                    json.put("hear",0);//心率
                List<Map<String, Object>> hearDo = monitorPlatformService.getHeartByPatient(patient, date, endDate);
                if (hearDo.size() > 0) {
                    json.put("hear", hearDo);//心率
                } else {
                    json.put("hear", 0);//心率
                }
            }
            if (type.equals("score") || type.equals("all")){
            if (type.equals("score") || type.equals("all")) {
                //健康分  retWeekTime("week");  周的健康分
                List<Map<String, Object>> scoreDO = monitorPlatformService.getHealthScoreByPatient(patient,date,endDate);
                if (scoreDO.size() > 0){
                    json.put("score",scoreDO); //健康分值
                }else {
                    json.put("score",0); //健康分值
                List<Map<String, Object>> scoreDO = monitorPlatformService.getHealthScoreByPatient(patient, date, endDate);
                if (scoreDO.size() > 0) {
                    json.put("score", scoreDO); //健康分值
                } else {
                    json.put("score", 0); //健康分值
                }
            }
            if (type.equals("realtime") || type.equals("all")){
            if (type.equals("realtime") || type.equals("all")) {
                // 实时数据
                List<Map<String, Object>> realtimeDateDo = monitorPlatformService.getRealtimeDateByPatient(patient,date);
                if (realtimeDateDo.size() > 0){
                    json.put("realtime",realtimeDateDo.get(0)); //实时心率
                List<Map<String, Object>> realtimeDateDo = monitorPlatformService.getRealtimeDateByPatient(patient, date);
                if (realtimeDateDo.size() > 0) {
                    json.put("realtime", realtimeDateDo.get(0)); //实时心率
//                    Map<String,Object> map = realtimeDateDo.get(0);
//                    json.put("realtimehr",map.get("hr")); //实时心率
//                    json.put("realtimest",map.get("st")); //实时步数,采集开始后的累积步数
//                    json.put("realtimecal",map.get("cal")); //实时卡路里,累积卡路里
                }else {
                    json.put("realtime",0);
                } else {
                    json.put("realtime", 0);
//                    json.put("realtimehr",0); //实时心率
//                    json.put("realtimest",0); //实时步数,采集开始后的累积步数
//                    json.put("realtimecal",0); //实时卡路里,累积卡路里
                }
            }
            if (type.equals("runData") || type.equals("all")){
            if (type.equals("runData") || type.equals("all")) {
                //运动数据  runDate
                List<Map<String , Object>> rundateDo = monitorPlatformService.getRundatePatient(patient,date);
                if (rundateDo.size() > 0){
                    json.put("runData",rundateDo.get(0));
                List<Map<String, Object>> rundateDo = monitorPlatformService.getRundatePatient(patient, date);
                if (rundateDo.size() > 0) {
                    json.put("runData", rundateDo.get(0));
//                    Map<String,Object> map = rundateDo.get(0);
//                    json.put("steps",map.get("steps")); //总步数
//                    json.put("distance",map.get("distance")); //总距离
@ -975,8 +978,8 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
//                    json.put("runTime",map.get("run_time")); //跑步时长
//                    json.put("calories",map.get("calories")); //总燃烧卡路里
//                    json.put("runCalories",map.get("run_calories")); //跑步消耗卡路里
                }else {
                    json.put("runData",0);
                } else {
                    json.put("runData", 0);
//                    json.put("steps",0); //总步数
//                    json.put("distance",0); //总距离
//                    json.put("walkTime",0); //步行时长
@ -986,25 +989,25 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
//                    json.put("runCalories",0); //跑步消耗卡路里
                }
            }
            if (type.equals("pai") || type.equals("all")){
            if (type.equals("pai") || type.equals("all")) {
                //PAI数据
                List<Map<String,Object>> paiDo = monitorPlatformService.getPaiPatient(patient,date);
                if (paiDo.size() > 0){
                    json.put("pai",paiDo.get(0));
                List<Map<String, Object>> paiDo = monitorPlatformService.getPaiPatient(patient, date);
                if (paiDo.size() > 0) {
                    json.put("pai", paiDo.get(0));
//                    Map<String,Object> map = paiDo.get(0);
//                    json.put("totalPai",map.get("total_pai")); //用户本周运动前获得的所有PAI
//                    json.put("dailyPai",map.get("daily_pai")); //用户在当天获得的PAI
                }else {
                    json.put("pai",0);
                } else {
                    json.put("pai", 0);
//                    json.put("totalPai",0); //总
//                    json.put("dailyPai",0); //总距离
                }
            }
            if (type.equals("sleepData") || type.equals("all")){
            if (type.equals("sleepData") || type.equals("all")) {
                //睡眠数据
                List<Map<String , Object>> sleepDo = monitorPlatformService.getSleepByPatient(patient,date);
                if (sleepDo.size() > 0){
                    json.put("sleepData",sleepDo.get(0));
                List<Map<String, Object>> sleepDo = monitorPlatformService.getSleepByPatient(patient, date);
                if (sleepDo.size() > 0) {
                    json.put("sleepData", sleepDo.get(0));
//                    Map<String,Object> map = sleepDo.get(0);
//                    json.put("deepSleepTime",map.get("deep_sleep_time")); //深度睡眠时长,单位为分钟
//                    json.put("shallowSleepTime",map.get("shallow_sleep_time")); //浅度睡眠时长,单位为分钟
@ -1012,8 +1015,8 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
//                    json.put("sleepScore",map.get("sleep_score")); //睡眠评分
//                    json.put("start",map.get("start")); //睡眠开始时间。Amazfit设备为分钟序号(0-1439),mifit设备为时间戳
//                    json.put("stop",map.get("stop")); //睡眠结束时间。Amazfit设备为分钟序号(0-1439),mifit设备为时间戳
                }else {
                    json.put("sleepData",sleepDo.get(0));
                } else {
                    json.put("sleepData", sleepDo.get(0));
//                    json.put("deepSleepTime",0); //深度睡眠时长,单位为分钟
//                    json.put("shallowSleepTime",0); //浅度睡眠时长,单位为分钟
//                    json.put("wakeTime",0); //睡眠期间清醒时长,单位为分钟
@ -1022,14 +1025,14 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
//                    json.put("stop",0); //睡眠结束时间。Amazfit设备为分钟序号(0-1439),mifit设备为时间戳
                }
            }
            return success("查询成功",json);
        }catch (Exception e){
            return success("查询成功", json);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError("查询失败");
        }
    }
    private String getNewDate(String date,Integer day) throws ParseException {
    private String getNewDate(String date, Integer day) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date newDate = sdf.parse(date);
        Calendar calendar = Calendar.getInstance();
@ -1040,29 +1043,110 @@ public class MonitorPlatformController extends EnvelopRestEndpoint {
    }
    @ApiOperation("获取赛客查询指标")
    @RequestMapping(value = "getXeekParameters",method = {RequestMethod.POST,RequestMethod.GET})
    public ObjEnvelop getSportRecord(){
    @RequestMapping(value = "getXeekParameters", method = {RequestMethod.POST, RequestMethod.GET})
    public ObjEnvelop getSportRecord() {
        try {
            String sql = "select value as code,name1 name from xmiot.wlyy_iot_tz_dict where code='COPD_PARAMETER' and del=1";
            List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
            return  ObjEnvelop.getSuccess("查询成功",result);
        }catch (Exception e){
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            return ObjEnvelop.getSuccess("查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("查询失败"+e.getMessage());
            return ObjEnvelop.getError("查询失败" + e.getMessage());
        }
    }
    @ApiOperation("获取华米手环查询指标")
    @RequestMapping(value = "getHuaMiParameters",method = {RequestMethod.POST,RequestMethod.GET})
    public ObjEnvelop getHuaMiParameters(){
    @RequestMapping(value = "getHuaMiParameters", method = {RequestMethod.POST, RequestMethod.GET})
    public ObjEnvelop getHuaMiParameters() {
        try {
            String sql = "select value as code,name from xmiot.wlyy_iot_tz_dict where code='HuaMiIot' and del=1";
            List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
            return  ObjEnvelop.getSuccess("查询成功",result);
        }catch (Exception e){
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            return ObjEnvelop.getSuccess("查询成功", result);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjEnvelop.getError("查询失败"+e.getMessage());
            return ObjEnvelop.getError("查询失败" + e.getMessage());
        }
    }
    @ApiOperation("获取智慧药房列表")
    @RequestMapping(value = "getMedicinecabinet", method = {RequestMethod.GET})
    public ObjEnvelop getMedicinecabinet() {
        List<Map<String, String>> list = monitorPlatformService.getMedicinecabinet();
        return ObjEnvelop.getSuccess("查询成功", list);
    }
    @ApiOperation("获取智慧药房数量")
    @RequestMapping(value = "getMedicinecabinetCount", method = {RequestMethod.GET})
    public ObjEnvelop getMedicinecabinetCount() {
        Map<String, Object> map = monitorPlatformService.getMedicinecabinetCount();
        return ObjEnvelop.getSuccess("查询成功", map);
    }
    @ApiOperation("获取智慧药房详细信息")
    @RequestMapping(value = "getMedicineCabinetDetails", method = {RequestMethod.POST})
    public ObjEnvelop getMedicineCabinetDetails(@ApiParam(name = "deviceid", defaultValue = "设备id")
                                                @RequestParam(value = "deviceid", required = true) String deviceid) {
        try {
            /*808080eb7da2717d017da2cdc43e003e*/
            Map<String, List<Map>> getadddd = monitorPlatformService.getadddd(deviceid, "365");
            return ObjEnvelop.getSuccess("成功", getadddd, 200);
        } catch (Exception e) {
            return ObjEnvelop.getError("失败" + e.getMessage());
        }
    }
    @ApiOperation("获取智慧药房详细曲线信息")
    @RequestMapping(value = "getCabinetCurve", method = {RequestMethod.POST})
    public ObjEnvelop getCabinetCurve(@ApiParam(name = "deviceid", defaultValue = "设备id")
                                      @RequestParam(value = "deviceid", required = true) String deviceid,
                                      @ApiParam(name = "day", defaultValue = "天数")
                                      @RequestParam(value = "day", required = false) String day) {
        try {
            Map<String, List<Map>> cabinetCurve = monitorPlatformService.getCabinetCurve(deviceid, day);
            return ObjEnvelop.getSuccess("成功", cabinetCurve, 200);
        } catch (Exception e) {
            return ObjEnvelop.getError("失败" + e.getMessage());
        }
    }
    @ApiOperation("获取智慧药房地标")
    @RequestMapping(value = "getLongitudeAndLatitude", method = {RequestMethod.GET})
    public ObjEnvelop getLongitudeAndLatitude() {
        try {
            List<Map<String, Object>> longitudeAndLatitude = monitorPlatformService.getLongitudeAndLatitude();
            return ObjEnvelop.getSuccess("成功", longitudeAndLatitude, 200);
        } catch (Exception e) {
            return ObjEnvelop.getError("失败" + e.getMessage());
        }
    }
    @ApiOperation("获取智慧药房取药信息")
    @RequestMapping(value = "getBuyDrugMessage",method = {RequestMethod.GET})
    public ObjEnvelop getBuyDrugMessage(@ApiParam(name = "deviceid", defaultValue = "设备id")
                                        @RequestParam(value = "deviceid", required = true) String deviceid,
                                        @ApiParam(name = "startTime", defaultValue = "开始时间")
                                        @RequestParam(value = "startTime", required = true) String startTime,
                                        @ApiParam(name = "endTime", defaultValue = "开始时间")
                                        @RequestParam(value = "endTime", required = true) String endTime){
        try {
            JSONObject jsonObject = monitorPlatformService.getBuyDrugMessage(deviceid,startTime,endTime);
            return ObjEnvelop.getSuccess("成功",jsonObject,200);
        } catch (Exception e) {
            return ObjEnvelop.getError("失败"+e.getMessage());
        }
    }
    @ApiOperation("智慧药房库存检测信息")
    @RequestMapping(value = "getYgStockDetection", method = {RequestMethod.GET})
    public ObjEnvelop getYgStockDetection(@ApiParam(name = "deviceid", defaultValue = "设备id")
                                          @RequestParam(value = "deviceid", required = true) String deviceid) {
        try {
            JSONArray jsonArray = monitorPlatformService.ygStockDetection(deviceid);
            return ObjEnvelop.getSuccess("成功", jsonArray, 200);
        } catch (Exception e) {
            return ObjEnvelop.getError("失败" + e.getMessage());
        }
    }
}

+ 13 - 0
svr/svr-iot/src/main/java/com/yihu/iot/service/analyzer/IotAnalyzerService.java

@ -58,6 +58,19 @@ public class IotAnalyzerService extends BaseJpaService<WlyyIotD, WlyyIotDDao> {
    private String bmiUnit = "kg/m^2";
    private String waistUnit = "cm";
//              type	        sign_name	sign_unit
//    收缩压	    BloodPressure	systolic 	mmHg
//    舒张压	    BloodPressure	diastolic	mmHg
//    血糖	    BloodSugar	    blood_sugar	mmol/L
//    身高	    Height	        height	    cm
//    体重	    Height	        weight	    kg
//    BMI	    Height	        bmi	        kg/m^2
//    腰围	    Waist	        waist	    cm
//    骨密度	    BMD	            bmd	        g/cm^3
//    骨密度T值	BMD	            bmd_t	    g/cm^3
//    骨密度Z值	BMD	            bmd_z	    g/cm^3
    public void initIHealthIntoEs(){
        try {
            Integer id = 0;

+ 1038 - 683
svr/svr-iot/src/main/java/com/yihu/iot/service/monitorPlatform/MonitorPlatformService.java

@ -43,7 +43,7 @@ import java.util.*;
 * Created by yeshijie on 2020/5/11.
 */
@Service
public class MonitorPlatformService  {
public class MonitorPlatformService {
    @Value("${spring.wlyy.url}")
    private String wlyyUrl;
@ -55,7 +55,7 @@ public class MonitorPlatformService  {
    private String wxId;
    @Value("${wechat.flag}")
    private boolean flag;
    public static Map<String,String> tokenMap = new HashMap<>();
    public static Map<String, String> tokenMap = new HashMap<>();
    @Autowired
    private HttpClientUtil httpClientUtil;
@ -82,26 +82,27 @@ public class MonitorPlatformService  {
    /**
     * 获取位置信息
     *
     * @param diseaseCondition
     * @return
     */
    public MixEnvelop<LocationDataVO, LocationDataVO> findDeviceLocations(Integer diseaseCondition, Integer page, Integer size, String type,String deviceType,String deviceName) throws IOException {
    public MixEnvelop<LocationDataVO, LocationDataVO> findDeviceLocations(Integer diseaseCondition, Integer page, Integer size, String type, String deviceType, String deviceName) throws IOException {
        MixEnvelop<LocationDataVO, LocationDataVO> envelop = new MixEnvelop<>();
        MixEnvelop<LocationDataVO, LocationDataVO> envelopTmp = null;
        Integer total = 0;
        if(org.apache.commons.lang.StringUtils.isNotBlank(type)){
            JSONObject json = iotSearchPatientDeviceSN(type,page,size,deviceName);
        if (org.apache.commons.lang.StringUtils.isNotBlank(type)) {
            JSONObject json = iotSearchPatientDeviceSN(type, page, size, deviceName);
            total = json.getInteger("total");
            JSONArray list = json.getJSONArray("list");
            for(int i=0;i<list.size();i++){
                String sql ="select id, idcard idCard,category_code categoryCode,device_sn deviceSn,location,device_time deviceTime,disease_condition diseaseCondition,\n" +
                        "create_time createTime,device_name equimentName from device.wlyy_patient_device_location where del=0 and  device_sn='"+list.getString(i)+"'";
                List<Map<String,Object>> result = jdbcTemplate.queryForList(sql.toString());
            for (int i = 0; i < list.size(); i++) {
                String sql = "select id, idcard idCard,category_code categoryCode,device_sn deviceSn,location,device_time deviceTime,disease_condition diseaseCondition,\n" +
                        "create_time createTime,device_name equimentName from device.wlyy_patient_device_location where del=0 and  device_sn='" + list.getString(i) + "'";
                List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString());
                List<LocationDataVO> locationDataVOList = new ArrayList<>();
                result.forEach(map->{
                result.forEach(map -> {
                    LocationDataVO locationDataVO = new LocationDataVO();
                    JSONObject location = JSONObject.parseObject(map.get("location").toString());
                    GeoPoint geoPoint = new GeoPoint(Double.parseDouble(location.get("lat").toString()),Double.parseDouble(location.get("lon").toString()));
                    GeoPoint geoPoint = new GeoPoint(Double.parseDouble(location.get("lat").toString()), Double.parseDouble(location.get("lon").toString()));
                    locationDataVO.setId(map.get("id").toString());
                    locationDataVO.setIdCard(AesEncryptUtils.decrypt(map.get("idCard").toString()));
                    locationDataVO.setCategoryCode(map.get("categoryCode").toString());
@ -120,50 +121,49 @@ public class MonitorPlatformService  {
            }
            envelop.setTotalCount(total);
            return envelop;
        }else {
        } else {
            List<LocationDataVO> euipmentList = new ArrayList<>();
            int totalEqCount=0;
            int totalCount=0;
            int totalEqCount = 0;
            int totalCount = 0;
            //小屋总数
            String manufacturerCode = deviceType;
            manufacturerCode = manufacturerCode.replace(",","','").replace("5","yituo").replace("10","xeek").replace("11","xiaomi");
            if(deviceType.contains("5")||deviceType.contains("10")||deviceType.contains("11")){
            manufacturerCode = manufacturerCode.replace(",", "','").replace("5", "yituo").replace("10", "xeek").replace("11", "xiaomi");
            if (deviceType.contains("5") || deviceType.contains("10") || deviceType.contains("11")) {
                totalEqCount = iotEqtDetailService.getEquipmentCount(manufacturerCode);
            }
            String[] categoryCodes= deviceType.split(",");
            if(categoryCodes.length==1&&(deviceType.contains("5")||deviceType.contains("10")||deviceType.contains("11"))){
                euipmentList = iotEqtDetailService.getEquipmentLocation(page,size,manufacturerCode);
            String[] categoryCodes = deviceType.split(",");
            if (categoryCodes.length == 1 && (deviceType.contains("5") || deviceType.contains("10") || deviceType.contains("11"))) {
                euipmentList = iotEqtDetailService.getEquipmentLocation(page, size, manufacturerCode);
                envelop.getDetailModelList().addAll(euipmentList);
            }
            else{
                if(deviceType.contains("5")||deviceType.contains("10")||deviceType.contains("11")){
                    euipmentList = iotEqtDetailService.getEquipmentLocation(page,size,manufacturerCode);
            } else {
                if (deviceType.contains("5") || deviceType.contains("10") || deviceType.contains("11")) {
                    euipmentList = iotEqtDetailService.getEquipmentLocation(page, size, manufacturerCode);
                    envelop.getDetailModelList().addAll(euipmentList);
                }
                StringBuffer sql = new StringBuffer("select id,idcard idCard,category_code categoryCode,device_sn deviceSn,location,device_time deviceTime,disease_condition diseaseCondition,\n" +
                        "create_time createTime,device_name equimentName\n" +
                        "from device.wlyy_patient_device_location  ");
                StringBuffer sqlCounts = new StringBuffer("select count(*) from device.wlyy_patient_device_location ");
                StringBuffer sqlCondition  = new StringBuffer("where del=0 ");
                if (diseaseCondition!=null){
                    sqlCondition.append(" and disease_condition ="+diseaseCondition);
                StringBuffer sqlCondition = new StringBuffer("where del=0 ");
                if (diseaseCondition != null) {
                    sqlCondition.append(" and disease_condition =" + diseaseCondition);
                }
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                    sqlCondition.append(" and category_code in('").append(deviceType.replace(",","','")).append("') ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                    sqlCondition.append(" and category_code in('").append(deviceType.replace(",", "','")).append("') ");
                }
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)){
                    sqlCondition.append(" and device_name in ('").append(deviceName.replace(",","','")).append("') ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)) {
                    sqlCondition.append(" and device_name in ('").append(deviceName.replace(",", "','")).append("') ");
                }
                sql.append(sqlCondition);
                sqlCounts.append(sqlCondition);
                sql.append( " limit "+(page-1)*size+","+size);
                totalCount = jdbcTemplate.queryForObject(sqlCounts.toString(),Integer.class);
                List<Map<String,Object>> result = jdbcTemplate.queryForList(sql.toString());
                sql.append(" limit " + (page - 1) * size + "," + size);
                totalCount = jdbcTemplate.queryForObject(sqlCounts.toString(), Integer.class);
                List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString());
                List<LocationDataVO> locationDataVOList = new ArrayList<>();
                result.forEach(map->{
                result.forEach(map -> {
                    LocationDataVO locationDataVO = new LocationDataVO();
                    JSONObject location = JSONObject.parseObject(map.get("location").toString());
                    GeoPoint geoPoint = new GeoPoint(Double.parseDouble(location.get("lat").toString()),Double.parseDouble(location.get("lon").toString()));
                    GeoPoint geoPoint = new GeoPoint(Double.parseDouble(location.get("lat").toString()), Double.parseDouble(location.get("lon").toString()));
                    locationDataVO.setId(map.get("id").toString());
                    locationDataVO.setIdCard(AesEncryptUtils.decrypt(map.get("idCard").toString()));
                    locationDataVO.setCategoryCode(map.get("categoryCode").toString());
@ -180,45 +180,45 @@ public class MonitorPlatformService  {
                });
                envelop.getDetailModelList().addAll(locationDataVOList);
            }
            envelop.setTotalCount(totalCount>totalEqCount?totalCount:totalEqCount);
            envelop.setTotalCount(totalCount > totalEqCount ? totalCount : totalEqCount);
            return envelop;
        }
    }
    public com.alibaba.fastjson.JSONObject iotSearchPatientDeviceSN(String type,Integer page,Integer pageSize,String deviceName){
    public com.alibaba.fastjson.JSONObject iotSearchPatientDeviceSN(String type, Integer page, Integer pageSize, String deviceName) {
        if(page != 0){
        if (page != 0) {
            page = page - 1;
        }
        StringBuffer sql = new StringBuffer("select t.device_sn from");
        sql.append("  ( SELECT DISTINCT d.* FROM wlyy.wlyy_patient_device d, wlyy.wlyy_sign_family f WHERE f.`status` > 0 AND f.patient = d.`user`  ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)){
            sql.append("and d.device_name in ('").append(deviceName.replace(",","','")).append("') ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)) {
            sql.append("and d.device_name in ('").append(deviceName.replace(",", "','")).append("') ");
        }
        sql.append("  ) t, wlyy.wlyy_patient p " );
        sql.append("  ) t, wlyy.wlyy_patient p ");
        sql.append("  LEFT JOIN wlyy.wlyy_sign_patient_label_info l on  p. CODE = l.patient");
        sql.append("   and l.`status`=1 AND l.label_type = 3 and l.label='"+type+"'");
        sql.append(" WHERE t.user = p. CODE limit "+page+","+pageSize);
        List<String> list = jdbcTemplate.queryForList(sql.toString(),String.class);
        sql.append("   and l.`status`=1 AND l.label_type = 3 and l.label='" + type + "'");
        sql.append(" WHERE t.user = p. CODE limit " + page + "," + pageSize);
        List<String> list = jdbcTemplate.queryForList(sql.toString(), String.class);
        Integer count = 0;
        StringBuffer countsql = new StringBuffer("select count(t.device_sn) total from");
        countsql.append("  ( SELECT DISTINCT d.* FROM wlyy.wlyy_patient_device d, wlyy.wlyy_sign_family f WHERE f.`status` > 0 AND f.patient = d.`user`  ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)){
            countsql.append("and d.device_name in ('").append(deviceName.replace(",","','")).append("') ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)) {
            countsql.append("and d.device_name in ('").append(deviceName.replace(",", "','")).append("') ");
        }
        countsql.append("   ) t,wlyy.wlyy_patient p " );
        countsql.append("   ) t,wlyy.wlyy_patient p ");
        countsql.append("  LEFT JOIN wlyy.wlyy_sign_patient_label_info l on  p. CODE = l.patient");
        countsql.append("   and l.`status`=1 AND l.label_type = 3 and l.label='"+type+"'");
        countsql.append("   and l.`status`=1 AND l.label_type = 3 and l.label='" + type + "'");
        countsql.append(" WHERE t.user = p. CODE ");
        count = jdbcTemplate.queryForObject(countsql.toString(),Integer.class);
        count = jdbcTemplate.queryForObject(countsql.toString(), Integer.class);
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        result.put("total",count);
        result.put("list",list);
        result.put("total", count);
        result.put("list", list);
        return result;
    }
@ -226,105 +226,106 @@ public class MonitorPlatformService  {
     * 根据病种类型,搜索已绑定设备的居民设备SN码
     * 类型(1高血压 2糖尿病)
     */
    public String searchpatientdevicesn(String type,Integer page,Integer size){
    public String searchpatientdevicesn(String type, Integer page, Integer size) {
        String url = "/wlyygc/iot_monitoring/searchpatientdevicesn";
        Map<String, Object> params = new HashMap<>();
        params.put("type",type);
        params.put("page",page);
        params.put("pageSize",size);
        return sendGet(url,params);
        params.put("type", type);
        params.put("page", page);
        params.put("pageSize", size);
        return sendGet(url, params);
    }
    /**
     * 设备发放情况
     */
    public String equipmentDistribution(String startTime,String endTime,
                                        String deviceType,String area,String hospital){
    public String equipmentDistribution(String startTime, String endTime,
                                        String deviceType, String area, String hospital) {
        String url = "/wlyygc/iot_monitoring/equipmentDistribution";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        String anotherResult = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        String anotherResult = sendGet(url, params);
        String sqlAre = dealSql(params);
        List<Map<String, Object>> iotEquip = hibenateUtils.createSQLQuery(sqlAre);
        if(StringUtils.isEmpty(deviceType)){
        if (StringUtils.isEmpty(deviceType)) {
            deviceType = "";
        }
        String[] str =deviceType.split(",");
        String[] str = deviceType.split(",");
        List<String> list = new ArrayList<>();
        for (int i=0;i<str.length;i++){
        for (int i = 0; i < str.length; i++) {
            list.add(str[i]);
        }
        JSONObject jsonObject = JSONObject.parseObject(anotherResult);
        IotSystemDictDO iotSystemDictDO = iotSystemDictDao.findByDictNameAndValueAndDel("DEVICE_TYPE","健康小屋",1);
        if (null!=iotSystemDictDO&&list.size()>1&&list.contains(iotSystemDictDO.getCode())){
            if("200".equals(jsonObject.get("status").toString())){
                JSONArray dataresult= jsonObject.getJSONArray("data");
        IotSystemDictDO iotSystemDictDO = iotSystemDictDao.findByDictNameAndValueAndDel("DEVICE_TYPE", "健康小屋", 1);
        if (null != iotSystemDictDO && list.size() > 1 && list.contains(iotSystemDictDO.getCode())) {
            if ("200".equals(jsonObject.get("status").toString())) {
                JSONArray dataresult = jsonObject.getJSONArray("data");
                JSONArray resultArray = new JSONArray();
                if (dataresult.size()>0){
                    for(int i=0;i<dataresult.size();i++){
                        JSONObject item= JSONObject.parseObject(dataresult.get(i).toString());
                        if(null!=item.get("num")){
                if (dataresult.size() > 0) {
                    for (int i = 0; i < dataresult.size(); i++) {
                        JSONObject item = JSONObject.parseObject(dataresult.get(i).toString());
                        if (null != item.get("num")) {
                            Integer itemCount = Integer.parseInt(item.get("num").toString());
                            for(Map<String, Object> map:iotEquip){
                                if (item.get("code").toString().equals(map.get("belong_are_code"))){
                                    itemCount = Integer.parseInt(map.get("total").toString())+itemCount;
                                    item.put("num",itemCount);
                            for (Map<String, Object> map : iotEquip) {
                                if (item.get("code").toString().equals(map.get("belong_are_code"))) {
                                    itemCount = Integer.parseInt(map.get("total").toString()) + itemCount;
                                    item.put("num", itemCount);
                                }
                            }
                        }
                        resultArray.add(item);
                    }
                }
                jsonObject.replace("data",resultArray);
                jsonObject.replace("data", resultArray);
                System.out.println(jsonObject.toString());
            }
            return jsonObject.toString();
        }else if (list.size()==1&&list.contains(iotSystemDictDO.getCode())){
        } else if (list.size() == 1 && list.contains(iotSystemDictDO.getCode())) {
            List list1 = new ArrayList();
            for (Map<String,Object> mao:iotEquip){
               JSONObject jo = new JSONObject(mao);
               list1.add(jo);
            for (Map<String, Object> mao : iotEquip) {
                JSONObject jo = new JSONObject(mao);
                list1.add(jo);
            }
            jsonObject.replace("data",JSONArray.parse(list1.toString()));
            jsonObject.replace("data", JSONArray.parse(list1.toString()));
            return jsonObject.toString();
        }else {
           return anotherResult;
        } else {
            return anotherResult;
        }
    }
    private String dealSql(Map<String, Object> params){
    private String dealSql(Map<String, Object> params) {
        StringBuffer sql = new StringBuffer();
        sql.append("select count(1) AS \"num\",t.belong_are AS \"name\",t.belong_are_code AS \"code\" from iot_equipmet_detail t ");
        sql.append(" where 1=1 ");
        if (null!=params.get("area")){
            sql.append(" and t.belong_are_code = '"+params.get("area").toString()+"'");
        if (null != params.get("area")) {
            sql.append(" and t.belong_are_code = '" + params.get("area").toString() + "'");
        }
        if (null!=params.get("startTime")) {
        if (null != params.get("startTime")) {
            //sql.append(" and t.update_time > '" + beginTime+"'");//DateUtil.stringToDate(beginTime,"yyyy-MM-dd HH:mm:ss")
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql.append( " and t.create_time >= str_to_date('" + params.get("startTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                }else {
                    sql.append(  " and t.create_time >= to_date('" + params.get("startTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                if (flag) {
                    sql.append(" and t.create_time >= str_to_date('" + params.get("startTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                } else {
                    sql.append(" and t.create_time >= to_date('" + params.get("startTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                }
            } else {
                sql.append( " AND t.create_time >='" + params.get("startTime").toString() + " 00:00:00'");
                sql.append(" AND t.create_time >='" + params.get("startTime").toString() + " 00:00:00'");
            }
        }
        if (null!=params.get("endTime")) {
        if (null != params.get("endTime")) {
            //sql.append(" and t.update_time < '" + endTime+"'");//DateUtil.stringToDate(endTime,"yyyy-MM-dd HH:mm:ss")
            if ("xm_ykyy_wx".equals(wxId)) {
                if (flag){
                    sql.append( " and t.create_time <= str_to_date('" + params.get("endTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                }else {
                    sql.append(  " and t.create_time <= to_date('" + params.get("endTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                if (flag) {
                    sql.append(" and t.create_time <= str_to_date('" + params.get("endTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                } else {
                    sql.append(" and t.create_time <= to_date('" + params.get("endTime").toString() + " 00:00:00','YYYY-MM-DD HH24:MI:SS')");
                }
            } else {
                sql.append( " AND t.create_time <='" + params.get("endTime").toString() + " 00:00:00'");
                sql.append(" AND t.create_time <='" + params.get("endTime").toString() + " 00:00:00'");
            }
        }
        sql.append(" group by t.belong_are_code order by \"total\" desc ");
@ -335,98 +336,105 @@ public class MonitorPlatformService  {
     * 慢病患者情况-统计
     * 类型(2糖尿病,1高血压)
     */
    public String chronicDiseaseCount(String type){
    public String chronicDiseaseCount(String type) {
        String url = "/wlyygc/iot_monitoring/chronicDiseaseCount";
        Map<String, Object> params = new HashMap<>();
        params.put("type",type);
        return sendGet(url,params);
        params.put("type", type);
        return sendGet(url, params);
    }
    /**
     * 预警信息警报
     *
     * @param page
     * @param pageSize
     * @return
     */
    public String warningInformationAlarm(Integer page,Integer pageSize){
    public String warningInformationAlarm(Integer page, Integer pageSize) {
        String url = "/wlyygc/iot_monitoring/warningInformationAlarm";
        Map<String, Object> params = new HashMap<>();
        params.put("page",page);
        params.put("pageSize",pageSize);
        return sendGet(url,params);
        params.put("page", page);
        params.put("pageSize", pageSize);
        return sendGet(url, params);
    }
    /**
     * 居民 医生搜索
     *
     * @param page
     * @param pageSize
     * @return
     */
    public String searchPatient(String name,Integer page,Integer pageSize,String idcards){
    public String searchPatient(String name, Integer page, Integer pageSize, String idcards) {
        String url = "/wlyygc/iot_monitoring/searchPatient";
        Map<String, Object> params = new HashMap<>();
        params.put("name",name);
        params.put("page",page);
        params.put("pageSize",pageSize);
        params.put("idcards",idcards);
        return sendGet(url,params);
        params.put("name", name);
        params.put("page", page);
        params.put("pageSize", pageSize);
        params.put("idcards", idcards);
        return sendGet(url, params);
    }
    /**
     * 设备绑定情况
     *
     * @param type 设备类型(1血糖仪,2血压计
     * @return
     */
    public String deviceBinding(String type){
    public String deviceBinding(String type) {
        String url = "/wlyygc/iot_monitoring/deviceBinding";
        Map<String, Object> params = new HashMap<>();
        params.put("type",type);
        return sendGet(url,params);
        params.put("type", type);
        return sendGet(url, params);
    }
    /**
     * 个人信息
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/persionalInfo",method = RequestMethod.GET)
    @RequestMapping(value = "/persionalInfo", method = RequestMethod.GET)
    @ApiOperation("个人信息")
    public String persionalInfo(String patient){
    public String persionalInfo(String patient) {
        String url = "/wlyygc/iot_monitoring/persionalInfo";
        Map<String, Object> params = new HashMap<>();
        params.put("patient",patient);
        return sendGet(url,params);
        params.put("patient", patient);
        return sendGet(url, params);
    }
    /**
     * 家人信息
     *
     * @param patient
     * @return
     */
    public String familyMember(String patient){
    public String familyMember(String patient) {
        String url = "/wlyygc/iot_monitoring/familyMember";
        Map<String, Object> params = new HashMap<>();
        params.put("patient",patient);
        return sendGet(url,params);
        params.put("patient", patient);
        return sendGet(url, params);
    }
    /**
     * 健康设备
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/healthDevice",method = RequestMethod.GET)
    @RequestMapping(value = "/healthDevice", method = RequestMethod.GET)
    @ApiOperation("健康设备")
    public String healthDevice(String patient){
    public String healthDevice(String patient) {
        String url = "/wlyygc/iot_monitoring/healthDevice";
        Map<String, Object> params = new HashMap<>();
        params.put("patient",patient);
        return sendGet(url,params);
        params.put("patient", patient);
        return sendGet(url, params);
    }
    /**
     * 体征数据
     *
     * @param patient
     * @param type
     * @param gi_type
@ -434,38 +442,40 @@ public class MonitorPlatformService  {
     * @param end
     * @return
     */
    public String getHealthIndexChartByPatient(String patient, Integer type, Integer gi_type, String begin, String end,String time) {
    public String getHealthIndexChartByPatient(String patient, Integer type, Integer gi_type, String begin, String end, String time) {
        String url = "/wlyygc/iot_monitoring/chart";
        Map<String, Object> params = new HashMap<>();
        params.put("patient",patient);
        params.put("type",type);
        params.put("time",time);
        params.put("begin",begin);
        params.put("end",end);
        params.put("gi_type",gi_type);
        return sendGet(url,params);
        params.put("patient", patient);
        params.put("type", type);
        params.put("time", time);
        params.put("begin", begin);
        params.put("end", end);
        params.put("gi_type", gi_type);
        return sendGet(url, params);
    }
    /**
     * 获取门诊记录/住院记录(基卫+APP)
     *
     * @param patient
     * @param type 类型(1血糖,2血压)
     * @param type     类型(1血糖,2血压)
     * @param page
     * @param pageSize
     * @return
     */
    public String getAllEvent(String patient,String type,String page,String pageSize) {
    public String getAllEvent(String patient, String type, String page, String pageSize) {
        String url = "/wlyygc/iot_monitoring/event";
        Map<String, Object> params = new HashMap<>();
        params.put("patient",patient);
        params.put("type",type);
        params.put("page",page);
        params.put("pageSize",pageSize);
        return sendGet(url,params);
        params.put("patient", patient);
        params.put("type", type);
        params.put("page", page);
        params.put("pageSize", pageSize);
        return sendGet(url, params);
    }
    /**
     * 根据患者标志获取健康指标
     *
     * @param idcard
     * @param type
     * @param begin
@ -474,56 +484,58 @@ public class MonitorPlatformService  {
     * @param pagesize
     * @return
     */
    public String getHealthIndexByIdcard(String idcard,int type, String begin,String end, int page,int pagesize,HttpServletRequest request) {
    public String getHealthIndexByIdcard(String idcard, int type, String begin, String end, int page, int pagesize, HttpServletRequest request) {
        String url = "/wlyygc/iot_monitoring/health_index/listByIdcard";
        Map<String, Object> params = new HashMap<>();
        params.put("idcard",idcard);
        params.put("begin",begin);
        params.put("end",end);
        params.put("type",type);
        params.put("page",page);
        params.put("pagesize",pagesize);
        try{
        params.put("idcard", idcard);
        params.put("begin", begin);
        params.put("end", end);
        params.put("type", type);
        params.put("page", page);
        params.put("pagesize", pagesize);
        try {
            //记录log
            iotInterfaceLogService.saveLog("zy808081724b116c017254d437fe000b",JSONObject.toJSONString(params),null, request,200,"getHealthIndexByIdcard");
        }catch (Exception e){
            iotInterfaceLogService.saveLog("zy808081724b116c017254d437fe000b", JSONObject.toJSONString(params), null, request, 200, "getHealthIndexByIdcard");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendGet(url,params);
        return sendGet(url, params);
    }
    /**
     * 获取居民信息
     *
     * @param idcard
     * @return
     */
    public String patientInfo(String idcard) {
        String url = "/wlyygc/iot_monitoring/patientInfo";
        Map<String, Object> params = new HashMap<>();
        params.put("idcard",idcard);
        return sendGet(url,params);
        params.put("idcard", idcard);
        return sendGet(url, params);
    }
    /**
     * 质控情况
     *
     * @param page
     * @param pageSize
     * @param deviceSn
     * @return
     */
    public List<JSONObject> deviceOverhaulList(Integer page,Integer pageSize,String deviceSn){
    public List<JSONObject> deviceOverhaulList(Integer page, Integer pageSize, String deviceSn) {
        String sql = "SELECT o.time,o.`status`,o.remark from iot_patient_device d,iot_device_overhaul o" +
                " WHERE d.device_sn = '"+deviceSn+"' and d.id = o.patient_device_id ORDER BY o.time desc limit ?,?";
        return myJdbcTemplate.queryJson(sql.toString(),new Object[]{(page-1)*pageSize,pageSize});
                " WHERE d.device_sn = '" + deviceSn + "' and d.id = o.patient_device_id ORDER BY o.time desc limit ?,?";
        return myJdbcTemplate.queryJson(sql.toString(), new Object[]{(page - 1) * pageSize, pageSize});
    }
    public Integer deviceOverhaulListTotal(String deviceSn){
    public Integer deviceOverhaulListTotal(String deviceSn) {
        String sql = "SELECT count(o.id) c from iot_patient_device d,iot_device_overhaul o" +
                " WHERE d.device_sn = '"+deviceSn+"' and d.id = o.patient_device_id ";
        List<JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),new Object[]{});
        if(list.size()>0){
                " WHERE d.device_sn = '" + deviceSn + "' and d.id = o.patient_device_id ";
        List<JSONObject> list = myJdbcTemplate.queryJson(sql.toString(), new Object[]{});
        if (list.size() > 0) {
            return list.get(0).getInteger("c");
        }
        return 0;
@ -531,18 +543,19 @@ public class MonitorPlatformService  {
    /**
     * 入住情况
     *
     * @return
     */
    public JSONObject residentUserType(){
    public JSONObject residentUserType() {
        String sql = "SELECT IFNULL(enter_type,'0') type,COUNT(id) num from iot_company WHERE del =1 GROUP BY enter_type";
        List<JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),new Object[]{});
        List<JSONObject> list = myJdbcTemplate.queryJson(sql.toString(), new Object[]{});
        int total = 0;
        int manufacturer = 0;//厂商
        int supplier = 0;// 供应商
        int agent = 0;//代理商
        int platform = 0;//接入平台
        for(JSONObject json:list){
            switch (json.getString("type")){
        for (JSONObject json : list) {
            switch (json.getString("type")) {
                case "0":
                    platform = json.getInteger("num");
                    break;
@ -557,25 +570,25 @@ public class MonitorPlatformService  {
                    break;
            }
        }
        total = manufacturer+supplier+agent+platform;
        total = manufacturer + supplier + agent + platform;
        JSONObject json = new JSONObject();
        json.put("total",total);
        json.put("manufacturer",manufacturer);
        json.put("supplier",supplier);
        json.put("agent",agent);
        json.put("platform",platform);
        if(total>0){
        json.put("total", total);
        json.put("manufacturer", manufacturer);
        json.put("supplier", supplier);
        json.put("agent", agent);
        json.put("platform", platform);
        if (total > 0) {
            DecimalFormat df = new DecimalFormat("0.00");
            json.put("manufacturerRange", df.format(manufacturer > 0.0 ? (manufacturer/ (total * 1.0000) * 100) : 0.0) + "%");
            json.put("supplierRange", df.format(supplier > 0.0 ? (supplier/ (total * 1.0000) * 100) : 0.0) + "%");
            json.put("agentRange", df.format(agent > 0.0 ? (agent/ (total * 1.0000) * 100) : 0.0) + "%");
            json.put("platformRange", df.format(platform > 0.0 ? (platform/ (total * 1.0000) * 100) : 0.0) + "%");
        }else {
            json.put("manufacturerRange","0.0%");
            json.put("supplierRange","0.0%");
            json.put("agentRange","0.0%");
            json.put("platformRange","0.0%");
            json.put("manufacturerRange", df.format(manufacturer > 0.0 ? (manufacturer / (total * 1.0000) * 100) : 0.0) + "%");
            json.put("supplierRange", df.format(supplier > 0.0 ? (supplier / (total * 1.0000) * 100) : 0.0) + "%");
            json.put("agentRange", df.format(agent > 0.0 ? (agent / (total * 1.0000) * 100) : 0.0) + "%");
            json.put("platformRange", df.format(platform > 0.0 ? (platform / (total * 1.0000) * 100) : 0.0) + "%");
        } else {
            json.put("manufacturerRange", "0.0%");
            json.put("supplierRange", "0.0%");
            json.put("agentRange", "0.0%");
            json.put("platformRange", "0.0%");
        }
        return json;
@ -583,50 +596,51 @@ public class MonitorPlatformService  {
    /**
     * 接口调用情况
     *
     * @param startTime
     * @param endTime
     * @param type
     * @return
     */
    public List<JSONObject> intefaceLogList(String startTime,String endTime,String type){
    public List<JSONObject> intefaceLogList(String startTime, String endTime, String type) {
        String sql = "SELECT ";
        switch (type){
        switch (type) {
            case "month":
                sql+= " date_format(time,'%m') ";
                sql += " date_format(time,'%m') ";
                break;
            case "year":
                sql+= " date_format(time,'%Y') ";
                sql += " date_format(time,'%Y') ";
                break;
            case "day":
                sql+= " date_format(time,'%Y-%m-%d') ";
                sql += " date_format(time,'%Y-%m-%d') ";
                break;
            case "week":
                sql+= " date_format(time,'%u') ";
                sql += " date_format(time,'%u') ";
                break;
        }
        sql+= " date ,COUNT(*) num from iot_interface_log where 1=1 ";
        if(StringUtils.isEmpty(startTime)){
            sql+= " and time>='"+startTime+"'";
        sql += " date ,COUNT(*) num from iot_interface_log where 1=1 ";
        if (StringUtils.isEmpty(startTime)) {
            sql += " and time>='" + startTime + "'";
        }
        if(StringUtils.isEmpty(endTime)){
            sql+= " and time>='"+endTime+"'";
        if (StringUtils.isEmpty(endTime)) {
            sql += " and time>='" + endTime + "'";
        }
        sql+=" GROUP BY date ";
        sql += " GROUP BY date ";
        return myJdbcTemplate.queryJson(sql.toString(),new Object[]{});
        return myJdbcTemplate.queryJson(sql.toString(), new Object[]{});
    }
    /**
     * 地区字典
     */
    public JSONArray areaDict(){
    public JSONArray areaDict() {
        String url = "/wlyygc/iot_monitoring/areaDict";
        Map<String, Object> params = new HashMap<>();
        String response = sendGet(url,params);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONArray("data");
        }
@ -636,13 +650,13 @@ public class MonitorPlatformService  {
    /**
     * 医院字典
     */
    public JSONArray hospitalDict(String town){
    public JSONArray hospitalDict(String town) {
        String url = "/wlyygc/iot_monitoring/hospitalDict";
        Map<String, Object> params = new HashMap<>();
        params.put("town",town);
        String response = sendGet(url,params);
        params.put("town", town);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONArray("data");
        }
@ -652,89 +666,89 @@ public class MonitorPlatformService  {
    /**
     * 智能设备发放
     */
    public JSONArray smartDeviceDistribution(String startTime,String endTime,
                                             String deviceType,String area,String hospital){
    public JSONArray smartDeviceDistribution(String startTime, String endTime,
                                             String deviceType, String area, String hospital) {
        String url = "/wlyygc/iot_monitoring/smartDeviceDistribution";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        String response = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
            IotSystemDictDO iotSystemDictDO = iotSystemDictDao.findByDictNameAndValueAndDel("DEVICE_TYPE","健康小屋",1);
        if (json.getInteger("status") == 200) {
            IotSystemDictDO iotSystemDictDO = iotSystemDictDao.findByDictNameAndValueAndDel("DEVICE_TYPE", "健康小屋", 1);
            JSONArray jsonArray = json.getJSONArray("data");
            String[] str =deviceType.split(",");
            String[] str = deviceType.split(",");
            List<String> list = new ArrayList<>();
            for (int i=0;i<str.length;i++){
            for (int i = 0; i < str.length; i++) {
                list.add(str[i]);
            }
            if (iotSystemDictDO!=null){
                if (!list.contains(iotSystemDictDO.getCode())){
                    for (int i=0;i<jsonArray.size();i++){
            if (iotSystemDictDO != null) {
                if (!list.contains(iotSystemDictDO.getCode())) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jo = jsonArray.getJSONObject(i);
                        String tmp = jo.getString("type");
                        if("1".equals(tmp)){
                            jo.put("typeName","血糖仪");
                        }else if("2".equals(tmp)){
                            jo.put("typeName","血压计");
                        }else if("3".equals(tmp)){
                            jo.put("typeName","智能药盒");
                        }else if("4".equals(tmp)){
                            jo.put("typeName","智能手表");
                        if ("1".equals(tmp)) {
                            jo.put("typeName", "血糖仪");
                        } else if ("2".equals(tmp)) {
                            jo.put("typeName", "血压计");
                        } else if ("3".equals(tmp)) {
                            jo.put("typeName", "智能药盒");
                        } else if ("4".equals(tmp)) {
                            jo.put("typeName", "智能手表");
                        }
                    }
                }else {
                    if (jsonArray!=null&&jsonArray.size()!=0){
                        for (int i=0;i<jsonArray.size();i++){
                } else {
                    if (jsonArray != null && jsonArray.size() != 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jo = jsonArray.getJSONObject(i);
                            String tmp = jo.getString("type");
                            if("1".equals(tmp)){
                                jo.put("typeName","血糖仪");
                            }else if("2".equals(tmp)){
                                jo.put("typeName","血压计");
                            }else if("3".equals(tmp)){
                                jo.put("typeName","智能药盒");
                            }else if("4".equals(tmp)){
                                jo.put("typeName","智能手表");
                            if ("1".equals(tmp)) {
                                jo.put("typeName", "血糖仪");
                            } else if ("2".equals(tmp)) {
                                jo.put("typeName", "血压计");
                            } else if ("3".equals(tmp)) {
                                jo.put("typeName", "智能药盒");
                            } else if ("4".equals(tmp)) {
                                jo.put("typeName", "智能手表");
                            }
                        }
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
                            JSONObject jsonObject= new JSONObject();
                            jsonObject.put("type",iotSystemDictDO.getCode());
                            jsonObject.put("typeName",iotSystemDictDO.getValue());
                            jsonObject.put("signNum",0);
                            jsonObject.put("unSignNum",0);
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", iotSystemDictDO.getCode());
                            jsonObject.put("typeName", iotSystemDictDO.getValue());
                            jsonObject.put("signNum", 0);
                            jsonObject.put("unSignNum", 0);
                            jsonArray.add(jsonObject);
                        }else {
                            Long count = iotEqtDetailService.findCountByHealthHourse(startTime,endTime,area);
                            JSONObject jsonObject= new JSONObject();
                            jsonObject.put("type",iotSystemDictDO.getCode());
                            jsonObject.put("typeName",iotSystemDictDO.getValue());
                            jsonObject.put("signNum",count);
                            jsonObject.put("unSignNum",0);
                        } else {
                            Long count = iotEqtDetailService.findCountByHealthHourse(startTime, endTime, area);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", iotSystemDictDO.getCode());
                            jsonObject.put("typeName", iotSystemDictDO.getValue());
                            jsonObject.put("signNum", count);
                            jsonObject.put("unSignNum", 0);
                            jsonArray.add(jsonObject);
                        }
                    }else {
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
                    } else {
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
                            jsonArray = new JSONArray();
                            JSONObject jsonObject= new JSONObject();
                            jsonObject.put("type",iotSystemDictDO.getCode());
                            jsonObject.put("typeName",iotSystemDictDO.getValue());
                            jsonObject.put("signNum",0);
                            jsonObject.put("unSignNum",0);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", iotSystemDictDO.getCode());
                            jsonObject.put("typeName", iotSystemDictDO.getValue());
                            jsonObject.put("signNum", 0);
                            jsonObject.put("unSignNum", 0);
                            jsonArray.add(jsonObject);
                        }else {
                            Long count = iotEqtDetailService.findCountByHealthHourse(startTime,endTime,area);
                        } else {
                            Long count = iotEqtDetailService.findCountByHealthHourse(startTime, endTime, area);
                            jsonArray = new JSONArray();
                            JSONObject jsonObject= new JSONObject();
                            jsonObject.put("type",iotSystemDictDO.getCode());
                            jsonObject.put("typeName",iotSystemDictDO.getValue());
                            jsonObject.put("signNum",count);
                            jsonObject.put("unSignNum",0);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("type", iotSystemDictDO.getCode());
                            jsonObject.put("typeName", iotSystemDictDO.getValue());
                            jsonObject.put("signNum", count);
                            jsonObject.put("unSignNum", 0);
                            jsonArray.add(jsonObject);
                        }
@ -750,20 +764,21 @@ public class MonitorPlatformService  {
    /**
     * 设备使用数据
     *
     * @param page
     * @param pageSize
     * @param deviceSn
     * @return
     */
    public JSONObject deviceUseData(Integer page,Integer pageSize,String deviceSn){
    public JSONObject deviceUseData(Integer page, Integer pageSize, String deviceSn) {
        String url = "/wlyygc/iot_monitoring/deviceUseData";
        Map<String, Object> params = new HashMap<>();
        params.put("page",page);
        params.put("pageSize",pageSize);
        params.put("deviceSn",deviceSn);
        String response = sendGet(url,params);
        params.put("page", page);
        params.put("pageSize", pageSize);
        params.put("deviceSn", deviceSn);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
@ -772,35 +787,36 @@ public class MonitorPlatformService  {
    /**
     * 设备使用数据
     *
     * @param patient
     * @param deviceSn
     * @return
     */
    public JSONObject deviceInfo(String deviceSn,String patient){
    public JSONObject deviceInfo(String deviceSn, String patient) {
        String url = "/wlyygc/iot_monitoring/deviceInfo";
        Map<String, Object> params = new HashMap<>();
        params.put("patient",patient);
        params.put("deviceSn",deviceSn);
        String response = sendGet(url,params);
        params.put("patient", patient);
        params.put("deviceSn", deviceSn);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            JSONObject tmp = json.getJSONObject("data");
            //查询物联网获取设备信息
            String sql = "SELECT d.device_sn,b.supplier_name supplierName,b.origin_place originPlace,e.product_img productImg" +
                    ",e.description  from iot_device d,iot_product_base_info b,iot_product_extend_info e" +
                    " WHERE d.device_sn = '"+deviceSn+"' and d.product_id = b.id and d.product_id = e.product_id";
            List<JSONObject> list = myJdbcTemplate.queryJson(sql,new Object[]{});
            if(list!=null&&list.size()>0){
                    " WHERE d.device_sn = '" + deviceSn + "' and d.product_id = b.id and d.product_id = e.product_id";
            List<JSONObject> list = myJdbcTemplate.queryJson(sql, new Object[]{});
            if (list != null && list.size() > 0) {
                JSONObject js = list.get(0);
                tmp.put("supplierName",js.getString("supplierName"));
                tmp.put("originPlace",js.getString("originPlace"));
                tmp.put("productImg",js.getString("productImg"));
                tmp.put("description",js.getString("description"));
            }else{
                tmp.put("supplierName","");
                tmp.put("originPlace","");
                tmp.put("productImg","");
                tmp.put("description","");
                tmp.put("supplierName", js.getString("supplierName"));
                tmp.put("originPlace", js.getString("originPlace"));
                tmp.put("productImg", js.getString("productImg"));
                tmp.put("description", js.getString("description"));
            } else {
                tmp.put("supplierName", "");
                tmp.put("originPlace", "");
                tmp.put("productImg", "");
                tmp.put("description", "");
            }
            return tmp;
        }
@ -810,18 +826,19 @@ public class MonitorPlatformService  {
    /**
     * 设备使用情况分析
     *
     * @param type
     * @param name
     * @return
     */
    public JSONObject deviceUsageAnalysis(String type,String name){
    public JSONObject deviceUsageAnalysis(String type, String name) {
        String url = "/wlyygc/iot_monitoring/deviceUsageAnalysis";
        Map<String, Object> params = new HashMap<>();
        params.put("type",type);
        params.put("name",name);
        String response = sendGet(url,params);
        params.put("type", type);
        params.put("name", name);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
@ -830,6 +847,7 @@ public class MonitorPlatformService  {
    /**
     * 85-发放率,96使用率,86绑定率,88指导率
     *
     * @param startTime
     * @param endTime
     * @param deviceType
@ -837,19 +855,19 @@ public class MonitorPlatformService  {
     * @param hospital
     * @return
     */
    public JSONObject totalRange(String startTime,String endTime,
                                 String deviceType,String area,String hospital,String quotaCode){
    public JSONObject totalRange(String startTime, String endTime,
                                 String deviceType, String area, String hospital, String quotaCode) {
        String url = "/wlyygc/iot_monitoring/totalRange";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        params.put("quotaCode",quotaCode);
        String response = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        params.put("quotaCode", quotaCode);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
@ -857,20 +875,21 @@ public class MonitorPlatformService  {
    }
    public JSONObject getTotalRange(String startTime, String endTime,
                                  String deviceType, String area, String hospital){
                                    String deviceType, String area, String hospital) {
        JSONObject result = new JSONObject();
        result.put("grant",totalRange(startTime,endTime,deviceType,area,hospital,"85"));
        result.put("binding",totalRange(startTime,endTime,deviceType,area,hospital,"86"));
        result.put("guide",totalRange(startTime,endTime,deviceType,area,hospital,"88"));
        result.put("malfunction",totalRange(startTime,endTime,deviceType,area,hospital,"0"));
        result.put("diseaseUsing",diseaseUseRange(startTime,endTime,deviceType,area,hospital));
        result.put("diseaseCover",diseaseRange(startTime,endTime,deviceType,area,hospital));
        result.put("grant", totalRange(startTime, endTime, deviceType, area, hospital, "85"));
        result.put("binding", totalRange(startTime, endTime, deviceType, area, hospital, "86"));
        result.put("guide", totalRange(startTime, endTime, deviceType, area, hospital, "88"));
        result.put("malfunction", totalRange(startTime, endTime, deviceType, area, hospital, "0"));
        result.put("diseaseUsing", diseaseUseRange(startTime, endTime, deviceType, area, hospital));
        result.put("diseaseCover", diseaseRange(startTime, endTime, deviceType, area, hospital));
        return result;
    }
    /**
     * 慢病患者设备使用率
     *
     * @param startTime
     * @param endTime
     * @param deviceType
@ -878,25 +897,27 @@ public class MonitorPlatformService  {
     * @param hospital
     * @return
     */
    public JSONObject diseaseUseRange(String startTime,String endTime,
                                      String deviceType,String area,String hospital){
    public JSONObject diseaseUseRange(String startTime, String endTime,
                                      String deviceType, String area, String hospital) {
        String url = "/wlyygc/iot_monitoring/diseaseUseRange";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        String response = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
        return new JSONObject();
    }
    /**
     * 慢病患者设备覆盖率
     *
     * @param startTime
     * @param endTime
     * @param deviceType
@ -904,18 +925,18 @@ public class MonitorPlatformService  {
     * @param hospital
     * @return
     */
    public JSONObject diseaseRange(String startTime,String endTime,
                                   String deviceType,String area,String hospital){
    public JSONObject diseaseRange(String startTime, String endTime,
                                   String deviceType, String area, String hospital) {
        String url = "/wlyygc/iot_monitoring/diseaseRange";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        String response = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
@ -924,6 +945,7 @@ public class MonitorPlatformService  {
    /**
     * 慢病患者设备覆盖率
     *
     * @param startTime
     * @param endTime
     * @param deviceType
@ -931,26 +953,28 @@ public class MonitorPlatformService  {
     * @param hospital
     * @return
     */
    public JSONObject yellowOrRedRange(String startTime,String endTime,
                                       String deviceType,String area,String hospital,Integer diseaseCondition){
    public JSONObject yellowOrRedRange(String startTime, String endTime,
                                       String deviceType, String area, String hospital, Integer diseaseCondition) {
        String url = "/wlyygc/iot_monitoring/yellowOrRedRange";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        params.put("diseaseCondition",diseaseCondition);
        String response = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        params.put("diseaseCondition", diseaseCondition);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
        return new JSONObject();
    }
    /**
     * 预警信息警报
     *
     * @param page
     * @param pageSize
     * @param startTime
@ -960,21 +984,21 @@ public class MonitorPlatformService  {
     * @param hospital
     * @return
     */
    public JSONArray warningInformationAlarm_new(Integer page,Integer pageSize,String startTime,String endTime,
                                                 String deviceType,String area,String hospital,String deviceName){
    public JSONArray warningInformationAlarm_new(Integer page, Integer pageSize, String startTime, String endTime,
                                                 String deviceType, String area, String hospital, String deviceName) {
        String url = "/wlyygc/iot_monitoring/warningInformationAlarm_new";
        Map<String, Object> params = new HashMap<>();
        params.put("page",page);
        params.put("pageSize",pageSize);
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        params.put("deviceName",deviceName);
        String response = sendGet(url,params);
        params.put("page", page);
        params.put("pageSize", pageSize);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        params.put("deviceName", deviceName);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONArray("data");
        }
@ -983,6 +1007,7 @@ public class MonitorPlatformService  {
    /**
     * 预警信息警报
     *
     * @param startTime
     * @param endTime
     * @param deviceType
@ -990,18 +1015,18 @@ public class MonitorPlatformService  {
     * @param hospital
     * @return
     */
    public JSONObject yellowAndRedRange(String startTime,String endTime,
                                        String deviceType,String area,String hospital){
    public JSONObject yellowAndRedRange(String startTime, String endTime,
                                        String deviceType, String area, String hospital) {
        String url = "/wlyygc/iot_monitoring/yellowAndRedRange";
        Map<String, Object> params = new HashMap<>();
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        params.put("deviceType",deviceType);
        params.put("area",area);
        params.put("hospital",hospital);
        String response = sendGet(url,params);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("deviceType", deviceType);
        params.put("area", area);
        params.put("hospital", hospital);
        String response = sendGet(url, params);
        JSONObject json = JSONObject.parseObject(response);
        if(json.getInteger("status")==200){
        if (json.getInteger("status") == 200) {
            return json.getJSONObject("data");
        }
        return new JSONObject();
@ -1009,29 +1034,30 @@ public class MonitorPlatformService  {
    /**
     * 数据筛选
     *
     * @param name
     * @return
     */
    public JSONArray datafiltering(String name){
    public JSONArray datafiltering(String name) {
        StringBuffer sql = new StringBuffer("SELECT d.category_code as categoryCode,d.id,d.device_sn deviceSn,p.code,p.name,d.device_name deviceName ");
        sql.append("from wlyy.wlyy_patient_device d,wlyy.wlyy_patient p  ");
        sql.append("WHERE d.`user` = p.`code` and d.del=0  ");
        if(org.apache.commons.lang3.StringUtils.isNotBlank(name)){
            sql.append("and (d.device_sn like '%"+name+"%' or p.`name` = '"+ name+"') ");
        if (org.apache.commons.lang3.StringUtils.isNotBlank(name)) {
            sql.append("and (d.device_sn like '%" + name + "%' or p.`name` = '" + name + "') ");
//            sql.append("and (d.device_sn like '%"+name+"%' or p.`name` = '"+ AesEncryptUtils.encrypt(name)+"') ");待i健康加密
        }
        List<JSONObject> jsonArray = myJdbcTemplate.queryJson(sql.toString(),new Object[]{});
        List<JSONObject> jsonArray = myJdbcTemplate.queryJson(sql.toString(), new Object[]{});
//        for (JSONObject obj:jsonArray){
//            obj.put("name",AesEncryptUtils.decrypt(obj.getString("name")));//待i健康加密
//        }
        if(jsonArray.size()==0){
            sql= new StringBuffer(" select '5' as categoryCode, id,device_code as deviceSn,null as code,null as name,'健康小屋' as deviceName from xmiot.iot_equipmet_detail where device_code like '%"+name+"%'");
            jsonArray = myJdbcTemplate.queryJson(sql.toString(),new Object[]{});
        if (jsonArray.size() == 0) {
            sql = new StringBuffer(" select '5' as categoryCode, id,device_code as deviceSn,null as code,null as name,'健康小屋' as deviceName from xmiot.iot_equipmet_detail where device_code like '%" + name + "%'");
            jsonArray = myJdbcTemplate.queryJson(sql.toString(), new Object[]{});
        }
        for (int i=0;i<jsonArray.size();i++){
            com.alibaba.fastjson.JSONObject jsonObj= jsonArray.get(i);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(jsonObj.getString("name"))){
        for (int i = 0; i < jsonArray.size(); i++) {
            com.alibaba.fastjson.JSONObject jsonObj = jsonArray.get(i);
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(jsonObj.getString("name"))) {
                jsonObj.put("name", ConcealUtil.nameOrAddrConceal(jsonObj.getString("name")));
            }
        }
@ -1043,33 +1069,33 @@ public class MonitorPlatformService  {
//        JSONObject json = JSONObject.parseObject(response);
//        if(json.getInteger("status")==200){
//            JSONArray jsonArray = json.getJSONArray("data");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject data = jsonArray.get(i);
                String deviceSn = data.getString("deviceSn");
                JSONArray jsonArray1 = new JSONArray();
                JSONObject json1 = new JSONObject();
                json1.put("andOr","and");
                json1.put("field","deviceSn");
                json1.put("condition","=");
                json1.put("value",deviceSn);
                jsonArray1.add(json1);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("filter",jsonArray1);
                jsonObject.put("page",1);
                jsonObject.put("size",5);
                String sqlLocation = "select idcard idCard,category_code categoryCode,device_sn deviceSn,location,device_time deviceTime,disease_condition diseaseCondition,\n" +
                        "create_time createTime,device_name equimentName\n" +
                        "from device.wlyy_patient_device_location where del=0 and  device_sn='"+deviceSn+"' limit 0,5 ";
                try {
                    List<Map<String,Object>> locationDataVOList = jdbcTemplate.queryForList(sqlLocation);
                    JSONObject location = JSONObject.parseObject(locationDataVOList.get(0).get("location").toString());
                    if(locationDataVOList.size()>0){
                        data.put("locationData",location);
                        data.put("diseaseCondition",Integer.parseInt(locationDataVOList.get(0).get("diseaseCondition").toString()));
                    }else{
                        data.put("locationData","{}");
                    }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject data = jsonArray.get(i);
            String deviceSn = data.getString("deviceSn");
            JSONArray jsonArray1 = new JSONArray();
            JSONObject json1 = new JSONObject();
            json1.put("andOr", "and");
            json1.put("field", "deviceSn");
            json1.put("condition", "=");
            json1.put("value", deviceSn);
            jsonArray1.add(json1);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("filter", jsonArray1);
            jsonObject.put("page", 1);
            jsonObject.put("size", 5);
            String sqlLocation = "select idcard idCard,category_code categoryCode,device_sn deviceSn,location,device_time deviceTime,disease_condition diseaseCondition,\n" +
                    "create_time createTime,device_name equimentName\n" +
                    "from device.wlyy_patient_device_location where del=0 and  device_sn='" + deviceSn + "' limit 0,5 ";
            try {
                List<Map<String, Object>> locationDataVOList = jdbcTemplate.queryForList(sqlLocation);
                JSONObject location = JSONObject.parseObject(locationDataVOList.get(0).get("location").toString());
                if (locationDataVOList.size() > 0) {
                    data.put("locationData", location);
                    data.put("diseaseCondition", Integer.parseInt(locationDataVOList.get(0).get("diseaseCondition").toString()));
                } else {
                    data.put("locationData", "{}");
                }
//                    list = iotPatientDeviceService.findDeviceLocationsBySn(jsonObject.toString());
//                    if(list.size()>0){
//                        data.put("locationData",list.get(0).getLocation());
@ -1077,37 +1103,38 @@ public class MonitorPlatformService  {
//                    }else{
//                        data.put("locationData","{}");
//                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONArray result = new JSONArray();
            result.addAll(jsonArray);
            return result;
        }
        JSONArray result = new JSONArray();
        result.addAll(jsonArray);
        return result;
    }
    /**
     * 访问i健康接口,自带登录信息
     *
     * @param url
     * @return
     */
    private String sendGet(String url,Map<String, Object> params){
    private String sendGet(String url, Map<String, Object> params) {
        String response = null;
        try{
            params.put("accesstoken",getAccessToken());
        try {
            params.put("accesstoken", getAccessToken());
            List<BasicNameValuePair> jsonParams = new ArrayList<>();
            //配置参数
            if(params!=null) {
            if (params != null) {
                for (String key : params.keySet()) {
                    if (!StringUtils.isEmpty(String.valueOf(params.get(key))) && !"null".equals( String.valueOf(params.get(key)))) {
                    if (!StringUtils.isEmpty(String.valueOf(params.get(key))) && !"null".equals(String.valueOf(params.get(key)))) {
                        jsonParams.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                    }
                }
            }
            response = httpClientUtil.get(wlyyUrl+url+"?"+ URLEncodedUtils.format(jsonParams, Consts.UTF_8),"utf-8");
        }catch (Exception e){
            response = httpClientUtil.get(wlyyUrl + url + "?" + URLEncodedUtils.format(jsonParams, Consts.UTF_8), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
@ -1115,15 +1142,16 @@ public class MonitorPlatformService  {
    /**
     * 返回accessToken
     *
     * @return
     * @throws IOException
     */
    private synchronized String getAccessToken(){
    private synchronized String getAccessToken() {
        String token = "";
        if(tokenMap.get("token")!=null){
        if (tokenMap.get("token") != null) {
            token = tokenMap.get("token");
            Long outTime = Long.valueOf(tokenMap.get("outTime"));
            if(new Date().getTime()<outTime){
            if (new Date().getTime() < outTime) {
                return token;
            }
        }
@ -1135,30 +1163,31 @@ public class MonitorPlatformService  {
            String url = "/gc/accesstoken";
            String response = HttpClientUtil.httpPost(wlyyUrl + url, params);
            JSONObject jsonObject = JSON.parseObject(response);
            if(jsonObject.getInteger("status")==10000){
            if (jsonObject.getInteger("status") == 10000) {
                String accesstoken = jsonObject.getJSONObject("result").getString("accesstoken");
                tokenMap.put("token",accesstoken);
                tokenMap.put("outTime", jsonObject.getJSONObject("result").getLong("outTime")+"");
                tokenMap.put("token", accesstoken);
                tokenMap.put("outTime", jsonObject.getJSONObject("result").getLong("outTime") + "");
                return accesstoken;
            }
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 返回健康小屋详情信息
     */
    public JSONObject getEquipmentDetail(String deviceSn){
    public JSONObject getEquipmentDetail(String deviceSn) {
        try {
            IotEquipmentDetailDO iotEquipmentDetailDO= iotEquipmentDetailDao.findByDeviceCode(deviceSn);
            JSONObject obj = (JSONObject)JSONObject.toJSON(iotEquipmentDetailDO);
            if(iotEquipmentDetailDO!=null){
                obj.put("deviceSn",iotEquipmentDetailDO.getDeviceCode());
            IotEquipmentDetailDO iotEquipmentDetailDO = iotEquipmentDetailDao.findByDeviceCode(deviceSn);
            JSONObject obj = (JSONObject) JSONObject.toJSON(iotEquipmentDetailDO);
            if (iotEquipmentDetailDO != null) {
                obj.put("deviceSn", iotEquipmentDetailDO.getDeviceCode());
            }
            return obj;
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
@ -1167,9 +1196,9 @@ public class MonitorPlatformService  {
    /**
     * 获取设备品牌以及商家品牌排行
     */
    public JSONObject getBrandsAndManufacturer(){
    public JSONObject getBrandsAndManufacturer() {
        try {
            String sql  = "select count(DISTINCT A.device_name) as total,A.device_name,A.manufacturer from (\n" +
            String sql = "select count(DISTINCT A.device_name) as total,A.device_name,A.manufacturer from (\n" +
                    "select pd.device_name,wd.manufacturer from wlyy.wlyy_patient_device pd,device.wlyy_devices wd\n" +
                    "where pd.device_sn = wd.device_code and pd.del=0 \n" +
                    "and wd.manufacturer_code is not null and wd.manufacturer_code <>'' and pd.device_name<>'血压计-null' and pd.device_name<>'血糖仪-自助体检一体机'  \n" +
@ -1179,10 +1208,10 @@ public class MonitorPlatformService  {
                    ")A\n" +
                    "GROUP BY A.manufacturer\n" +
                    "ORDER BY total desc";
            List<Map<String,Object>>Manufacturers = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> Manufacturers = jdbcTemplate.queryForList(sql);
            JSONObject result = new JSONObject();
            JSONArray arr = JSONArray.parseArray(JSON.toJSONString(Manufacturers));
            result.put("Manufacturers",arr);
            result.put("Manufacturers", arr);
            sql = "select count(DISTINCT A.device_name)from (\n" +
                    "select pd.device_name from wlyy.wlyy_patient_device pd,device.wlyy_devices wd\n" +
                    "where pd.device_sn = wd.device_code and pd.del=0 \n" +
@ -1191,13 +1220,13 @@ public class MonitorPlatformService  {
                    "UNION\n" +
                    "select case device_name when '自助体检一体机' then '健康小屋'  else device_name  end AS device_name from xmiot.iot_equipmet_detail group BY manufacturer_code,device_name\n" +
                    ")A";
            Integer BrandsCount = jdbcTemplate.queryForObject(sql,Integer.class);
            Integer BrandsCount = jdbcTemplate.queryForObject(sql, Integer.class);
            result.put("Brands",BrandsCount);
            result.put("manufacturerCount",arr.size());
            result.put("Brands", BrandsCount);
            result.put("manufacturerCount", arr.size());
            return result;
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
@ -1205,149 +1234,214 @@ public class MonitorPlatformService  {
    /**
     * 谁设备库存、使用中、总备案、物联率、失联率
     *
     * @param deviceType
     * @param deviceName
     * @param showLevel
     * @return
     */
    public JSONObject getEquipmentStatistics(String deviceType,String deviceName,String showLevel){
    public JSONObject getEquipmentStatistics(String deviceType, String deviceName, String showLevel) {
        try {
            WlyyIotTzDict dictObj =wlyyIotTzDictDao.findByCodeAndDel("IOT_LOST_DAY",1);
            WlyyIotTzDict dictObj = wlyyIotTzDictDao.findByCodeAndDel("IOT_LOST_DAY", 1);
            String lost_day = dictObj.getValue();
            JSONObject result = new JSONObject();
            JSONArray arrTmp = new JSONArray();
            result.put("deviceInfo",arrTmp);
            result.put("iotCount",0);
            result.put("grantCount",0);
            result.put("lostContact",0);
            if (deviceType.contains("1")||deviceType.contains("2")) {
            result.put("deviceInfo", arrTmp);
            result.put("iotCount", 0);
            result.put("grantCount", 0);
            result.put("lostContact", 0);
            List<String> deviceTypeTmp = Arrays.asList(deviceType.split(",").clone());
            if (deviceTypeTmp.contains("1") || deviceTypeTmp.contains("2")) {
                StringBuffer sql = new StringBuffer("SELECT a.category_code type,a.device_name,a.c as 'using',b.c-a.c as 'stock',b.c as 'total' from ( ");
                StringBuffer sqlCondition = new StringBuffer();
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)){
                    sqlCondition.append("and d.device_name in ('").append(deviceName.replace(",","','")).append("') ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)) {
                    sqlCondition.append("and d.device_name in ('").append(deviceName.replace(",", "','")).append("') ");
                }
                sql.append("SELECT d.category_code,d.device_name, COUNT(*) c from wlyy.wlyy_patient_device d,wlyy.wlyy_sign_family f WHERE f.`status`>0 and d.del=0 and f.patient = d.`user` "+sqlCondition+" ");
                if ("0".equals(showLevel)){//组合一体机(5健康小屋,取自物联网),单体征测量仪(2血压计、1血糖仪)
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                        sql.append("and d.category_code in ('").append(deviceType.replace(",","','")).append("'))a, ");
                sql.append("SELECT d.category_code,d.device_name, COUNT(*) c from wlyy.wlyy_patient_device d,wlyy.wlyy_sign_family f WHERE f.`status`>0 and d.del=0 and f.patient = d.`user` " + sqlCondition + " ");
                if ("0".equals(showLevel)) {//组合一体机(5健康小屋,取自物联网),单体征测量仪(2血压计、1血糖仪)
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                        sql.append("and d.category_code in ('").append(deviceType.replace(",", "','")).append("'))a, ");
                    }
                    sql.append("(SELECT d.category_code,d.device_name,COUNT(*) c from wlyy.wlyy_patient_device d where 1=1 "+sqlCondition+" ");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                        sql.append("and d.category_code in ('").append(deviceType.replace(",","','")).append("'))b ");
                    sql.append("(SELECT d.category_code,d.device_name,COUNT(*) c from wlyy.wlyy_patient_device d where 1=1 " + sqlCondition + " ");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                        sql.append("and d.category_code in ('").append(deviceType.replace(",", "','")).append("'))b ");
                    }
                }
                else if("1".equals(showLevel)){ //血压计,血糖仪。。。
                } else if ("1".equals(showLevel)) { //血压计,血糖仪。。。
                    sql.append("GROUP BY d.category_code )a, ");
                    sql.append("(SELECT d.category_code,d.device_name,COUNT(*) c from wlyy.wlyy_patient_device d where 1=1 "+sqlCondition+" ");
                    sql.append("(SELECT d.category_code,d.device_name,COUNT(*) c from wlyy.wlyy_patient_device d where 1=1 " + sqlCondition + " ");
                    sql.append("GROUP BY d.category_code )b ");
                    sql.append("WHERE a.category_code = b.category_code ");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                        sql.append("and a.category_code in ('").append(deviceType.replace(",","','")).append("') ");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                        sql.append("and a.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
                    }
                }else if ("2".equals(showLevel)){//XX血压计1,XX血压计1
                } else if ("2".equals(showLevel)) {//XX血压计1,XX血压计1
                    sql.append("GROUP BY d.category_code,d.device_name) a, ");
                    sql.append("(SELECT d.category_code,d.device_name,COUNT(*) c from wlyy.wlyy_patient_device d where 1=1 "+sqlCondition+" ");
                    sql.append("(SELECT d.category_code,d.device_name,COUNT(*) c from wlyy.wlyy_patient_device d where 1=1 " + sqlCondition + " ");
                    sql.append("GROUP BY d.category_code,d.device_name) b ");
                    sql.append("WHERE a.category_code = b.category_code and a.device_name = b.device_name ");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                        sql.append("and a.category_code in ('").append(deviceType.replace(",","','")).append("') ");
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                        sql.append("and a.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
                    }
                }
                List<Map<String,Object>> sqlResult = jdbcTemplate.queryForList(sql.toString());
                List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sql.toString());
                JSONArray arr = JSONArray.parseArray(JSON.toJSONString(sqlResult));
                for(int i=0;i<arr.size();i++){
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    if ("0".equals(showLevel)){
                        obj.put("device_name","单体征测量仪");
                        obj.put("Subdivision",true);//是否可查看下一层次
                    if ("0".equals(showLevel)) {
                        obj.put("device_name", "单体征测量仪");
                        obj.put("Subdivision", true);//是否可查看下一层次
                        StringBuffer sqlTmp = new StringBuffer("select code from xmiot.iot_system_dict where dict_name='DEVICE_TYPE' and `code` in ('");
                        sqlTmp.append(deviceType.replace(",","','")).append("') ");
                        sqlTmp.append(deviceType.replace(",", "','")).append("') ");
                        sqlTmp.append("and del=1 and parent_code \n" +
                                "in(select id from xmiot.iot_system_dict where dict_name='DEVICE' and `value`='单体征测量仪' and del=1)");
                        List<String> list = jdbcTemplate.queryForList(sqlTmp.toString(),String.class);
                        List<String> list = jdbcTemplate.queryForList(sqlTmp.toString(), String.class);
                        sqlTmp = new StringBuffer();
                        for (String s:list){
                            sqlTmp.append(","+s);
                        for (String s : list) {
                            sqlTmp.append("," + s);
                        }
                        if (list.size()!=0){
                        if (list.size() != 0) {
                            sqlTmp.deleteCharAt(0);
                        }
                        obj.put("type",sqlTmp.toString());
                    }
                    else if("1".equals(showLevel)){
                        obj.put("type", sqlTmp.toString());
                    } else if ("1".equals(showLevel)) {
                        String temp = obj.getString("type");
                        if("1".equals(temp)){
                            obj.put("device_name","血糖仪");
                        }else if("2".equals(temp)){
                            obj.put("device_name","血压计");
                        if ("1".equals(temp)) {
                            obj.put("device_name", "血糖仪");
                        } else if ("2".equals(temp)) {
                            obj.put("device_name", "血压计");
                        }
                        obj.put("Subdivision",true);
                        obj.put("Subdivision", true);
                    } else {
                        obj.put("Subdivision", false);
                    }
                    else{
                        obj.put("Subdivision",false);
                    }
                    obj.put("showLevel",Integer.parseInt(showLevel));
                    obj.put("showLevel", Integer.parseInt(showLevel));
                }
                result.put("deviceInfo",arr);//设备信息统计
                result.put("deviceInfo", arr);//设备信息统计
                //统计物联率设备,失联设备
                sql = new StringBuffer("select count(*) from wlyy.wlyy_patient_device d ,wlyy.wlyy_sign_family f   ");
                sql.append("where  f.`status`>0 and d.del=0 and f.patient = d.`user` and d.device_sn in(select DISTINCT device_sn from device.wlyy_patient_health_index where device_sn<>'') "+sqlCondition+" ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                    sql.append("and d.category_code in ('").append(deviceType.replace(",","','")).append("') ");
                sql.append("where  f.`status`>0 and d.del=0 and f.patient = d.`user` and d.device_sn in(select DISTINCT device_sn from device.wlyy_patient_health_index where device_sn<>'') " + sqlCondition + " ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                    sql.append("and d.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
                }
                Integer iotCount = jdbcTemplate.queryForObject(sql.toString(),Integer.class);//物联设备数量
                result.put("iotCount",iotCount);
                Integer iotCount = jdbcTemplate.queryForObject(sql.toString(), Integer.class);//物联设备数量
                result.put("iotCount", iotCount);
                sql = new StringBuffer("select count(*) from wlyy.wlyy_patient_device d ,wlyy.wlyy_sign_family f WHERE f.`status`>0 and d.del=0 and f.patient = d.`user` "+sqlCondition+" ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                    sql.append("and d.category_code in ('").append(deviceType.replace(",","','")).append("') ");
                sql = new StringBuffer("select count(*) from wlyy.wlyy_patient_device d ,wlyy.wlyy_sign_family f WHERE f.`status`>0 and d.del=0 and f.patient = d.`user` " + sqlCondition + " ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                    sql.append("and d.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
                }
                Integer grantCount = jdbcTemplate.queryForObject(sql.toString(),Integer.class);//设备发放总数
                result.put("grantCount",grantCount);
                Integer grantCount = jdbcTemplate.queryForObject(sql.toString(), Integer.class);//设备发放总数
                result.put("grantCount", grantCount);
                //失联设备(一周未上传当作失联)
                sql.append("and d.device_sn not in (select device_sn from ( select device_sn,MAX(record_date) record_date from device.wlyy_patient_health_index where device_sn<>'' GROUP BY device_sn)a ");
                sql.append("where TIMESTAMPDIFF(DAY,record_date,NOW()) <= "+lost_day+")");
                Integer lostContact = jdbcTemplate.queryForObject(sql.toString(),Integer.class);
                result.put("lostContact",lostContact);
                sql.append("where TIMESTAMPDIFF(DAY,record_date,NOW()) <= " + lost_day + ")");
                Integer lostContact = jdbcTemplate.queryForObject(sql.toString(), Integer.class);
                result.put("lostContact", lostContact);
            }
            //deviceType包含小屋且设备名称为空||deviceType包含小屋且设备名称为健康小屋。
          if ((deviceType.contains("5")&&org.apache.commons.lang3.StringUtils.isBlank(deviceName))||(deviceType.contains("5")&&org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName)&&deviceName.contains("健康小屋"))){
            if ((deviceTypeTmp.contains("5") && org.apache.commons.lang3.StringUtils.isBlank(deviceName))
                    || (deviceTypeTmp.contains("5") && org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName) && deviceName.contains("健康小屋"))
                    || (deviceTypeTmp.contains("22") && org.apache.commons.lang3.StringUtils.isBlank(deviceName))
                    || (deviceTypeTmp.contains("22") && org.apache.commons.lang3.StringUtils.isNoneBlank(deviceName) && deviceName.contains("智慧药房"))
            ) {
                String sql = "select COUNT(*) from xmiot.iot_equipmet_detail";
                Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
                /*取到智慧药房*/
                Map<String, Object> medicinecabinetCount = getMedicinecabinetCount();
                //智慧药房
                int ygtotal = Integer.parseInt(medicinecabinetCount.get("total").toString());
                int ygusing = Integer.parseInt(medicinecabinetCount.get("using").toString());
                int ygstock = Integer.parseInt(medicinecabinetCount.get("stock").toString());
                Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
                JSONObject tmp = new JSONObject();
                tmp.put("using",count);
                tmp.put("total",count);
                tmp.put("type","5");
                tmp.put("stock",0);
                if("0".equals(showLevel)){
                    tmp.put("device_name","组合一体机");
                    tmp.put("Subdivision",true);
                }else{
                    tmp.put("device_name","健康小屋");
                    tmp.put("Subdivision",false);
                if ("0".equals(showLevel)) {
                    String typeTmp = "";
                    Integer usingTmp = 0;
                    Integer totalTmp = 0;
                    Integer stockTmp = 0;
                    if (deviceTypeTmp.contains("5")&&deviceName.contains("健康小屋")){
                        if (org.apache.commons.lang3.StringUtils.isBlank(typeTmp)){
                            typeTmp+="5";
                        }else {
                            typeTmp+=",5";
                        }
                        usingTmp +=count;
                        totalTmp +=count;
                    }
                    if (deviceTypeTmp.contains("22")&&deviceName.contains("智慧药房")){
                        if (org.apache.commons.lang3.StringUtils.isBlank(typeTmp)){
                            typeTmp+="22";
                        }else {
                            typeTmp+=",22";
                        }
                        usingTmp +=ygusing;
                        totalTmp +=ygtotal;
                        stockTmp +=ygstock;
                    }
                    tmp.put("device_name", "组合一体机");
                    tmp.put("Subdivision", true);
                    tmp.put("using", usingTmp);
                    tmp.put("total", totalTmp);
                    tmp.put("type", typeTmp);
                    tmp.put("stock", stockTmp);
                    result.getJSONArray("deviceInfo").add(tmp);
                    tmp.put("showLevel", Integer.parseInt(showLevel));
                } else {
                    /*string用,分割*/
                    String[] arrays = deviceType.split(",");
                    for (String string : arrays) {
                        if ("5".equals(string)&&deviceName.contains("健康小屋")) {
                            /*健康小屋*/
                            tmp.put("device_name", "健康小屋");
                            tmp.put("Subdivision", false);
                            tmp.put("total", count);
                            tmp.put("using", count);
                            tmp.put("stock", 0);
                            tmp.put("type", 5);
                            tmp.put("showLevel", Integer.parseInt(showLevel));
                            result.getJSONArray("deviceInfo").add(tmp);
                        }
                        if ("22".equals(string)&&deviceName.contains("智慧药房")) {
                            //智慧药房
                            medicinecabinetCount.put("Subdivision", false);
                            medicinecabinetCount.put("showLevel", Integer.parseInt(showLevel));
                            medicinecabinetCount.put("type", 22);
                            result.getJSONArray("deviceInfo").add(medicinecabinetCount);
                        }
                    }
                }
                if (deviceTypeTmp.contains("5")&&deviceName.contains("健康小屋")){
                    result.put("grantCount", result.getInteger("grantCount") +count);
                    //统计健康小屋数据/ 小屋全部统计为正常使用
                    sql = "select count(*) from xmiot.iot_equipmet_detail where device_code in (select DISTINCT sn device_model from xmiot.wlyy_iot_m)";
                    count = jdbcTemplate.queryForObject(sql, Integer.class);
                    result.put("iotCount", result.getInteger("iotCount") + count);//小屋物联
                }
                tmp.put("showLevel",Integer.parseInt(showLevel));
                result.getJSONArray("deviceInfo").add(tmp);
                result.put("grantCount",result.getInteger("grantCount")+count);
                //统计健康小屋数据/ 小屋全部统计为正常使用
                sql ="select count(*) from xmiot.iot_equipmet_detail where device_code in (select DISTINCT sn device_model from xmiot.wlyy_iot_m)";
                count = jdbcTemplate.queryForObject(sql,Integer.class);
                result.put("iotCount",result.getInteger("iotCount")+count);//小屋物联
                if (deviceTypeTmp.contains("22")&&deviceName.contains("智慧药房")){
                    result.put("grantCount", result.getInteger("grantCount") +ygtotal);
                }
            }
            arrTmp = result.getJSONArray("deviceInfo");
            for (int i=0;i<arrTmp.size();i++){
            for (int i = 0; i < arrTmp.size(); i++) {
                JSONObject tmp = arrTmp.getJSONObject(i);
                if (tmp.getInteger("total")==0){
                if (tmp.getInteger("total") == 0) {
                    arrTmp.remove(tmp);
                }
            }
            result.put("iotRangeString",result.getInteger("iotCount")+"/"+result.getInteger("grantCount"));
            result.put("lostRangeString",result.getInteger("lostContact")+"/"+result.getInteger("grantCount"));
            result.put("iotRange",getRange(result.getInteger("iotCount"),result.getInteger("grantCount"),2));
            result.put("lostRange",getRange(result.getInteger("lostContact"),result.getInteger("grantCount"),2));
            result.put("iotRangeString", result.getInteger("iotCount") + "/" + result.getInteger("grantCount"));
            result.put("lostRangeString", result.getInteger("lostContact") + "/" + result.getInteger("grantCount"));
            result.put("iotRange", getRange(result.getInteger("iotCount"), result.getInteger("grantCount"), 2));
            result.put("lostRange", getRange(result.getInteger("lostContact"), result.getInteger("grantCount"), 2));
            return result;
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
@ -1367,6 +1461,7 @@ public class MonitorPlatformService  {
    /**
     * 获取物联率与失联率
     *
     * @param startTime
     * @param endTime
     * @param deviceType
@ -1375,178 +1470,181 @@ public class MonitorPlatformService  {
     * @param quotaCode
     * @return
     */
    public JSONObject iotAndLostRange(String startTime,String endTime,
                                      String deviceType,String area,String hospital,String quotaCode){
        WlyyIotTzDict dictObj =wlyyIotTzDictDao.findByCodeAndDel("IOT_LOST_DAY",1);
    public JSONObject iotAndLostRange(String startTime, String endTime,
                                      String deviceType, String area, String hospital, String quotaCode) {
        WlyyIotTzDict dictObj = wlyyIotTzDictDao.findByCodeAndDel("IOT_LOST_DAY", 1);
        String lost_day = dictObj.getValue();
        JSONObject result = new JSONObject();
        StringBuffer sql = new StringBuffer("select count(*) from wlyy.wlyy_patient_device d ,wlyy.wlyy_sign_family f WHERE f.`status`>0 and d.del=0 and f.patient = d.`user`  ");
        StringBuffer sqlCondition = new StringBuffer(" ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
            sqlCondition.append(" and f.hospital in (SELECT dh.code from wlyy.dm_hospital dh where dh.town ='"+area+"' and dh.del =1 )  ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
            sqlCondition.append(" and f.hospital in (SELECT dh.code from wlyy.dm_hospital dh where dh.town ='" + area + "' and dh.del =1 )  ");
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
            sqlCondition.append(" and d.hospital ="+hospital+"  ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
            sqlCondition.append(" and d.hospital =" + hospital + "  ");
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
            sqlCondition.append("and d.category_code in ('").append(deviceType.replace(",","','")).append("') ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
            sqlCondition.append("and d.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
        }
        sql.append(sqlCondition);
        Integer grantCount = jdbcTemplate.queryForObject(sql.toString(),Integer.class);//单体征设备发放总数
        result.put("totalAll",grantCount);
        Integer total=0;
        if("1".equals(quotaCode)){
        Integer grantCount = jdbcTemplate.queryForObject(sql.toString(), Integer.class);//单体征设备发放总数
        result.put("totalAll", grantCount);
        Integer total = 0;
        if ("1".equals(quotaCode)) {
            //物联
            sql = new StringBuffer("select count(*) from wlyy.wlyy_patient_device d ,wlyy.wlyy_sign_family f ");
            sqlCondition = new StringBuffer(" where 1=1 ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
                sql.append("LEFT JOIN wlyy.dm_hospital dh on f.hospital = dh.`code` ");
                sqlCondition.append("and dh.town='"+area+"' ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
                    sqlCondition.append("and dh.code='"+hospital+"' ");
                sqlCondition.append("and dh.town='" + area + "' ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
                    sqlCondition.append("and dh.code='" + hospital + "' ");
                }
            }
            sqlCondition.append("and  f.`status`>0 and d.del=0 and f.patient = d.`user` and d.device_sn in(select DISTINCT device_sn from device.wlyy_patient_health_index where device_sn<>''  ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime)&&org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)){
                sqlCondition.append("and record_date >='"+startTime+" 00:00:00' and record_date<='"+endTime+" 23:59:59'  ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime) && org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)) {
                sqlCondition.append("and record_date >='" + startTime + " 00:00:00' and record_date<='" + endTime + " 23:59:59'  ");
            }
            sqlCondition.append(" ) and d.category_code in ('").append(deviceType.replace(",","','")).append("') ");
            sqlCondition.append(" ) and d.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
            sql.append(sqlCondition);
            total=jdbcTemplate.queryForObject(sql.toString(),Integer.class);
            total = jdbcTemplate.queryForObject(sql.toString(), Integer.class);
        }
        //失联
        if("2".equals(quotaCode)){
        if ("2".equals(quotaCode)) {
            sql = new StringBuffer("SELECT count(*) from wlyy.wlyy_patient_device d,wlyy.wlyy_sign_family f ");
            sqlCondition = new StringBuffer(" where 1=1 ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
                sql.append("LEFT JOIN wlyy.dm_hospital dh on f.hospital = dh.`code` ");
                sqlCondition.append("and dh.town='"+area+"' ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
                    sqlCondition.append("and dh.code='"+hospital+"' ");
                sqlCondition.append("and dh.town='" + area + "' ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
                    sqlCondition.append("and dh.code='" + hospital + "' ");
                }
            }
            sqlCondition.append("and f.`status`>0 and d.del=0 and f.patient = d.`user` ");
            sqlCondition.append("  and d.category_code in ('").append(deviceType.replace(",","','")).append("') ");
            sqlCondition.append("  and d.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
            sqlCondition.append("and d.device_sn not in (select DISTINCT device_sn from device.wlyy_patient_health_index where device_sn<>''  ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime)&&org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)){
                sqlCondition.append("and record_date >='"+startTime+" 00:00:00' and record_date<='"+endTime+" 23:59:59'  ");
            }
            else{
                sqlCondition.append("and  TIMESTAMPDIFF(DAY,record_date,NOW()) <= "+lost_day+"  ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime) && org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)) {
                sqlCondition.append("and record_date >='" + startTime + " 00:00:00' and record_date<='" + endTime + " 23:59:59'  ");
            } else {
                sqlCondition.append("and  TIMESTAMPDIFF(DAY,record_date,NOW()) <= " + lost_day + "  ");
            }
            sqlCondition.append(")");
            sql.append(sqlCondition);
            total=jdbcTemplate.queryForObject(sql.toString(),Integer.class);
            total = jdbcTemplate.queryForObject(sql.toString(), Integer.class);
        }
        Integer count =0;
        if ((org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)&&deviceType.contains("5"))||org.apache.commons.lang3.StringUtils.isBlank(deviceType)){
        Integer count = 0;
        if ((org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType) && deviceType.contains("5")) || org.apache.commons.lang3.StringUtils.isBlank(deviceType)) {
            String sqll = "select COUNT(*) from xmiot.iot_equipmet_detail";
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
                sqll+=" where belong_are_code='"+area+"' ";
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
                sqll += " where belong_are_code='" + area + "' ";
            }
             count = jdbcTemplate.queryForObject(sqll,Integer.class);
            result.put("totalAll",grantCount+count);
            count =0;
            if("1".equals(quotaCode)){//小屋物联率
                sql= new StringBuffer("select count(*) from xmiot.iot_equipmet_detail ");
            count = jdbcTemplate.queryForObject(sqll, Integer.class);
            result.put("totalAll", grantCount + count);
            count = 0;
            if ("1".equals(quotaCode)) {//小屋物联率
                sql = new StringBuffer("select count(*) from xmiot.iot_equipmet_detail ");
                sqlCondition = new StringBuffer(" where 1=1 ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
                    sqlCondition.append("and belong_are_code='"+area+"' ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
                    sqlCondition.append("and belong_are_code='" + area + "' ");
                }
                sqlCondition.append("and device_code in (select DISTINCT sn device_model from xmiot.wlyy_iot_m where 1=1 ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime)&&org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)){
                    sqlCondition.append("and create_time >='"+startTime+" 00:00:00' and create_time<='"+endTime+" 23:59:59'  ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime) && org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)) {
                    sqlCondition.append("and create_time >='" + startTime + " 00:00:00' and create_time<='" + endTime + " 23:59:59'  ");
                }
                sql.append(sqlCondition+")");
                count = jdbcTemplate.queryForObject(sql.toString(),Integer.class);
                sql.append(sqlCondition + ")");
                count = jdbcTemplate.queryForObject(sql.toString(), Integer.class);
            }
            if("2".equals(quotaCode)){//小屋失联数0
                count=0;
            if ("2".equals(quotaCode)) {//小屋失联数0
                count = 0;
            }
            result.put("total",total+count);//互联设备\失联设备数量
        }
        else{
            result.put("total",total+count);//互联设备\失联设备数量
            result.put("total", total + count);//互联设备\失联设备数量
        } else {
            result.put("total", total + count);//互联设备\失联设备数量
        }
        DecimalFormat df = new DecimalFormat("0.00");
        if (result.getInteger("totalAll") > 0) {
            result.put("totalRange", df.format(result.getDouble("total") > 0.0 ? ((result.getDouble("total")) / (result.getInteger("totalAll") * 1.0000) * 100) : 0.0) );
            result.put("totalRange", df.format(result.getDouble("total") > 0.0 ? ((result.getDouble("total")) / (result.getInteger("totalAll") * 1.0000) * 100) : 0.0));
        } else {
            result.put("totalRange", 0.0 );
            result.put("totalRange", 0.0);
        }
        return result;
    }
    /**
     * 获取设备品牌详细
     *
     * @param deviceType
     * @return
     */
    public JSONObject getBrandsDetail(String deviceType){
    public JSONObject getBrandsDetail(String deviceType) {
        try {
            StringBuffer sql = new StringBuffer("select DISTINCT A.device_name from (\n" +
                    "select pd.device_name from wlyy.wlyy_patient_device pd,device.wlyy_devices wd\n" +
                    "where pd.device_sn = wd.device_code and pd.del=0 \n" +
                    "and wd.manufacturer_code is not null and wd.manufacturer_code <>'' " +
                    "and pd.device_name<>'血压计-null' and pd.device_name<>'血糖仪-自助体检一体机' ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)){
                sql.append("and pd.category_code in ('").append(deviceType.replace(",","','")).append("') ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
                sql.append("and pd.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
            }
            sql.append("GROUP BY wd.manufacturer_code,pd.device_name ");
            if ((org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)&&deviceType.contains("5"))||org.apache.commons.lang3.StringUtils.isBlank(deviceType)){
                sql.append("UNION select case device_name when '自助体检一体机' then '健康小屋'  else device_name  end AS device_name from xmiot.iot_equipmet_detail group BY manufacturer_code,device_name");
            if ((org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType) && deviceType.contains("5")) || org.apache.commons.lang3.StringUtils.isBlank(deviceType)) {
                sql.append(" UNION select case device_name when '自助体检一体机' then '健康小屋'  else device_name  end AS device_name from xmiot.iot_equipmet_detail group BY manufacturer_code,device_name");
            }
            if ((org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType) && deviceType.contains("22")) || org.apache.commons.lang3.StringUtils.isBlank(deviceType)) {
                sql.append(" UNION select case device_name when '自助体检一体机' then '智慧药房'  else device_name  end AS device_name from xmiot.iot_equipmet_detail group BY manufacturer_code,device_name");
            }
            sql.append(")A");
            List<String> list = jdbcTemplate.queryForList(sql.toString(),String.class);
            List<String> list = jdbcTemplate.queryForList(sql.toString(), String.class);
            List<String> reList = new ArrayList<>();
            int i=0;
            for(String tmp:list){
                if ("三诺血糖仪".equals(tmp)||"血糖仪-三诺亲智".equals(tmp)||"三诺亲智".equals(tmp)||"健康之路亲智血糖仪".equals(tmp)||"血糖仪".equals(tmp)||"血糖仪-健康之路亲智血糖仪".equals(tmp)){
                    i=1;
            int i = 0;
            for (String tmp : list) {
                if ("三诺血糖仪".equals(tmp) || "血糖仪-三诺亲智".equals(tmp) || "三诺亲智".equals(tmp) || "健康之路亲智血糖仪".equals(tmp) || "血糖仪".equals(tmp) || "血糖仪-健康之路亲智血糖仪".equals(tmp)) {
                    i = 1;
                    continue;
                }
                reList.add(tmp);
            }
            if (i==1){//上面去除的元素统一返回为三诺血糖仪
            if (i == 1) {//上面去除的元素统一返回为三诺血糖仪
                reList.add("三诺血糖仪");
            }
            JSONObject result = new JSONObject();
            result.put("brands",reList);
            result.put("brands", reList);
            return result;
        }catch (Exception e){
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public JSONObject getDeviceData(){
    public JSONObject getDeviceData() {
        JSONObject object = new JSONObject();
        //血糖仪数量
        String bloodGlucosemeterCount = "SELECT COUNT(1) FROM wlyy.wlyy_patient_device WHERE category_code = 1 AND del = 0";
        //血压计数量
        String sphygmomanometerCount = "SELECT COUNT(1) FROM wlyy.wlyy_patient_device WHERE category_code = 2 AND del = 0";
        Integer aa = jdbcTemplate.queryForObject(bloodGlucosemeterCount,Integer.class);
        Integer bb = jdbcTemplate.queryForObject(sphygmomanometerCount,Integer.class);
        object.put("homeHealthEquipment",aa+bb);
        Integer aa = jdbcTemplate.queryForObject(bloodGlucosemeterCount, Integer.class);
        Integer bb = jdbcTemplate.queryForObject(sphygmomanometerCount, Integer.class);
        object.put("homeHealthEquipment", aa + bb);
        //血糖仪 血压计 体征数据
        String physicalSignData = "SELECT count(1) from wlyy.wlyy_sign_family s,wlyy.wlyy_patient_device d, device.wlyy_patient_health_index p WHERE s.`status`>0 \n" +
                "and d.`user` = s.patient and p.`user`=d.`user` and p.del=1 and (p.type=1 or p.type=2)";
        Integer cc = jdbcTemplate.queryForObject(physicalSignData,Integer.class);
        object.put("homePhysicalSignData",cc);
        Integer cc = jdbcTemplate.queryForObject(physicalSignData, Integer.class);
        object.put("homePhysicalSignData", cc);
        //异常数据
        String abnormalPhysicalSignData = "SELECT count(1) from wlyy.wlyy_sign_family s,wlyy.wlyy_patient_device d,device.wlyy_patient_health_index p WHERE s.`status`>0 \n" +
                "and d.`user` = s.patient and p.`user`=d.`user` and p.`status`=1 and p.del=1 and (p.type=1 or p.type=2)";
        Integer dd = jdbcTemplate.queryForObject(abnormalPhysicalSignData,Integer.class);
        object.put("homeAbnormalSignData",dd);
        Integer dd = jdbcTemplate.queryForObject(abnormalPhysicalSignData, Integer.class);
        object.put("homeAbnormalSignData", dd);
        //小屋数量
        String cabinCount = "SELECT COUNT(1) FROM xmiot.iot_equipmet_detail";
        Integer ee = jdbcTemplate.queryForObject(cabinCount,Integer.class);
        object.put("medicalInstitutionIquipment",ee);
        Integer ee = jdbcTemplate.queryForObject(cabinCount, Integer.class);
        object.put("medicalInstitutionIquipment", ee);
        //小屋体征数据
        String cabinSignData = "SELECT count(1) FROM xmiot.wlyy_iot_m ";
        Integer ff = jdbcTemplate.queryForObject(cabinSignData,Integer.class);
        object.put("medicalPhysicalSignData",ff);
        Integer ff = jdbcTemplate.queryForObject(cabinSignData, Integer.class);
        object.put("medicalPhysicalSignData", ff);
        //小屋异常体征数据
        String abnormalSignDataOfCabin = "select count(1)\n" +
                "from  xmiot.wlyy_iot_d d \n" +
@ -1555,136 +1653,157 @@ public class MonitorPlatformService  {
                "(d.`code`='HighPressure' and (d.`value` not BETWEEN 90.0 and 140))\n" +
                "or (d.`code`='LowPressure' and (d.`value` not BETWEEN 60.0 and 90))\n" +
                ");";
        Integer gg = jdbcTemplate.queryForObject(abnormalSignDataOfCabin,Integer.class);
        object.put("medicalAbnormalSignData",gg);
        Integer gg = jdbcTemplate.queryForObject(abnormalSignDataOfCabin, Integer.class);
        object.put("medicalAbnormalSignData", gg);
        return object;
    }
    public JSONArray getSearchTags(){
    public JSONArray getSearchTags() {
        String sql = "select id,`value` from xmiot.iot_system_dict where dict_name='DEVICE' and (value='组合一体机' or value ='单体征测量仪') and del=1;";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        JSONArray result = new JSONArray();
        for (Map<String,Object> map :list){
            sql="select `code`,`value` from xmiot.iot_system_dict where dict_name='DEVICE_TYPE' and del=1 and code!=10 and code!=11  and parent_code='"+map.get("id").toString()+"'";
        for (Map<String, Object> map : list) {
            sql = "select `code`,`value` from xmiot.iot_system_dict where dict_name='DEVICE_TYPE' and del=1 and code!=10 and code!=11  and parent_code='" + map.get("id").toString() + "'";
            StringBuffer buffer = new StringBuffer();
            List<Map<String,Object>> reList = jdbcTemplate.queryForList(sql);
            for (Map<String,Object> reMap:reList){
            List<Map<String, Object>> reList = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> reMap : reList) {
                JSONObject tmp = new JSONObject();
                tmp.put("name",reMap.get("value").toString());
                tmp.put("code",reMap.get("code").toString());
                buffer.append(","+reMap.get("code").toString());
                tmp.put("name", reMap.get("value").toString());
                tmp.put("code", reMap.get("code").toString());
                buffer.append("," + reMap.get("code").toString());
                result.add(tmp);
            }
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(buffer.toString())){
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(buffer.toString())) {
                buffer.deleteCharAt(0);
                JSONObject tmp = new JSONObject();
                tmp.put("name",map.get("value").toString());
                tmp.put("code",buffer.toString());
                tmp.put("name", map.get("value").toString());
                tmp.put("code", buffer.toString());
                result.add(tmp);
            }
        }
        return  result;
        return result;
    }
    public JSONObject getDeviceTotalCount(String startTime,String endTime,String deviceType,String area,String hospital){
        Integer totalAll=0;
        Integer grant=0;
        if (deviceType.contains("5")){
    public JSONObject getDeviceTotalCount(String startTime, String endTime, String deviceType, String area, String hospital) {
        Integer totalAll = 0;
        Integer grant = 0;
        if (deviceType.contains("5")) {
            StringBuffer sql = new StringBuffer("select count(*) from xmiot.iot_equipmet_detail where 1=1 ");
            if(org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
                sql.append("and belong_are_code='"+area+"' ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
                sql.append("and belong_are_code='" + area + "' ");
            }
            Integer tmp = jdbcTemplate.queryForObject(sql.toString(),Integer.class);
            totalAll +=tmp;
            grant +=tmp;
            Integer tmp = jdbcTemplate.queryForObject(sql.toString(), Integer.class);
            totalAll += tmp;
            grant += tmp;
        }
        if (deviceType.contains("22")) {
            Map<String, Object> medicinecabinetCount = getMedicinecabinetCount();
            Integer total = Integer.parseInt(medicinecabinetCount.get("total").toString());
            Integer using = Integer.parseInt(medicinecabinetCount.get("using").toString());
            deviceType = deviceType.replaceAll("22", " ");
            totalAll += total;
            grant += using;
        }
        String allCountSql = "SELECT COUNT(*) FROM device.wlyy_devices d where 1=1 ";
        int i = 0;
        if(org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)&&deviceType.contains("1")){
            allCountSql+= "   ";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType) && deviceType.contains("1")) {
            allCountSql += " ";
            i = 1;
        }
        if(org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)&&deviceType.contains("2")){
            if(i==1){
                allCountSql+= " or device_name like '%血压计%'";
            }else{
                allCountSql+= " and ( device_name like '%血压计%' ";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType) && deviceType.contains("2")) {
            if (i == 1) {
                allCountSql += " or device_name like '%血压计%'";
            } else {
                allCountSql += " and ( device_name like '%血压计%' )";
            }
        }
        allCountSql+= " ) ";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
            allCountSql+=" and grant_org_code in (SELECT dh.code from wlyy.dm_hospital dh where dh.town ='"+area+"' and dh.del =1 )";
        // allCountSql += "  ";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
            allCountSql += " and grant_org_code in (SELECT dh.code from wlyy.dm_hospital dh where dh.town ='" + area + "' and dh.del =1 )";
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
            allCountSql+=" and grant_org_code ="+hospital+"  ";
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
            allCountSql += " and grant_org_code =" + hospital + "  ";
        }
        if(org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)&&(deviceType.contains("1")||deviceType.contains("2"))){
            Integer allCount = jdbcTemplate.queryForObject(allCountSql, Integer.class);//单体征总数
            totalAll+=allCount;
            StringBuffer sql = new StringBuffer("SELECT COUNT(*) from wlyy.wlyy_patient_device d,wlyy.wlyy_sign_family f  WHERE 1=1 and f.`status`>0 and d.del=0 and f.patient = d.`user` ");
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)){
                sql.append(" and f.hospital in (SELECT dh.code from wlyy.dm_hospital dh where dh.town ='"+area+"' and dh.del =1 )  ");
            }
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)){
                sql.append(" and d.hospital ="+hospital+"  ");
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(deviceType)) {
            String deviceTypes[] = deviceType.split(",");
            boolean flag = false;
            for(String type : deviceTypes){
                if("1".equals(type)||"2".equals(type)){
                    flag = true;
                    break;
                }
            }
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime)&& org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)){
                sql.append(" and d.czrq <='"+endTime+" 23:59:59'  ");
            if(flag){
                Integer allCount = jdbcTemplate.queryForObject(allCountSql, Integer.class);//单体征总数
                totalAll += allCount;
                StringBuffer sql = new StringBuffer("SELECT COUNT(*) from wlyy.wlyy_patient_device d,wlyy.wlyy_sign_family f  WHERE 1=1 and f.`status`>0 and d.del=0 and f.patient = d.`user` ");
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(area)) {
                    sql.append(" and f.hospital in (SELECT dh.code from wlyy.dm_hospital dh where dh.town ='" + area + "' and dh.del =1 )  ");
                }
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(hospital)) {
                    sql.append(" and d.hospital =" + hospital + "  ");
                }
                if (org.apache.commons.lang3.StringUtils.isNoneBlank(startTime) && org.apache.commons.lang3.StringUtils.isNoneBlank(endTime)) {
                    sql.append(" and d.czrq <='" + endTime + " 23:59:59'  ");
                }
                sql.append("and d.category_code in ('").append(deviceType.replace(",", "','")).append("') ");
                Integer count = jdbcTemplate.queryForObject(sql.toString(), Integer.class);//发放总数
                grant += count;
            }
            sql.append("and d.category_code in ('").append(deviceType.replace(",","','")).append("') ");
            Integer count = jdbcTemplate.queryForObject(sql.toString(),Integer.class);//发放总数
            grant +=count;
        }
        JSONObject result = new JSONObject();
        result.put("totalAll",totalAll);
        result.put("using",grant);
        result.put("stock",totalAll-grant);
        result.put("totalAll", totalAll);
        result.put("using", grant);
        result.put("stock", totalAll - grant);
        return result;
    }
    /**
     * deviceName处理
     *
     * @param deviceName
     * @return
     */
    public String getDeviceNameByRequestParam(String deviceName){
        if (deviceName.contains("三诺血糖仪")){
            return deviceName.replace("三诺血糖仪","三诺血糖仪,血糖仪-三诺亲智,三诺亲智,健康之路亲智血糖仪,血糖仪,血糖仪-健康之路亲智血糖仪");
    public String getDeviceNameByRequestParam(String deviceName) {
        if (deviceName.contains("三诺血糖仪")) {
            return deviceName.replace("三诺血糖仪", "三诺血糖仪,血糖仪-三诺亲智,三诺亲智,健康之路亲智血糖仪,血糖仪,血糖仪-健康之路亲智血糖仪");
        }
        return deviceName;
    }
    public JSONObject savePatientDeviceLocation(String categoryCode){
    public JSONObject savePatientDeviceLocation(String categoryCode) {
        String sql = "select DISTINCT pd.category_code ,pd.czrq create_time,pd.device_sn ,pd.device_name, p.disease_condition ,p.`code`,p.idcard ,p.address,sf.hospital_name\n" +
                "from  wlyy.wlyy_patient_device pd \n" +
                "INNER JOIN wlyy.wlyy_sign_family sf on pd.`user` = sf.patient and sf.type=2 \n" +
                "INNER JOIN wlyy.wlyy_patient p on p.idcard = sf.idcard and p.`status`=1\n" +
                "where  pd.del=0 and pd.category_code in ("+categoryCode+")";
                "where  pd.del=0 and pd.category_code in (" + categoryCode + ")";
//                "where  pd.del=0 and pd.category_code in (1,2)";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        list.forEach(map->{
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        list.forEach(map -> {
            try {
                if(map.get("disease_condition")==null){
                if (map.get("disease_condition") == null) {
                    //未定标的居民设置成-1
                    map.put("disease_condition","-1");
                    map.put("disease_condition", "-1");
                }
                Map<String, String> json = null;
                if (map.get("address")!=null){
                if (map.get("address") != null) {
                    if (org.apache.commons.lang3.StringUtils.isNoneBlank(map.get("address").toString())) {
                        json = LatitudeUtils.getGeocoderLatitude(("福建省厦门市"+map.get("address").toString()).replace("G.", "").replace("(糖友网)", "").replace("(高友网)", ""));
                        json = LatitudeUtils.getGeocoderLatitude(("福建省厦门市" + map.get("address").toString()).replace("G.", "").replace("(糖友网)", "").replace("(高友网)", ""));
                    }
                }
                if (json==null||map.get("address")==null){
                    if (map.get("hospital_name")!=null){
                if (json == null || map.get("address") == null) {
                    if (map.get("hospital_name") != null) {
                        if (org.apache.commons.lang3.StringUtils.isNoneBlank(map.get("hospital_name").toString())) {
                            json = LatitudeUtils.getGeocoderLatitude(("福建省厦门市"+map.get("hospital_name").toString()).replace("G.", "").replace("(糖友网)", "").replace("(高友网)", ""));
                            json = LatitudeUtils.getGeocoderLatitude(("福建省厦门市" + map.get("hospital_name").toString()).replace("G.", "").replace("(糖友网)", "").replace("(高友网)", ""));
                        }
                    }
                }
                if (json !=null) {
                if (json != null) {
                    JSONObject location = new JSONObject();
                    location.put("lat", Double.valueOf(json.get("lat")));
                    location.put("lon", Double.valueOf(json.get("lng")));
@ -1694,53 +1813,289 @@ public class MonitorPlatformService  {
                            "'" + map.get("category_code").toString() + "','" + map.get("create_time") + "','" + map.get("create_time").toString() + "','" + location.toJSONString() + "')\n";
                    jdbcTemplate.execute(insertSql);
                }
            }catch (Exception e){
                System.out.println(map.get("device_sn").toString()+"-----"+map.get("idcard").toString());
            } catch (Exception e) {
                System.out.println(map.get("device_sn").toString() + "-----" + map.get("idcard").toString());
                e.printStackTrace();
            }
        });
        return null;
    }
    public List<Map<String, Object>> getHealthScoreByPatient(String patient,String date,String endDate){
    public List<Map<String, Object>> getHealthScoreByPatient(String patient, String date, String endDate) {
        String sql = "SELECT chhs.device_sn deviceSn,chhs.export_key exportKey,chhs.export_time exportTime,chhs.name name,chhs.score score,chhs.total total,chhs.date date FROM xmiot.wlyy_copd_huami_device chd,xmiot.wlyy_copd_huami_health_score chhs,wlyy.hm_token t\n" +
                "WHERE t.patient = '"+patient+"' AND t.patient = chd.patient AND chd.device_sn = chhs.device_sn and chhs.date > '"+endDate+"' and chhs.date < '"+date+"' ORDER BY export_time DESC ";
                "WHERE t.patient = '" + patient + "' AND t.patient = chd.patient AND chd.device_sn = chhs.device_sn and chhs.date > '" + endDate + "' and chhs.date < '" + date + "' ORDER BY export_time DESC ";
        List<Map<String, Object>> scoreDO = jdbcTemplate.queryForList(sql);
        return scoreDO;
    }
    public List<Map<String,Object>> getRealtimeDateByPatient(String patient,String date){
    public List<Map<String, Object>> getRealtimeDateByPatient(String patient, String date) {
        String sql = "SELECT chrd.device_sn deviceSn,chrd.hr hr,chrd.st st,chrd.cal cal,chrd.date date FROM xmiot.wlyy_copd_huami_device chd,xmiot.wlyy_copd_huami_realtime_date chrd,wlyy.hm_token t\n" +
                "WHERE t.patient = '"+patient+"' AND t.patient = chd.patient AND chd.device_sn = chrd.device_sn and chrd.date = '"+date+"' ORDER BY chrd.`date` DESC";
                "WHERE t.patient = '" + patient + "' AND t.patient = chd.patient AND chd.device_sn = chrd.device_sn and chrd.date = '" + date + "' ORDER BY chrd.`date` DESC";
        List<Map<String, Object>> realtimeDateDo = jdbcTemplate.queryForList(sql);
        return realtimeDateDo;
    }
    public List<Map<String,Object>> getRundatePatient(String patient,String date){
    public List<Map<String, Object>> getRundatePatient(String patient, String date) {
        String sql = "SELECT chr.device_sn deviceSn,chr.date date,chr.last_sync_time lastSyncTime,chr.steps steps,chr.distance distance,chr.run_distance runDistance,chr.run_time runTime,chr.walk_time walkTime,chr.calories calories,chr.run_calories runCalories,chr.hour hour FROM xmiot.wlyy_copd_huami_device chd,xmiot.wlyy_copd_huami_rundate chr,wlyy.hm_token t\n" +
                "WHERE t.patient = '"+patient+"' AND t.patient = chd.patient AND chd.device_sn = chr.device_sn and chr.date = '"+date+"' ORDER BY chr.`date` DESC";
                "WHERE t.patient = '" + patient + "' AND t.patient = chd.patient AND chd.device_sn = chr.device_sn and chr.date = '" + date + "' ORDER BY chr.`date` DESC";
        List<Map<String, Object>> rundataDo = jdbcTemplate.queryForList(sql);
        return rundataDo;
    }
    public List<Map<String,Object>> getPaiPatient(String patient,String date){
    public List<Map<String, Object>> getPaiPatient(String patient, String date) {
        String sql = "SELECT chp.device_sn deviceSn,chp.calendar_day calendarDay,chp.timestamp timestamp,chp.total_pai totalPai,chp.daily_pai dailyPai,chp.date date FROM xmiot.wlyy_copd_huami_device chd,xmiot.wlyy_copd_huami_pai chp,wlyy.hm_token t\n" +
                "WHERE t.patient = '"+patient+"' AND t.patient = chd.patient AND chd.device_sn = chp.device_sn and chp.date = '"+date+"' ORDER BY chp.`timestamp` DESC";
                "WHERE t.patient = '" + patient + "' AND t.patient = chd.patient AND chd.device_sn = chp.device_sn and chp.date = '" + date + "' ORDER BY chp.`timestamp` DESC";
        List<Map<String, Object>> paiDo = jdbcTemplate.queryForList(sql);
        return paiDo;
    }
    public List<Map<String,Object>> getSleepByPatient(String patient,String date){
    public List<Map<String, Object>> getSleepByPatient(String patient, String date) {
        String sql = "SELECT chs.device_sn deviceSn,chs.date date,chs.last_sync_time lastSyncTime,chs.deep_sleep_time deepSleepTime,chs.shallow_sleep_time shallowSleepTime,chs.wake_time wakeTime,chs.sleep_score sleepScore,chs.start start,chs.stop stop,chs.mode mode FROM xmiot.wlyy_copd_huami_device chd,xmiot.wlyy_copd_huami_sleep chs,wlyy.hm_token t\n" +
                "WHERE t.patient = '"+patient+"' AND t.patient = chd.patient AND chd.device_sn = chs.device_sn and chs.date = '"+date+"' ORDER BY chs.`last_sync_time` DESC";
                "WHERE t.patient = '" + patient + "' AND t.patient = chd.patient AND chd.device_sn = chs.device_sn and chs.date = '" + date + "' ORDER BY chs.`last_sync_time` DESC";
        List<Map<String, Object>> paiDo = jdbcTemplate.queryForList(sql);
        return paiDo;
    }
    public List<Map<String , Object>> getHeartByPatient(String patient,String date,String endDate){
    public List<Map<String, Object>> getHeartByPatient(String patient, String date, String endDate) {
        String sql = "SELECT chh.device_sn deviceSn,chh.date date,chh.minute minute,chh.last_sync_time lastSyncTime,chh.timestamp timestamp,chh.heart_rate_data heartRateData,chh.measure_type measureType FROM xmiot.wlyy_copd_huami_device chd,xmiot.wlyy_copd_huami_heart chh,wlyy.hm_token t\n" +
                "WHERE t.patient = '"+patient+"' AND t.patient = chd.patient AND chd.device_sn = chh.device_sn and chh.`date` > '"+endDate+"' and chh.`date` < '"+date+"' ORDER BY chh.`date` DESC";
                "WHERE t.patient = '" + patient + "' AND t.patient = chd.patient AND chd.device_sn = chh.device_sn and chh.`date` > '" + endDate + "' and chh.`date` < '" + date + "' ORDER BY chh.`date` DESC";
        List<Map<String, Object>> heartDo = jdbcTemplate.queryForList(sql);
        return heartDo;
    }
    /*获取智慧药房所有设备信息  地址  编号  名字*/
    public List<Map<String, String>> getMedicinecabinet() {
        JSONArray resultArr = new JSONArray();
        List<Map<String, String>> list = new ArrayList<>();
        try {
            JSONObject resultObject = getUrl("/open/noLogin/getDeviceList", null, "obj");
            resultArr = resultObject.getJSONArray("usedDeviceList");
            for (int i = 0; i < resultArr.size(); i++) {
                Map<String, String> resultMap = new HashMap<>();
                JSONObject jsonObject = resultArr.getJSONObject(i);
                /*获取设备名称*/
                String equName = jsonObject.getString("equName");
                resultMap.put("equName", equName);
                /*获取设备地址*/
                String deliveryAddress = jsonObject.getString("deliveryAddress");
                resultMap.put("deliveryAddress", deliveryAddress);
                /*获取设备编号*/
                String equNum = jsonObject.getString("equNum");
                resultMap.put("equNum", equNum);
                /*获取设备编号*/
                String id = jsonObject.getString("id");
                resultMap.put("id", id);
                /*投放经度*/
                String lng = jsonObject.getString("lng");
                resultMap.put("lng", lng);
                /*投放纬度*/
                String lat = jsonObject.getString("lat");
                resultMap.put("lat", lat);
                list.add(resultMap);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /*智慧药房总数*/
    public Map<String, Object> getMedicinecabinetCount() {
        Map resultMap = new HashMap<>();
        JSONObject jsonObject = getUrl("/open/noLogin/getDeviceList", null, "obj");
        //设备总数
        String total = jsonObject.get("total").toString();
        //库存量
        String notUsedTotal = jsonObject.get("notUsedTotal").toString();
        //使用中
        String usedTotal = jsonObject.get("usedTotal").toString();
        resultMap.put("total", total);
        resultMap.put("stock", notUsedTotal);
        resultMap.put("using", usedTotal);
        resultMap.put("device_name", "智慧药房");
        return resultMap;
    }
    /*获取智慧药房详细信息*/
    public Map<String, List<Map>> getadddd(String deviceId, String day) throws Exception {
        //返回参数
        Map<String, List<Map>> resoultMap = new HashMap<>();
        //参数加密
        Map parameterMap = new HashMap<String, String>();
        parameterMap.put("deviceId", deviceId);
        parameterMap.put("day", day);
        String content = com.alibaba.fastjson.JSONObject.toJSONString(parameterMap);
        String params = AesEncryptUtils.agEncrypt(content);
        JSONObject jsonObject = getUrl("/open/noLogin/getDeviceInfo", params, "obj");
        //取药列表获取
        List<Map> mediicineorderListMap = new ArrayList<>();
        JSONArray mediicineorderList = jsonObject.getJSONArray("mediicineorderList");
        for (int i = 0; i < mediicineorderList.size(); i++) {
            Map listMap = new HashMap<>();
            JSONObject quyaoQbject = mediicineorderList.getJSONObject(i);
            //取药方式(1、扫码,2、医保卡)
            String shippingType = quyaoQbject.getString("shippingType");
            String shippingTime = quyaoQbject.getString("shippingTime");
            String name = quyaoQbject.getString("name");
            listMap.put("shippingType", shippingType);
            listMap.put("shippingTime", shippingTime);
            listMap.put("name", name);
            mediicineorderListMap.add(listMap);
        }
        //设备信息获取
        List<Map> deviceListMap = new ArrayList<>();
        JSONObject deviceObject = jsonObject.getJSONObject("device");
        Map deviceListMapObject = new HashMap<>();
        //设备名称
        deviceListMapObject.put("equName", deviceObject.getString("equName"));
        //设备地址
        deviceListMapObject.put("deliveryAddress", deviceObject.getString("deliveryAddress"));
        //设备编号
        deviceListMapObject.put("equNum", deviceObject.getString("equNum"));
        //湿度
        deviceListMapObject.put("humidity", deviceObject.getString("humidity"));
        //温度
        deviceListMapObject.put("temperature", deviceObject.getString("temperature"));
        deviceListMap.add(deviceListMapObject);
        //取药方式获取
        JSONArray shippingTypeArray = jsonObject.getJSONArray("shippingTypeTotal");
        List<Map> shippingTypeList = JSONObject.parseArray(shippingTypeArray.toJSONString(), Map.class);
        //取药列表存放
        resoultMap.put("mediicineorderList", mediicineorderListMap);
        //设备信息存放
        resoultMap.put("deviceList", deviceListMap);
        //取药方式存放
        resoultMap.put("shippingTypeTotal", shippingTypeList);
        return resoultMap;
    }
    /*获取智慧药房曲线图信息*/
    public Map<String, List<Map>> getCabinetCurve(String deviceId, String day) throws Exception {
        if ("".equals(day) || day == null) {
            day = "365";
        }
        //返回参数
        Map<String, List<Map>> resoultMap = new HashMap<>();
        //参数加密
        Map parameterMap = new HashMap<String, String>();
        parameterMap.put("deviceId", deviceId);
        parameterMap.put("day", day);
        String content = com.alibaba.fastjson.JSONObject.toJSONString(parameterMap);
        String params = AesEncryptUtils.agEncrypt(content);
        JSONObject jsonObject = getUrl("/open/noLogin/getDeviceInfo", params, "obj");
        //医保曲线
        JSONArray yibaoArray = jsonObject.getJSONArray("yibaoList");
        List<Map> yibaoList = JSONObject.parseArray(yibaoArray.toJSONString(), Map.class);
        //扫码曲线获取
        JSONArray saomaArray = jsonObject.getJSONArray("saomaList");
        List<Map> saomaList = JSONObject.parseArray(yibaoArray.toJSONString(), Map.class);
        //医保曲线存放
        resoultMap.put("yibaoList", yibaoList);
        //扫码曲线存放
        resoultMap.put("saomaList", saomaList);
        return resoultMap;
    }
    /*智慧药房地标*/
    public List<Map<String, Object>> getLongitudeAndLatitude() {
        JSONArray resultArr = new JSONArray();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            JSONObject resultObject = getUrl("/open/noLogin/getDeviceList", null, "obj");
            resultArr = resultObject.getJSONArray("usedDeviceList");
            for (int i = 0; i < resultArr.size(); i++) {
                Map<String, Object> resultMap = new HashMap<>();
                JSONObject jsonObject = resultArr.getJSONObject(i);
                /*投放经度*/
                String lng = jsonObject.getString("lng");
                resultMap.put("lng", lng);
                /*投放纬度*/
                String lat = jsonObject.getString("lat");
                resultMap.put("lat;", lat);
                /*id*/
                String id = jsonObject.getString("id");
                resultMap.put("id;", id);
                list.add(resultMap);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /*取药信息*/
    public JSONObject getBuyDrugMessage(String deviceid, String startTime,String endTime) throws Exception {
        Map parameterMap = new HashMap<String, String>();
        parameterMap.put("deviceId", deviceid);
        parameterMap.put("startTime", startTime);
        parameterMap.put("endTime", endTime);
        String content = com.alibaba.fastjson.JSONObject.toJSONString(parameterMap);
        String params = AesEncryptUtils.agEncrypt(content);
        JSONObject jsonObject = getUrl("/open/noLogin/getDeviceOrderInfo", params, "detailModelList");
        System.out.println(jsonObject);
        return jsonObject;
    }
    /*智慧药房库存检测
     * 药房有6层,每层40个货道
     * 商品状态:未设商品、已有商品
     * 货道状态:货道故障、货道关闭、货道正常
     * */
    public JSONArray ygStockDetection(String id) throws Exception {
        //请求药房 获取参数
        String url = "/open/noLogin/findMediicinecabinetInventoryByDeviceId";
        Map parameterMap = new HashMap<>();
        parameterMap.put("deviceId", id);
        String content = com.alibaba.fastjson.JSONObject.toJSONString(parameterMap);
        String params = AesEncryptUtils.agEncrypt(content);
        JSONObject jsonObject = getUrl(url, params, "detailModelList");
        JSONArray jsonArray = jsonObject.getJSONArray("obj");
        return jsonArray;
    }
    /*请求接口*/
    public JSONObject getUrl(String url, String parame, String obj) {
        JSONObject resultObj = new JSONObject();
        List<Map<String, String>> list = new ArrayList<>();
        try {
            //智慧药房请求地址
            String ygurl = "SELECT isd.dict_name,isd.`code` from iot_system_dict isd WHERE dict_name = 'HLW_YGBASEURL'";
            Map<String, Object> baseUrll = jdbcTemplate.queryForMap(ygurl);
            String urlResult = httpClientUtil.getBodyRawForm(baseUrll.get("code") + url, parame);
            JSONObject resultObject = JSONObject.parseObject(urlResult);
            if (resultObject.get("status").equals("200")) {
                JSONObject jsonObjectData = JSONObject.parseObject(AesEncryptUtils.agDecrypt(resultObject.get("data").toString()));
                if (jsonObjectData.get("status").equals(200)) {
                    if ("obj".equals(obj)) {
                        resultObj = jsonObjectData.getJSONObject(obj);
                    }
                    if ("detailModelList".equals(obj)) {
                        JSONArray jsonArray = jsonObjectData.getJSONArray(obj);
                        resultObj.put("obj", jsonArray);
                    }
                }
            }
            return resultObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

+ 106 - 25
svr/svr-iot/src/main/resources/application.yml

@ -72,15 +72,31 @@ spring:
    url: jdbc:mysql://172.26.0.204:3306/xmiot?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
  elasticsearch:
    cluster-name: jkzl #默认即为elasticsearch  集群名
    cluster-nodes: 172.26.0.203:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
    jest:
      uris: http://172.26.0.202:9200
#  elasticsearch:
#    cluster-name: jkzl #默认即为elasticsearch  集群名
#    cluster-nodes: 172.26.0.203:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
#    jest:
#      uris: http://172.26.0.202:9200
  wlyy:
    url: http://www.xmtyw.cn/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
    FollowUp: wlyy_followup
  type:
    Statistics: hlw_quota_test
    FollowUpContent: wlyy_followup_content
  host:  http://172.26.0.112:9200
  tHost: 172.26.0.112:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
fast-dfs:
  tracker-server: 172.26.0.200:22122 #服务器地址
fastDFS:
@ -95,15 +111,31 @@ spring:
    url: jdbc:mysql://172.26.0.104:3306/xmiot?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
  elasticsearch:
    cluster-name: jkzl #默认即为elasticsearch  集群名
    cluster-nodes: 172.26.0.203:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
    jest:
      uris: http://172.26.0.202:9200
#  elasticsearch:
#    cluster-name: jkzl #默认即为elasticsearch  集群名
#    cluster-nodes: 172.26.0.203:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
#    jest:
#      uris: http://172.26.0.202:9200
  wlyy:
    url: http://www.xmtyw.cn/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
    FollowUp: wlyy_followup
  type:
    Statistics: hlw_quota_test
    FollowUpContent: wlyy_followup_content
  host:  http://172.26.0.112:9200
  tHost: 172.26.0.112:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
fast-dfs:
  tracker-server: 172.26.0.200:22122 #服务器地址
fastDFS:
@ -118,15 +150,31 @@ spring:
    url: jdbc:mysql://172.26.0.104/xmiot?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
  elasticsearch:
    cluster-name: jkzl #默认即为elasticsearch  集群名
    cluster-nodes: 172.26.0.112:9300,172.26.0.112:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
    jest:
      uris: http://172.26.0.112:9200,http://172.26.0.112:9200
#  elasticsearch:
#    cluster-name: jkzl #默认即为elasticsearch  集群名
#    cluster-nodes: 172.26.0.112:9300,172.26.0.112:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
#    jest:
#      uris: http://172.26.0.112:9200,http://172.26.0.112:9200
  wlyy:
    url: http://ehr.yihu.com/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee62
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee62
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
    FollowUp: wlyy_followup
  type:
    Statistics: hlw_quota_test
    FollowUpContent: wlyy_followup_content
  host:  http://172.26.0.112:9200
  tHost: 172.26.0.112:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
fast-dfs:
  tracker-server: 172.19.103.54:22122 #服务器地址
fastDFS:
@ -141,15 +189,32 @@ spring:
    url: jdbc:mysql://172.26.0.104/xmiot?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: ssgg
    password: ssgg@jkzl2019
  elasticsearch:
    cluster-name: jkzl #默认即为elasticsearch  集群名
    cluster-nodes: 172.26.0.112:9300,172.26.0.112:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
    jest:
      uris: http://172.26.0.112:9200,http://172.26.0.112:9200
#  elasticsearch:
#    cluster-name: jkzl #默认即为elasticsearch  集群名
#    cluster-nodes: 172.26.0.112:9300,172.26.0.112:9300 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
#    jest:
#      uris: http://172.26.0.112:9200,http://172.26.0.112:9200
  wlyy:
    url: http://ehr.yihu.com/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee62
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee62
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base    正式
#  #http://ehr.yihu.com/hlwyy/cityihealth/base     测试
es:
  pwflag: 1 # 1需要密码,2不需要密码
  index:
    Statistics: hlw_quota_test
    FollowUp: wlyy_followup
  type:
    Statistics: hlw_quota_test
    FollowUpContent: wlyy_followup_content
  host:  http://172.26.0.112:9200
  tHost: 172.26.0.112:9300
  clusterName: jkzl
  securityUser: lion:jkzlehr
  user: lion
  password: jkzlehr
fast-dfs:
  tracker-server: 172.19.103.54:22122 #服务器地址
fastDFS:
@ -173,6 +238,8 @@ spring:
    url: http://ehr.yihu.com/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee62
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee62
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base
fast-dfs:
  tracker-server: 172.26.0.110:22122 #服务器地址
fastDFS:
@ -197,6 +264,8 @@ spring:
    url: http://www.xmtyw.cn/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
#hlw:
#  baseUrl: http://ehr.yihu.com/hlwyy/cityihealth/base
fast-dfs:
  tracker-server: 10.95.22.139:22122 #服务器地址
fastDFS:
@ -220,6 +289,8 @@ spring:
    url: http://www.xmtyw.cn/wlyy/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee61
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee57
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base
fast-dfs:
  tracker-server: 10.95.22.139:22122 #服务器地址
fastDFS:
@ -234,15 +305,25 @@ spring:
    url: jdbc:mysql://10.90.32.3:20002/xmiot?useUnicode=true&amp;characterEncoding=utf-8&amp;autoReconnect=true
    username: wlyy_new
    password: J4&y9sk#1G
  elasticsearch:
    cluster-name: jkzl #默认即为elasticsearch  集群名
    cluster-nodes: 10.90.32.3:20011,10.90.32.3:20011 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
    jest:
      uris: http://10.90.32.3:20011,http://10.90.32.3:20012
#  elasticsearch:
#    cluster-name: jkzl #默认即为elasticsearch  集群名
#    cluster-nodes: 10.90.32.3:20011,10.90.32.3:20011 #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
#    jest:
#      uris: http://10.90.32.3:20011,http://10.90.32.3:20012
  wlyy:
    url: http://www.xmtyw.cn/wlyytest/
    appid: 915d0345-5b1d-11e6-8344-fa163e8aee62
    appsecret: 915d0345-5b1d-11e6-8344-fa163e8aee62
#hlw:
#  baseUrl: https://zb.xmtyw.cn/medicine/cityihealth/base
es:
  pwflag: 1 # 1需要密码,2不需要密码
  host:  http://10.90.32.3:20011
  tHost: 10.90.32.3:20012
  clusterName: jkzl
  securityUser: zjxl:6Dbq&fHg
  user: zjxl
  password: 6Dbq&fHg
fast-dfs:
  tracker-server: 172.19.103.54:22122 #服务器地址
fastDFS:

+ 1 - 1
svr/svr-iot/src/main/resources/bootstrap.yml

@ -1,6 +1,6 @@
spring:
  application:
    name:  svr-iot
    name:  svr-iot-wsl
  cloud:
    config:
      failFast: true

+ 0 - 13
svr/svr-statistics-es/pom.xml

@ -39,7 +39,6 @@
        <version.jul-over-slf4j>1.7.21</version.jul-over-slf4j>
        <version.joda-time>2.8.2</version.joda-time>
        <version.junit>4.12</version.junit>
        <version.log4j2>2.4.1</version.log4j2>
        <version.logback>1.2.3</version.logback>
        <version.mysql>5.1.44</version.mysql>
        <version.quartz>2.2.3</version.quartz>
@ -208,18 +207,6 @@
            <version>${version.commons-codec}</version>
        </dependency>
        <!--Log framework-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <!--Log framework to SLF4J bridge: x-over-slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>

+ 0 - 13
svr/svr-statistics/pom.xml

@ -39,7 +39,6 @@
        <version.jul-over-slf4j>1.7.21</version.jul-over-slf4j>
        <version.joda-time>2.8.2</version.joda-time>
        <version.junit>4.12</version.junit>
        <version.log4j2>2.4.1</version.log4j2>
        <version.logback>1.2.3</version.logback>
        <version.mysql>5.1.44</version.mysql>
        <version.quartz>2.2.3</version.quartz>
@ -211,18 +210,6 @@
            <version>${version.commons-codec}</version>
        </dependency>
        <!--Log framework-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <!--Log framework to SLF4J bridge: x-over-slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>

+ 0 - 8
svr/svr-wlyy-health-bank/pom.xml

@ -45,14 +45,6 @@
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!-- redis start  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>

+ 2 - 2
svr/svr-wlyy-health-bank/src/main/java/com/yihu/jw/config/jpa/WlyyHealthBankJpa.java

@ -27,7 +27,7 @@ import java.util.Properties;
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyHealthBankEntityManagerFactory",
        transactionManagerRef = "wlyyHealthBankTransactionManager",
        basePackages = {"com.yihu.jw.dao"})   //设置Repository所在位置
        basePackages = {"com.yihu.jw.dao","com.yihu.jw.restmodel.exception.dao","com.yihu.jw.util.dao"})   //设置Repository所在位置
public class WlyyHealthBankJpa {
    @Autowired
@ -39,7 +39,7 @@ public class WlyyHealthBankJpa {
        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
        emfb.setDataSource(dataSource);
        emfb.setPackagesToScan("com.yihu.jw.entity.health");
        emfb.setPackagesToScan("com.yihu.jw.entity");
        emfb.setPersistenceUnitName("bank");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        emfb.setJpaVendorAdapter(vendorAdapter);

+ 0 - 1
svr/svr-wlyy-health-bank/src/main/java/com/yihu/jw/service/ExchangeGoodsService.java

@ -2,7 +2,6 @@ package com.yihu.jw.service;/**
 * Created by nature of king on 2018/5/3.
 */
import com.netflix.discovery.converters.jackson.EurekaXmlJacksonCodec;
import com.yihu.jw.dao.*;
import com.yihu.jw.entity.health.bank.*;
import com.yihu.jw.restmodel.web.MixEnvelop;

+ 0 - 13
svr/svr-wlyy-specialist/pom.xml

@ -41,23 +41,10 @@
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- 支持Tomcat启动 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-sleuth-zipkin</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>

+ 1 - 170
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/controller/common/FileUploadController.java

@ -10,7 +10,7 @@ import com.yihu.jw.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
@ -42,175 +42,6 @@ public class FileUploadController {
    @Autowired
    protected HttpServletRequest request;
    /*@PostMapping(value = IotRequestMapping.FileUpload.api_upload_stream_img)
    @ApiOperation(value = "文件流上传图片", notes = "文件流上传图片")
    public MixEnvelop<UploadVO, UploadVO> uploadImg(@ApiParam(value = "文件", required = true)
                                       @RequestParam(value = "file", required = true) MultipartFile file){
        try {
            // 得到文件的完整名称  xxx.txt
            String fullName = file.getOriginalFilename();
            if(StringUtils.isBlank(fullName)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            //得到文件类型
            String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
            if(StringUtils.isBlank(fileType)||!"jpg,jpeg,png".contains(fileType)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            long size = file.getSize();
            long max = 5*1024*1024;
            if(size>max){
                return MixEnvelop.getError("文件大小不超过5M",IotRequestMapping.api_iot_fail);
            }
            String fileName = fullName.substring(0, fullName.lastIndexOf("."));
            //上传到fastdfs
            ObjectNode objectNode = null;
            //解析返回的objectNode
            UploadVO uploadVO = null;
            if(isneiwang){
                objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
                uploadVO = new UploadVO();
                uploadVO.setFileName(fileName);
                uploadVO.setFileType(fileType);
                uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
                uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            }else {
                uploadVO = fileUploadService.request(request,file.getInputStream(),fullName);
                if(uploadVO==null){
                    return MixEnvelop.getError("文件上传失败",IotRequestMapping.api_iot_fail);
                }
            }
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_create, uploadVO);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
        }
    }
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_stream_attachment)
    @ApiOperation(value = "文件流上传附件", notes = "文件流上传附件")
    public MixEnvelop<UploadVO, UploadVO> uploadAttachment(@ApiParam(value = "文件", required = true)
                                              @RequestParam(value = "file", required = true) MultipartFile file){
        try {
            // 得到文件的完整名称  xxx.txt
            String fullName = file.getOriginalFilename();
            if(StringUtils.isBlank(fullName)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            //得到文件类型
            String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
            if(StringUtils.isBlank(fileType)||!"doc、docx、pdf、xls、xlsx、jpg、jpeg、png".contains(fileType)){
                return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload_format,IotRequestMapping.api_iot_fail);
            }
            long size = file.getSize();
            long max = 5*1024*1024;
            if(size>max){
                return MixEnvelop.getError("文件大小不超过5M",IotRequestMapping.api_iot_fail);
            }
            String fileName = fullName.substring(0, fullName.lastIndexOf("."));
            //上传到fastdfs
            ObjectNode objectNode = null;
            //解析返回的objectNode
            UploadVO uploadVO = null;
            if(isneiwang){
                objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
                uploadVO = new UploadVO();
                uploadVO.setFileName(fileName);
                uploadVO.setFileType(fileType);
                uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
                uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            }else {
                uploadVO = fileUploadService.request(request,file.getInputStream(),fullName);
                if(uploadVO==null){
                    return MixEnvelop.getError("文件上传失败",IotRequestMapping.api_iot_fail);
                }
            }
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_create, uploadVO);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
        }
    }
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_stream)
    @ApiOperation(value = "文件流上传文件", notes = "文件流上传文件")
    public MixEnvelop<UploadVO, UploadVO> uploadStream(@ApiParam(value = "文件", required = true) @RequestParam(value = "file", required = true) MultipartFile file) {
        try {
            // 得到文件的完整名称  xxx.txt
            String fullName = file.getOriginalFilename();
            //得到文件类型
            String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
            String fileName = fullName.substring(0, fullName.lastIndexOf("."));
            //上传到fastdfs
            ObjectNode objectNode = null;
            //解析返回的objectNode
            UploadVO uploadVO = null;
            if(isneiwang){
                objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
                uploadVO = new UploadVO();
                uploadVO.setFileName(fileName);
                uploadVO.setFileType(fileType);
                uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
                uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            }else {
                uploadVO = fileUploadService.request(request,file.getInputStream(),fullName);
                if(uploadVO==null){
                    return MixEnvelop.getError("文件上传失败",IotRequestMapping.api_iot_fail);
                }
            }
            return MixEnvelop.getSuccess(IotRequestMapping.Common.message_success_create, uploadVO);
        } catch (Exception e) {
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
        }
    }
    @PostMapping(value = IotRequestMapping.FileUpload.api_upload_string)
    @ApiOperation(value = "base64上传图片",notes = "base64上传图片")
    public MixEnvelop<UploadVO, UploadVO> uploadImages(@ApiParam(name = "jsonData", value = "头像转化后的输入流") @RequestBody String jsonData) throws Exception {
        try {
            String date = URLDecoder.decode(jsonData,"UTF-8");
            String[] fileStreams = date.split(",");
            String is = URLDecoder.decode(fileStreams[1],"UTF-8").replace(" ","+");
            byte[] in = Base64.getDecoder().decode(is);
            InputStream inputStream = new ByteArrayInputStream(in);
            ObjectNode objectNode = null;
            //上传到fastdfs
            String fileType = "png";
            //解析返回的objectNode
            UploadVO uploadVO = null;
            if(isneiwang){
                objectNode = fastDFSHelper.upload(inputStream, fileType, "");
                String groupName = objectNode.get("groupName").toString();
                String remoteFileName = objectNode.get("remoteFileName").toString();
                uploadVO = new UploadVO();
                uploadVO.setFileName(remoteFileName);
                uploadVO.setFileType(groupName);
                uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
                uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
            }else {
                uploadVO = fileUploadService.request(request,inputStream,"");
                if(uploadVO ==null){
                    return MixEnvelop.getError("文件上传失败",IotRequestMapping.api_iot_fail);
                }
            }
            //返回文件路径
            return MixEnvelop.getSuccess(IotRequestMapping.FileUpload.message_success_upload, uploadVO);
        }catch (Exception e){
            e.printStackTrace();
            return MixEnvelop.getError(IotRequestMapping.FileUpload.message_fail_upload, IotRequestMapping.api_iot_fail);
        }
    }*/
    @RequestMapping(value = "commonUpload", method = RequestMethod.POST)
    @ResponseBody

+ 0 - 12
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/PatientLabelDao.java

@ -1,12 +0,0 @@
//package com.yihu.jw.dict;
//
//import com.yihu.jw.entity.specialist.PatientLabelDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/5/29.
// */
//public interface PatientLabelDao extends PagingAndSortingRepository<PatientLabelDO, String>,
//        JpaSpecificationExecutor<PatientLabelDO> {
//}

+ 0 - 12
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/PatientLabelInfoDao.java

@ -1,12 +0,0 @@
//package com.yihu.jw.dict;
//
//import com.yihu.jw.entity.specialist.PatientLabelDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/5/29.
// */
//public interface PatientLabelInfoDao extends PagingAndSortingRepository<PatientLabelDO, String>,
//        JpaSpecificationExecutor<PatientLabelDO> {
//}

+ 0 - 12
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/SpecialistArticleDao.java

@ -1,12 +0,0 @@
//package com.yihu.jw.dict;
//
//import com.yihu.jw.entity.specialist.SpecialistArticleDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/4/25.
// */
//public interface SpecialistArticleDao extends PagingAndSortingRepository<SpecialistArticleDO, String>,
//        JpaSpecificationExecutor<SpecialistArticleDO> {
//}

+ 0 - 12
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/SpecialistConsultDao.java

@ -1,12 +0,0 @@
//package com.yihu.jw.dict;
//
//import com.yihu.jw.entity.specialist.SpecialistConsultDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/4/25.
// */
//public interface SpecialistConsultDao extends PagingAndSortingRepository<SpecialistConsultDO, String>,
//        JpaSpecificationExecutor<SpecialistConsultDO> {
//}

+ 0 - 12
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/dao/SpecialistDao.java

@ -1,12 +0,0 @@
//package com.yihu.jw.dict;
//
//import com.yihu.jw.entity.specialist.SpecialistDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/4/25.
// */
//public interface SpecialistDao extends PagingAndSortingRepository<SpecialistDO, String>,
//        JpaSpecificationExecutor<SpecialistDO> {
//}

+ 1 - 1
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/service/SpecialistScreenResultService.java

@ -5,7 +5,7 @@ import com.yihu.jw.restmodel.specialist.SurveyTemplateQuestionsVo;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.IdCardUtil;
import org.apache.commons.lang.StringUtils;
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.BeanPropertyRowMapper;

+ 1 - 1
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/service/SpecialistService.java

@ -18,7 +18,7 @@ import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.rm.specialist.SpecialistMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

+ 2 - 1
svr/svr-wlyy-specialist/src/main/java/com/yihu/jw/util/AddressUtils.java

@ -1,6 +1,7 @@
package com.yihu.jw.util;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;

+ 1 - 1
wlyy-parent-pom/pom.xml

@ -85,7 +85,7 @@
        <!-- Version start -->
        <version.wlyy-common>2.0.0</version.wlyy-common>
        <version.jackson>2.8.1</version.jackson>
        <verion.fastjson>1.2.72</verion.fastjson>
        <verion.fastjson>1.2.76</verion.fastjson>
        <version.json>20160212</version.json>
        <version.net-json>2.4</version.net-json>
        <version.logback>1.2.3</version.logback>