فهرست منبع

Merge branch 'dev' of liubing/wlyy2.0 into dev

liubing 3 سال پیش
والد
کامیت
a9b4764634

+ 6 - 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,7 @@ 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);
}

+ 150 - 0
business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java

@ -393,6 +393,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);
@ -1192,6 +1195,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
     *
@ -1324,6 +1455,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
@ -1520,6 +1665,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岁以上患者

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

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

@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.service.statistics.StatisticsService;
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;
@ -15,6 +16,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Locale;
/**
 * Created by yeshijie on 2021/4/7.
 */
@ -208,5 +211,76 @@ public class StatisticsEndpoint extends EnvelopRestEndpoint {
        return ObjEnvelop.getError("查询失败",-1);
    }
    @GetMapping("olderBindingDeviceStatus")
    @ApiOperation("管理端首页老人接入情况")
    public ObjEnvelop olderBindingDeviceStatus(@RequestParam(required = false) String area){
        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){
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.deviceGrantAndService());
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "getAllDeviceLostMessage")
    @ApiOperation("设备分析--异常消息通知")
    public ObjEnvelop getAllDeviceLostMessage(@RequestParam(required = false) String area,
                                              @RequestParam(required = false) Integer page,
                                              @RequestParam(required = false) Integer size){
        try {
            return ObjEnvelop.getSuccess("查询成功",statisticsService.getAllDeviceLostMessage(area,page,size));
        }catch (Exception e){
            return failedObjEnvelopException2(e);
        }
    }
    @GetMapping(value = "deviceUsingInfo")
    @ApiOperation("设备分析--使用管理")
    public ObjEnvelop deviceUsingInfo(@RequestParam(required = false) String area){
        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) 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);
        }
    }
}

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

+ 265 - 33
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,22 +13,31 @@ 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 javax.persistence.criteria.CriteriaBuilder;
import java.awt.print.Pageable;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
@ -56,6 +67,12 @@ public class StatisticsService {
    private StatisticsUtilService statisticsUtilService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private SystemMessageDao messageDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    private static final String defalutArea = "330100";
@ -454,8 +471,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 +545,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 +671,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 +690,7 @@ 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);
            for(Map<String,Object> map:list){
                JSONObject json = new JSONObject();
                DecimalFormat df = new DecimalFormat("0.00");
                json.put("rate", df.format((Integer.parseInt(map.get("total").toString())*1.00) / count * 100));
                json.put("num", map.get("total"));
                json.put("code",map.get("dict_code").toString());
                json.put("name",map.get("dict_value").toString());
                levelArray.add(json);
            }
            res.put("levelList",levelArray);
            res.put("levelList",capacityAssessment(null,null,null));
            //年龄分布 50
//            ageList = elasticsearchUtil.findDateAllQuotaLevel1(endDate, endDate, area, level, "50", SaveModel.timeLevel_DDL,null,null,"2");
@ -704,17 +708,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 +812,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 +998,196 @@ 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());
        }
        String sql = "SELECT dict_code code from wlyy_hospital_sys_dict WHERE dict_name = 'security_server_dict'";//46指标一级纬度
        List<String> dictCodes = jdbcTemplate.queryForList(sql,String.class);
        JSONArray addDetail = new JSONArray();
        for (String dictCode:dictCodes){
            if(StringUtils.isNotBlank(type)){
                //周/月 增量
                String start = statisticsUtilService.calStart(endDate,type);
                SaveModel saveModelAdd = elasticsearchUtil.findOneDateQuotaLevel1(start,endDate, area,level, "46", SaveModel.timeLevel_ZL, dictCode,areaLevel);
                JSONObject json = new JSONObject();
                json.put("num",saveModelAdd.getResult2().longValue());
                json.put("code",saveModelAdd.getSlaveKey1());
                json.put("name",saveModelAdd.getSlaveKey1Name());
                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 Page<SystemMessageDO> getAllDeviceLostMessage(String area,Integer page,Integer size){
        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<SystemMessageDO> systemMessageDOS = messageDao.getByType("43",pageRequest);
        return systemMessageDOS;
    }
    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("notLost",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){
        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);
    }
    /**
     * 计算开始时间

+ 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 + "%";
    }
}