Sfoglia il codice sorgente

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

LAPTOP-KB9HII50\70708 3 anni fa
parent
commit
3762be6114
23 ha cambiato i file con 1357 aggiunte e 126 eliminazioni
  1. 100 1
      business/base-service/src/main/java/com/yihu/jw/file_upload/FileUploadService.java
  2. 10 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  3. 24 0
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java
  4. 6 1
      business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/HcyyEntranceService.java
  5. 15 1
      business/base-service/src/main/java/com/yihu/jw/order/BusinessOrderService.java
  6. 309 1
      business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java
  7. 10 0
      server/svr-authentication/pom.xml
  8. 56 0
      server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java
  9. 35 26
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java
  10. 58 0
      server/svr-authentication/src/main/java/com/yihu/jw/security/service/HcyyService.java
  11. 13 35
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/device/DeviceManageEndpoint.java
  12. 29 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/WlyyPatientDeviceService.java
  13. 10 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/OpenStatisticsEndpoint.java
  14. 143 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/StatisticsEndpoint.java
  15. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/security/SecurityMonitoringOrderService.java
  16. 4 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/DetectionPlatformService.java
  17. 430 30
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsService.java
  18. 13 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/CommonUtil.java
  19. 42 0
      svr/svr-internet-hospital-entrance/src/main/resources/application.yml
  20. 1 1
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java
  21. 29 7
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/patient/PatientNoLoginEndPoint.java
  22. 13 4
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/prescription/PrescriptionEndpoint.java
  23. 6 10
      svr/svr-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/compute/ComputeHelper.java

+ 100 - 1
business/base-service/src/main/java/com/yihu/jw/file_upload/FileUploadService.java

@ -279,7 +279,106 @@ public class FileUploadService {
    /**
     * 调用健康上传语音文件.
     * 调用内网本地fasdf
     * @param voices_Path
     * @return
     * @throws Exception
     */
    public String uploadInLocalWxVoice(String voices_Path,String remote_inner_url) throws Exception {
        UploadVO uploadVO = new UploadVO();
        String url = "";
        File f = new File(voices_Path);
        if (f.exists()) {
            logger.info("语音文件转换file-start");
            FileInputStream input = new FileInputStream(f);
            String fileContenType = "text/plain";
            try {
                logger.info("获取文件类型--开始");
                fileContenType = new MimetypesFileTypeMap().getContentType(f);
                logger.info("获取文件类型--成功--fileContenType:"+fileContenType);
            } catch (Exception e) {
                logger.info("获取文件类型--失败:"+e.getMessage());
            }
            MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
            logger.info("语音文件转换file-转换-multipartFile");
            long size = multipartFile.getSize();
            if(size<=0){
                return url;
            }
            String fileName = multipartFile.getOriginalFilename();
            logger.info("语音文件转换file-转换-multipartFile-成功,开始调用内网接口上传文件");
            String rs = request(remote_inner_url, multipartFile, null);
            logger.info(rs);
            JSONObject json = JSON.parseObject(rs);
            uploadVO = objectMapper.readValue(json.getJSONObject("obj").toJSONString(),UploadVO.class);
            if (uploadVO !=null) {
                url = uploadVO.getFullUri();
                logger.info("开始调用内网接口上传文件成功:url:"+url);
//                map.put("uploadStatus", 0);//文件类型正确
//                map.put("accessory", url);//
                return url;
            }
        }
        return url;
    }
    /**
     * 调用内网上传图片.
     * @param files
     * @return
     * @throws Exception
     */
    public String uploadInLocalWxImage(String files,String tempPath,String remote_inner_url) throws Exception {
        UploadVO uploadVO = new UploadVO();
        System.out.println("files====="+files);
        System.out.println("tempPath====="+tempPath);
        // 文件保存的临时路径
        String[] fileArray = files.split(",");
        String fileUrls = "";
        for (String file : fileArray) {
            System.out.println("file+++"+file);
            File f = new File(tempPath + "/"+file);
            File fs = new File(tempPath +"/"+ file + "_small");
            if (f.exists()) {
                logger.info("图片文件转换file-start");
                FileInputStream input = new FileInputStream(f);
                String fileContenType = "text/plain";
                try {
                    logger.info("获取文件类型--开始");
                    fileContenType = new MimetypesFileTypeMap().getContentType(f);
                    logger.info("获取文件类型--成功--fileContenType:"+fileContenType);
                } catch (Exception e) {
                    logger.info("获取文件类型--失败:"+e.getMessage());
                }
                MultipartFile multipartFile = new MockMultipartFile("file", f.getName(), fileContenType, IOUtils.toByteArray(input));
                logger.info("图片文件转换file-转换-multipartFile");
                long size = multipartFile.getSize();
                if(size<=0){
                    return fileUrls;
                }
                logger.info("图片文件转换file-转换-multipartFile-成功,开始调用内网接口上传文件");
                String rs = request(remote_inner_url, multipartFile, null);
                logger.info(rs);
                JSONObject json = JSON.parseObject(rs);
                uploadVO = objectMapper.readValue(json.getJSONObject("obj").toJSONString(),UploadVO.class);
                if (uploadVO != null) {
                    fileUrls += uploadVO.getFullUri();
                    f.delete();
                    if (fs.exists()) {
                        fs.delete();
                    }
                }
            }
        }
        return fileUrls;
    }
    /**
     * 调用内网上传语音文件.
     * @param voices_Path
     * @return
     * @throws Exception

+ 10 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java

@ -1,7 +1,10 @@
package com.yihu.jw.hospital.message.dao;
import com.yihu.jw.entity.care.device.BaseSleepPlanDetail;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import org.hibernate.annotations.SQLUpdate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
@ -55,4 +58,11 @@ public interface SystemMessageDao extends PagingAndSortingRepository<SystemMessa
    @Query("select a from SystemMessageDO a where a.receiver=?1 and a.type=?2 and  a.del='1'")
    List<SystemMessageDO> getByReceiverAndType(String doctor,String type);
    @Query("select a from SystemMessageDO a where  a.type=?1 and  a.del='1'")
    Page<SystemMessageDO> getByType(String type, Pageable pageRequest);
    @Modifying
    @Query("update SystemMessageDO a set a.del=0 where a.id in (?1)")
    Integer delMessage(String[] ids);
}

+ 24 - 0
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/PrescriptionService.java

@ -11391,6 +11391,30 @@ public class PrescriptionService extends BaseJpaService<WlyyPrescriptionDO, Pres
                                  String checkPart,String chargeFlag,String chargeCode,String icdCode) throws Exception {
        Map returnMap = new HashMap();
        Integer winNo = 6;
        if (checkPart==null||checkPart==""){
            List<WlyyHospitalSysDictDO> natConfigList = wlyyHospitalSysDictDao.findByDictName("natConfigList");
            checkPart = "鼻/咽拭子";
            chargeFlag = "2";
            chargeCode = "361322";
            icdCode = "Z00.000";
            for (WlyyHospitalSysDictDO wlyyHospitalSysDictDO:natConfigList){
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"checkPart".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    checkPart = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"chargeFlag".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    chargeFlag = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"chargeCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    chargeCode = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"icdCode".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    icdCode = wlyyHospitalSysDictDO.getDictValue();
                }
                if (StringUtils.isNoneBlank(wlyyHospitalSysDictDO.getDictValue())&&"winNo".equalsIgnoreCase(wlyyHospitalSysDictDO.getDictCode())){
                    winNo = Integer.parseInt(wlyyHospitalSysDictDO.getDictValue());
                }
            }
        }
        if (wechatId.equalsIgnoreCase("xm_zsyy_wx")){
            net.sf.json.JSONObject jsondate = new JSONObject();
            jsondate.put("checkPart",checkPart);

+ 6 - 1
business/base-service/src/main/java/com/yihu/jw/hospital/prescription/service/entrance/HcyyEntranceService.java

@ -625,7 +625,11 @@ public class HcyyEntranceService {
     * @throws Exception
     */
    //查询患者就诊卡
    public String findPatientCard(String idCard)throws Exception{
    public String findPatientCard(String patient)throws Exception{
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO==null){
            throw new Exception("不存在该患者!");
        }
        String api = "FindPatientCard";
        String msgHeader ="<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<root> " +
@ -635,6 +639,7 @@ public class HcyyEntranceService {
                "   <certificate>"+key+"</certificate> " +
                "</root>";
        String condition ="";
        String idCard = patientDO.getIdcard();
        if (!StringUtils.isEmpty(idCard)){
            condition = "<identity_no>"+idCard+"</identity_no>";
        }

+ 15 - 1
business/base-service/src/main/java/com/yihu/jw/order/BusinessOrderService.java

@ -255,6 +255,18 @@ public class BusinessOrderService extends BaseJpaService<BusinessOrderDO,Busines
                        }
                    }
                }
            }else {
                BigDecimal b = new BigDecimal(String.valueOf(wlyyPrescriptionDO.getDrugFee()==null?0:wlyyPrescriptionDO.getDrugFee()));
                BigDecimal c = new BigDecimal(String.valueOf(100));
                BigDecimal bc = b.multiply(c);
                BigDecimal dc = new BigDecimal(0);
                //判断检查检验项目是否有金额
                if (wlyyPrescriptionDO.getInspectFee()!=null){
                    BigDecimal d = new BigDecimal(String.valueOf(wlyyPrescriptionDO.getInspectFee()));
                    dc= d.multiply(c);
                }
                businessOrderDO.setPayPrice(bc.doubleValue());
                businessOrderDao.save(businessOrderDO);
            }
        }
        return businessOrderDOS;
