Browse Source

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

wangzhinan 3 years ago
parent
commit
9a2a23a4ed
54 changed files with 2482 additions and 384 deletions
  1. 6 0
      business/base-service/src/main/java/com/yihu/jw/hospital/message/dao/SystemMessageDao.java
  2. 150 0
      business/es-service/src/main/java/com/yihu/jw/es/util/ElasticsearchUtil.java
  3. 33 0
      common/common-entity/sql记录
  4. 9 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/contacts/PatientSosContactsDO.java
  5. 9 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java
  6. 54 5
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java
  7. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientDevice.java
  8. 166 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/label/BaseCapacityLabelDO.java
  9. 36 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/iot/device/WlyyPatientDeviceVO.java
  10. 16 0
      common/common-util/src/main/java/com/yihu/jw/util/common/StringUtil.java
  11. 11 1
      common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java
  12. 78 0
      svr/svr-base/src/main/java/com/yihu/jw/base/config/YsConfig.java
  13. 33 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/DeviceDao.java
  14. 32 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/DeviceDetailDao.java
  15. 75 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/PatientDeviceDao.java
  16. 396 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/device/DeviceManageEndpoint.java
  17. 24 38
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/patient/BasePatientEndpoint.java
  18. 185 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DeviceManageService.java
  19. 63 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DmDeviceService.java
  20. 66 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/WlyyPatientDeviceService.java
  21. 188 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/device/YsDeviceService.java
  22. 31 31
      svr/svr-base/src/main/java/com/yihu/jw/base/service/equipment/BaseHospitalEquipmentService.java
  23. 2 2
      svr/svr-base/src/main/resources/application.yml
  24. 3 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDao.java
  25. 19 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/label/BaseCapacityLabelDao.java
  26. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/assistance/EmergencyAssistanceEndpoint.java
  27. 0 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/DoctorConsultController.java
  28. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/consult/DoctorConsultEndpoint.java
  29. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorDeviceController.java
  30. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorHealthController.java
  31. 3 111
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PadDeviceController.java
  32. 5 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorBirthdayWishesEndpoint.java
  33. 1 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorEndpoint.java
  34. 5 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorServiceEndPoint.java
  35. 16 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/DoctorDoorCoachOrderController.java
  36. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/exam/DoctorChildrenExaminationEndpoint.java
  37. 2 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/lifeCare/DoctorLifeCareEndpoint.java
  38. 4 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/message/DoctorMessageEndpoint.java
  39. 1 1
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/org/OrgEndpoint.java
  40. 26 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/patient/PatientEndpoint.java
  41. 1 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/sign/SignEndpoint.java
  42. 74 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/statistics/StatisticsEndpoint.java
  43. 29 11
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java
  44. 52 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/patient/CarePatientService.java
  45. 4 4
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/DetectionPlatformService.java
  46. 265 33
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/statistics/StatisticsService.java
  47. 7 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/third/PatientInfoPlatFormService.java
  48. 13 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/CommonUtil.java
  49. 1 120
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/DeviceController.java
  50. 14 1
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/OnenetController.java
  51. 32 0
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/HvDeviceService.java
  52. 227 19
      svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/OnenetService.java
  53. 3 1
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/PatientSosContactsJob.java
  54. 1 0
      svr/svr-cloud-job/src/main/java/com/yihu/jw/care/service/device/NetworkCardService.java

+ 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岁以上患者

+ 33 - 0
common/common-entity/sql记录