@ -960,10 +972,12 @@ public class BusinessOrderService extends BaseJpaService<BusinessOrderDO,Busines
                                        if (StringUtils.isNoneBlank(wlyyPrescriptionDO.getAdmNo())){
                                            condition = " t.JZXH = '"+wlyyPrescriptionDO.getAdmNo()+"' and ";
                                        }
                                        String address =wlyyPrescriptionExpressageDO.getProvinceName()+ wlyyPrescriptionExpressageDO.getCityName()+wlyyPrescriptionExpressageDO.getTownName()+wlyyPrescriptionExpressageDO.getAddress();
                                        //同步his写入自取信息
                                        String updatesql = "update v_ms_dd01 t set t.PSFS = 0 ,t.FKZT=1 ,t.SJR= '"+wlyyPrescriptionExpressageDO.getName()+"' ," +
                                                " t.SJRDH = '"+wlyyPrescriptionExpressageDO.getMobile()+"' ,"+
                                                " t.SJRDZ = '"+wlyyPrescriptionExpressageDO.getAddress()+"' ,"+
                                                " t.SJRDZ = '"+address+"' ,"+
                                                " t.YFSB = '"+wlyyPrescriptionExpressageDO.getHospitalCode()+"'"+
                                                " where "+condition+" t.CFSB ='"+wlyyPrescriptionDO.getRealOrder()+"'";
                                        ykyyEntranceService.updateHisStatus(updatesql);

+ 309 - 1
business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java

@ -23,6 +23,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@ -48,6 +49,8 @@ public class ElasticsearchUtil {
    private ElasticFactory elasticFactory;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${es.type.Statistics}")
    private String esType;
    @Value("${es.index.Statistics}")
@ -336,6 +339,12 @@ public class ElasticsearchUtil {
     */
        public List findDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel) throws Exception {
        String areaLevel="6";
        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);
        }
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
@ -392,7 +401,7 @@ public class ElasticsearchUtil {
//        sql.append(" quotaCode='" + index + "'  ");
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='6'");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
@ -433,6 +442,9 @@ public class ElasticsearchUtil {
    public List findDateQuotaLevel0(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel,String areaLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isBlank(areaLevel)){
            areaLevel="6";
        }
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
@ -1100,6 +1112,135 @@ public class ElasticsearchUtil {
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 多维度指标查寻(可控纬度与分组)
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @param groupKey
     * @param slaveKeys
     * @return
     */
    public List findDateQuotaLevels(String startDate, String endDate, String area, int level, String index, String timeLevel,String interval, String lowLevel,String groupKey,String ...slaveKeys) {
        String areaLevel="6";
        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);
        }
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        String[] groupKeys = groupKey.split(",");
        StringBuffer selectKeys = new StringBuffer();
        StringBuffer groupStr = new StringBuffer();
        int i=1;
        for (String slaveKeyTmp:slaveKeys){
            selectKeys.append(" slaveKey").append(i).append(" as slaveKey").append(i).append(",slaveKey").append(i).append("Name as slaveKey").append(i).append("Name, ");
            i++;
        }
        for (String groupKeyTmp:groupKeys){
            groupStr.append(",slaveKey"+groupKeyTmp+",slaveKey"+groupKeyTmp+"Name");
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName").append(groupStr.toString());
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName").append(groupStr.toString());
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName").append(groupStr.toString());
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName").append(groupStr.toString());
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,"+selectKeys.toString()+"sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName").append(groupStr.toString());
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        i=1;
        for (String slaveKeyTmp:slaveKeys){
            if (StringUtils.isNotBlank(slaveKeyTmp)){
                String[] str = slaveKeyTmp.split(",");
                StringBuffer buffer = new StringBuffer();
                for (int j=0;j<str.length;j++){
                    buffer.append("'"+str[j]+"',");
                }
                buffer.deleteCharAt(buffer.length()-1);
                sql.append(" and slaveKey").append(i).append(" in (" + buffer + ")");
            }
            i++;
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql :" + sql.toString());
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 二级指标查询
     */
@ -1232,6 +1373,134 @@ public class ElasticsearchUtil {
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 二级指标查询,并根据key分组查询
     *
     */
    public List findDateQuotaLevel2ByKeyGroup(String startDate, String endDate, String area, int level, String index, String timeLevel, String slaveKey1, String slaveKey2, String interval, String lowLevel,String areaLevel,String keyGroup) {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
        if (StringUtils.isNotEmpty(startDate)) {
            if (startDate.length() > 10) {
                startDate = changeTime(startDate);
            } else {
                startDate = changeDate(startDate);
            }
        }
        if (StringUtils.isNotEmpty(endDate)) {
            if (endDate.length() > 10) {
                endDate = changeTime(endDate);
            } else {
                endDate = changeDate(endDate);
            }
        }
        StringBuffer sql = new StringBuffer();
        StringBuffer groupBy = new StringBuffer();
        String low_level = level + "";
        if (StringUtils.isNotEmpty(lowLevel)) {
            low_level = lowLevel;
        }
        if (SaveModel.doctorLevel.equals(low_level)) {
            sql.append("select doctor as doctor,doctorName as doctorName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by doctor,doctorName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }else if (SaveModel.deptLevel.equals(low_level)) {
            sql.append("select dept as dept,deptName as deptName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by dept,deptName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.OrgLevel.equals(low_level)) {
            sql.append("select hospital as hospital,hospitalName as hospitalName,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by hospital,hospitalName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.townLevel.equals(low_level)) {
            sql.append("select town as town,townName as townName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by town,townName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        } else if (SaveModel.cityLevel.equals(low_level)) {
            sql.append("select city as city,cityName as cityName,slaveKey1 as slaveKey1,slaveKey1Name as slaveKey1Name,slaveKey2 as slaveKey2,slaveKey2Name as slaveKey2Name,sum(result1) as result1,sum(result2) as result2 from " + esIndex + " where ");
            groupBy.append("  group by city,cityName");
            if ("2".equals(keyGroup)){
                groupBy.append(",slaveKey2,slaveKey2Name");
            }else {
                groupBy.append(",slaveKey1,slaveKey1Name");
            }
        }
        if (StringUtils.isNotEmpty(area)) {
            if (SaveModel.doctorLevel.equals(level + "")) {
                sql.append(" doctor='" + area + "'");
            }else if (SaveModel.deptLevel.equals(level + "")) {
                sql.append(" dept='" + area + "'");
            } else if (SaveModel.OrgLevel.equals(level + "")) {
                sql.append(" hospital='" + area + "'");
            } else if (SaveModel.townLevel.equals(level + "")) {
                sql.append(" town='" + area + "'");
            } else if (SaveModel.cityLevel.equals(level + "")) {
                sql.append(" city='" + area + "'");
            }
            sql.append(" and ");
        }
        sql.append(" quotaCode in(" + index + ")  ");
        sql.append(" and timeLevel='" + timeLevel + "'  ");
        sql.append(" and areaLevel='"+areaLevel+"'");
        if (StringUtils.isNotEmpty(startDate)) {
            sql.append(" and quotaDate>='" + startDate + "'");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            sql.append(" and quotaDate<='" + endDate + "'");
        }
        if (StringUtils.isNotBlank(slaveKey1) && (!commonParams.equals(slaveKey1))) {
            String[] str = slaveKey1.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey1 in (" + buffer + ")");
        }
        if (StringUtils.isNotBlank(slaveKey2) && (!commonParams.equals(slaveKey2))) {
            String[] str = slaveKey2.split(",");
            StringBuffer buffer = new StringBuffer();
            for (int i=0;i<str.length;i++){
                buffer.append("'"+str[i]+"',");
            }
            buffer.deleteCharAt(buffer.length()-1);
            sql.append(" and slaveKey2 in (" + buffer + ")");
        }
        //根据时间维度分组
        if (StringUtils.isNotEmpty(interval)) {
            if (SaveModel.interval_month.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='month','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_week.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='week','time_zone'='+08:00','alias'='quotaDate') ");
            } else if (SaveModel.interval_day.equals(interval)) {
                groupBy.append(" ,date_histogram(field='quotaDate','interval'='1d','time_zone'='+08:00','alias'='quotaDate') ");
            }
        }
        sql.append(groupBy);
        logger.info("sql :" + sql.toString());
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     * 时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
     *
@ -1364,6 +1633,20 @@ public class ElasticsearchUtil {
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    /**
     *获取一个指标下所有二级维度按维度分组的数据
     * @param startDate
     * @param endDate
     * @param area
     * @param level
     * @param index
     * @param timeLevel
     * @param interval
     * @param lowLevel
     * @param areaLevel
     * @return
     * @throws Exception
     */
    public List findDateAllQuotaLevel2(String startDate, String endDate, String area, int level, String index, String timeLevel, String interval, String lowLevel,String areaLevel) throws Exception {
        //时间格式转换  yyyy-MM-dd转成 2017-07-17T00:00:00+0800
@ -1560,6 +1843,11 @@ public class ElasticsearchUtil {
        return (SaveModel) list.get(0);
    }
//    public SaveModel findOneDateQuotaLevel1(String startDate, String endDate, String area, int level, String index, String timelevel,String slaveKey1,String areaLevel) throws Exception {
//        List list = findDateQuotaLevel1(startDate, endDate, area, level, index, timelevel, slaveKey1, null, null);
//        return (SaveModel) list.get(0);
//    }
    /**
     * 1级维度
     * 查询某一天某一个1级维度的某个1级维度下的指标 例如查询65岁以上患者
@ -1660,6 +1948,14 @@ public class ElasticsearchUtil {
        return (SaveModel) list.get(0);
    }
    /**
     * 多维度指标查询 可控制key与group
     */
    public  SaveModel findOneDateQuotaLevels(String startDate, String endDate, String area, int level, String index, String timelevel,String groupKey,String ...slaveKeys) throws Exception {
        List list = findDateQuotaLevels(startDate, endDate, area, level, index, timelevel,null, null,groupKey,slaveKeys);
        return (SaveModel) list.get(0);
    }
    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
@ -1676,6 +1972,14 @@ public class ElasticsearchUtil {
        return list;
    }
    /**
     * 多维度指标查询 可控制key与group
     */
    public  List<SaveModel> findDateQuotaLevelList(String startDate, String endDate, String area, int level, String index, String timelevel,String groupKey,String ...slaveKeys) throws Exception {
        List list = findDateQuotaLevels(startDate, endDate, area, level, index, timelevel,null, null,groupKey,slaveKeys);
        return list;
    }
    /**
     * 1级维度
     * 查询某一天某一个所有1级维度下的指标 例如某个机构下的所有维度的患者列表
@ -2429,4 +2733,8 @@ public class ElasticsearchUtil {
        return excute(sql.toString(), SaveModel.class, "", "");
    }
    public List searchBySql(String sql){
        return excute(sql, SaveModel.class, "", "");
    }
}

+ 10 - 0
server/svr-authentication/pom.xml

@ -196,6 +196,16 @@
            <artifactId>spring-test</artifactId>
            <!--<version>RELEASE</version>-->
        </dependency>
        <dependency>
            <groupId>com.zy</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>4.10.159.ALL</version>
        </dependency>
        <dependency>
            <groupId>com.zy</groupId>
            <artifactId>kasite-sdk</artifactId>
            <version>20201027</version>
        </dependency>
    </dependencies>
    <build>

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

@ -1,5 +1,6 @@
package com.yihu.jw.security.core.userdetails.jdbc;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.login.BaseLoginLogDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
@ -14,6 +15,7 @@ import com.yihu.jw.security.dao.patient.BasePatientWechatDao;
import com.yihu.jw.security.dao.patient.WlyyPatientFamilyMemberDao;
import com.yihu.jw.security.model.WlyyUserDetails;
import com.yihu.jw.security.model.WlyyUserSimple;
import com.yihu.jw.security.service.HcyyService;
import com.yihu.jw.security.utils.IdCardUtil;
import com.yihu.jw.security.utils.ImUtil;
import com.yihu.jw.util.date.DateUtil;
@ -105,6 +107,8 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
    @Autowired
    private BaseGetuiClientDao baseGetuiClientDao;
    @Autowired
    private HcyyService hcyyService;
    @Autowired
    private ImUtil imUtil;
    @Value("${kick.eachOther}")
    private String kickEachOther;
@ -971,6 +975,58 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        return null;
    }
    public JSONObject getHcHLWyyUser(String openid,String memberId){
        JSONObject patient = new JSONObject();
        try {
            String result = hcyyService.queryMemberByOpenId(openid,memberId);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String RespCode = jsonObject.getString("RespCode");
            BasePatientDO patient1 = new BasePatientDO();
            if (RespCode.equalsIgnoreCase("10000")){
                JSONArray array = jsonObject.getJSONArray("Data");
                if (array!=null&&array.size()!=0){
                    patient = array.getJSONObject(0);
                    String idcard = patient.getString("IdCardNo");
                    BasePatientDO patientDO2 = patientDao.findByIdcardAndDel(idcard,"1");
                    String salt = UUID.randomUUID().toString().substring(0,5);
                    String mobile = patient.getString("Mobile");
                    String pw = null;
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(mobile)){
                        pw = mobile.substring(mobile.length()-6);
                    }else{
                        pw = idcard.substring(idcard.length()-6);
                    }
                    if (patientDO2!=null){
                        patient1=patientDO2;
                    }else {
                        patient1.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                        patient1.setSalt(salt);
                    }
                    patient1.setIdcard(idcard);
                    patient1.setCardType(patient.getString("CardType"));
                    patient1.setName(patient.getString("MemberName"));
                    patient1.setSex(StringUtils.isNotBlank(idcard)?Integer.parseInt(IdCardUtil.getSexForIdcard_new(idcard)):null);
                    patient1.setMobile(mobile);
                    patient1.setDel("1");
                    patient1.setEnabled(1);
                    patient1.setLocked(0);
                    patient1.setCreateTime(new Date());
                    patient1.setUpdateTime(new Date());
                    patient1.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));
                    patient1 = patientDao.save(patient1);
                    logger.info("结束同步患者数据");
                }
            }
                return patient;
        }catch (Exception e){
            logger.error(e);
        }
        return null;
    }
    public static void main(String arg[]){
        String ps = MD5.md5Hex("327127" + "{" + "Ar8f2" + "}");

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

@ -1727,41 +1727,50 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    }
    @RequestMapping(value = "/oauth/ssoPatientLogin", method = RequestMethod.POST)
    public ObjEnvelop ssoPatientLogin(String authCode,String client_id,String code,String appId,String login_type){
    public ObjEnvelop ssoPatientLogin(String authCode,String client_id,String code,String appId,String login_type,String openId,String memberId){
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id is null");
        }
        if (StringUtils.isEmpty(authCode)) {
            throw new InvalidRequestException("authCode is null");
        }
        if (StringUtils.isEmpty(code)) {
            throw new InvalidRequestException("code is null");
        }
        if (StringUtils.isEmpty(appId)) {
            throw new InvalidRequestException("appId is null");
        if (!wechatId.equalsIgnoreCase("xm_hcyy_wx")){
            if (StringUtils.isEmpty(client_id)) {
                throw new InvalidRequestException("client_id is null");
            }
            if (StringUtils.isEmpty(authCode)) {
                throw new InvalidRequestException("authCode is null");
            }
            if (StringUtils.isEmpty(code)) {
                throw new InvalidRequestException("code is null");
            }
            if (StringUtils.isEmpty(appId)) {
                throw new InvalidRequestException("appId is null");
            }
        }
        try {
            logger.info("authCode :"+authCode);
            Map<String, String> parameters = new HashedMap();
            if (!wechatId.equalsIgnoreCase("xm_hcyy_wx")) {
                logger.info("authCode :"+authCode);
            Map<String,Object> rs = oauthSsoService.savePatient(code,appId,authCode,wechatId);
            Integer c = (Integer) rs.get("code");
            if(c != 1){
                return ObjEnvelop.getError(rs.get("mes")+"");
            }
                Map<String,Object> rs = oauthSsoService.savePatient(code,appId,authCode,wechatId);
                Integer c = (Integer) rs.get("code");
                if(c != 1){
                    return ObjEnvelop.getError(rs.get("mes")+"");
                }
            BasePatientDO patientDO = (BasePatientDO)rs.get("patient");
            if(patientDO==null){
                return ObjEnvelop.getError("获取居民信息失败");
                BasePatientDO patientDO = (BasePatientDO)rs.get("patient");
                if(patientDO==null){
                    return ObjEnvelop.getError("获取居民信息失败");
                }
                parameters.put("username",patientDO.getIdcard());
                parameters.put("grant_type", "ihealthCode");
            }else {
                JSONObject patient = userDetailsService.getHcHLWyyUser(openId,memberId);
                if (patient==null){
                    return ObjEnvelop.getError("获取居民信息失败");
                }
                parameters.put("username",patient.getString("IdCardNo"));
                parameters.put("grant_type", "ihealthCode");
            }
            ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
            Map<String, String> parameters = new HashedMap();
            parameters.put("username",patientDO.getIdcard());
            parameters.put("grant_type", "ihealthCode");
            TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
            if (authenticatedClient != null) {
                oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);

File diff suppressed because it is too large
+ 58 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/service/HcyyService.java


+ 13 - 35
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/device/DeviceManageEndpoint.java

@ -39,6 +39,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@ -79,6 +81,8 @@ public class DeviceManageEndpoint extends EnvelopRestEndpoint {
    private YsDeviceService ysDeviceService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @GetMapping("findWlyyDevices")
    @ApiOperation("获取设备列表")
@ -133,46 +137,20 @@ public class DeviceManageEndpoint extends EnvelopRestEndpoint {
    @GetMapping(value = "getUserDevice")
    @ApiOperation("居民设备查询")
    public PageEnvelop<WlyyPatientDeviceVO> getUserDevice(
            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
            @RequestParam(value = "fields", required = false) String fields,
            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
            @RequestParam(value = "filters", required = false) String filters,
            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
            @RequestParam(value = "sorts", required = false) String sorts,
            @ApiParam(name = "id", value = "id")
            @RequestParam(value = "id", required = false) String id,
            @ApiParam(name = "userName", value = "userName")
            @RequestParam(value = "userName", required = false) String userName,
            @ApiParam(name = "userIdcard", value = "userIdcard")
            @RequestParam(value = "userIdcard", required = false) String userIdcard,
            @ApiParam(name = "categoryCode", value = "userIdcard")
            @RequestParam(value = "categoryCode", required = false) String categoryCode,
            @ApiParam(name = "page", value = "分页大小", required = true, defaultValue = "1")
            @RequestParam(value = "page") int page,
            @ApiParam(name = "size", value = "页码", required = true, defaultValue = "15")
            @RequestParam(value = "size") int size){
        try {
             if (StringUtils.isBlank(filters)){
                 filters="del=0";
             }else {
                 filters+=";del=0";
             }
             List<DevicePatientDevice> list = patientDeviceService.search(fields, filters, sorts,page,size);
             List<WlyyPatientDeviceVO> list2 = new ArrayList<>();
             for (DevicePatientDevice tmp:list){
                 WlyyPatientDeviceVO deviceVO= new WlyyPatientDeviceVO();
                 BeanUtils.copyProperties(tmp, deviceVO, getNullPropertyNames(tmp));
                 deviceVO.setId(tmp.getId().intValue());
                 BasePatientDO patient = patientDao.findById(tmp.getUser());
                 if (patient!=null){
                     deviceVO.setUserName(patient.getName());
                 }
                 List<DeviceDetail> deviceDetails = deviceDetailDao.findByDeviceCode(deviceVO.getDeviceSn());
                 if (deviceDetails.size()>0){
                     DeviceDetail deviceDetail = deviceDetails.get(0);
                     deviceVO.setSim(deviceDetail.getSim());
                     deviceVO.setIccid(deviceDetail.getIccid());
                     deviceVO.setImsi(deviceDetail.getImsi());
                     deviceVO.setDeviceModel(deviceDetail.getDeviceModel());
                     deviceVO.setManufacturer(deviceDetail.getManufacturer());
                 }
                 list2.add(deviceVO);
             }
             int count = (int) patientDeviceService.getCount(filters);
             return success(list2, count, page, size);
            return patientDeviceService.getUserDevice(id,userName,userIdcard,categoryCode,page,size);
        }catch (Exception e){
            return failedPageEnvelopException2(e);
        }

+ 29 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/WlyyPatientDeviceService.java

@ -2,8 +2,12 @@ package com.yihu.jw.base.service.device;
import com.yihu.jw.base.dao.device.PatientDeviceDao;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.restmodel.iot.device.WlyyPatientDeviceVO;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import java.util.List;
@ -34,4 +38,29 @@ public class WlyyPatientDeviceService extends BaseJpaService<DevicePatientDevice
            jdbcTemplate.update(sql,new Object[]{2,deviceSn});
        }
    }
    public PageEnvelop<WlyyPatientDeviceVO> getUserDevice(String id,String userName,String userIdcard,String categoryCode,Integer page,Integer size){
        page = page>0?page-1:0;
        String sqlCondition = " from wlyy_patient_device pd " +
                " INNER JOIN base_patient p on pd.`user` = p.id INNER JOIN wlyy_devices wd on pd.device_sn = wd.device_code " +
                " where pd.del=0 ";
        if (StringUtils.isNotBlank(id)){
            sqlCondition+=" and pd.id='"+id+"' ";
        }
        if (StringUtils.isNotBlank(userName)){
            sqlCondition+=" and p.name like '%"+userName+"%' ";
        }
        if (StringUtils.isNotBlank(userIdcard)){
            sqlCondition+=" and pd.user_idcard like '%"+userIdcard+"%' ";
        }
        if (StringUtils.isNotBlank(categoryCode)){
            sqlCondition+=" and pd.category_code = '"+categoryCode+"' ";
        }
        String sqlCount = "select count(pd.id) " + sqlCondition;
        Long count = jdbcTemplate.queryForObject(sqlCount,Long.class);
        String sql = "select pd.*,p.name user_name,wd.device_model,wd.manufacturer " + sqlCondition +" limit "+page*size+","+size ;
        List<WlyyPatientDeviceVO> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(WlyyPatientDeviceVO.class));
        return PageEnvelop.getSuccessListWithPage("查询成功",list,page, size,count);
    }
}

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

@ -258,4 +258,14 @@ public class OpenStatisticsEndpoint extends EnvelopRestEndpoint {
        }
    }
    @GetMapping("searchBySql")
    @ApiOperation(value = "ES查询")
    public ListEnvelop searchBySql(
            @RequestParam(required = true) String sql) {
        try {
            return ListEnvelop.getSuccess("查询成功",statisticsService.searchBySql(sql));
        } catch (Exception e) {
            return failedListEnvelopException2(e);
        }
    }
}

+ 143 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/StatisticsEndpoint.java

@ -2,18 +2,20 @@ package com.yihu.jw.care.endpoint.statistics;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.service.statistics.StatisticsService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import java.util.Locale;
/**
 * Created by yeshijie on 2021/4/7.
@ -208,5 +210,142 @@ public class StatisticsEndpoint extends EnvelopRestEndpoint {
        return ObjEnvelop.getError("查询失败",-1);
    }
    @GetMapping("olderBindingDeviceStatus")
    @ApiOperation("管理端首页老人接入情况")
    public ObjEnvelop olderBindingDeviceStatus(@RequestParam(required = false) String area,
                                               @RequestParam(required = false) Integer level){
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.olderBindingDeviceStatus(area));
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "statisticsSecurityOlder")
    @ApiOperation(value = "管理端首页安防监护统计分析")
    public ObjEnvelop statisticsSecurityOlder(
            @RequestParam(required = true) String endDate,
            @RequestParam(required = true) String area,
            @RequestParam(required = true) int level,
            @ApiParam(name="type",value="类型:1本周,2本月",defaultValue = "")@RequestParam(required = false) String type) {
        try {
            JSONObject result = statisticsService.statisticsSecurityOlder(endDate,area,level, type);
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "deviceGrantAndService")
    @ApiOperation("设备分析--投放、照护类型")
    public ObjEnvelop deviceGrantAndService(@RequestParam(required = false) String area,
                                            @RequestParam(required = false) Integer level){
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.deviceGrantAndService());
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "getAllDeviceLostMessage")
    @ApiOperation("设备分析--异常消息通知")
    public PageEnvelop getAllDeviceLostMessage(@RequestParam(required = false) String area,
                                              @RequestParam(required = false) Integer level,
                                              @RequestParam(required = false) Integer page,
                                              @RequestParam(required = false) Integer size){
        try {
           return statisticsService.getAllDeviceLostMessage(area,page,size);
        }catch (Exception e){
            return failedPageEnvelopException2(e);
        }
    }
    @PostMapping(value = "/delMessageRead")
    @ApiOperation("删除消息")
    @ObserverRequired
    public Envelop delMessageRead(@ApiParam(name = "messageId",required = true)
                                  @RequestParam(value = "messageId")String messageId){
        try {
            statisticsService.delMessageRead(messageId);
            return Envelop.getSuccess("修改成功");
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @GetMapping(value = "deviceUsingInfo")
    @ApiOperation("设备分析--使用管理")
    public ObjEnvelop deviceUsingInfo(@RequestParam(required = false) String area,
                                      @RequestParam(required = false) Integer level){
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.deviceUsingInfo(area));
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "getSecurityOrderList")
    @ApiOperation("管理端安防监护--安防动态")
    public PageEnvelop getSecurityOrderList(@RequestParam(required = false) String area,
                                            @RequestParam(required = false) String status,
                                            @RequestParam(required = false) Integer level,
                                            @RequestParam(required = false) String svrDesc,
                                            @RequestParam(required = false) String topicItem,
                                            @RequestParam(required = false) Integer page,
                                            @RequestParam(required = false) Integer size){
        try {
            return statisticsService.getSecurityOrderList(area,status,svrDesc,topicItem,page,size);
        }catch (Exception e){
            return failedPageEnvelopException2(e);
        }
    }
    @GetMapping(value = "getSecurityTab")
    @ApiOperation(value = "获取安防tab数量")
    public ObjEnvelop getSecurityTab(@RequestParam(required = false) String area,
                                     @RequestParam(required = false) Integer level,
                                     @ApiParam(name="status",value = "工单状态-2误报警-1已取消0已完成1申请中")
                                     @RequestParam(value = "status",required = false)String status,
                                     @ApiParam(name="svrDesc",value = "服务类型 关联security_server_dict字典")
                                     @RequestParam(value = "svrDesc",required = false)String svrDesc,
                                     @ApiParam(name = "topicItem", value = "专题code,关联security_topic_dict字典", required = false)
                                     @RequestParam(value = "topicItem",required = false) String topicItem){
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.getSecurityTab(area,status,svrDesc,topicItem));
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "statisticsSecurityWarnInfo")
    @ApiOperation(value = "管理端安防监护--预警分析")
    public ObjEnvelop statisticsOrderServer(
            @RequestParam(required = true) String endDate,
            @RequestParam(required = true) String area,
            @RequestParam(required = true) Integer level,
            @RequestParam(required = true) String index) {
        try {
            JSONObject result = statisticsService.statisticsSecurityWarnInfo(endDate,area,level,index);
            return success(result);
        } catch (Exception e) {
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "statisticsSecurityTrend")
    @ApiOperation(value = "管理端安防监护--安防工单累计趋势折线")
    public ListEnvelop statisticsSecurityTrend(
            @RequestParam(required = true) String startDate,
            @RequestParam(required = true) String endDate,
            @RequestParam(required = true) String area,
            @RequestParam(required = true) Integer level,
            @RequestParam(required = true) String index) {
        try {
            return ListEnvelop.getSuccess("查询成功",statisticsService.statisticsSecurityTrend(startDate,endDate,area,level,index)) ;
        } catch (Exception e) {
            return failedListEnvelopException2(e);
        }
    }
}

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

@ -250,7 +250,7 @@ public class SecurityMonitoringOrderService extends BaseJpaService<SecurityMonit
        for (BaseDoctorDO doctorDO:doctorDOS){
            try {
                if (StringUtils.isNotBlank(doctorDO.getMobile())){
                    messageUtil.sendTXYSJson("1099807",doctorDO.getMobile(),orderDO.getPatientName(),orderDO.getServeDesc());
                    messageUtil.sendTXYSJson("1141719",doctorDO.getMobile(),orderDO.getPatientName(),orderDO.getServeDesc());
                }
            }catch (Exception e){}
            imUtil.sendMDTSocketMessageToDoctor(doctorDO.getId(),message.toString());

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

@ -135,10 +135,10 @@ public class DetectionPlatformService  {
        Long healthIsUser = (Long) healthList.get(0).get("isUse");
        Long securityAllCount = (Long) securityList.get(0).get("allCount");
        Long healthAllCount = (Long) healthList.get(0).get("allCount");
        object.put("lawOfIOT",getRange( (securityIsUser.intValue() + healthIsUser.intValue() ),( securityAllCount.intValue() + healthAllCount.intValue()  ) ));//物联率
        object.put("lawOfIOT",getRange( (securityIsUser.intValue() + healthIsUser.intValue() ),( securityAllCount.intValue() + healthAllCount.intValue()  ) ));//物联率 发放了就算物联
        object.put("isUseAllIot",(securityIsUser.intValue() + healthIsUser.intValue()));//已发放设备
        object.put("allIot",securityAllCount.intValue() + healthAllCount.intValue());//总设备
        String unUseSql = "SELECT wd.* FROM wlyy_devices wd INNER JOIN wlyy_patient_device pd on wd.device_code =pd.device_sn  WHERE contact_status = 0";//contact_status = 0   失联
        String unUseSql = "SELECT DISTINCT wd.device_code FROM wlyy_devices wd INNER JOIN wlyy_patient_device pd on wd.device_code =pd.device_sn  WHERE contact_status = 0";//contact_status = 0   失联
        List<Map<String , Object>> unUseList = jdbcTemplate.queryForList(unUseSql);
        int unUseCount = unUseList.size();
        object.put("unUseCount",unUseCount);//设备失联数量
@ -403,10 +403,10 @@ public class DetectionPlatformService  {
                model = (String) passportType.get(i).get("model");
                model = model.replace(",","','");
                if ( count.intValue() > 0) {
                    useSql = "SELECT COUNT(1) FROM wlyy_patient_device WHERE category_code IN ("+ passportType.get(i).get("category_code") +") AND del = 0";
                    useSql = "SELECT COUNT(DISTINCT device_sn) FROM wlyy_patient_device WHERE category_code IN ("+ passportType.get(i).get("category_code") +") AND del = 0";
                    use = jdbcTemplate.queryForObject(useSql,Integer.class);
                    passportType.get(i).put("use",use);//使用
                    allSql = "SELECT COUNT(1) FROM wlyy_devices WHERE device_model IN ('"+ model +"')";
                    allSql = "SELECT COUNT(DISTINCT device_code) FROM wlyy_devices WHERE device_model IN ('"+ model +"')";
                    putOnFile = jdbcTemplate.queryForObject(allSql,Integer.class);
                    passportType.get(i).put("putOnFile",putOnFile); //备案
                    passportType.get(i).put("stock",putOnFile - use); //库存

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

@ -3,6 +3,8 @@ package com.yihu.jw.care.service.statistics;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.util.CommonUtil;
import com.yihu.jw.care.util.ConstantUtil;
import com.yihu.jw.care.vo.NumVo;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
@ -11,23 +13,35 @@ import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.login.BaseLoginLogDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.hospital.message.SystemMessageDO;
import com.yihu.jw.es.util.ElasticsearchUtil;
import com.yihu.jw.es.util.SaveModel;
import com.yihu.jw.hospital.message.dao.SystemMessageDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
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.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.Transient;
import javax.persistence.criteria.CriteriaBuilder;
import java.awt.print.Pageable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@ -56,6 +70,14 @@ public class StatisticsService {
    private StatisticsUtilService statisticsUtilService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private SystemMessageDao systemMessageDao;
    private static final String defalutArea = "330100";
@ -454,8 +476,8 @@ public class StatisticsService {
        }
        String sql1 = "SELECT COUNT(*) c,IFNULL(on_line,0) online from base_patient a WHERE archive_type = 1" +
                " and del='1' "+oldFilter+" GROUP BY on_line";
        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){
            Integer num = Integer.valueOf(map.get("c").toString());
@ -528,14 +550,21 @@ public class StatisticsService {
    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){
            //总量
            SaveModel saveModel = elasticsearchUtil.findOneDateQuotaLevel0(endDate, endDate, area, level, ind, SaveModel.timeLevel_DDL);
            if (ind.equals("41")||ind.equals("46")){//指标统计最小单位
                areaLevel="4";
            }
            if (ind.equals("45")){
                areaLevel="2";
            }
            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);
                SaveModel saveModelAdd = elasticsearchUtil.findOneDateQuotaLevel0(start, endDate, area, level, ind, SaveModel.timeLevel_ZL,areaLevel);
                res.put("index_"+ind+"_add",saveModelAdd.getResult2().longValue());
            }
@ -647,7 +676,6 @@ public class StatisticsService {
     */
    public JSONObject patientAnalysis(String endDate, String area, int level,String index) throws Exception{
        JSONObject res = new JSONObject();
        String areaLevel = "6";
        if("42".equals(index)){
            areaLevel = "4";
@ -667,26 +695,31 @@ public class StatisticsService {
        }else{
            //老人
            //能力评估 从签约时服务标签取
            JSONArray levelArray = new JSONArray();
            String sql = " select dict.dict_code,dict_value,count(DISTINCT lab.patient) total from wlyy_hospital_sys_dict dict \n" +
                    "LEFT JOIN wlyy_patient_label lab  on  dict.dict_code = lab.label_code AND  lab.label_type='1' " +
                    "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);
            String older = "  select count(DISTINCT patient) from wlyy_patient_label where label_type='1' ";
            Integer count = jdbcTemplate.queryForObject(older,Integer.class);
            res.put("levelList",capacityAssessment(null,null,null));
            for(Map<String,Object> map:list){
            //居民健康标签
            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();
                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());
                levelArray.add(json);
                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);
            }
            res.put("levelList",levelArray);
            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");
@ -704,17 +737,47 @@ public class StatisticsService {
                ageArray.add(json);
            }
            res.put("ageList",ageArray);
        }
        //性别
        List<SaveModel> sexList = elasticsearchUtil.findDateAllQuotaLevel2(endDate, endDate, area, level, index, SaveModel.timeLevel_DDL,null,null,areaLevel);
            //居住小区分布
            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.getSlaveKey2());
            json.put("name",saveModel.getSlaveKey2Name());
            json.put("code",saveModel.getSlaveKey1());
            json.put("name",saveModel.getSlaveKey1Name());
            sexArray.add(json);
        }
        res.put("sexList",sexArray);
@ -778,16 +841,24 @@ public class StatisticsService {
    /**
     * 能力评估评估类型
     */
    public JSONArray capacityAssessment(String endDate, String area, int 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){
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " not in ('"+orgCodes+"')";
        }
        JSONArray jsonArray = new JSONArray();
        String sql = " select dict.dict_code,dict_value,count(DISTINCT lab.patient) total from wlyy_hospital_sys_dict dict \n" +
                "LEFT JOIN wlyy_patient_label lab  on  dict.dict_code = lab.label_code AND  lab.label_type='1' " +
                "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 lab.patient "+filter+" 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);
        String older = "  select count(DISTINCT patient) from wlyy_patient_label where label_type='1' ";
        String older = "  select count(DISTINCT patient) from wlyy_patient_label where label_type='1' and patient "+filter;
        Integer count = jdbcTemplate.queryForObject(older,Integer.class);
        for(Map<String,Object> map:list){
@ -956,6 +1027,328 @@ public class StatisticsService {
        return res;
    }
    /**
     * 管理端首页老人接入情况
     * @return
     */
    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){
            String orgCodes = String.valueOf(listtmp.get(0).get("orgCodes"));
            orgCodes = orgCodes.replaceAll(",","','");
            filter = " not in ('"+orgCodes+"')";
        }
        String sql =" select count(id) from base_patient where del=1 and id "+filter;
        Integer olderCount  = jdbcTemplate.queryForObject(sql,Integer.class);
        sql = " select count(DISTINCT pd.id) from base_patient p INNER JOIN wlyy_patient_device pd on p.id = pd.user 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 {
        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)){
            //周/月 增量
            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)){
            //周/月 增量
            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){
                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());
                addDetail.add(json);
            }
        }
        res.put("index_add_detail",addDetail);
        return res;
    }
    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){
            String orgCodes = String.valueOf(listtmp.get(0).get("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);
        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);
        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," +
                " 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);
        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" +
                "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);
        return PageEnvelop.getSuccessListWithPage("查询成功",list,page++,size,count);
    }
    @Transactional
    public void delMessageRead(String msgId){
        if (StringUtils.isNotBlank(msgId)){
            String[] ids = msgId.split(",");
            if (ids.length>0){
                systemMessageDao.delMessage(ids);
            }
        }
    }
    public JSONObject deviceUsingInfo(String area){
        JSONObject result = new JSONObject();
        String sql = "SELECT COUNT(DISTINCT device_sn) FROM wlyy_patient_device WHERE del = 0";
        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);//库存
        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";//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));
        return result;
    }
    public PageEnvelop getSecurityOrderList(String area,String status, String svrDesc,String topicItem, Integer page, Integer pageSize){
        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 " +
                "where 1=1 ";
        String fliter = "  ";
        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(svrDesc)){
            fliter+=" and ord.serve_desc='"+svrDesc+"' ";
        }
        if (org.apache.commons.lang3.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);
        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("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")+""));
            String conclusionStatusName = "";
            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"));
            }
            String statusName = "";
            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);
            //患者设备
            List<DevicePatientDevice> devices = patientDeviceDao.findAllByUser(tmp.get("patientCode").toString());
            if (devices.size()>0){
                tmp.put("deviceFlag","1");
            }
            else {
                tmp.put("deviceFlag","0");
            }
            result.add(tmp);
        }
        return PageEnvelop.getSuccessListWithPage("success",result,page,pageSize,count);
    }
    public JSONObject getSecurityTab(String area,String status,String svrDesc,String topicItem){
        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);//
        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());
        }
        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(svrDesc)){
            fliter+=" and ord.serve_desc='"+svrDesc+"' ";
        }
        if (org.apache.commons.lang3.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);
        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()));
            }
        }
        return result;
    }
    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){
                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++){
                SaveModel saveModel = list.get(i);
                JSONObject json = new JSONObject();
                if (saveModel.getResult2().longValue()==0&&StringUtils.isBlank(saveModel.getSlaveKey1())){
                    continue;
                }
                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();
                jsonArray.add(json);
            }
            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);
                long finish = saveModel.getResult2().longValue();
                saveModel = elasticsearchUtil.findOneDateQuotaLevel2NoSlaveKey1(endDate,area,level,"46","2","0",areaLevel);
                finish += saveModel.getResult2().longValue();
                res.put("index_"+46+"_finish",finish);
                //安防误报警
                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 {
        //安防总数
        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){
            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));
            jsonArray.add(jsonTmp);
        }
        return jsonArray;
    }
    /**
     * 计算开始时间
@ -979,4 +1372,11 @@ public class StatisticsService {
        }
        return DateUtil.dateToStrShort(cal.getTime());
    }
    public List searchBySql(String sql){
        if (sql.startsWith("select")||sql.startsWith("SELECT")){
            return elasticsearchUtil.searchBySql(sql);
        }
        return null;
    }
}

+ 13 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/CommonUtil.java

@ -207,5 +207,18 @@ public class CommonUtil {
        return result;
    }
    public String getRange(Integer first, Integer second) {
        if (second == 0 && first > 0) {
            //如果分母为0 分子不为0 返回100%
            return "100%";
        } else if (second == 0 && first == 0) {
            //如果分母为0 分子为0 返回0%
            return "0%";
        }
        float size = (float) (first * 100) / second;
        DecimalFormat df = new DecimalFormat("0.00");//格式化小数,不足的补0
        String filesize = df.format(size);
        return filesize + "%";
    }
}

+ 42 - 0
svr/svr-internet-hospital-entrance/src/main/resources/application.yml

@ -527,3 +527,45 @@ express:
  sf_code: WH000091
  sf_check_word: SFAHKAOFAAITyjt7890
---
#海沧医院内网
spring:
  profiles: hcyyProd
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/base?useUnicode:true&characterEncoding=utf-8&autoReconnect=true&useSSL=false
    username: wlyy
    password: 2oEq3Kf7@zjxl
# mq 是否获取his数据,flag代表获取演示数据,false代表获取his真实数据
demo:
  flag: false
#支付支付
pay:
  flag: true
hospital:
  url: https://wx.xmzsh.com
  mqUser: JKZL
  mqPwd: 123456
  SourceSysCode: S60
  TargetSysCode: S01
im:
  im_list_get: http://192.168.118.240:3000/
  data_base_name: im
fastDFS:
  fastdfs_file_url: http://127.0.0.1:8888/
fast-dfs:
  tracker-server: :22122 #服务器地址
#是否开启i健康接口 0关闭,1开启
testPattern:
  sign: 0
wlyy:
  url: http://www.xmtyw.cn/wlyytest/
wechat:
  id: xm_xzzx_wx  # base库中,wx_wechat 的id字段
  flag: false #演示环境  true走Mysql数据库  false走Oracle
  url: http://172.16.100.37:8090/hospitalPortal-sms/sms/sendMessage
express:
  sf_url: http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService
  sf_code: WH000061
  sf_check_word: BEWFSCXSyjt4314rz

+ 1 - 1
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/consult/PatientConsultEndpoint.java

@ -368,7 +368,7 @@ public class PatientConsultEndpoint extends EnvelopRestEndpoint {
							logger.info("voice_wx_type:"+wechat_appid);
							voiceurl = fileUploadService.uploadWxVoice(voicepath);
//					uploadVO.setFullUri(map.get("accessory").toString());
						}else if ("xm_xzzx_wx".equalsIgnoreCase(wechat_appid)){
						}else if ("xm_xzzx_wx".equalsIgnoreCase(wechat_appid)||"xm_hcyy_wx".equalsIgnoreCase(wechat_appid)){
							voiceurl = fileUploadService.uploadWxVoiceToEntrance(remote_inner_url,voicepath);
							logger.info(voiceurl);
						}else {

+ 29 - 7
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/patient/PatientNoLoginEndPoint.java

@ -54,6 +54,7 @@ import com.yihu.jw.order.pay.utils.PayLogService;
import com.yihu.jw.order.pay.ylz.YlzPayService;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionInfoVO;
import com.yihu.jw.restmodel.hospital.prescription.WlyyPrescriptionVO;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
@ -86,18 +87,23 @@ import net.sf.json.JSONArray;
import net.sf.json.xml.XMLSerializer;
import org.apache.axis.utils.StringUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.time.DateUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.jasper.tagplugins.jstl.core.Url;
import org.apache.http.entity.ContentType;
import org.apache.poi.util.IOUtils;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@ -234,6 +240,11 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private YqfkService yqfkService;
    @Value("${testPattern.sign}")
    private String isClose;
    @Value("${testPattern.remote_inner_url}")
    private String remote_inner_url;
    @GetMapping(value = BaseHospitalRequestMapping.PatientNoLogin.findDoctorByHospitalAndDiseaseAndDept)
@ -509,7 +520,7 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
            return  failedObjEnvelopException(e);
        }
    }
    
    @GetMapping(value = BaseHospitalRequestMapping.PatientNoLogin.getUpcomingByDoctor)
    @ApiOperation(value = "获取医生待办详情", notes = "获取医生待办详情")
    public Envelop getUpcomingByDoctor(@ApiParam(name = "doctorIdcard", value = "doctorIdcard", required = true)
@ -1962,6 +1973,7 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
            @ApiParam(name = "times", value = "")
            @RequestParam(value = "times",required = false) Integer times) throws Exception {
        JSONObject object = new JSONObject();
        UploadVO uploadVO = new UploadVO();
        //处理语音文件
        if(!org.springframework.util.StringUtils.isEmpty(wxId)){
@ -1979,7 +1991,12 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
                        voiceurl = fileUploadService.uploadWxVoice(voicepath);
//					uploadVO.setFullUri(map.get("accessory").toString());
                    }else {
                        voiceurl = fileUtil.copyTempVoice(voicepath,fastdfs_file_url);
                        if(isClose.equals("2")){
                            voiceurl = fileUploadService.uploadInLocalWxVoice(voicepath,remote_inner_url);
                        }else {
                            voiceurl = fileUtil.copyTempVoice(voicepath,fastdfs_file_url);
                        }
                    }
                    obj.put("path", voiceurl);
                    obj.put("times", times);
@ -1997,7 +2014,12 @@ public class PatientNoLoginEndPoint extends EnvelopRestEndpoint {
                        imgeUrl = fileUploadService.uploadWxImage(imagepath);
//					uploadVO.setFullUri(map.get("accessory").toString());
                    }else{
                        imgeUrl = fileUtil.copyTempImage(imagepath,upload_temp_path);
                        if(isClose.equals("2")){
                            imgeUrl = fileUploadService.uploadInLocalWxImage(imagepath,upload_temp_path,remote_inner_url);
                        }else {
                            imgeUrl = fileUtil.copyTempImage(imagepath,upload_temp_path);
                        }
                    }
                    logger.info("imgeUrl"+imgeUrl);
                    object.put("path",imgeUrl);

+ 13 - 4
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/prescription/PrescriptionEndpoint.java

@ -28,10 +28,7 @@ import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionDiagnosisDao;
import com.yihu.jw.hospital.prescription.dao.PrescriptionInfoDao;
import com.yihu.jw.hospital.prescription.service.*;
import com.yihu.jw.hospital.prescription.service.entrance.DoctorPreSignService;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.TnyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.*;
import com.yihu.jw.hospital.service.SystemMessage.HospitalSystemMessageService;
import com.yihu.jw.im.dao.ConsultDao;
import com.yihu.jw.im.service.ImService;
@ -158,6 +155,8 @@ public class PrescriptionEndpoint extends EnvelopRestEndpoint {
    private String qywxUrl;
    @Autowired
    public ImUtil imUtil;
    @Autowired
    private HcyyEntranceService hcyyEntranceService;
    
    @GetMapping(value = BaseHospitalRequestMapping.Prescription.findOutpatientList)
    @ApiOperation(value = " 查询某个时间段的患者门诊就诊记录")
@ -372,6 +371,16 @@ public class PrescriptionEndpoint extends EnvelopRestEndpoint {
        try {
            if ("xm_zsyy_wx".equalsIgnoreCase(wxId)){
                return success(prescriptionService.findPatientCard(patient));
            }else if ("xm_hcyy_wx".equalsIgnoreCase(wxId)){
                String result = hcyyEntranceService.findPatientCard(patient);
                JSONArray jsonArray = new JSONArray();
                if (result!=null&&result!=""){
                    JSONArray array = JSONArray.parseArray(result);
                    if (array!=null&&array.size()!=0){
                        jsonArray = array.getJSONArray(0);
                    }
                }
                return success(jsonArray);
            }else if ("xm_tasy_wx".equalsIgnoreCase(wxId)){
                return success(tasyNatService.findPatientCard(patient));
            }else {

+ 6 - 10
svr/svr-statistics-es/src/main/java/com/yihu/wlyy/statistics/etl/compute/ComputeHelper.java

@ -159,16 +159,12 @@ public class ComputeHelper {
    private String getCityKey(DataModel one, int size) {
        try {
            if (size > 0) {
                StringBuffer str = new StringBuffer("330100");
                for (int i = 1; i <= size; i++) {
                    String invokeKey = (String) DataModel.class.getMethod("getSlaveKey" + i).invoke(one);
                    str.append("-" + invokeKey);
                }
                return str.toString();
            } else {
                return one.getHospital();
            }
             StringBuffer str = new StringBuffer("330100");
             for (int i = 1; i <= size; i++) {
                 String invokeKey = (String) DataModel.class.getMethod("getSlaveKey" + i).invoke(one);
                 str.append("-" + invokeKey);
             }
             return str.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;