@ -1494,3 +1494,36 @@ ALTER table wlyy_job_config_new add COLUMN area_level VARCHAR(1) default null co
-- 2021-09-13
alter table base_admin_service_dynamic add column photo varchar(255) default null COMMENT '用户头像';
alter table base_admin_service_dynamic add column del TINYINT(2) default 1 COMMENT '1有效,0失效';
-- 2021-09-22
alter table base_patient_sos_contacts add column error_info varchar(1000) default null comment '同步错误信息';
ALTER table wlyy_devices add column iccid VARCHAR(20) default null COMMENT '物联网卡iccid';
ALTER table wlyy_devices add column imsi VARCHAR(20) default null COMMENT '物联网卡IMSI';
ALTER table wlyy_devices add column  category_code varchar(50) DEFAULT NULL COMMENT '设备类型 dm_device表定义';
ALTER table dm_device add column device_type tinyint(2) DEFAULT NULL COMMENT '设备种类 0健康设备 1安防设备';
-- 2021-09-26
CREATE TABLE `base_capacity_label` (
  `id` varchar(50) NOT NULL,
  `patient` varchar(255) DEFAULT NULL,
  `family` varchar(1) DEFAULT NULL COMMENT '是否有家属 1是0否',
  `hypertension` varchar(1) DEFAULT NULL COMMENT '高血压 1是 0否',
  `hyperglycemia` varchar(1) DEFAULT NULL COMMENT '高血糖 1是 0否',
  `heart_disease` varchar(1) DEFAULT NULL COMMENT '心脏疾病 1是 0否',
  `work_status` varchar(1) DEFAULT NULL COMMENT '行走状态 1迟缓 2一般 3健步如飞',
  `disability` varchar(1) DEFAULT NULL COMMENT '残疾 1是 0否',
  `disabled_part` varchar(100) DEFAULT NULL COMMENT '残疾部位',
  `visual_condition` varchar(1) DEFAULT NULL COMMENT '视觉状况 1看不见 2近距离 3正常',
  `auditory_condition` varchar(1) DEFAULT NULL COMMENT '听觉状况 1听不见 2大声量 3正常',
  `communication` varchar(1) DEFAULT NULL COMMENT '交流情况 1不善于 2一般 3善于',
  `mental_illness` varchar(1) DEFAULT NULL COMMENT '精神类疾病 1是 0否',
  `often_go_out` varchar(1) DEFAULT NULL COMMENT '经常外出 1是 0否',
  `use_phone` varchar(1) DEFAULT NULL COMMENT '会使用智能手机 1是 0否',
  `take_exercise` varchar(1) DEFAULT NULL COMMENT '参加锻炼 1是 0否',
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='能力状况记录表';

+ 9 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/contacts/PatientSosContactsDO.java

@ -25,6 +25,7 @@ public class PatientSosContactsDO extends IdEntity {
    private Integer del;
    private Integer phoneSeqid;// 联系人序号 1 或2
    private String updateInfo;//同步信息 -1失败 1成功
    private String errorInfo;//同步错误信息
    private String relationName;
@ -109,4 +110,12 @@ public class PatientSosContactsDO extends IdEntity {
    public void setUpdateInfo(String updateInfo) {
        this.updateInfo = updateInfo;
    }
    public String getErrorInfo() {
        return errorInfo;
    }
    public void setErrorInfo(String errorInfo) {
        this.errorInfo = errorInfo;
    }
}

+ 9 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java

@ -28,6 +28,7 @@ public class Device extends IdEntity {
	private String del;
	private String serviceTopic;//设备所属专题 防走失 preventLost
	private String needRegister;//设备是否注册iot(脉搏波血压计)
	private Integer deviceType;//0健康设备 1安防设备
	@Column(name="category_code")
	public String getCategoryCode() {
@ -126,4 +127,12 @@ public class Device extends IdEntity {
	public void setNeedRegister(String needRegister) {
		this.needRegister = needRegister;
	}
	public Integer getDeviceType() {
		return deviceType;
	}
	public void setDeviceType(Integer deviceType) {
		this.deviceType = deviceType;
	}
}

+ 54 - 5
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java

@ -3,11 +3,10 @@ package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by ysj on 2018/01/10.
@ -43,7 +42,7 @@ public class DeviceDetail extends IdEntity {
    private Integer isBinding;//是否绑定(0否 1 绑定单端口 2 绑定双端口)
    private String bindingCount;//绑定次数({"1":"0", "2":"0"})
    private Date grantTime;//发放时间
    private Integer deviceType;
    private Integer deviceType;//0健康设备 1安防设备
    //1.5.0版本新增字段
    private String grantDoctor;//发放医生code
@ -51,6 +50,14 @@ public class DeviceDetail extends IdEntity {
    private Integer contactStatus;// 失联状态 1未失联 0失联
    private Date contactStatusTime;//失联状态更新时间
    private String iccid;//设备物联卡iccid
    private String imsi;//设备物联卡imsi
    private String categoryCode; // 设备类型 dm_device表定义
    //导入设备错误信息
    private String errorMsg;
    private Map<String,String> errorMsgMap = new HashMap<>();
    /** default constructor */
    public DeviceDetail() {
    }
@ -344,4 +351,46 @@ public class DeviceDetail extends IdEntity {
    public void setContactStatusTime(Date contactStatusTime) {
        this.contactStatusTime = contactStatusTime;
    }
    public String getIccid() {
        return iccid;
    }
    public void setIccid(String iccid) {
        this.iccid = iccid;
    }
    public String getImsi() {
        return imsi;
    }
    public void setImsi(String imsi) {
        this.imsi = imsi;
    }
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    @Transient
    public String getErrorMsg() {
        return errorMsg;
    }
    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
    @Transient
    public Map<String, String> getErrorMsgMap() {
        return errorMsgMap;
    }
    public void setErrorMsgMap(Map<String, String> errorMsgMap) {
        this.errorMsgMap = errorMsgMap;
    }
}

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientDevice.java

@ -22,7 +22,7 @@ public class DevicePatientDevice extends IdEntity {
    // 用户code
    private String user;
    // 设备类型标识 1血糖仪,2.血压计,3药盒,4智能手表,7 = 居家报警器,12 监控器 13 睡眠带 14气感报警器 15烟感报警器 16拐杖 17随身wifi
    private String categoryCode;
    private String categoryCode;//DEVICE_CATEGORY_CODE字典同步更新
    // 用户类型标准 -1代表单用户
    private String userType;
    // 用户身份证

+ 166 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/label/BaseCapacityLabelDO.java

@ -0,0 +1,166 @@
package com.yihu.jw.entity.care.label;
import com.yihu.jw.entity.UuidIdentityEntityWithCreateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * 能力状况记录表
 */
@Entity
@Table(name = "base_capacity_label")
public class BaseCapacityLabelDO extends UuidIdentityEntityWithCreateTime {
    private String patient;
    private String family;//是否有家属 1是0否
    private String hypertension;//高血压 1是 0否
    private String hyperglycemia;//高血糖 1是 0否
    private String heartDisease;//心脏疾病 1是 0否
    private String workStatus;//行走状态 1迟缓 2一般 3健步如飞
    private String disability;//残疾 1是 0否
    private String disabledPart;//残疾部位
    private String visualCondition;//视觉状况 1看不见 2近距离 3正常
    private String auditoryCondition;//听觉状况 1听不见 2大声量 3正常
    private String communication;//交流情况 1不善于 2一般 3善于
    private String mentalIllness;//精神类疾病 1是 0否
    private String oftenGoOut;//经常外出 1是 0否
    private String usePhone;//会使用智能手机 1是 0否
    private String takeExercise;//参加锻炼 1是 0否
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "family")
    public String getFamily() {
        return family;
    }
    public void setFamily(String family) {
        this.family = family;
    }
    @Column(name = "hypertension")
    public String getHypertension() {
        return hypertension;
    }
    public void setHypertension(String hypertension) {
        this.hypertension = hypertension;
    }
    @Column(name = "hyperglycemia")
    public String getHyperglycemia() {
        return hyperglycemia;
    }
    public void setHyperglycemia(String hyperglycemia) {
        this.hyperglycemia = hyperglycemia;
    }
    @Column(name = "heart_disease")
    public String getHeartDisease() {
        return heartDisease;
    }
    public void setHeartDisease(String heartDisease) {
        this.heartDisease = heartDisease;
    }
    @Column(name = "work_status")
    public String getWorkStatus() {
        return workStatus;
    }
    public void setWorkStatus(String workStatus) {
        this.workStatus = workStatus;
    }
    @Column(name = "disability")
    public String getDisability() {
        return disability;
    }
    public void setDisability(String disability) {
        this.disability = disability;
    }
    @Column(name = "disabled_part")
    public String getDisabledPart() {
        return disabledPart;
    }
    public void setDisabledPart(String disabledPart) {
        this.disabledPart = disabledPart;
    }
    @Column(name = "visual_condition")
    public String getVisualCondition() {
        return visualCondition;
    }
    public void setVisualCondition(String visualCondition) {
        this.visualCondition = visualCondition;
    }
    @Column(name = "auditory_condition")
    public String getAuditoryCondition() {
        return auditoryCondition;
    }
    public void setAuditoryCondition(String auditoryCondition) {
        this.auditoryCondition = auditoryCondition;
    }
    @Column(name = "communication")
    public String getCommunication() {
        return communication;
    }
    public void setCommunication(String communication) {
        this.communication = communication;
    }
    @Column(name = "mental_illness")
    public String getMentalIllness() {
        return mentalIllness;
    }
    public void setMentalIllness(String mentalIllness) {
        this.mentalIllness = mentalIllness;
    }
    @Column(name = "often_go_out")
    public String getOftenGoOut() {
        return oftenGoOut;
    }
    public void setOftenGoOut(String oftenGoOut) {
        this.oftenGoOut = oftenGoOut;
    }
    @Column(name = "use_phone")
    public String getUsePhone() {
        return usePhone;
    }
    public void setUsePhone(String usePhone) {
        this.usePhone = usePhone;
    }
    @Column(name = "take_exercise")
    public String getTakeExercise() {
        return takeExercise;
    }
    public void setTakeExercise(String takeExercise) {
        this.takeExercise = takeExercise;
    }
}

+ 36 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/iot/device/WlyyPatientDeviceVO.java

@ -27,6 +27,10 @@ public class WlyyPatientDeviceVO {
	private String hospitalName;
	private String doctorHealthName;
	private String doctorHealth;
	private String deviceModel;
	private String iccid;//设备物联卡iccid
	private String imsi;//设备物联卡imsi
	private String manufacturer;//厂家名称
	
	public Integer getId() {
		return id;
@ -164,4 +168,36 @@ public class WlyyPatientDeviceVO {
	public void setDoctorHealth(String doctorHealth) {
		this.doctorHealth = doctorHealth;
	}
	public String getDeviceModel() {
		return deviceModel;
	}
	public void setDeviceModel(String deviceModel) {
		this.deviceModel = deviceModel;
	}
	public String getIccid() {
		return iccid;
	}
	public void setIccid(String iccid) {
		this.iccid = iccid;
	}
	public String getImsi() {
		return imsi;
	}
	public void setImsi(String imsi) {
		this.imsi = imsi;
	}
	public String getManufacturer() {
		return manufacturer;
	}
	public void setManufacturer(String manufacturer) {
		this.manufacturer = manufacturer;
	}
}

+ 16 - 0
common/common-util/src/main/java/com/yihu/jw/util/common/StringUtil.java

@ -1,5 +1,6 @@
package com.yihu.jw.util.common;
import java.text.DecimalFormat;
import java.util.Random;
/**
@ -23,4 +24,19 @@ public class StringUtil {
        return buffer.toString();
    }
    /**
     * 2数相除保留1位小数
     * @param a
     * @param b
     * @return
     */
    public static String division(int a,int b){
        String result = "";
        float num =(float)a/b;
        DecimalFormat df = new DecimalFormat("0.0");
        result = df.format(num);
        return result;
    }
}

+ 11 - 1
common/common-util/src/main/java/com/yihu/jw/util/date/DateUtil.java

@ -1427,6 +1427,16 @@ public class DateUtil {
        return result.toString();
    }
    /**
     * 1970年1月1日来的 秒转化成时间
     * @param seconds
     * @return
     */
    public static Date secondTransfor(int seconds){
        Calendar calendar = Calendar.getInstance();
        calendar.set(1970,Calendar.JANUARY,1,0,0,0);
        calendar.add(Calendar.SECOND,seconds);
        return calendar.getTime();
    }
}

+ 78 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/config/YsConfig.java

@ -0,0 +1,78 @@
package com.yihu.jw.base.config;
/**
 * Created by Bing on 2021/6/1.
 * 萤石摄像头配置
 */
public class YsConfig {
    //文档地址 https://www.yuque.com/u1400669/kb/lmfp6u
    public static final String AppKey="43e44c2071114743925eda34088045f8";
    public static final String Secret="82051725cf0547208f8bc8ae2bff1323";
    public static final String baseUrl = "https://esopen.ys7.com";
    public static final String iotBaseUrl = "https://open.ys7.com";
   //saas平台 https://www.yuque.com/u1400669/kb/wdvi3b#9ZP70
    public static final String saasAssesToken =baseUrl+ "/api/user/open-app/auth/gettoken";
    //开放平台  https://open.ys7.com/doc/zh/book/index/user.html
    public static final String iotAssesToken =baseUrl+ "/api/user/component-open/sso/oauth2/getEZAccessToken";
    //获取通道列表
    public static final String surveillanceWayList =baseUrl+ "/api/resource/open-app/surveillance/camera/list/page";
    //获取通道信息(通道默认为1)
    public static final String surveillanceWay =baseUrl+ "/api/resource/open-app/surveillance/camera/info";
    //设备抓拍
    public static final String deviceCapture =baseUrl +"/api/resource/device/capture";
    //获取设备有效直播地址
    public static final String getDeviceLiveAddress = iotBaseUrl+ "/api/lapp/live/address/limited";
    //设备视频加解密开关
    public static final String deviceEncrypt = baseUrl+ "/api/resource/device/encrypt/switch";
    //跌倒检测功能查询、设置(立即检测!判断是否有跌倒通过推送消息)
    public static final String deviceFailConfig = iotBaseUrl + "/api/route/device/devconfig/keyValue/{0}/{1}/op";
    //云台控制
    public static final String ptzStart = iotBaseUrl +"/api/lapp/device/ptz/start";
    //云台停止
    public static final String ptzStop = iotBaseUrl +"/api/lapp/device/ptz/stop";
    public static final String openChannelNo = iotBaseUrl +"/api/lapp/live/video/open";
    public static final String defenceSet = iotBaseUrl +"/open.ys7.com/api/lapp/device/intelligence/detection/switch/set";
    /**
     * 录像相关
     */
    //获取录像accessKey、上传录像地址
    public static final String videoKey = baseUrl +"/seastart/vod/token";
    //上传录像上传地址通过videoKey接口获取
    public static final String videoUpload = "https://seastart.ss.bscstorage.com";
    //录像列表
    public static final String videoList = baseUrl +"/seastart/vod/list";
    //批量获取录像详情
    public static final String videoDetailList = baseUrl +"/seastart/vod";
    //录像详情
    public static final String videoDetail = baseUrl +"/seastart/vod/get";
    public static final String redisKey = "ysAssesToken";
    public static final String iotRedisKey = "iotYsAssesToken";
    public static final String secretKey = "secretKey"; //设备的解密秘钥  通过iotAssesToken接口获取的
    public static final String msgDataKey = "HZADP68PNSNVZ4UW"; //消息解密密钥
}

+ 33 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/DeviceDao.java

@ -0,0 +1,33 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.base.dao.device;
import com.yihu.jw.entity.care.device.Device;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface DeviceDao extends PagingAndSortingRepository<Device, Long> {
	@Query("select a from Device a where a.categoryCode = ?1 and a.del = '1'")
	List<Device> findByCategoryCode(String categoryCode);
	@Query("select a from Device a where a.del = '1'")
	List<Device> findAll();
	@Query("select count(1) from Device a where a.del = '1' and a.categoryCode=?1 ")
	Integer findTotalByCategoryCode(String categoryCode);
	@Query("select count(1) from Device a where a.del = '1' and a.name=?1 ")
	Integer findTotalByName(String name);
	@Query("select count(1) from Device a where a.del = '1' and a.model=?1")
	Integer findTotalByModel(String model);
	@Query("select a from Device a where a.del = '1' and a.model=?1")
	Device findByModel(String model);
}

+ 32 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/DeviceDetailDao.java

@ -0,0 +1,32 @@
package com.yihu.jw.base.dao.device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * @author yeshijie on 2018/1/10.
 */
public interface DeviceDetailDao extends PagingAndSortingRepository<DeviceDetail, Long>, JpaSpecificationExecutor<DeviceDetail> {
    @Query(value = "select a.* from wlyy_devices a where a.device_code=?1 limit 0,1",nativeQuery = true)
    DeviceDetail findBySn(String sn);
    List<DeviceDetail> findByDeviceCode(String deviceCode);
    @Query("select a from DeviceDetail a where a.deviceCode = ?1 and a.manufacturerCode = ?2")
    DeviceDetail findByDeviceCodeAndManufacturerCode(String deviceCode,String manufacturerCode);
    @Query("select a from DeviceDetail a where a.sim = ?2")
    List<DeviceDetail> findBySim(String sim);
    @Query("select a from DeviceDetail a where a.iccid = ?2")
    List<DeviceDetail> findByIccid(String iccid);
    @Query("select a from DeviceDetail a where a.imsi = ?2")
    List<DeviceDetail> findByImsi(String sim);
}

+ 75 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/device/PatientDeviceDao.java

@ -0,0 +1,75 @@
package com.yihu.jw.base.dao.device;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
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;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface PatientDeviceDao extends PagingAndSortingRepository<DevicePatientDevice, Long>, JpaSpecificationExecutor<DevicePatientDevice> {
    @Query("select a from DevicePatientDevice a where a.user = ?1 ")
    Iterable<DevicePatientDevice> findByUser(String user);
    @Query("select a from DevicePatientDevice a where a.del = 0 ")
    List<DevicePatientDevice> findByAll();
    @Query("select a from DevicePatientDevice a where a.user = ?1 ")
    List<DevicePatientDevice> findByPatient(String user);
    @Query("select a from DevicePatientDevice a where a.user = ?1 and a.del=0 and a.deviceName like '%药盒%'")
    List<DevicePatientDevice> findByPatientAndDel(String user);
    @Query("select a from DevicePatientDevice a where a.user = ?1 and a.deviceSn=?2 ")
    List<DevicePatientDevice> findByPatientAndDeviceSn(String user, String deviceSn);
    List<DevicePatientDevice> findByUser(String user, Pageable pageRequest);
    List<DevicePatientDevice> findByUserAndDoctor(String user, String doctor, Pageable pageRequest);
    List<DevicePatientDevice> findByDeviceSnAndCategoryCode(String deviceSn, String categoryCode);
    DevicePatientDevice findByDeviceSnAndCategoryCodeAndUserType(String deviceSn, String categoryCode, String userType);
    DevicePatientDevice findByDeviceIdAndDeviceSnAndUserType(Long deviceId, String deviceSn, String userType);
    DevicePatientDevice findByDeviceSnAndUserType(String deviceSn, String userType);
    @Query("select pd from DevicePatientDevice pd where pd.deviceSn = ?1 and pd.del=0")
    List<DevicePatientDevice> findByDeviceSn(String deviceSn);
    //更换患者绑定的血糖仪
    @Modifying
    @Query("update DevicePatientDevice t set t.deviceSn = ?3 , t.userType = ?4,t.sim=?5,t.hospital=?6,t.hospitalName=?7,t.checkDoctorName=?8 where t.user = ?1 and t.deviceSn = ?2 ")
    int updatePatientDevice(String user, String deviceSN, String newDeviceSN, String userType, String sim, String hospital, String hospitalName, String checkDoctorName);
    //管理员解绑居民设备
    @Modifying
    @Query("update DevicePatientDevice t set t.del = 1  where t.deviceSn = ?1 and t.del =0  ")
    int updatePatientDevice(String deviceSN);
    @Query("select a from DevicePatientDevice a")
    List<DevicePatientDevice> findAll();
    @Query("select a from DevicePatientDevice a group by a.user")
    List<DevicePatientDevice> findAllGroupUser();
    @Query("select a from DevicePatientDevice a where a.categoryCode = ?1 and a.del=0 group by a.user")
    List<DevicePatientDevice> findAllByCategoryCode(String categoryCode);
    @Modifying
    @Query("delete DevicePatientDevice a where a.deviceSn = ?1")
    int deleteByDeviceSn(String deviceSN);
    @Query("select a from DevicePatientDevice a where a.user=?1 and a.del=0")
    List<DevicePatientDevice> findAllByUser(String user);
    @Query("select a from DevicePatientDevice a where a.user=?1 and a.categoryCode =?2 and a.del=0")
    List<DevicePatientDevice> findAllByUserAndCategoryCode(String user,String categoryCode);
    @Query("select a from DevicePatientDevice a where a.user=?1 and a.categoryCode =?2 and a.del=0")
    List<DevicePatientDevice> findByUserAndCategoryCode(String user,String categoryCode);
}

+ 396 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/device/DeviceManageEndpoint.java

@ -0,0 +1,396 @@
package com.yihu.jw.base.endpoint.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.dao.device.DeviceDetailDao;
import com.yihu.jw.base.service.device.DeviceManageService;
import com.yihu.jw.base.service.device.DmDeviceService;
import com.yihu.jw.base.service.device.WlyyPatientDeviceService;
import com.yihu.jw.base.service.device.YsDeviceService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.jw.restmodel.iot.device.WlyyPatientDeviceVO;
import com.yihu.jw.restmodel.web.Envelop;
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 jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.yihu.jw.util.common.BeanUtils.getNullPropertyNames;
/**
 * Created by Bing on 2021/9/22.
 */
@RestController
@RequestMapping(value = "baseDevice",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "设备管理", description = "设备管理", tags = {"设备管理"})
public class DeviceManageEndpoint extends EnvelopRestEndpoint {
    private static Logger logger = LoggerFactory.getLogger(DeviceManageEndpoint.class);
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private DeviceManageService deviceManageService;
    @Autowired
    private WlyyPatientDeviceService patientDeviceService;
    @Autowired
    private DmDeviceService dmDeviceService;
    @Autowired
    private YsDeviceService ysDeviceService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @GetMapping("findWlyyDevices")
    @ApiOperation("获取设备列表")
    public PageEnvelop<DeviceDetail> findDevices(
            @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 = "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 {
            List<DeviceDetail> list = deviceManageService.search(fields,filters,sorts,page,size);
            int count = (int) deviceManageService.getCount(filters);
            return success(list, count, page, size, DeviceDetail.class);
        }catch (Exception e){
            return failedPageEnvelopException2(e);
        }
    }
    @PostMapping("delWlyyDevice")
    @ApiOperation("删除设备")
    public Envelop delWlyyDevice(@ApiParam(name = "id")@RequestParam(value = "id")String id){
        try {
            deviceDetailDao.delete(Long.parseLong(id));
            return success(id);
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @PostMapping("saveWlyyDevice")
    @ApiOperation("保存/修改设备")
    public Envelop saveDevice(@ApiParam(name="json")@RequestParam(value = "json")String json){
        try {
            JSONObject response = deviceManageService.saveWlyyDevice(json);
            if (1==response.getInteger(ResponseContant.resultFlag)){
                return success("修改成功") ;
            }
            else {
                return Envelop.getError(response.getString(ResponseContant.resultMsg)) ;
            }
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @GetMapping(value = "getUserDevice")
    @ApiOperation("居民设备查询")
    public PageEnvelop<WlyyPatientDeviceVO> getUserDevice(
            @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 {
            return patientDeviceService.getUserDevice(id,userName,userIdcard,categoryCode,page,size);
        }catch (Exception e){
            return failedPageEnvelopException2(e);
        }
    }
    @PostMapping("delPatientDevice")
    @ApiOperation("删除患者设备-解绑")
    public Envelop delPatientDevice(@ApiParam(name = "id")
                                    @RequestParam(value = "id", required = false) String id){
        try {
            patientDeviceService.delPatientDevice(id);
            return success();
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @GetMapping("findDmDeviceDict")
    @ApiOperation("获取设备字典")
    public PageEnvelop<Device> findDmDeviceDict(@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 = "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=1";
            }else {
                filters+=";del=1";
            }
            List<Device> list = dmDeviceService.search(fields, filters, sorts,page,size);
            int count = (int) dmDeviceService.getCount(filters);
            return success(list, count, page, size);
        }catch (Exception e){
            return failedPageEnvelopException2(e);
        }
    }
    @PostMapping("delDmDevice")
    @ApiOperation("删除设备字典定义")
    public Envelop delDmDevice(@ApiParam(name = "id")
                             @RequestParam(value = "id", required = false) String id){
        try {
            dmDeviceService.delete(Long.parseLong(id));
            return success();
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @PostMapping("saveDmDevice")
    @ApiOperation("保存设备字典定义")
    public Envelop saveDmDevice(@ApiParam(name="json")@RequestParam(value = "json")String json){
        try {
            JSONObject response = dmDeviceService.saveDmDevice(json);
            if (1==response.getInteger(ResponseContant.resultFlag)){
                return success("修改成功") ;
            }
            else {
                return Envelop.getError(response.getString(ResponseContant.resultMsg)) ;
            }
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @PostMapping(value = "/importDeviceFromExcel", produces = "application/json;charset=UTF-8")
    @ApiOperation("设备数据导入")
    public ObjEnvelop importFromExcel(HttpServletRequest request, @ApiParam(value = "文件", required = true)
    @RequestParam(value = "file", required = true) MultipartFile file,HttpServletResponse response) {
        List errorLs = new ArrayList<>();
        List correctLs = new ArrayList<>();
        Map<String, String> errorMsgMapTotal = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> deviceCodes = new ArrayList<>();
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = file.getInputStream();
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet[] sheets = rwb.getSheets();
            int rows;
            int row;
            String manufacturer=null;//厂商名称
            String deviceName; //设备名称
            String deviceModel; //设备型号
            String deviceCode;  //设备SN
            String sim;  //sim卡号
            String iccid;  //iccid卡号
            String imsi;  //imsi卡号
            Sheet sheet = sheets[0];    //第一张表
            rows = sheet.getRows();
            for (int j = 1; j < rows; j++) {
                if (sheet.getRow(j).length == 0) {
                    continue;
                }
                String errorMsg = "";
                DeviceDetail deviceDetail = new DeviceDetail();
                Map<String, String> errorMsgMap = deviceDetail.getErrorMsgMap();
                row = j;
                manufacturer = sheet.getCell(0, row).getContents().trim();    //0 厂商名称
                deviceName = sheet.getCell(1, row).getContents().trim();  //1 设备名称
                deviceModel = sheet.getCell(2, row).getContents().trim();   //2 设备型号
                deviceCode = sheet.getCell(3, row).getContents().trim(); //3 设备SN
                sim = sheet.getCell(4, row).getContents().trim();  //4 sim卡号
                iccid = sheet.getCell(5, row).getContents().trim();  //4 iccid卡号
                imsi = sheet.getCell(6, row).getContents().trim();  //4 imsi卡号
                if (org.apache.commons.lang.StringUtils.isBlank(deviceCode)){
                    continue;
                }
                if (deviceCodes.contains(deviceCode)){
                    errorMsgMapTotal.put(deviceCode,"设备SN码重复");
                    errorMsgMap.put("deviceCode", "设备SN码重复!;");
                    errorMsg += "设备SN码重复!;";
                }
                deviceCodes.add(deviceCode);
                if (org.apache.commons.lang.StringUtils.isBlank(manufacturer)){
                    errorMsgMapTotal.put(deviceCode,"厂商名称不能为空");
                    errorMsgMap.put("manufacturer", "厂商名称不能为空!;");
                    errorMsg += "厂商名称不能为空!;";
                }
                if (org.apache.commons.lang.StringUtils.isBlank(deviceName)){
                    errorMsgMapTotal.put(deviceCode,"设备名称不能为空");
                    errorMsgMap.put("deviceName", "设备名称不能为空!;");
                    errorMsg += "设备名称不能为空!;";
                }
                if (org.apache.commons.lang.StringUtils.isBlank(deviceModel)){
                    errorMsgMapTotal.put(deviceCode,"设备型号不能为空");
                    errorMsgMap.put("deviceModel", "设备型号不能为空!;");
                    errorMsg += "设备型号不能为空!;";
                }
                //名称、设备类型、设备型号判断
                if (0==deviceDao.findTotalByName(deviceName)){
                    errorMsgMapTotal.put(deviceCode,"设备名称不存在");
                    errorMsgMap.put("deviceName", "设备名称不存在!;");
                    errorMsg += "设备名称不存在!;";
                }
                if (0==deviceDao.findTotalByModel(deviceModel)){
                    errorMsgMapTotal.put(deviceCode,"设备型号不存在");
                    errorMsgMap.put("deviceModel", "设备型号不存在!;");
                    errorMsg += "设备型号不存在!;";
                }
                if (deviceDetailDao.findByDeviceCode(deviceCode).size()>0){
                    errorMsgMapTotal.put(deviceCode,"该设备SN码已存在");
                    errorMsgMap.put("deviceCode", "该设备SN码已存在!;");
                    errorMsg += "该设备SN码已存在!;";
                }
                if (org.apache.commons.lang.StringUtils.isNotBlank(sim) && deviceDetailDao.findBySim(sim).size()>0){
                    errorMsgMapTotal.put(deviceCode,"该sim卡号已存在");
                    errorMsgMap.put("sim", "该sim卡号已存在!;");
                    errorMsg += "该sim卡号已存在!;";
                }
                if (org.apache.commons.lang.StringUtils.isNotBlank(iccid) && deviceDetailDao.findByIccid(iccid).size()>0){
                    errorMsgMapTotal.put(deviceCode,"该iccid卡号已存在");
                    errorMsgMap.put("iccid", "该iccid卡号已存在!;");
                    errorMsg += "该iccid卡号已存在!;";
                }
                if (org.apache.commons.lang.StringUtils.isNotBlank(imsi) && deviceDetailDao.findByImsi(imsi).size()>0){
                    errorMsgMapTotal.put(deviceCode,"该imsi卡号已存在");
                    errorMsgMap.put("imsi", "该imsi卡号已存在!;");
                    errorMsg += "该imsi卡号已存在!;";
                }
                if (!StringUtils.isEmpty(errorMsg.trim())) {
                    deviceDetail.setErrorMsg(errorMsg);
                    errorLs.add(deviceDetail);
                    continue;
                }
                if ("CS-C6Wi-3E4WFR".equals(deviceModel)){//监控器 直播地址开通->关闭视频加密 后续暂时先于APP操作
                    ysDeviceService.videoOpen(deviceCode,null);
                }
                deviceDetail.setApplyDate(sdf.format(new Date()));
                deviceDetail.setManufacturer(manufacturer);
                deviceDetail.setDeviceName(deviceName);
                deviceDetail.setDeviceModel(deviceModel);
                deviceDetail.setDeviceCode(deviceCode);
                deviceDetail.setSim(sim);
                Device device = deviceDao.findByModel(deviceModel);
                if (device!=null){
                    deviceDetail.setDeviceType(device.getDeviceType());
                    deviceDetail.setCategoryCode(device.getCategoryCode());//设备类型判断
                    if ("1".equals(device.getIsMultiUser())){
                        deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
                    }else if ("0".equals(device.getIsMultiUser())){
                        deviceDetail.setBindingCount("{\"1\":\"0\"}");
                    }
                }
                correctLs.add(deviceDetail);
            }
            deviceDetailDao.save(correctLs);
            //包装导入结果(导入成功数量、错误对象集合)
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", rows-1 - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMapTotal, SerializerFeature.WriteMapNullValue));
            map.put("errorData", errorLs);
            //失败数据下载
            if (errorLs.size()>0){
                response.setContentType("octets/stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + new String("deviceImport.xls"));
                OutputStream os = response.getOutputStream();
                deviceManageService.write(os, errorLs);
            }
            return ObjEnvelop.getSuccess("success",JSON.toJSONString(map,SerializerFeature.WriteMapNullValue));
        } catch (Exception e) {
            failedObjEnvelopException2(e);
        }
        return ObjEnvelop.getSuccess("success",correctLs.size());
    }
    @GetMapping(value = "downLoadDeviceModelExcel", produces = "application/json;charset=UTF-8")
    @ApiOperation(("模板下载"))
    public void downLoadDeviceModelExcel(HttpServletResponse response) {
        try {
            response.setContentType("octets/stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + new String("deviceImport.xls"));
            OutputStream os = response.getOutputStream();
            deviceManageService.write(os, null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /***初始化设备表 设备类型字段****/
    @PostMapping("initCategoryCode")
    @ApiOperation("设备库存表新增字段初始化")
    public Envelop initCategoryCode(){
        try {
            deviceManageService.initCategoryCode();
            return success();
        }catch (Exception e){
            return failedException2(e);
        }
    }
}

+ 24 - 38
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/patient/BasePatientEndpoint.java

@ -33,6 +33,7 @@ import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -72,6 +73,8 @@ public class BasePatientEndpoint extends EnvelopRestEndpoint {
    private ArchiveDao archiveDao;
    @Autowired
    private WlyyPatientLabelDao patientLabelDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @PostMapping(value = BaseRequestMapping.BasePatient.CREATE)
    @ApiOperation(value = "创建")
@ -226,33 +229,21 @@ public class BasePatientEndpoint extends EnvelopRestEndpoint {
     *   姓名	性别	年龄	身份证号	      联系方式	   小区	            地址	                 签约团队	        能力类型
     * 沈xxx	女	    88	330103xxxxxxxx0720	1525xxxx711	朝晖九区	朝晖九区10幢4单元103	    虹园/稻香园服务团队	    能力完好
     * 沈xxx	女	    86	330103xxxxxxxx0720	1525xxxx711	朝晖九区	朝晖九区天盛居4幢1202室	  大木桥服务团队	    能力完好
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "/importPatientFromExcel", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @RequestMapping(value = "/open/importPatientFromTmp" ,method = RequestMethod.POST)
    @ResponseBody
    public ObjEnvelop importPatientFromExcel(HttpServletRequest request, @ApiParam(value = "文件", required = true)
    @RequestParam(value = "file", required = true) MultipartFile file) {
        Calendar c1 = Calendar.getInstance();
        /**
         * c1  签约结束时间
         */
        c1.set(2023, 12 - 1, 31,23,59,59);
        List errorLs = new ArrayList<>();
    public ObjEnvelop importPatientFromTmp() {
        Calendar cal = Calendar.getInstance();
        int year= 100;
        List correctLs = new ArrayList<>();
        List idcardList = new ArrayList<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> deviceCodes = new ArrayList<>();
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = file.getInputStream();
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet[] sheets = rwb.getSheets();
            int rows;
            int row;
            String name=null;//用户姓名
            String sql = "select * from patient_tmp";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            String name;//用户姓名
            String sex; //性别
            String age; //年龄
            String idcard;  //身份证号
@ -261,24 +252,18 @@ public class BasePatientEndpoint extends EnvelopRestEndpoint {
            String address; //居住地址
            String signTeam; //签约团队
            String label; //能力类型
            Sheet sheet = sheets[0];    //第一张表
            rows = sheet.getRows();
            for (int j = 1; j < rows; j++) {
                if (sheet.getRow(j).length == 0) {
                    continue;
                }
            for (Map<String,Object> map:list) {
                BasePatientDO basePatientVO = new BasePatientDO();
                JSONObject infoMap = new JSONObject();
                row = j;
                name = sheet.getCell(0, row).getContents().trim();    //0 用户姓名
                sex = sheet.getCell(1, row).getContents().trim();  //1 性别
                age = sheet.getCell(2, row).getContents().trim();   //2 年龄
                idcard = sheet.getCell(3, row).getContents().trim(); //3 身份证号
                mobile = sheet.getCell(4, row).getContents().trim();  //4 联系方式
                residentialArea = sheet.getCell(5, row).getContents().trim(); //5 居住小区
                address = sheet.getCell(6, row).getContents().trim(); //6 居住地址
                signTeam = sheet.getCell(7, row).getContents().trim();; //签约团队
                label = sheet.getCell(8, row).getContents().trim();; //能力类型
                name = map.get("name")+"";    //0 用户姓名
                sex = map.get("sex")+"";  //1 性别
                age = map.get("age")+"";   //2 年龄
                idcard = map.get("idcard")+""; //3 身份证号
                mobile = map.get("mobile")+"";  //4 联系方式
                residentialArea = map.get("area")+""; //5 居住小区
                address = map.get("address")+""; //6 居住地址
                signTeam = map.get("sign")+""; //签约团队
                label = map.get("label")+""; //能力类型
                if (StringUtils.isBlank(idcard)){
                    continue;
                }
@ -352,7 +337,8 @@ public class BasePatientEndpoint extends EnvelopRestEndpoint {
                        signRecordDO.setName(name);
                        signRecordDO.setStatus(1);
                        signRecordDO.setStartTime(new Date());
                        signRecordDO.setEndTime(c1.getTime());
                        cal.add(Calendar.YEAR,year);
                        signRecordDO.setEndTime(cal.getTime());
                        BaseTeamDO teamDO = baseTeamDao.findByName(signTeam);
                        if (teamDO == null) {
                            errorMsgMap.put(idcard,"团队信息获取失败");
@ -403,7 +389,7 @@ public class BasePatientEndpoint extends EnvelopRestEndpoint {
            //包装导入结果(导入成功数量、错误对象集合)
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", rows-1 - correctLs.size() );
            map.put("failedNum", list.size() - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMap, SerializerFeature.WriteMapNullValue));
            System.out.println(map);
            return ObjEnvelop.getSuccess("获取成功",map);

+ 185 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DeviceManageService.java

@ -0,0 +1,185 @@
package com.yihu.jw.base.service.device;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.dao.device.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.mysql.query.BaseJpaService;
import jxl.Workbook;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
/**
 * Created by Bing on 2021/9/22.
 */
@Service
public class DeviceManageService extends BaseJpaService<DeviceDetail,DeviceDetailDao> {
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DeviceDao deviceDao;
    public JSONObject saveWlyyDevice(String json)throws Exception{
        JSONObject result = new JSONObject();
        DeviceDetail deviceDetail = objectMapper.readValue(json, DeviceDetail.class);
        String deviceName = deviceDetail.getDeviceName();
        String deviceModel = deviceDetail.getDeviceModel();
        String categoryCode= deviceDetail.getCategoryCode();
        String deviceSn = deviceDetail.getDeviceCode();
        String manufacturer = deviceDetail.getManufacturer();
        if (StringUtils.isBlank(deviceName)||StringUtils.isBlank(deviceModel)||StringUtils.isBlank(categoryCode)||
                StringUtils.isBlank(deviceSn)||StringUtils.isBlank(manufacturer)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"数据数据错误,必填字段为空");
            return result;
        }
        String sim = deviceDetail.getSim();
        String iccid = deviceDetail.getIccid();
        String imsi = deviceDetail.getImsi();
        DeviceDetail tmps1 =  deviceDetailDao.findBySn(deviceSn);
        if (tmps1!=null){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备SN码重复");
            return result;
        }
        if (StringUtils.isNotBlank(sim)){
            List<DeviceDetail> tmps = deviceDetailDao.findBySim(sim);
            if (tmps.size()>0){
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"sim卡号重复");
                return result;
            }
        }
        if (StringUtils.isNotBlank(iccid)){
            List<DeviceDetail> tmps =  deviceDetailDao.findByIccid(iccid);
            if (tmps.size()>0){
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"iccid重复");
                return result;
            }
        }
        if (StringUtils.isNotBlank(imsi)){
            List<DeviceDetail> tmps =  deviceDetailDao.findByImsi(imsi);
            if (tmps.size()>0){
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"imsi重复");
                return result;
            }
        }
        //名称、设备类型、设备型号判断
        if (0==deviceDao.findTotalByCategoryCode(categoryCode)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备类型不存在");
            return result;
        }
        if (0==deviceDao.findTotalByName(deviceName)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备名称不存在");
            return result;
        }
        if (0==deviceDao.findTotalByModel(deviceModel)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"设备型号不存在");
            return result;
        }
        Device device = deviceDao.findByModel(deviceModel);
        if (device!=null){
            deviceDetail.setDeviceType(device.getDeviceType());
            if ("1".equals(device.getIsMultiUser())){
                deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
            }else if ("0".equals(device.getIsMultiUser())){
                deviceDetail.setBindingCount("{\"1\":\"0\"}");
            }
        }
        if (null==deviceDetail.getId()){
            deviceDetail.setContactStatus(1);
        }
        deviceDetailDao.save(deviceDetail);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,"success");
        return result;
    }
    public void initCategoryCode(){
        String sql = " select GROUP_CONCAT(model) model,category_code from dm_device GROUP BY category_code ";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> tmp:list){
            String category = tmp.get("category_code").toString();
            String model = tmp.get("model").toString();
            model = "'"+model.replace(",","','")+"'";
            sql = " UPDATE wlyy_devices set category_code='"+category+"' where device_model in ("+model+") ";
            jdbcTemplate.execute(sql);
        }
    }
    public void write(OutputStream os, List ls) throws Exception {
        write(Workbook.createWorkbook(os), ls);
    }
    public void write(WritableWorkbook wwb, List ls) throws Exception {
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);
            addHeader(ws);
            int i = 1;
            for (DeviceDetail tmp : (List<DeviceDetail>) ls) {
                Map<String, String> map = tmp.getErrorMsgMap();
                addCell(ws, i, 0, tmp.getManufacturer(), map.get("manufacturer"));
                addCell(ws, i, 1, tmp.getDeviceName(), map.get("deviceName"));
                addCell(ws, i, 2, tmp.getDeviceModel(), map.get("deviceModel"));
                addCell(ws, i, 3, tmp.getDeviceCode(), map.get("deviceCode"));
                addCell(ws, i, 4, tmp.getSim(), map.get("sim"));
                addCell(ws, i,5,  tmp.getIccid(), map.get("iccid"));
                addCell(ws, i,6,  tmp.getImsi(), map.get("imsi"));
                i++;
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }
    public void addHeader(WritableSheet ws) throws WriteException {
        String[] header = {"厂商(必填)", "设备名称(必填)", "设备型号(必填)", "设备SN(必填)", "sim卡号",  "iccid卡号", "imsi卡号"};
        int i = 0;
        for (String h : header) {
            addCell(ws, 0, i, h);//表名,行,列,header
            i++;
        }
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data) throws WriteException {
        Label label = new Label(column, row, data);
        ws.addCell(label);
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data, String memo) throws WriteException {
        Label label = new Label(column, row, data);
        if (!org.springframework.util.StringUtils.isEmpty(memo)) {
            WritableCellFeatures cellFeatures = new WritableCellFeatures();
            cellFeatures.setComment(memo);
            label.setCellFeatures(cellFeatures);
        }
        ws.addCell(label);
    }
}

+ 63 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/DmDeviceService.java

@ -0,0 +1,63 @@
package com.yihu.jw.base.service.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.device.DeviceDao;
import com.yihu.jw.base.dao.device.DeviceDetailDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.restmodel.ResponseContant;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
/**
 * Created by Bing on 2021/9/23.
 */
@Service
public class DmDeviceService extends BaseJpaService<Device, DeviceDao> {
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private ObjectMapper objectMapper;
    public JSONObject saveDmDevice(String json) throws IOException {
        JSONObject result = new JSONObject();
        Device device = objectMapper.readValue(json,Device.class);
        Integer deviceType = device.getDeviceType();
        String categoryCode = device.getCategoryCode();
        String name = device.getName();
        String model = device.getCategoryCode();
        String brands = device.getBrands();
        String photo =device.getPhoto();
        String isMultiUser = device.getIsMultiUser();
        if (null==deviceType||StringUtils.isBlank(categoryCode)||StringUtils.isBlank(name)||StringUtils.isBlank(model)||
                StringUtils.isBlank(brands)||StringUtils.isBlank(photo)||StringUtils.isBlank(isMultiUser)){
            result.put(ResponseContant.resultFlag,ResponseContant.fail);
            result.put(ResponseContant.resultMsg,"数据数据错误,必填字段为空");
            return result;
        }
        //判断型号是否重复
        Device deviceTmp = deviceDao.findByModel(device.getModel());
        if (null!=deviceTmp){
            if (null==device.getId()){
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"设备型号已存在");
                return result;
            }else if (deviceTmp.getId()!=device.getId()){//
                result.put(ResponseContant.resultFlag,ResponseContant.fail);
                result.put(ResponseContant.resultMsg,"设备型号已存在");
                return result;
            }
        }
        deviceDao.save(device);
        result.put(ResponseContant.resultFlag,ResponseContant.success);
        result.put(ResponseContant.resultMsg,"success");
        return result;
    }
}

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

@ -0,0 +1,66 @@
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;
/**
 * Created by Bing on 2021/9/22.
 */
@Service
public class WlyyPatientDeviceService extends BaseJpaService<DevicePatientDevice, PatientDeviceDao> {
    @Autowired
    private
    PatientDeviceDao patientDeviceDao;
    public void delPatientDevice(String id){
        DevicePatientDevice patientDevice = patientDeviceDao.findOne(Long.parseLong(id));
        String deviceSn = patientDevice.getDeviceSn();
        patientDeviceDao.delete(Long.parseLong(id));
        List<DevicePatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(deviceSn);
        String sql = "update device.wlyy_devices dd set dd.is_binding=? where dd.device_code=?";
        if (patientDeviceList.size()==0){
            jdbcTemplate.update(sql,new Object[]{0,deviceSn});
        }
        if (patientDeviceList.size()==1){
            jdbcTemplate.update(sql,new Object[]{1,deviceSn});
        }
        if (patientDeviceList.size()>1){
            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);
    }
}

+ 188 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/device/YsDeviceService.java

@ -0,0 +1,188 @@
package com.yihu.jw.base.service.device;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.config.YsConfig;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.encode.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.concurrent.TimeUnit;
/**
 * Created by Bing on 2021/9/24.
 */
@Service
public class YsDeviceService {
    private static Logger logger = LoggerFactory.getLogger(YsDeviceService.class);
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpClientUtil httpClientUtil;
    /**
     * 获取萤石设备assesToken
     */
    public String getAccessToken() throws Exception {
        if(redisTemplate.hasKey(YsConfig.redisKey)){
            return redisTemplate.opsForValue().get(YsConfig.redisKey);
        }
        JSONObject param = new JSONObject();
        param.put("appKey",YsConfig.AppKey);
        param.put("appSecret",YsConfig.Secret);
        HttpEntity<JSONObject> response = httpClientUtil.assesTokenPostHttp(YsConfig.saasAssesToken,param, HttpMethod.POST);
        JSONObject responseBody = response.getBody();
        String assToken = null;
        if (responseBody.getInteger("code")==200){
            assToken = responseBody.getJSONObject("data").getString("accessToken");
            Long expireTime = responseBody.getJSONObject("data").getLong("expiresIn");//token有效期
            redisTemplate.opsForValue().set(YsConfig.redisKey,assToken,expireTime, TimeUnit.SECONDS);
//            Long ss= redisTemplate.getExpire(YsConfig.redisKey);
//            System.out.println(expireTime+"---"+ss);
        }else {
            throw new Exception("获取token失败");
        }
        return assToken;
    }
    /**
     * 获取IOT开放平台assesToken
     * @return
     * @throws Exception
     */
    public String getIotAccessToken() throws Exception {
        if(redisTemplate.hasKey(YsConfig.iotRedisKey)){
            return redisTemplate.opsForValue().get(YsConfig.iotRedisKey);
        }
        JSONObject param = new JSONObject();
        param.put("accessToken",getAccessToken());
        HttpEntity<JSONObject> response = httpClientUtil.assesTokenPostHttp(YsConfig.iotAssesToken,param, HttpMethod.POST);
        JSONObject responseBody = response.getBody();
        String assToken = null;
        if (responseBody.getInteger("code")==200){
            assToken = responseBody.getJSONObject("data").getString("ezOpenAccessToken");
            Long expireTime = responseBody.getJSONObject("data").getLong("expireTime");//token有效截止日期
            Long nowTime = System.currentTimeMillis();
            expireTime = expireTime-nowTime;
            redisTemplate.opsForValue().set(YsConfig.iotRedisKey,assToken,expireTime, TimeUnit.MILLISECONDS);
            //设备解密密钥
            String secretKey = responseBody.getJSONObject("data").getString("secretKey");
            redisTemplate.opsForValue().set(YsConfig.secretKey,secretKey,expireTime, TimeUnit.MILLISECONDS);
//            Long ss= redisTemplate.getExpire(YsConfig.iotRedisKey);
//            System.out.println(expireTime+"---"+ss);
        }else {
            throw new Exception("获取token失败");
        }
        return assToken;
    }
    /**
     * 获取设备解密密钥
     * @return
     * @throws Exception
     */
    public String getSecretKey() throws Exception {
        if(redisTemplate.hasKey(YsConfig.secretKey)){
            return redisTemplate.opsForValue().get(YsConfig.secretKey);
        }
        else {
            getIotAccessToken();
            return redisTemplate.opsForValue().get(YsConfig.secretKey);
        }
    }
    @Async
    public void videoOpen(String deviceSn, HttpServletRequest request){
        try {
            StringBuilder responseStr = new StringBuilder("--"+deviceSn+"-- ");
            MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
            param.add("accessToken",getIotAccessToken());
            param.add("source",deviceSn+":"+1);
            HttpEntity<JSONObject> response = httpClientUtil.iotAssesTokenPostHttp(YsConfig.openChannelNo,param, HttpMethod.POST);
            JSONObject responseBody = response.getBody();
            responseStr.append("->开通通道:"+responseBody.getInteger("code"));
            JSONObject param2 = new JSONObject();
            param2.put("accessToken",getAccessToken());
            param2.put("deviceSerial",deviceSn);
            param2.put("channelNo","1");
            param2.put("isTrust",0);
            response = httpClientUtil.assesTokenPostHttp(YsConfig.surveillanceWay,param2,HttpMethod.POST);
            responseBody = response.getBody();
            responseStr.append("->获取通道详情:"+responseBody.getInteger("code"));
            if (responseBody.getInteger("code")==200){
                try {
                    JSONObject tmp =  responseBody.getJSONObject("data");
                    String validateCode = tmp.getString("ipcValidateCode");
                    param2 = new JSONObject();
                    param2.put("accessToken",getAccessToken());
                    param2.put("deviceSerial",deviceSn);
                    param2.put("isEncrypt","0");
                    validateCode = messageDecrypt(validateCode,getSecretKey());
                    param2.put("validateCode",validateCode);
                    response = httpClientUtil.assesTokenPostHttp(YsConfig.deviceEncrypt,param2,HttpMethod.POST);
                    responseBody = response.getBody();
                    responseStr.append("->视频解密:"+responseBody.getInteger("code"));
                }catch (Exception e){
                }
            }
//        //设置编码格式
//
//
//        //设置活动检测
//        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
//        param.add("accessToken",getIotAccessToken());
//        param.add("deviceSerial",deviceSn);
//        param.add("enable","1");
//        param.add("channelNo","1");
//        HttpEntity<JSONObject> response = httpClientUtil.iotAssesTokenPostHttp("https://open.ys7.com/api/lapp/device/intelligence/detection/switch/set",param, HttpMethod.POST);
//        JSONObject responseBody = response.getBody();
//        responseStr.append("->活动检测:"+responseBody.getInteger("code"));
            logger.info(responseStr.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 消息解密
     * @param sSrc
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String messageDecrypt(String sSrc, String sKey) throws Exception {
        try {
            byte[] raw = sKey.getBytes("utf-8");
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.decode(sSrc);//先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception ex) {
            logger.error("AES解密异常:Str"+sSrc+"\nkey:"+sKey);
            throw new Exception("解密失败");
        }
    }
}

+ 31 - 31
svr/svr-base/src/main/java/com/yihu/jw/base/service/equipment/BaseHospitalEquipmentService.java

@ -105,35 +105,35 @@ public class BaseHospitalEquipmentService extends BaseJpaService<BaseHospitalEqu
        return map;
    }
    public List<BaseHospitalEquipmentDO> synEquipment(String deviceNo){
        String str[]=deviceNo.split(",");
        for (int i=0;i<str.length;i++){
            String deviceNoString  = str[i];
            //获取第三方设备详情
            String result = juMiAiService.getEquipmentInfo(deviceNoString);
            if (result!=null&&result!=""){
                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = jsonObject.getString("code");
                if (code.equalsIgnoreCase("0")){
                    JSONObject object = jsonObject.getJSONObject("data");
                    String device_no= object.getString("device_no");
                    String device_name = object.getString("device_name");
                    Integer isonline = object.getInteger("isonline");//是否在线 0离线 1在线
                    Integer state= object.getInteger("state");//状态1开启 3关闭(故障) 0已解绑
                    String riss = object.getString("riss");//信号强度 长度限制为1~10个字符
                    String device_category = object.getString("device_category");//设备分类
                    String device_category_name = object.getString("device_category_name");//设备分类名称
                    BaseHospitalEquipmentDO equipmentDO = baseHospitalEquipmentDao.findAllByCode(device_no);
                    if (equipmentDO!=null){
                        equipmentDO.setName(device_name);
                        equipmentDO.
                    }
                }
            }
        }
        return map;
    }
//    public List<BaseHospitalEquipmentDO> synEquipment(String deviceNo){
//        String str[]=deviceNo.split(",");
//        for (int i=0;i<str.length;i++){
//            String deviceNoString  = str[i];
//            //获取第三方设备详情
//            String result = juMiAiService.getEquipmentInfo(deviceNoString);
//            if (result!=null&&result!=""){
//                JSONObject jsonObject = JSONObject.parseObject(result);
//                String code = jsonObject.getString("code");
//                if (code.equalsIgnoreCase("0")){
//                    JSONObject object = jsonObject.getJSONObject("data");
//                    String device_no= object.getString("device_no");
//                    String device_name = object.getString("device_name");
//                    Integer isonline = object.getInteger("isonline");//是否在线 0离线 1在线
//                    Integer state= object.getInteger("state");//状态1开启 3关闭(故障) 0已解绑
//                    String riss = object.getString("riss");//信号强度 长度限制为1~10个字符
//                    String device_category = object.getString("device_category");//设备分类
//                    String device_category_name = object.getString("device_category_name");//设备分类名称
//                    BaseHospitalEquipmentDO equipmentDO = baseHospitalEquipmentDao.findAllByCode(device_no);
//                    if (equipmentDO!=null){
//                        equipmentDO.setName(device_name);
//                        equipmentDO.
//                    }
//
//                }
//            }
//        }
//
//
//        return map;
//    }
}

+ 2 - 2
svr/svr-base/src/main/resources/application.yml

@ -615,8 +615,8 @@ spring:
    user: admin
    password: admin
  redis:
    host: 172.26.0.13 # Redis server host.
    port: 6379  # Redis server port.
    host: 10.18.43.40 # Redis server host.
    port: 6379 # Redis server port.
    password: Kb6wKDQP1W4
fastDFS:
  fastdfs_file_url: http://10.18.43.40:80/

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

@ -18,4 +18,7 @@ public interface DeviceDao extends PagingAndSortingRepository<Device, Long> {
	@Query("select a from Device a where a.del = '1'")
	List<Device> findAll();
	@Query("select a from Device a where a.del = '1' and a.model=?1")
	Device findByModel(String model);
}

+ 19 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/label/BaseCapacityLabelDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.care.dao.label;
import com.yihu.jw.entity.care.label.BaseCapacityLabelDO;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by yeshijie on 2021/9/26.
 */
public interface BaseCapacityLabelDao  extends PagingAndSortingRepository<BaseCapacityLabelDO, String>,
        JpaSpecificationExecutor<BaseCapacityLabelDO> {
    @Query("select a from BaseCapacityLabelDO a where a.patient=?1")
    BaseCapacityLabelDO findByPatient(String patient);
}

+ 2 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/assistance/EmergencyAssistanceEndpoint.java

@ -301,6 +301,7 @@ public class EmergencyAssistanceEndpoint extends EnvelopRestEndpoint {
    @PostMapping("errorWarning")
    @ApiOperation(value = "误报警")
    @ObserverRequired
    public ObjEnvelop errorWarning(@ApiParam(value = "工单id", name = "orderId", required = true)
                                   @RequestParam(value = "orderId") String orderId,
                                   @ApiParam(value = "误报警类型 字典emergency_cancel的code", name = "emergencyCancel", required = true)
@ -318,6 +319,7 @@ public class EmergencyAssistanceEndpoint extends EnvelopRestEndpoint {
    @PostMapping("doctorSendMessageLog")
    @ApiOperation(value = "助老员紧急预警im发送消息日志")
    @ObserverRequired
    public ObjEnvelop doctorSendMessageLog(
            @ApiParam(name="doctor")@RequestParam(value = "doctor")String doctor,
            @ApiParam(name="type",value = "im会话对应type")@RequestParam(value = "type")String type,

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

@ -32,7 +32,6 @@ public class DoctorConsultController extends EnvelopRestEndpoint {
     */
    @ApiOperation("结束咨询接口")
    @RequestMapping(value = "finish_consult",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @ObserverRequired
    public Envelop finishConsult(@RequestParam(required = false) String consult) {
        try {

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

@ -1,6 +1,7 @@
package com.yihu.jw.care.endpoint.consult;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.service.consult.ConsultService;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
@ -42,6 +43,7 @@ public class DoctorConsultEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "finish")
    @ApiOperation(value = "医生结束咨询", notes = "医生结束咨询")
    @ObserverRequired
    public Envelop finish(
            @ApiParam(name = "consult", value = "咨询CODE")
            @RequestParam(value = "consult",required = true) String consult,

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

@ -2,6 +2,7 @@ package com.yihu.jw.care.endpoint.device;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.contacts.ContactsService;
@ -124,6 +125,7 @@ public class DoctorDeviceController extends BaseController {
	@RequestMapping(value ="updatePatientSosContacts",method = RequestMethod.POST)
	@ApiOperation(value = "设置居民紧急联系人")
	@ObserverRequired
	public String updatePatientSosContacts(@ApiParam(name = "patient", value = "patient", defaultValue = "patient")
										   @RequestParam(value = "patient", required = true) String patient,
										   @ApiParam(name="num",value = "成员配置的语音白名单号码 新增时只能传一个,删除时最多两个,用下划线隔开")

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

@ -1,6 +1,7 @@
package com.yihu.jw.care.endpoint.device;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.PatientHealthIndexService;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
@ -337,6 +338,7 @@ public class DoctorHealthController extends BaseController {
	@RequestMapping(value = "handleHealthIndex",method = RequestMethod.POST)
	@ApiOperation("医生体征干预")
	@ObserverRequired
	public String handleHealthIndex(@ApiParam(name="user")@RequestParam(value = "user")String ids) {
		try {
			healthIndexService.handleHealthIndex(ids);

+ 3 - 111
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PadDeviceController.java

@ -77,12 +77,14 @@ public class PadDeviceController extends BaseController {
                                     @RequestParam(value = "patientName", required = false) String patientName,
                                     @ApiParam(name = "doctor", value = "doctor")
                                     @RequestParam(value = "doctor", required = false) String doctor,
                                     @ApiParam(name = "categoryCode", value = "设备类型标识 1血糖仪,2.血压计,3药盒,4智能手表,7 = 居家报警器,12 监控器 13 睡眠带 14气感报警器 15烟感报警器 16拐杖 17随身wifi")
                                     @RequestParam(value = "categoryCode", required = false) String categoryCode,
                                     @ApiParam(name = "page", value = "分页起始id", defaultValue = "1")
                                     @RequestParam(value = "page", required = true) int page,
                                     @ApiParam(name = "pagesize", value = "每页条数", defaultValue = "10")
                                     @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            List<Map<String , Object>> list = patientDeviceService.findDeviceFromAdmin(doctor,patientName, page, pagesize);
            List<Map<String , Object>> list = patientDeviceService.findDeviceFromAdmin(doctor,patientName,categoryCode, page, pagesize);
            return write(200, "查询成功", "data", list);
        } catch (Exception ex) {
@ -200,116 +202,6 @@ public class PadDeviceController extends BaseController {
        }
    }
    @RequestMapping(value = "/importDeviceFromExcel", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public String importFromExcel(HttpServletRequest request,@ApiParam(value = "文件", required = true)
    @RequestParam(value = "file", required = true) MultipartFile file) {
        List errorLs = new ArrayList<>();
        List correctLs = new ArrayList<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        List<String> deviceCodes = new ArrayList<>();
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = file.getInputStream();
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet[] sheets = rwb.getSheets();
            int rows;
            int row;
            String manufacturer=null;//厂商名称
            String deviceName; //设备名称
            String deviceModel; //设备型号
            String deviceCode;  //设备SN
            String sim;  //sim卡号
            String bindingCount; //单人{"1":"0"}  多人{"1":"0", "2":"0"}
            String deviceType; //设备种类  0健康设备 1安防设备
            Sheet sheet = sheets[0];    //第一张表
            rows = sheet.getRows();
            for (int j = 1; j < rows; j++) {
                if (sheet.getRow(j).length == 0) {
                    continue;
                }
                DeviceDetail deviceDetail = new DeviceDetail();
                row = j;
                manufacturer = sheet.getCell(0, row).getContents().trim();    //0 厂商名称
                deviceName = sheet.getCell(1, row).getContents().trim();  //1 设备名称
                deviceModel = sheet.getCell(2, row).getContents().trim();   //2 设备型号
                deviceCode = sheet.getCell(3, row).getContents().trim(); //3 设备SN
                sim = sheet.getCell(4, row).getContents().trim();  //4 sim卡号
                bindingCount = sheet.getCell(5, row).getContents().trim(); //5
                deviceType = sheet.getCell(6, row).getContents().trim(); //6 设备种类
                if (StringUtils.isBlank(deviceCode)){
                    continue;
                }
                if (deviceCodes.contains(deviceCode)){
                    errorMsgMap.put(deviceCode,"设备SN码重复");
                    continue;
                }
                deviceCodes.add(deviceCode);
                if (StringUtils.isBlank(manufacturer)){
                    errorMsgMap.put(deviceCode,"厂商名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceName)){
                    errorMsgMap.put(deviceCode,"设备名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceModel)){
                    errorMsgMap.put(deviceCode,"设备型号不能为空");
                    continue;
                }
                if (StringUtils.isBlank(bindingCount)){
                    errorMsgMap.put(deviceCode,"设备类型不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceType)){
                    errorMsgMap.put(deviceCode,"设备种类不能为空");
                    continue;
                }else {
                    if ("健康设备".equals(deviceType)){
                        deviceType = "1";
                    }
                    else if ("安防设备".equals(deviceType)){
                        deviceType= "0";
                    }
                    else {
                        errorMsgMap.put(deviceCode,"不支持该设备种类");
                        continue;
                    }
                }
                if (deviceDetailDao.findByDeviceCode(deviceCode).size()>0){
                    errorMsgMap.put(deviceCode,"该设备SN码已存在");
                    continue;
                }
                if (deviceDetailDao.findBySim(sim).size()>0){
                    errorMsgMap.put(deviceCode,"该sim卡号已存在");
                    continue;
                }
                deviceDetail.setManufacturer(manufacturer);
                deviceDetail.setDeviceName(deviceName);
                deviceDetail.setDeviceModel(deviceModel);
                deviceDetail.setDeviceCode(deviceCode);
                deviceDetail.setSim(sim);
                deviceDetail.setBindingCount(bindingCount);
                deviceDetail.setDeviceType(Integer.parseInt(deviceType));
                correctLs.add(deviceDetail);
            }
            deviceDetailDao.save(correctLs);
            //包装导入结果(导入成功数量、错误对象集合)
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", rows-1 - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMap, SerializerFeature.WriteMapNullValue));
            return write(200, "操作成功", "data", map);
        } catch (Exception e) {
            error(e);
            return error(-1, "操作失败!");
        }
    }
    @RequestMapping(value ="addPatientSosContacts",method = RequestMethod.POST)
    @ApiOperation(value = "设备绑定添加联系人")
    public String addPatientSosContacts(@ApiParam(name = "patient", value = "patient", defaultValue = "patient")

+ 5 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorBirthdayWishesEndpoint.java

@ -2,6 +2,7 @@ package com.yihu.jw.care.endpoint.doctor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.birthday.BirthdayWishesService;
import com.yihu.jw.care.util.MessageUtil;
@ -52,6 +53,7 @@ public class DoctorBirthdayWishesEndpoint extends BaseController {
    @RequestMapping(value = "/createTemplate", method = RequestMethod.POST)
    @ApiOperation(value = "创建模板")
    @ObserverRequired
    public String createTemplate(@ApiParam(name = "content", value = "医生新建的祝福语")
                                 @RequestParam(required = false) String content,
                                 @ApiParam(name = "applicableRange", value = "适用人群")
@ -94,6 +96,7 @@ public class DoctorBirthdayWishesEndpoint extends BaseController {
    @RequestMapping(value = "/deleteTemplateById", method = RequestMethod.POST)
    @ApiOperation(value = "根据模板id删除祝福模板")
    @ObserverRequired
    public String deleteTemplateById(@ApiParam(name = "id", value = "模板id")
                                     @RequestParam(required = true) Long id) {
        try {
@ -106,6 +109,7 @@ public class DoctorBirthdayWishesEndpoint extends BaseController {
    @RequestMapping(value = "/setDefalutTemplateById", method = RequestMethod.POST)
    @ApiOperation(value = "设置默认模板")
    @ObserverRequired
    public String setDefalutTemplateById(
            @ApiParam(name = "id", value = "模板ID",required = true)
            @RequestParam Long id) {
@ -171,6 +175,7 @@ public class DoctorBirthdayWishesEndpoint extends BaseController {
    @RequestMapping(value = "/doctorSendBirthdayWishes", method = RequestMethod.POST)
    @ApiOperation(value = "医生发送生日祝福")
    @ObserverRequired
    public String pushBirthdayWishes(@ApiParam(name = "patient", value = "发送人群集合")
                                     @RequestParam(required = true) String patient,
                                     @ApiParam(name = "templateId", value = "生日祝福模板id")

+ 1 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorEndpoint.java

@ -45,6 +45,7 @@ public class DoctorEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "updOnline")
    @ApiOperation(value = "更新在线状态")
    @ObserverRequired
    public Envelop updOnline(@ApiParam(name = "doctorId", value = "医生id", required = true)
                                 @RequestParam(value = "doctorId",required = true) String doctorId,
                             @ApiParam(name = "online", value = "在线状态 1在线 0离线")

+ 5 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doctor/DoctorServiceEndPoint.java

@ -1,5 +1,6 @@
package com.yihu.jw.care.endpoint.doctor;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.doctor.service.BaseDoctorInfoService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
@ -79,6 +80,7 @@ public class DoctorServiceEndPoint extends EnvelopRestEndpoint {
    @PostMapping(value = BaseHospitalRequestMapping.DoctorSetting.update)
    @ApiOperation(value = "修改医生服务配置")
    @ObserverRequired
    public Envelop update(
            @ApiParam(name = "baseDoctorVo", value = "JSON数据", required = true)
            @RequestParam(value = "baseDoctorVo") String baseDoctorVo)throws Exception{
@ -97,6 +99,7 @@ public class DoctorServiceEndPoint extends EnvelopRestEndpoint {
    @PostMapping(value = BaseHospitalRequestMapping.DoctorSetting.updateList)
    @ApiOperation(value = "批量修改医生服务配置")
    @ObserverRequired
    public Envelop updateList(
            @ApiParam(name = "baseDoctorVos", value = "JSON数据", required = true)
            @RequestParam(value = "baseDoctorVos") String baseDoctorVos)throws Exception{
@ -113,6 +116,7 @@ public class DoctorServiceEndPoint extends EnvelopRestEndpoint {
    @GetMapping(value = BaseHospitalRequestMapping.DoctorSetting.updateStatus)
    @ApiOperation(value = "修改医生状态")
    @ObserverRequired
    public Envelop updateStatus(
            @ApiParam(name = "doctorId", value = "状态")
            @RequestParam(value = "doctorId", required = true) String doctorId,
@ -125,6 +129,7 @@ public class DoctorServiceEndPoint extends EnvelopRestEndpoint {
    @PostMapping(value = BaseHospitalRequestMapping.DoctorSetting.updateDoctorPw)
    @ApiOperation(value = "修改医生账号密码")
    @ObserverRequired
    public Envelop updateDoctorPw(@ApiParam(name = "id", value = "医生ID")
                                  @RequestParam(value = "id", required = true)String id,
                                  @ApiParam(name = "pw", value = "密码")

+ 16 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/doorCoach/DoctorDoorCoachOrderController.java

@ -3,6 +3,7 @@ package com.yihu.jw.care.endpoint.doorCoach;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.consult.ConsultTeamService;
@ -50,6 +51,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "proxyCreate")
    @ApiOperation(value = "创建上门预约咨询--医生代预约")
    @ObserverRequired
    public String create(@ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {
        try{
            JSONObject result = patientDoorCoachOrderService.proxyCreate(jsonData,getUID());
@ -102,6 +104,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "sendOrderToDoctor")
    @ApiOperation(value = "调度员给医生派单")
    @ObserverRequired
    public String sendOrderToDoctor(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "remark", value = "调度员备注") @RequestParam(value = "remark", required = false) String remark,
@ -123,6 +126,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "transferOrder")
    @ApiOperation(value = "医生转派单")
    @ObserverRequired
    public String transferOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "remark", value = "当前医生备注") @RequestParam(value = "remark", required = false) String remark,
@ -144,6 +148,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("acceptOrder")
    @ApiOperation(value = "接单")
    @ObserverRequired
    public String acceptOrder(
            @ApiParam(value = "工单id", name = "orderId", required = true) @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(value = "医生职称code", name = "jobCode", required = false) @RequestParam(value = "jobCode", required = false) String jobCode,
@ -159,6 +164,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("refuse")
    @ApiOperation(value = "拒单")
    @ObserverRequired
    public String refuseOrder(
            @ApiParam(value = "工单id", name = "orderId", required = true)
            @RequestParam(value = "orderId", required = true) String orderId,
@ -174,6 +180,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "cancelOrder")
    @ApiOperation(value = "取消工单")
    @ObserverRequired
    public String cancelOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "type", value = "取消类型:1-调度员主动取消,2-居民取消, 3-医生取消") @RequestParam(value = "type", required = true) int type,
@ -194,6 +201,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("signIn")
    @ApiOperation(value = "上门预约签到")
    @ObserverRequired
    public String signIn(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
@ -221,6 +229,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("updateDoorConclusion")
    @ApiOperation("编辑保存服务工单小结")
    @ObserverRequired
    public String updateDoorConclusion(
            @ApiParam(value = "工单id", name = "orderId",required = true)
            @RequestParam(value = "orderId", required = true) String orderId,
@ -264,6 +273,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("saveOrderFinishByDoctor")
    @ApiOperation(value = "确认完成工单")
    @ObserverRequired
    public String saveOrderFinishByDoctor(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
@ -280,6 +290,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("updateArrivingTime")
    @ApiOperation(value = "修改预计到达时间")
    @ObserverRequired
    public String updateArrivingTime(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
@ -504,6 +515,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "payOrder")
    @ApiOperation(value = "医生确认付款")
    @ObserverRequired
    public ObjEnvelop payOrder(
            @ApiParam(name = "orderId", value = "工单id") @RequestParam(value = "orderId", required = true) String orderId,
            @ApiParam(name = "payWay", value = "支付方式:1-微信支付,2-线下支付") @RequestParam(value = "payWay", required = false,defaultValue = "2") int payWay) {
@ -538,6 +550,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("/initDoorStatus")
    @ApiOperation(value = "初始化医生分派订单开关状态")
    @ObserverRequired
    public String initDoorStatus() {
        try {
            doctorDoorCoachOrderService.initDoorStatus(null);
@ -564,6 +577,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping("/dispatchOrderSwitch")
    @ApiOperation(value = "分派订单开关修改")
    @ObserverRequired
    public String dispatchOrderSwitch(
            @ApiParam(name = "doctor", value = "医生code")
            @RequestParam(value = "doctor", required = true) String doctor,
@ -579,6 +593,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "dispatcherIntoTopic")
    @ApiOperation(value = "调度员进入会话")
    @ObserverRequired
    public ObjEnvelop dispatcherIntoTopic(
            @ApiParam(name = "orderId", value = "工单id", required = true) @RequestParam String orderId,
            @ApiParam(name = "hospitalName", value = "机构名称", required = true) @RequestParam String hospitalName,
@ -639,6 +654,7 @@ public class DoctorDoorCoachOrderController extends EnvelopRestEndpoint {
    @PostMapping(value = "updateOrderCardInfo")
    @ApiOperation(value = "更新预约简要信息")
    @ObserverRequired
    public String updateOrderCardInfo(
            @ApiParam(name = "jsonData", value = "json数据") @RequestParam(value = "jsonData", required = true) String jsonData) {
        try{

+ 2 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/exam/DoctorChildrenExaminationEndpoint.java

@ -1,5 +1,6 @@
package com.yihu.jw.care.endpoint.exam;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.service.exam.ChildrenExaminationService;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
@ -22,6 +23,7 @@ public class DoctorChildrenExaminationEndpoint extends EnvelopRestEndpoint {
    @PostMapping("newRecord")
    @ApiOperation("居民居家自建记录添加")
    @ObserverRequired
    public ObjEnvelop newRecord(@ApiParam(name="patient",value ="儿童id")
                                @RequestParam(value = "patient",required = true)String patient,
                                @ApiParam(name="examTime",value ="体检日期 yyyy-mm-dd")

+ 2 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/lifeCare/DoctorLifeCareEndpoint.java

@ -105,6 +105,7 @@ public class DoctorLifeCareEndpoint extends EnvelopRestEndpoint {
    @PostMapping("updateConclusion")
    @ApiOperation("编辑保存服务工单小结")
    @ObserverRequired
    public Envelop updateConclusion(
            @ApiParam(value = "工单id", name = "orderId")
            @RequestParam(value = "orderId", required = true) String orderId,
@ -144,6 +145,7 @@ public class DoctorLifeCareEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "proxyCreate")
    @ApiOperation(value = "创建生活照料--医生代预约")
    @ObserverRequired
    public Envelop proxyCreate(
            @ApiParam(name = "doctor", value = "医生id") @RequestParam(value = "doctor", required = true) String doctor,
            @ApiParam(name = "jsonData", value = "Json数据", required = true) @RequestParam String jsonData) {

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

@ -1,6 +1,7 @@
package com.yihu.jw.care.endpoint.message;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.aop.ObserverRequired;
import com.yihu.jw.care.service.message.DoctorMessageService;
import com.yihu.jw.care.service.message.PatientMessageService;
import com.yihu.jw.restmodel.ResponseContant;
@ -41,6 +42,7 @@ public class DoctorMessageEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "newOrgNotice")
    @ApiOperation("创建机构通知消息")
    @ObserverRequired
    public ObjEnvelop newOrgNotice(@ApiParam(name = "jsonDate", value = "消息通知json")
                               @RequestParam(value = "jsonDate", required = false) String jsonDate,
                               @ApiParam(name = "patients", value = "通知居民列表")
@ -101,6 +103,7 @@ public class DoctorMessageEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "/updateMessageRead")
    @ApiOperation("已读消息")
    @ObserverRequired
    public Envelop updateMessageRead(@ApiParam(name = "messageId",required = true)
                                     @RequestParam(value = "messageId")String messageId){
        try {
@ -114,6 +117,7 @@ public class DoctorMessageEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "/delMessageRead")
    @ApiOperation("删除消息")
    @ObserverRequired
    public Envelop delMessageRead(@ApiParam(name = "messageId",required = true)
                                     @RequestParam(value = "messageId")String messageId){
        try {

+ 1 - 1
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/org/OrgEndpoint.java

@ -23,7 +23,7 @@ public class OrgEndpoint extends EnvelopRestEndpoint {
    @RequestMapping(value = "/findOrgList", method = RequestMethod.GET)
    @ApiOperation(value = "获取机构成员")
    public ListEnvelop findOrgList(@ApiParam(name = "type", value = "机构类型1. 等级医院2. 社区医院3.  养老机构")
    public ListEnvelop findOrgList(@ApiParam(name = "type", value = "机构类型1. 等级医院2. 社区医院3.  养老机构 4.  托育机构")
                                      @RequestParam(value = "type", required = false) String type,
                                      @ApiParam(name = "name", value = "机构名称")
                                      @RequestParam(value = "name", required = false) String name,

+ 26 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/patient/PatientEndpoint.java

@ -144,6 +144,32 @@ public class PatientEndpoint extends EnvelopRestEndpoint {
        }
    }
    @GetMapping(value = "findCapLabel")
    @ApiOperation(value = "获取居民能力状况信息")
    public Envelop findCapLabel(
            @ApiParam(name = "patientId", value = "居民id")
            @RequestParam(value = "patientId", required = true) String patientId) {
        try{
            return success("获取成功", patientService.findCapLabel(patientId));
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @PostMapping(value = "updCapLabel")
    @ApiOperation(value = "修改居民能力状况信息")
    @ObserverRequired
    public Envelop updCapLabel(
            @ApiParam(name = "jsonData", value = "能力状况")
            @RequestParam(value = "jsonData", required = true) String jsonData) {
        try{
            return success("获取成功", patientService.updCapLabel(jsonData));
        }catch (Exception e){
            return failedException2(e);
        }
    }
    @PostMapping(value = "updLatLon")
    @ApiOperation(value = "修改居民经纬度信息")
    public Envelop updLatLon(@ApiParam(name = "latLon", value = "经纬度24.48923061,118.10388605")

+ 1 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/sign/SignEndpoint.java

@ -50,6 +50,7 @@ public class SignEndpoint extends EnvelopRestEndpoint {
    @PostMapping(value = "addPatientSignList")
    @ApiOperation(value = "添加签约数据")
    @ObserverRequired
    public Envelop addPatientSignList () throws Exception {
        try{
            servicePackageService.addPatientSignList();

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

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

@ -258,18 +258,30 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
            DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
            if (device != null && !device.getId().equals(devicePatientDevice.getId()) && device.getDel() == 0) {
                //V1.0.0    监控器、报警器、燃气传感器 烟雾传感器支持一个设备绑定多个居民
                //监控器 12   报警器 7  14  15
                if ("12".equals(type) || "14".equals(type) || "15".equals(type)) {
                    if (devicePatientDevice.getUser().equals(device.getUser())) {
                        System.out.println("居民已经绑定此sn码:"+sn);
                        return -5;
                //V1.0.0    监控器、燃气传感器 烟雾传感器支持一个设备绑定多个居民
                //监控器 12     14  15
                DeviceDetail deviceDetail = deviceDetailDao.findBySn(device.getDeviceSn());
                if (null==deviceDetail){
                    return -1;
                }
                Device dmDevice = deviceDao.findByModel(deviceDetail.getDeviceModel());
                if (dmDevice!=null){
                    if ("1".equals(dmDevice.getIsMultiUser())) {//支持多人绑定设备在dm_device表定义
                        if (devicePatientDevice.getUser().equals(device.getUser())) {
                            System.out.println("居民已经绑定此sn码:"+sn);
                            return -5;
                        }
                        System.out.println("此类设备支持多绑定");
                    }
                    System.out.println("此类设备支持多绑定");
                } else {
                    else {
                        System.out.println("sn码" + sn + "已被使用!");
                        return -3;
                    }
                }
               else {
                    System.out.println("sn码" + sn + "已被使用!");
                    return -3;
                }
               }
            }
        }
        devicePatientDevice.setCzrq(new Date());
@ -310,7 +322,10 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        String sql = "select * from wlyy_patient_device where del = 0 and device_sn = '"+deviceSn+"'";
        List<Map<String , Object>> list = jdbcTemplate.queryForList(sql);
        if (list.size() > 0){
            return patientDeviceDao.deleteByDeviceSn(deviceSn);
            Integer count = patientDeviceDao.deleteByDeviceSn(deviceSn);
            sql = "update device.wlyy_devices dd set dd.is_binding=? where dd.device_code=?";
            jdbcTemplate.update(sql,new Object[]{0,deviceSn});
            return count;
        }else {
            return 0;
        }
@ -391,7 +406,7 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        return page;
    }
    public List<Map<String , Object>> findDeviceFromAdmin(String doctor,String patientName, int page, int pageSize) {
    public List<Map<String , Object>> findDeviceFromAdmin(String doctor,String patientName,String categoryCode, int page, int pageSize) {
        String sql = "select Distinct p.id,p.`name`,dd.photo,pd.device_id deviceId,pd.category_code categoryCode,pd.device_name deviceName, " +
                " pd.device_sn deviceSn,pd.czrq,pd.doctor,pd.doctor_name doctorName,pd.agent,pd.agent_name agentName " +
                " from wlyy_patient_device pd,wlyy_devices wd,base_patient p,dm_device dd where p.id = pd.`user`  and pd.del = 0 " +
@ -399,6 +414,9 @@ public class PatientDeviceService extends BaseJpaService<DevicePatientDevice, Pa
        if (StringUtils.isNotBlank(patientName)){
            sql += " AND (p.`name` LIKE '%" + patientName +"%' or  p.idcard LIKE '%" + patientName + "%') ";
        }
        if(StringUtils.isNotBlank(categoryCode)){
            sql+= " and pd.category_code ='"+categoryCode+"'";
        }
        if (StringUtils.isNotBlank(doctor)){//著老远查看时之查看签约居民的绑定
            sql += " and EXISTS (SELECT sr.patient from base_service_package_sign_record sr,base_service_package_record r,base_team_member m " +
                    " WHERE sr.patient = p.id and sr.status=1 and m.team_code = r.team_code and sr.id=r.sign_id " +

+ 52 - 4
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/patient/CarePatientService.java

@ -3,6 +3,8 @@ package com.yihu.jw.care.service.patient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.label.BaseCapacityLabelDao;
import com.yihu.jw.care.dao.label.WlyyPatientLabelDao;
import com.yihu.jw.care.service.common.DictService;
import com.yihu.jw.care.service.device.DeviceService;
@ -14,6 +16,7 @@ import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.servicePackage.ServicePackageSignRecordDO;
import com.yihu.jw.entity.care.label.BaseCapacityLabelDO;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import com.yihu.jw.entity.care.sign.CapacityAssessmentRecordDO;
import com.yihu.jw.im.util.ImUtil;
@ -27,6 +30,7 @@ import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.StringUtil;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -74,6 +78,31 @@ public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatien
    private DeviceService deviceService;
    @Autowired
    private HospitalSysDictDao hospitalSysDictDao;
    @Autowired
    private BaseCapacityLabelDao capacityLabelDao;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 获取能力状况
     * @param patient
     * @return
     */
    public BaseCapacityLabelDO findCapLabel(String patient){
        return capacityLabelDao.findByPatient(patient);
    }
    /**
     * 更新能力状况
     * @param jsonData
     * @return
     * @throws Exception
     */
    public BaseCapacityLabelDO updCapLabel(String jsonData) throws Exception{
        BaseCapacityLabelDO capacityLabelDO = objectMapper.readValue(jsonData, BaseCapacityLabelDO.class);
        capacityLabelDao.save(capacityLabelDO);
        return capacityLabelDO;
    }
    /**
     * 签约记录
@ -208,6 +237,10 @@ public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatien
                res.put("capAssRecordDO",recordDO);
            }
        }
        //能力状况
        BaseCapacityLabelDO capacityLabelDO = capacityLabelDao.findByPatient(patientId);
        res.put("capacityLabelDO",capacityLabelDO);
        JSONObject tmp = res.getJSONObject("patient");
        tmp.put("deviceType",deviceService.getPatientDeviceCategoryCode(patientId));
        res.put("patient",tmp);
@ -576,10 +609,11 @@ public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatien
     */
    public List<Map<String,Object>> findOld(String name,String residentialArea,String limit,String filter1){
        String sql = "SELECT a.id,a.name,a.photo,a.idcard,CAST(IFNULL(a.birthday,'') AS char ) birthday,a.residential_area residentialArea,a.sex " +
                ", GROUP_CONCAT(DISTINCT d.category_code) deviceFlag,if(openid is null,0,1) onlineWx,IFNULL(a.on_line,0) onlinePad,IFNULL(sign_status,0) signStatus from base_patient a " +
                " LEFT JOIN wlyy_patient_device d on d.`user`=a.id  WHERE a.archive_type = 1 and a.del = '1' ";
                ", case 1 WHEN openid is not null then 1 WHEN a.on_line = '1' then 1 ELSE 0 end as online,IFNULL(sign_status,0) signStatus from base_patient a " +
                " WHERE a.archive_type = 1 and a.del = '1' ";
        //case 1 WHEN openid is not null then 1 WHEN a.on_line = '1' then 1 ELSE 0 end as online
        //if(openid is null,0,1) onlineWx,IFNULL(a.on_line,0) onlinePad
        if(!StringUtil.isBlank(name)){
            sql+= " and name like '%"+name+"%' ";
        }
@ -587,15 +621,17 @@ public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatien
            sql+= " and residential_area = '"+residentialArea+"' ";
        }
        sql += filter1;
        sql += " GROUP BY a.id,a.name,a.photo,a.idcard,a.birthday,a.residential_area,a.sex,on_line,signStatus ";
        sql += " ORDER BY a.on_line desc,signStatus desc";
        sql += " GROUP BY a.id,a.name,a.photo,a.idcard,a.birthday,a.residential_area,a.sex,online,signStatus ";
        sql += " ORDER BY online desc,signStatus desc";
        sql += limit;
        List<Map<String,Object>>  list = jdbcTemplate.queryForList(sql);
        String sqlLife= "SELECT COUNT(*) from base_life_care_order where `status` = 2";
        String sqlEmergency= "SELECT COUNT(*) from base_emergency_assistance_order where `status` = 0";
        String sqlSecurity= "SELECT COUNT(*) from base_security_monitoring_order where `status` = 7 ";
        String sqlDevice = "SELECT pd.category_code deviceFlag, IFNULL(d.contact_status,0) status from wlyy_patient_device pd,wlyy_devices d";
        for (Map<String,Object> map:list){
            String paientId = map.get("id").toString();
            String filterDevice = " WHERE pd.device_sn = d.device_code and pd.user = '"+paientId+"' ORDER BY deviceFlag,status desc";
            String idcardNo = map.get("idcard") + "";
            Date birthday = DateUtil.strToDate(map.get("birthday").toString());
            Integer age = IdCardUtil.getAgeByIdcardOrBirthday(idcardNo,birthday);
@ -604,9 +640,21 @@ public class CarePatientService extends BaseJpaService<BasePatientDO, BasePatien
            Integer lifeCare = jdbcTemplate.queryForObject(sqlLife+filter,Integer.class);
            Integer emergency = jdbcTemplate.queryForObject(sqlEmergency+filter,Integer.class);
            Integer security = jdbcTemplate.queryForObject(sqlSecurity+filter,Integer.class);
            List<Map<String,Object>> deviceList = jdbcTemplate.queryForList(sqlDevice+filterDevice);
            Iterator it = deviceList.listIterator();
            Map<Object,Object> deviceMap = new HashedMap();
            while (it.hasNext()){
                Map<String,Object> tmp = (Map<String,Object>)it.next();
                if(deviceMap.containsKey(tmp.get("deviceFlag"))){
                    it.remove();
                }else{
                    deviceMap.put(tmp.get("deviceFlag"),tmp.get("deviceFlag"));
                }
            }
            map.put("lifeCare",lifeCare);
            map.put("emergency",emergency);
            map.put("security",security);
            map.put("devices",deviceList);
        }
        return list;
    }

+ 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);
    }
    /**
     * 计算开始时间

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

@ -1,6 +1,7 @@
package com.yihu.jw.care.service.third;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.label.BaseCapacityLabelDao;
import com.yihu.jw.care.dao.label.WlyyPatientLabelDao;
import com.yihu.jw.care.service.course.CourseService;
import com.yihu.jw.care.service.device.PatientDeviceService;
@ -11,6 +12,7 @@ import com.yihu.jw.care.service.security.SecurityMonitoringOrderService;
import com.yihu.jw.care.service.sign.CapacityAssessmentRecordService;
import com.yihu.jw.care.service.sign.ServicePackageService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.label.BaseCapacityLabelDO;
import com.yihu.jw.entity.care.label.WlyyPatientLabelDO;
import com.yihu.jw.entity.care.sign.CapacityAssessmentRecordDO;
import com.yihu.jw.patient.dao.BasePatientDao;
@ -55,6 +57,8 @@ public class PatientInfoPlatFormService {
    private PatientHealthIndexService healthIndexService;
    @Autowired
    private CapacityAssessmentRecordService capacityAssessmentRecordService;
    @Autowired
    private BaseCapacityLabelDao capacityLabelDao;
    /**
@ -107,6 +111,9 @@ public class PatientInfoPlatFormService {
            }catch (Exception e){
                e.printStackTrace();
            }
            //能力状况
            BaseCapacityLabelDO capacityLabelDO = capacityLabelDao.findByPatient(patient);
            result.put("capacityLabelDO",capacityLabelDO);
            return result;
        }
        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 + "%";
    }
}

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

@ -48,126 +48,7 @@ public class DeviceController {
    @Autowired
    private DeviceDataPushLogUtil dataPushLogUtil;
    @RequestMapping(value = "/importDeviceFromExcel", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public String importFromExcel(HttpServletRequest request,@ApiParam(value = "文件", required = true)
    @RequestParam(value = "file", required = true) MultipartFile file) {
        List errorLs = new ArrayList<>();
        List correctLs = new ArrayList<>();
        Map<String, String> errorMsgMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> deviceCodes = new ArrayList<>();
        try {
            request.setCharacterEncoding("UTF-8");
            InputStream inputStream = file.getInputStream();
            Workbook rwb = Workbook.getWorkbook(inputStream);
            Sheet[] sheets = rwb.getSheets();
            int rows;
            int row;
            String manufacturer=null;//厂商名称
            String deviceName; //设备名称
            String deviceModel; //设备型号
            String deviceCode;  //设备SN
            String sim;  //sim卡号
            String bindingCount; //单人{"1":"0"}  多人{"1":"0", "2":"0"}
            String deviceType; //设备种类  0健康设备 1安防设备
            Sheet sheet = sheets[0];    //第一张表
            rows = sheet.getRows();
            for (int j = 1; j < rows; j++) {
                if (sheet.getRow(j).length == 0) {
                    continue;
                }
                DeviceDetail deviceDetail = new DeviceDetail();
                row = j;
                manufacturer = sheet.getCell(0, row).getContents().trim();    //0 厂商名称
                deviceName = sheet.getCell(1, row).getContents().trim();  //1 设备名称
                deviceModel = sheet.getCell(2, row).getContents().trim();   //2 设备型号
                deviceCode = sheet.getCell(3, row).getContents().trim(); //3 设备SN
                sim = sheet.getCell(4, row).getContents().trim();  //4 sim卡号
                bindingCount = sheet.getCell(5, row).getContents().trim(); //5
                deviceType = sheet.getCell(6, row).getContents().trim(); //6 设备种类
                if (StringUtils.isBlank(deviceCode)){
                    continue;
                }
                if (deviceCodes.contains(deviceCode)){
                    errorMsgMap.put(deviceCode,"设备SN码重复");
                    continue;
                }
                deviceCodes.add(deviceCode);
                if (StringUtils.isBlank(manufacturer)){
                    errorMsgMap.put(deviceCode,"厂商名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceName)){
                    errorMsgMap.put(deviceCode,"设备名称不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceModel)){
                    errorMsgMap.put(deviceCode,"设备型号不能为空");
                    continue;
                }
                if (StringUtils.isBlank(bindingCount)){
                    errorMsgMap.put(deviceCode,"设备类型不能为空");
                    continue;
                }
                if (StringUtils.isBlank(deviceType)){
                    errorMsgMap.put(deviceCode,"设备种类不能为空");
                    continue;
                }else {
                    if ("健康设备".equals(deviceType)){
                        deviceType = "0";
                    }
                    else if ("安防设备".equals(deviceType)){
                        deviceType= "1";
                    }
                    else {
                        errorMsgMap.put(deviceCode,"不支持该设备种类");
                        continue;
                    }
                }
                if (deviceDetailDao.findByDeviceCode(deviceCode).size()>0){
                    errorMsgMap.put(deviceCode,"该设备SN码已存在");
                    continue;
                }
                if (StringUtils.isNotBlank(sim) && deviceDetailDao.findBySim(sim).size()>0){
                    errorMsgMap.put(deviceCode,"该sim卡号已存在");
                    continue;
                }
                if ("CS-C6Wi-3E4WFR".equals(deviceModel)){//监控器 直播地址开通->关闭视频加密 后续暂时先于APP操作
                    ysDeviceService.videoOpen(deviceCode,null);
                }
                deviceDetail.setApplyDate(sdf.format(new Date()));
                deviceDetail.setManufacturer(manufacturer);
                deviceDetail.setDeviceName(deviceName);
                deviceDetail.setDeviceModel(deviceModel);
                deviceDetail.setDeviceCode(deviceCode);
                deviceDetail.setSim(sim);
                if (bindingCount.equals("多人设备")) {
                    bindingCount = "{\"1\":\"0\",\"2\":\"0\"}";
                } else {
                    bindingCount = "{\"1\":\"0\"}";
                }
                deviceDetail.setBindingCount(bindingCount);
                deviceDetail.setDeviceType(Integer.parseInt(deviceType));
                correctLs.add(deviceDetail);
            }
            deviceDetailDao.save(correctLs);
            //包装导入结果(导入成功数量、错误对象集合)
            Map<String, Object> map = new HashMap<>();
            map.put("successNum", correctLs.size());
            map.put("failedNum", rows-1 - correctLs.size() );
            map.put("errorData", JSON.toJSONString(errorMsgMap, SerializerFeature.WriteMapNullValue));
            System.out.println(map);
            return write(200,JSON.toJSONString(map,SerializerFeature.WriteMapNullValue));
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "操作失败!");
        }
    }
    //设备移至导入svr_base
    @GetMapping("test")
    public String test(){

+ 14 - 1
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/endpoint/OnenetController.java

@ -111,7 +111,7 @@ public class OnenetController extends BaseController{
    }
    @ApiOperation("触发器消息通知接收--废弃")
    @ApiOperation("添加onenet设备")
    @RequestMapping(value = "addDevice",method = {RequestMethod.GET})
    public String addDevice() {
        try {
@ -123,6 +123,19 @@ public class OnenetController extends BaseController{
        }
    }
    @ApiOperation("同步设备信息")
    @RequestMapping(value = "sysDevice",method = {RequestMethod.POST})
    public String sysDevice(Integer page) {
        try {
            onenetService.sysDevice(page);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"addDevice failure");
        }
    }
    @ApiOperation("触发器消息通知接收--废弃")
    @RequestMapping(value = "triggerMessage",method = {RequestMethod.POST,RequestMethod.GET})
    public String triggerMessage(@RequestBody String body) {

+ 32 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/HvDeviceService.java

@ -234,5 +234,37 @@ public class HvDeviceService {
        }
    }
    public static void main(String[] args) {
//        String value = "01018B00000000000061444C7F0001921900FFBC00000070000000003839383630343334313832313830313337323531383637303730303336313331313231000000000034363030343534343733303732353100000000002235343030302E313030302E33352E30332E31332E30380000000000001300600001006100010062000000000001000079";
        String value = "02018B000000000000614443850001921800FFBA00000070000000013839383630343334313832313830313337323531383637303730303336313331313231000000000034363030343534343733303732353100000000002235343030302E313030302E33352E30332E31332E30380000000000001300600001006100010064000000020001008700";
        String byMessageId = value.substring(0,2);//业务类型
        String byFixedSign = value.substring(2,4);
        String byDevType = value.substring(4,6);//设备类型
        String byMax6 = value.substring(6,18);//max地址
        String byTime = value.substring(18,26);//时间 秒
        String byDevTypeEx =value.substring(26,28);
        String wPCI = value.substring(28,32);//16
        String bySnr = value.substring(32,34);
        String byEcl = value.substring(34,36);
        String byRsrp = value.substring(36,40);//16
        String dwUpHeaderLen = value.substring(40,48);//32 上报头长度
        String dwPackageNo = value.substring(48,56);//32 报警时 从1累加
        String byQCCID20 = value.substring(56,96);
        String byIMEI20 = value.substring(96,136);
        String byIMSI20 = value.substring(136,176);
        String byNBModuleVersion24 = value.substring(176,224);
        System.out.println(byTime);
        System.out.println(dwPackageNo);
        System.out.println(byQCCID20);
        System.out.println(byIMEI20);
        System.out.println(byIMSI20);
        System.out.println(byNBModuleVersion24);
        System.out.println(value.substring(240));
        System.out.println(Integer.parseInt("0087",16));
    }
}

+ 227 - 19
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/OnenetService.java

@ -13,6 +13,7 @@ import com.yihu.jw.care.util.SecurityOrderUtil;
import com.yihu.jw.entity.care.device.DeviceHealthIndex;
import com.yihu.jw.entity.care.device.OnenetDevice;
import com.yihu.jw.entity.care.device.OnenetReceiveRecord;
import com.yihu.jw.util.common.StringUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.slf4j.Logger;
@ -22,6 +23,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.*;
/**
@ -97,10 +99,19 @@ public class OnenetService {
            Integer type = msg.getInteger("type");
            String value = msg.getString("value");
            if("1".equals(onenetDevice.getDeviceType())){
                wlyDateDel(categoryCode,msg);
                if ("14".equals(categoryCode)){//燃气
                    wlyDateDelGas(categoryCode,msg);
                }
                if ("15".equals(categoryCode)){//烟雾设备
                    wlyDateDelSmoke(msg);
                }
            }else if("2".equals(onenetDevice.getDeviceType())){
                //海康设备
                if("14".equals(onenetDevice.getCategoryCode())){
                    hkDeviceQi(onenetDevice,msg);
                }else if("15".equals(onenetDevice.getCategoryCode())){
                    hkDeviceYan(onenetDevice,msg);
                }
            }
@ -152,6 +163,155 @@ public class OnenetService {
        }
    }
    /**
     * 海康设备解析-烟感
     */
    public void hkDeviceYan(OnenetDevice onenetDevice,JSONObject jsonObject){
        String value = jsonObject.getString("value");
        String byMessageId = value.substring(0,2);
//        String byDevType = value.substring(4,6);
        if("01".equals(byMessageId)){
            //信息上报
            String valueTmp = value.substring(236);
            //0060 0001 0061 0001 0062 0000 0000 0001 0000 79
            String wChanRscType = valueTmp.substring(0,4);
            String num = valueTmp.substring(4,8);
            String wEventType = valueTmp.substring(16,20);
            String wParamType = valueTmp.substring(28,32);
            String wParamValue = valueTmp.substring(32,36);
            if("0062".equals(wEventType)&&"0017".equals(wParamType)){
                String byTime = value.substring(18,26);//时间 秒
                String time = DateUtil.dateToStrLong(DateUtil.secondTransfor(Integer.valueOf(byTime,16)));
                //烟雾浓度
                String monitorValue = Integer.valueOf(wParamValue,16)+"";
                String resourceSerial = onenetDevice.getSn();
                addDeviceIndex(resourceSerial,monitorValue,time,"2","%");
                dataPushLogUtil.savePushLog(resourceSerial,jsonObject.toJSONString(jsonObject,SerializerFeature.WriteMapNullValue),"可燃气体探测器监测信息接收");
            }
            return;
        }
        if("02".equals(byMessageId)){
            //报警
            String byTime = value.substring(18,26);//时间 秒
            String time = DateUtil.dateToStrLong(DateUtil.secondTransfor(Integer.parseInt(byTime)));
            String valueTmp = value.substring(236);
            //0060 0001 0061 0001 0064 0000 0002 0001 0087 00
            String wChanRscType = valueTmp.substring(0,4);
            String num = valueTmp.substring(4,8);
            String wEventType = valueTmp.substring(16,20);
            String wEventValue = valueTmp.substring(24,28);
            String wParamType = valueTmp.substring(28,32);
            String wParamValue = valueTmp.substring(32,36);
            if("0064".equals(wEventType)&&"0002".equals(wEventValue)){
                //报警
                if("0017".equals(wParamType)){
                    //烟雾浓度
                    String monitorValue = Integer.valueOf(wParamValue,16)+"";
                    String resourceSerial = onenetDevice.getSn();
                    String sql = "select count(*) from base_device_health_index where device_sn = '"+resourceSerial+"'" +
                            " and value>0 and create_time>='"+DateUtil.getNextMinute(-60)+"' ";
                    Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
                    if(count==0){
                        logger.info("烟雾浓度大于0触发报警,deviceSn:{}",resourceSerial);
                        //1小时内不重复发起
                        JSONObject tmp = new JSONObject();
                        tmp.put("smoke",monitorValue);
                        orderUtil.createSecurityOrder(resourceSerial,null,new JSONObject(),null,7,"10","preventFire",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
                        dataPushLogUtil.savePushLog(resourceSerial,jsonObject.toJSONString(jsonObject,SerializerFeature.WriteMapNullValue),"烟感探测器报警信息接收");
                    }
                    addDeviceIndex(resourceSerial,monitorValue,time,"2","%");
                }
            }
        }
        //其他信息暂时不处理
        // 03消音 04自检 05故障 06信号查询 07注册 08注销 ...
    }
    /**
     * 保存记录
     * @param resourceSerial
     * @param monitorValue
     * @param time
     * @param deviceType
     * @param unit
     */
    public void addDeviceIndex(String resourceSerial,String monitorValue,String time,String deviceType,String unit){
        DeviceHealthIndex index = new DeviceHealthIndex();
        index.setDeviceSn(resourceSerial);
        index.setUnit(unit);
        index.setValue(monitorValue);
        index.setRecordTime(time);
        index.setDeviceType(deviceType);
        deviceHealthIndexDao.save(index);
    }
    /**
     * 海康设备解析-气感
     */
    public void hkDeviceQi(OnenetDevice onenetDevice,JSONObject jsonObject){
        String value = jsonObject.getString("value");
        String byMessageId = value.substring(0,2);
//        String byDevType = value.substring(4,6);
        if("01".equals(byMessageId)){
            //信息上报
            String valueTmp = value.substring(236);
            //0060 0001 0061 0001 0062 0000 0000 0001 0000 79
            String wChanRscType = valueTmp.substring(0,4);
            String num = valueTmp.substring(4,8);
            String wEventType = valueTmp.substring(16,20);
            String wParamType = valueTmp.substring(28,32);
            String wParamValue = valueTmp.substring(32,36);
            if("0062".equals(wEventType)&&"0001".equals(wParamType)){
                String byTime = value.substring(18,26);//时间 秒
                String time = DateUtil.dateToStrLong(DateUtil.secondTransfor(Integer.valueOf(byTime,16)));
                //气感浓度
                String monitorValue = StringUtil.division(Integer.valueOf(wParamValue,16),10);
                String resourceSerial = onenetDevice.getSn();
                addDeviceIndex(resourceSerial,monitorValue,time,"1","%LEL");
                dataPushLogUtil.savePushLog(resourceSerial,jsonObject.toJSONString(jsonObject,SerializerFeature.WriteMapNullValue),"可燃气体探测器监测信息接收");
            }
            return;
        }
        if("02".equals(byMessageId)){
            //报警
            String byTime = value.substring(18,26);//时间 秒
            String time = DateUtil.dateToStrLong(DateUtil.secondTransfor(Integer.parseInt(byTime)));
            String valueTmp = value.substring(236);
            //0060 0001 0061 0001 0064 0000 0002 0001 0087 00
            String wChanRscType = valueTmp.substring(0,4);
            String num = valueTmp.substring(4,8);
            String wEventType = valueTmp.substring(16,20);
            String wEventValue = valueTmp.substring(24,28);
            String wParamType = valueTmp.substring(28,32);
            String wParamValue = valueTmp.substring(32,36);
            if("0064".equals(wEventType)&&"0002".equals(wEventValue)){
                //气感报警
                if("0001".equals(wParamType)){
                    //气感浓度
                    String monitorValue = StringUtil.division(Integer.valueOf(wParamValue,16),10);
                    String resourceSerial = onenetDevice.getSn();
                    String sql = "select count(*) from base_device_health_index where device_sn = '"+resourceSerial+"'" +
                            " and value>0 and create_time>='"+DateUtil.getNextMinute(-60)+"' ";
                    Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
                    if(count==0){
                        logger.info("气体浓度大于0触发报警,deviceSn:{}",resourceSerial);
                        //1小时内不重复发起
                        JSONObject tmp = new JSONObject();
                        tmp.put("gas",monitorValue);
                        orderUtil.createSecurityOrder(resourceSerial,null,new JSONObject(),null,6,"11","preventGasLeakage",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
                        dataPushLogUtil.savePushLog(resourceSerial,jsonObject.toJSONString(jsonObject,SerializerFeature.WriteMapNullValue),"可燃气体探测器报警信息接收");
                    }
                    addDeviceIndex(resourceSerial,monitorValue,time,"1","%LEL");
                }
            }
        }
        //其他信息暂时不处理
        // 03消音 04自检 05故障 06信号查询 07注册 08注销 ...
    }
    /**
     * 同步设备
     */
@ -164,7 +324,7 @@ public class OnenetService {
            List<OnenetDevice> onenetDeviceList = new ArrayList<>();
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("devices");
            for (int i=0;i<jsonArray.size();i++){
                JSONObject json = jsonArray.getJSONObject(0);
                JSONObject json = jsonArray.getJSONObject(i);
                String sn = json.getString("rg_id");
                String id = json.getString("id");
                OnenetDevice device = onenetDeviceDao.findBySn(sn);
@ -207,36 +367,84 @@ public class OnenetService {
    }
    /**
     * 未来鹰设备数据处理
     * @param categoryCode
     * 未来鹰设备烟雾数据处理
     * @param msg
     */
    public void wlyDateDel(String categoryCode,JSONObject msg){
    public void wlyDateDelSmoke(JSONObject msg){
        String dsId = msg.getString("ds_id");
        String msgId = dsId.split("_")[2];
        String value = msg.getString("value");
        String deviceSn = msg.getString("imei");
        if ("14".equals(categoryCode)){//燃气设备
        }else if ("15".equals(categoryCode)){//烟雾设备
            if ("5504".equals(msgId)){//烟雾浓度消息 大于0 触发报警
                Integer gasValue = Integer.parseInt(value);
                if (gasValue>0){
        if ("5504".equals(msgId)){//烟雾浓度消息 大于0 触发报警
            Integer gasValue = Integer.parseInt(value);
            if (gasValue>0){
                String sql = "select count(*) from base_device_health_index where device_sn = '"+deviceSn+"'" +
                        " and value>0 and create_time>='"+DateUtil.getNextMinute(-60)+"' ";
                Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
                if(count==0){
                    JSONObject tmp = new JSONObject();
                    tmp.put("smoke",value);
                    orderUtil.createSecurityOrder(deviceSn,null,new JSONObject(),null,7,"10","preventFire",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
                }
                DeviceHealthIndex index = new DeviceHealthIndex();
                index.setDeviceSn(deviceSn);
            }
            DeviceHealthIndex index = new DeviceHealthIndex();
            index.setDeviceSn(deviceSn);
            index.setUnit("%");
            index.setDeviceType("2");
            index.setValue(value);
            index.setRecordTime(DateUtil.getStringDate());
            deviceHealthIndexDao.save(index);
        }
        if ("5503".equals(msgId)){//各消息类型
            if ("1".equals(value)) {//设备烟雾报警
                String sql = "select count(*) from base_device_health_index where device_sn = '"+deviceSn+"'" +
                        " and value>0 and create_time>='"+DateUtil.getNextMinute(-60)+"' ";
                Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
                if(count==0){
                    JSONObject tmp = new JSONObject();
                    tmp.put("smoke","100");
                    orderUtil.createSecurityOrder(deviceSn,null,new JSONObject(),null,7,"10","preventFire",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
                }
            }
        }
    }
    public void wlyDateDelGas(String categoryCode,JSONObject msg){
        String deviceSn = msg.getString("imei");
        Integer type = msg.getInteger("type");
        String value = msg.getString("value");
        String order = value.substring(10,14);
        if("1401".equals(order)){
            //自定义命令数据更新(心跳/设备状态上报)
            String gas_Level = value.substring(22,24);
            Integer gas = Integer.parseInt(gas_Level, 16);
            if(gas>0){
                //气体浓度大于0触发报警
                String sql = "select count(*) from base_device_health_index where device_sn = '"+deviceSn+"'" +
                        " and value>0 and create_time>='"+DateUtil.getNextMinute(-60)+"' ";
                Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
                if(count==0){
                    logger.info("气体浓度大于0触发报警,deviceSn:{}",deviceSn);
                    //1小时内不重复发起
                    JSONObject tmp = new JSONObject();
                    tmp.put("gas",gas);
                    orderUtil.createSecurityOrder(deviceSn,null,new JSONObject(),null,6,"11","preventGasLeakage",JSON.toJSONString(tmp, SerializerFeature.WriteMapNullValue));
                }
            }
            DeviceHealthIndex index = new DeviceHealthIndex();
            index.setDeviceSn(deviceSn);
            if("14".equals(categoryCode)){
                index.setUnit("%LEL");
                index.setDeviceType("1");
            }else if("15".equals(categoryCode)){
                index.setUnit("%");
                index.setDeviceType("2");
                index.setValue(value);
                index.setRecordTime(DateUtil.getStringDate());
                deviceHealthIndexDao.save(index);
            }
            if ("5503".equals(msgId)){//各消息类型
            }
            index.setValue(gas+"");
            index.setRecordTime(DateUtil.getStringDate());
            deviceHealthIndexDao.save(index);
        }
    }
}

+ 3 - 1
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/job/device/PatientSosContactsJob.java

@ -42,7 +42,7 @@ public class PatientSosContactsJob implements Job {
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("PATIENT_SOS_CONTACTS_JOB start");
        String sql = " select pd.device_sn,pd.category_code,wd.sim,sc.* from  wlyy_patient_device pd inner join wlyy_devices wd " +
        String sql = " select pd.device_sn,pd.category_code,wd.iccid as sim,sc.* from  wlyy_patient_device pd inner join wlyy_devices wd " +
                " on pd.device_sn = wd.device_code and pd.del=0 " +
                "INNER JOIN base_patient_sos_contacts sc on sc.patient = pd.user and sc.del=1 " +
                "where  sc.success_flag=0 and pd.category_code in('7','4','16')  group by wd.device_code ";
@ -76,6 +76,7 @@ public class PatientSosContactsJob implements Job {
                        }else {
                            sosContactsDO.setSuccessFlag(-1);
                            sosContactsDO.setUpdateInfo(sosContactsDO.getUpdateInfo()+",{sim:"+sim+":"+-1+"}");
                            sosContactsDO.setErrorInfo(sosContactsDO.getUpdateInfo()+",{sim:"+sim+":"+response.getString("message")+"}");
                        }
                    }
                    //设备修改
@ -91,6 +92,7 @@ public class PatientSosContactsJob implements Job {
                        }else {
                            sosContactsDO.setSuccessFlag(-1);
                            sosContactsDO.setUpdateInfo(sosContactsDO.getUpdateInfo()+",{deviceSn:"+device_sn+":"+-1+"}");
                            sosContactsDO.setErrorInfo(sosContactsDO.getUpdateInfo()+",{sim:"+sim+":"+response2.getString("message")+"}");
                        }
                    }else if ("16".equals(category_code)){
                        sql =" select sos_phone from base_patient_sos_contacts where patient='"+patient+"' and del=1 order by phone_seqid asc ";

+ 1 - 0
svr/svr-cloud-job/src/main/java/com/yihu/jw/care/service/device/NetworkCardService.java

@ -134,6 +134,7 @@ public class NetworkCardService {
        }
        JSONObject result = new  JSONObject();
        result.put("status",-1);
        result.put("message",responseBody.getString("message"));
        return result;
    }