Browse Source

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

Conflicts:
	common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationTemplateDetailDO.java
yeshijie 4 years ago
parent
commit
7b33ee1ddb
21 changed files with 5239 additions and 1 deletions
  1. 111 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/Device.java
  2. 317 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java
  3. 241 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientHealthIndex.java
  4. 297 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/PatientDevice.java
  5. 6 1
      svr/svr-cloud-care/pom.xml
  6. 21 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDao.java
  7. 16 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DeviceDetailDao.java
  8. 70 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/DevicePatientHealthIndexDao.java
  9. 51 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/dao/device/PatientDeviceDao.java
  10. 793 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/BaseController.java
  11. 8 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/WeixinBaseController.java
  12. 53 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DeviceController.java
  13. 128 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/DoctorDeviceController.java
  14. 214 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/device/PatientDeviceController.java
  15. 185 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/DeviceDetailService.java
  16. 38 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/DeviceService.java
  17. 656 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientDeviceService.java
  18. 1599 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/service/device/PatientHealthIndexService.java
  19. 211 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/CommonUtil.java
  20. 143 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ConcealUtil.java
  21. 81 0
      svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MyJdbcTemplate.java

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

@ -0,0 +1,111 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
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 java.util.Date;
/**
 * 设备列表
 */
@Entity
@Table(name = "dm_device")
@SequenceGenerator(name="id_generated", sequenceName="dm_device")
public class Device extends IdEntity {
	private String categoryCode;
	private String photo;
	private String brands;
	private String model;
	private String isMultiUser;
	private String multiUser;
	private String name;
	private Date czrq;
	private String del;
	@Column(name="category_code")
	public String getCategoryCode() {
		return categoryCode;
	}
	public void setCategoryCode(String categoryCode) {
		this.categoryCode = categoryCode;
	}
	@Column(name="photo")
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	@Column(name="brands")
	public String getBrands() {
		return brands;
	}
	public void setBrands(String brands) {
		this.brands = brands;
	}
	@Column(name="model")
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	@Column(name="is_multi_user")
	public String getIsMultiUser() {
		return isMultiUser;
	}
	public void setIsMultiUser(String isMultiUser) {
		this.isMultiUser = isMultiUser;
	}
	@Column(name="multi_user")
	public String getMultiUser() {
		return multiUser;
	}
	public void setMultiUser(String multiUser) {
		this.multiUser = multiUser;
	}
	@Column(name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	@Column(name="czrq")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	@Column(name="del")
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
}

+ 317 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceDetail.java

@ -0,0 +1,317 @@
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 java.util.Date;
/**
 * Created by ysj on 2018/01/10.
 * 设备表
 */
@Entity
@Table(name = "wlyy_devices")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_devices")
public class DeviceDetail extends IdEntity {
    private String deviceName;//设备名称
    private String deviceModel;//型号
    private String deviceCode;//设备唯一标识
    private String manufacturer;//厂家名称
    private String applyDate;//申请日期
    private String orgName;//(居民)机构名称
    private String linkman;//联系人(居民)
    private String tel;//联系人(居民)电话
    private String serverIp;//服务IP地址
    private String manufacturerCode;//厂商代码threeNod:三诺 urion:优瑞恩 bioland:爱奥乐 comvee:康为
    private String address;//厂家地址
    private String representative;//法人代表
    private String applicantName;//申请注册人(发放人/医生)
    private String applicantIdentity;//申请人(发放人/医生)身份证号
    private String applicantTel;//申请人(发放人/医生)手机
    private String applicantMail;//申请人(发放人/医生)邮箱
    //1.4.8版本新增字段
    private String sim;//SIM卡
    private String manufacturerId;//厂商表的业务关联code
    private Integer isGrant;//是否发放(0否1是)
    private String grantAdminTeam;//发放的患者所在团队
    private String grantOrgCode;//发放所在机构
    private Integer isBinding;//是否绑定(0否 1 绑定单端口 2 绑定双端口)
    private String bindingCount;//绑定次数({"1":"0", "2":"0"})
    private Date grantTime;//发放时间
    //1.5.0版本新增字段
    private String grantDoctor;//发放医生code
    private String grantDoctorName;//发放医生姓名
    /** default constructor */
    public DeviceDetail() {
    }
    /** full constructor */
    public DeviceDetail(String deviceName, String deviceModel, String deviceCode, String manufacturer, String applyDate
            , String orgName, String linkman, String tel, String serverIp, String manufacturerCode, String address
            , String representative, String applicantName, String applicantIdentity, String applicantTel, String applicantMail) {
        this.deviceName = deviceName;
        this.deviceModel = deviceModel;
        this.deviceCode = deviceCode;
        this.manufacturer = manufacturer;
        this.applyDate = applyDate;
        this.orgName = orgName;
        this.linkman = linkman;
        this.tel = tel;
        this.serverIp = serverIp;
        this.manufacturerCode = manufacturerCode;
        this.address = address;
        this.representative = representative;
        this.applicantName = applicantName;
        this.applicantIdentity = applicantIdentity;
        this.applicantTel = applicantTel;
        this.applicantMail = applicantMail;
    }
    @Column(name = "device_name")
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    @Column(name = "device_model")
    public String getDeviceModel() {
        return deviceModel;
    }
    public void setDeviceModel(String deviceModel) {
        this.deviceModel = deviceModel;
    }
    @Column(name = "device_code")
    public String getDeviceCode() {
        return deviceCode;
    }
    public void setDeviceCode(String deviceCode) {
        this.deviceCode = deviceCode;
    }
    @Column(name = "manufacturer")
    public String getManufacturer() {
        return manufacturer;
    }
    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }
    @Column(name = "apply_date")
    public String getApplyDate() {
        return applyDate;
    }
    public void setApplyDate(String applyDate) {
        this.applyDate = applyDate;
    }
    @Column(name = "org_name")
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "linkman")
    public String getLinkman() {
        return linkman;
    }
    public void setLinkman(String linkman) {
        this.linkman = linkman;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "tel")
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    @Column(name = "server_ip")
    public String getServerIp() {
        return serverIp;
    }
    public void setServerIp(String serverIp) {
        this.serverIp = serverIp;
    }
    @Column(name = "manufacturerCode")
    public String getManufacturerCode() {
        return manufacturerCode;
    }
    public void setManufacturerCode(String manufacturerCode) {
        this.manufacturerCode = manufacturerCode;
    }
    @Column(name = "address")
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "representative")
    public String getRepresentative() {
        return representative;
    }
    public void setRepresentative(String representative) {
        this.representative = representative;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "applicant_name")
    public String getApplicantName() {
        return applicantName;
    }
    public void setApplicantName(String applicantName) {
        this.applicantName = applicantName;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "applicant_identity")
    public String getApplicantIdentity() {
        return applicantIdentity;
    }
    public void setApplicantIdentity(String applicantIdentity) {
        this.applicantIdentity = applicantIdentity;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "applicant_tel")
    public String getApplicantTel() {
        return applicantTel;
    }
    public void setApplicantTel(String applicantTel) {
        this.applicantTel = applicantTel;
    }
    @Column(name = "applicant_mail")
    public String getApplicantMail() {
        return applicantMail;
    }
    public void setApplicantMail(String applicantMail) {
        this.applicantMail = applicantMail;
    }
    @Column(name = "manufacturer_id")
    public String getManufacturerId() {
        return manufacturerId;
    }
    public void setManufacturerId(String manufacturerId) {
        this.manufacturerId = manufacturerId;
    }
    @Column(name = "sim")
    public String getSim() {
        return sim;
    }
    public void setSim(String sim) {
        this.sim = sim;
    }
    @Column(name = "is_grant")
    public Integer getIsGrant() {
        return isGrant;
    }
    public void setIsGrant(Integer grant) {
        isGrant = grant;
    }
    @Column(name = "grant_admin_team")
    public String getGrantAdminTeam() {
        return grantAdminTeam;
    }
    public void setGrantAdminTeam(String grantAdminTeam) {
        this.grantAdminTeam = grantAdminTeam;
    }
    @Column(name = "grant_org_code")
    public String getGrantOrgCode() {
        return grantOrgCode;
    }
    public void setGrantOrgCode(String grantOrgCode) {
        this.grantOrgCode = grantOrgCode;
    }
    @Column(name = "is_binding")
    public Integer getIsBinding() {
        return isBinding;
    }
    public void setIsBinding(Integer isBinding) {
        this.isBinding = isBinding;
    }
    @Column(name = "binding_count")
    public String getBindingCount() {
        return bindingCount;
    }
    public void setBindingCount(String bindingCount) {
        this.bindingCount = bindingCount;
    }
    @Column(name = "grant_time")
    public Date getGrantTime() {
        return grantTime;
    }
    public void setGrantTime(Date grantTime) {
        this.grantTime = grantTime;
    }
    @Column(name = "grant_doctor")
    public String getGrantDoctor() {
        return grantDoctor;
    }
    public void setGrantDoctor(String grantDoctor) {
        this.grantDoctor = grantDoctor;
    }
//    @Convert(converter = StringFStringEncryptConverter.class)
    @Column(name = "grant_doctor_name")
    public String getGrantDoctorName() {
        return grantDoctorName;
    }
    public void setGrantDoctorName(String grantDoctorName) {
        this.grantDoctorName = grantDoctorName;
    }
}

+ 241 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DevicePatientHealthIndex.java

@ -0,0 +1,241 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.*;
import java.util.Date;
/**
 * 健康指标
 * @author George
 *
 */
@Entity
@Table(name = "wlyy_patient_health_index")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_patient_health_index")
public class DevicePatientHealthIndex extends IdEntity {
	// 患者标志
	private String user;
	// 干预标志
	private String intervene;
	// 血糖/收缩压/体重/腰围/早餐前空腹
	private String value1;
	// 舒张压/早餐后空腹/身高
	private String value2;
	// 午餐空腹/BMI
	private String value3;
	// 午餐后/偏胖-1/正常0/偏瘦1
	private String value4;
	// 晚餐空腹
	private String value5;
	// 晚餐后
	private String value6;
	// 睡前
	private String value7;
	// 健康指标类型(1血糖,2血压,3体重/身高/BMI,4腰围)
	private Integer type;
	// 记录时间
	private Date recordDate;
	// 排序日期
	private Date sortDate;
	// 添加时间
	private Date czrq;
	// 是否作废,1正常,0作废
	private String del;
	//身份证号码
	private String idcard;
	//设备编号
	private String deviceSn;
	private Integer status;//状态:0为标准,1为异常
	private String name;//居民姓名
	private String hospital;//医院
	private String hospitalName;//医院名称
	@Transient
	private Integer flag;//标识智能设备或者健康小屋
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getIntervene() {
		return intervene;
	}
	public void setIntervene(String intervene) {
		this.intervene = intervene;
	}
	public String getValue1() {
		return value1;
	}
	public void setValue1(String value1) {
		this.value1 = value1;
	}
	public String getValue2() {
		return value2;
	}
	public void setValue2(String value2) {
		this.value2 = value2;
	}
	public String getValue3() {
		return value3;
	}
	public void setValue3(String value3) {
		this.value3 = value3;
	}
	public String getValue4() {
		return value4;
	}
	public void setValue4(String value4) {
		this.value4 = value4;
	}
	public String getValue5() {
		return value5;
	}
	public void setValue5(String value5) {
		this.value5 = value5;
	}
	public String getValue6() {
		return value6;
	}
	public void setValue6(String value6) {
		this.value6 = value6;
	}
	public String getValue7() {
		return value7;
	}
	public void setValue7(String value7) {
		this.value7 = value7;
	}
	@Column(name = "record_date")
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getRecordDate() {
		return recordDate;
	}
	public void setRecordDate(Date recordDate) {
		this.recordDate = recordDate;
	}
	public Integer getType() {
		return type;
	}
	public void setType(Integer type) {
		this.type = type;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	@Column(name = "sort_date")
	public Date getSortDate() {
		return sortDate;
	}
	public void setSortDate(Date sortDate) {
		this.sortDate = sortDate;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	@Column(name = "Idcard")
//	@Convert(converter = StringFStringEncryptConverter.class)
	public String getIdcard() {
		return idcard;
	}
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	@Column(name = "device_sn")
	public String getDeviceSn() {
		return deviceSn;
	}
	public void setDeviceSn(String deviceSn) {
		this.deviceSn = deviceSn;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	@Transient
	public Integer getFlag() {
		return flag;
	}
	public void setFlag(Integer flag) {
		this.flag = flag;
	}
//	@Convert(converter = StringFStringEncryptConverter.class)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getHospital() {
		return hospital;
	}
	public void setHospital(String hospital) {
		this.hospital = hospital;
	}
	@Column(name = "hospital_name")
	public String getHospitalName() {
		return hospitalName;
	}
	public void setHospitalName(String hospitalName) {
		this.hospitalName = hospitalName;
	}
}

+ 297 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/PatientDevice.java

@ -0,0 +1,297 @@
package com.yihu.jw.entity.care.device;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "wlyy_patient_device")
@SequenceGenerator(name="id_generated", sequenceName="wlyy_patient_device")
public class PatientDevice extends IdEntity {
    // 设备ID
    private Long deviceId;
    // 设备标识
    private String deviceSn;
    //sim卡号
    private String sim;
    // 设备名称
    private String deviceName;
    // 用户code
    private String user;
    // 设备类型标识 1血糖仪,2.血压计,3药盒,4智能手表
    private String categoryCode;
    // 用户类型标准 -1代表单用户
    private String userType;
    // 用户身份证
    private String userIdcard;
    // 操作医生代码
    private String doctor;
    //操作医生姓名
    private String doctorName;
    //代绑人代码(家人)
    private String agent;
    //代绑人姓名
    private String agentName;
    // 操作时间
    private Date czrq;
    //解绑人
    private String delUser;
    //1-解绑,0-绑定
    private Integer del;
    //设备活动类型
    private String deviceActivityType;
    //上传的协议图片地址
    private String agreementPhoto;
    //居民签约所在社区
    private String hospital;
    //居民签约所在社区名字
    private String hospitalName;
    //登记医生名字
    private String checkDoctorName;
    
    //0未申请 1审核中 2被拒绝
    private Integer applyStatus;
    
    //申请原因
    private String applyReason;
    //医生拒绝原因
    private String refuseReason;
  //========================非表字段======================
    //患者居住地址
    private String address;
    @Column(name = "device_id")
    public Long getDeviceId() {
        return deviceId;
    }
    public void setDeviceId(Long deviceId) {
        this.deviceId = deviceId;
    }
    @Column(name = "device_sn")
    public String getDeviceSn() {
        return deviceSn;
    }
    public void setDeviceSn(String deviceSn) {
        this.deviceSn = deviceSn;
    }
    @Column(name = "sim")
    public String getSim() {
        return sim;
    }
    public void setSim(String sim) {
        this.sim = sim;
    }
    @Column(name = "device_name")
    public String getDeviceName() {
        return deviceName;
    }
    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }
    @Column(name = "user")
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    @Column(name = "category_code")
    public String getCategoryCode() {
        return categoryCode;
    }
    public void setCategoryCode(String categoryCode) {
        this.categoryCode = categoryCode;
    }
    @Column(name = "user_type")
    public String getUserType() {
        return userType;
    }
    public void setUserType(String userType) {
        this.userType = userType;
    }
    @Column(name = "user_idcard")
    public String getUserIdcard() {
        return userIdcard;
    }
    public void setUserIdcard(String userIdcard) {
        this.userIdcard = userIdcard;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    @Column(name = "czrq")
    public Date getCzrq() {
        return czrq;
    }
    public void setCzrq(Date czrq) {
        this.czrq = czrq;
    }
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "agent")
    public String getAgent() {
        return agent;
    }
    public void setAgent(String agent) {
        this.agent = agent;
    }
    @Column(name = "agent_name")
    public String getAgentName() {
        return agentName;
    }
    public void setAgentName(String agentName) {
        this.agentName = agentName;
    }
    @Column(name = "del_user")
    public String getDelUser() {
        return delUser;
    }
    public void setDelUser(String delUser) {
        this.delUser = delUser;
    }
    @Column(name = "del")
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    @Column(name = "device_activity_type")
    public String getDeviceActivityType() {
        return deviceActivityType;
    }
    public void setDeviceActivityType(String deviceActivityType) {
        this.deviceActivityType = deviceActivityType;
    }
    @Column(name = "agreement_photo")
    public String getAgreementPhoto() {
        return agreementPhoto;
    }
    public void setAgreementPhoto(String agreementPhoto) {
        this.agreementPhoto = agreementPhoto;
    }
    @Column(name = "hospital")
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Column(name = "hospital_name")
    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    @Column(name = "check_doctor_name")
    public String getCheckDoctorName() {
        return checkDoctorName;
    }
    public void setCheckDoctorName(String checkDoctorName) {
        this.checkDoctorName = checkDoctorName;
    }
    @Transient
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public PatientDevice(String address, Date czrq, String userIdcard, String deviceSn, Long deviceId) {
        this.address = address;
        this.czrq = czrq;
        this.userIdcard = userIdcard;
        this.deviceSn = deviceSn;
        this.deviceId = deviceId;
    }
    public PatientDevice() {
    }
    
    public Integer getApplyStatus() {
        return applyStatus;
    }
    
    public void setApplyStatus(Integer applyStatus) {
        this.applyStatus = applyStatus;
    }
    
    public String getApplyReason() {
        return applyReason;
    }
    
    public void setApplyReason(String applyReason) {
        this.applyReason = applyReason;
    }
    public String getRefuseReason() {
        return refuseReason;
    }
    public void setRefuseReason(String refuseReason) {
        this.refuseReason = refuseReason;
    }
}

+ 6 - 1
svr/svr-cloud-care/pom.xml

@ -109,7 +109,12 @@
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-web</artifactId>
        </dependency>
        <!-- SPRINGSIDE -->
        <dependency>
            <groupId>org.springside</groupId>
            <artifactId>springside-core</artifactId>
            <version>4.2.3-GA</version>
        </dependency>
        <!-- 文件服务器 -->
        <dependency>

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

@ -0,0 +1,21 @@
/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.jw.care.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();
}

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

@ -0,0 +1,16 @@
package com.yihu.jw.care.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;
/**
 * @author yeshijie on 2018/1/10.
 */
public interface DeviceDetailDao extends PagingAndSortingRepository<DeviceDetail, Long>, JpaSpecificationExecutor<DeviceDetail> {
    @Query(value = "select a.* from device.wlyy_devices a where a.device_code=?1 limit 0,1",nativeQuery = true)
    DeviceDetail findBySn(String sn);
}

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

@ -0,0 +1,70 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
import java.util.List;
public interface DevicePatientHealthIndexDao
		extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
	List<DevicePatientHealthIndex> findByIdcardAndType(String idcard, Integer type);
	/**
	 * 按录入时间和患者标识查询健康记录
	 *
	 * @param patientCode
	 * @param date
	 * @return
	 */
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and type = ?2 and a.recordDate = ?3 and a.del = '1'")
	Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.recordDate between ?3 and ?4 and a.del = '1' group by recordDate order by recordDate asc")
	Iterable<DevicePatientHealthIndex> findByPatient(String user, int type, Date begin, Date end);
	@Query("select a from DevicePatientHealthIndex a where a.user = ?1 and a.type = ?2 and a.del = '1'")
	List<DevicePatientHealthIndex> findIndexByPatient(String patient, int type, Pageable pageRequest);
	@Query("SELECT a FROM DevicePatientHealthIndex a where a.user = ?1 and a.del = '1' order by a.recordDate desc ")
	List<DevicePatientHealthIndex> findRecentByPatient(String patient);
	@Query(value = "select a.* from wlyy_patient_health_index a where a.user=?1 and a.type=?2 and a.del='1' order by a.record_date desc limit 0,1",nativeQuery = true)
	DevicePatientHealthIndex findLastData(String patient, Integer type);
	/**
	 * 获取患者一天的具体某个类型的数据
	 */
	@Query("select a from DevicePatientHealthIndex a where a.type=?1 and a.user = ?2 and DATE_FORMAT(a.recordDate,'%Y-%m-%d') = ?3 and a.deviceSn = ?4 and a.del = '1' order by a.recordDate,a.id")
	List<DevicePatientHealthIndex> findByDateAndType(int type, String patient, String date, String devicesn);
	
	/**
	 * 获取患者单月的具体某个类型的数据
	 */
	@Query(value = "SELECT a.* FROM wlyy_patient_health_index a WHERE a.type=?1 AND a.USER=?2 AND DATE_FORMAT(a.record_date,'%Y-%m')=?3 AND a.device_sn=?4 AND a.del='1' ORDER BY a.record_date,a.id",nativeQuery = true)
	List<DevicePatientHealthIndex> findByDateMonthAndType(int type, String patient, String date, String devicesn);
	@Query(value = "select a.* from wlyy_patient_health_index a where a.user = ?1 and a.type = ?2 and a.record_date >= ?3 and a.record_date <= ?4 and a.del = '1' order by a.sort_date desc ,record_date desc limit ?5 ,?6",nativeQuery = true)
	List<DevicePatientHealthIndex> findIndexByPatientNative(String patient, int type, Date start, Date end, int currentSize, int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from wlyy_patient_health_index a where a.user = ?1 and a.record_date >= ?2 and a.record_date <= ?3 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?4 ,?5",nativeQuery = true)
	List<String> findDateList(String patient, Date start, Date end, int currentSize, int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from wlyy_patient_health_index a where a.user = ?1 and a.type=?2 and a.record_date >= ?3 and a.record_date <= ?4 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?5 ,?6",nativeQuery = true)
	List<String> findDateList(String patient, int type, Date start, Date end, int currentSize, int pageSize);
	
	@Query(value= " select * from wlyy_patient_health_index where type in (1,2) and record_date BETWEEN ?1 AND ?2  AND user in (select p.code from wlyy.wlyy_patient p INNER JOIN wlyy.wlyy_sign_family s on s.patient = p.code RIGHT JOIN wlyy.wlyy_sign_patient_label_info sp on sp.patient = p.code where  s.status > 0 AND s.admin_team_code = ?3 and (s.doctor = ?4 or s.doctor_health =?4) and sp.status = 1 and sp.label_type = 3 and (sp.label = 1 or sp.label = 2))",nativeQuery = true)
	List<DevicePatientHealthIndex> findByTeamcodeAndRecordDate(Date start, Date end, String teamcode, String doctorcode);
	@Query(value="select * from wlyy_patient_health_index where user = ?1 and type = ?2 ORDER BY record_date desc limit 0 ,5",nativeQuery = true)
	List<DevicePatientHealthIndex> findByPatientAndTypeByPage(String patientCode, int type);
	@Query("select count(a) from DevicePatientHealthIndex a where a.recordDate >= ?1 and a.recordDate <= ?2 and a.type in (1,2) and a.status = ?3 and a.del = '1' and user = ?4")
	int getCountByTimeAndStatus(Date start, Date end, int status, String patientCode);
}

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

@ -0,0 +1,51 @@
package com.yihu.jw.care.dao.device;
import com.yihu.jw.entity.care.device.PatientDevice;
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<PatientDevice, Long>, JpaSpecificationExecutor<PatientDevice> {
    @Query("select a from PatientDevice a where a.user = ?1 ")
    Iterable<PatientDevice> findByUser(String user);
    @Query("select a from PatientDevice a where a.user = ?1 ")
    List<PatientDevice> findByPatient(String user);
    @Query("select a from PatientDevice a where a.user = ?1 and a.del=0 and a.deviceName like '%药盒%'")
    List<PatientDevice> findByPatientAndDel(String user);
    @Query("select a from PatientDevice a where a.user = ?1 and a.deviceSn=?2 ")
    List<PatientDevice> findByPatientAndDeviceSn(String user, String deviceSn);
    List<PatientDevice> findByUser(String user, Pageable pageRequest);
    List<PatientDevice> findByUserAndDoctor(String user, String doctor, Pageable pageRequest);
    List<PatientDevice> findByDeviceSnAndCategoryCode(String deviceSn, String categoryCode);
    PatientDevice findByDeviceSnAndCategoryCodeAndUserType(String deviceSn, String categoryCode, String userType);
    PatientDevice findByDeviceIdAndDeviceSnAndUserType(Long deviceId, String deviceSn, String userType);
    PatientDevice findByDeviceSnAndUserType(String deviceSn, String userType);
    @Query("select pd from PatientDevice pd where pd.deviceSn = ?1 and pd.del=0")
    List<PatientDevice> findByDeviceSn(String deviceSn);
    //更换患者绑定的血糖仪
    @Modifying
    @Query("update PatientDevice 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);
    @Query("select a from PatientDevice a")
    List<PatientDevice> findAll();
}

+ 793 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/BaseController.java

@ -0,0 +1,793 @@
package com.yihu.jw.care.endpoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.iot.gateway.IdEntity;
import com.yihu.jw.util.date.DateUtil;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.ReflectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "返回的json里的status是200,成功"),
        @ApiResponse(code = 403, message = "返回的json里的status是403,该操作没有权限"),
        @ApiResponse(code = 997, message = "返回的json里的status是997,重新登陆"),
        @ApiResponse(code = 998, message = "返回的json里的status是998,登录超时,请重新登录"),
        @ApiResponse(code = 999, message = "返回的json里的status是999,帐号在别处登录,请重新登录")
})
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger("error_logger");
    @Autowired
    protected HttpServletRequest request;
    /**
     * 獲取髮送請求用戶的uid
     * @return
     */
    public String getUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("uid");
//            return "xh1D2017031502222";// wjw00000001000e6badcfa163e424589/wjw00000001000e6badcfa163e424525
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人的code
     * @return
     */
    public String getRepresentedUID() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取平台端
     * @return
     */
    public Integer getPlatform() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getInt("platform");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取被代理人code,若没有则返回当前登录者
     * @return
     */
    public String getRepUID(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            if(json.isNull("represented")){
                return json.getString("uid");
            }
            return json.getString("represented");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 獲取髮送請求用戶的uid
     *
     * @return
     */
    public String getLastUid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String id = json.getString("lastUid");
            if(StringUtils.isNoneBlank(id)){
                return id;
            }else{
               return json.getString("uid");
            }
        } catch (Exception e) {
            return null;
        }
    }
    public String getAppVersion() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("appVersion");
        } catch (Exception e) {
            return null;
        }
    }
    public String getOpenid() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("openid");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取用户ID
     *
     * @return
     */
    public long getId() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getLong("id");
        } catch (Exception e) {
            return 0;
        }
    }
    public String getIMEI() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("imei");
        } catch (Exception e) {
            return null;
        }
    }
    public String getToken() {
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getString("token");
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色code
     * @return
     */
    public String getCurrentRoleCode(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            String currentUserRole = json.getJSONObject("currentUserRole").getString("code");
            return currentUserRole;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色级别
     * @return
     */
    public String getCurrentRoleLevel(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").get("level")+"";
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取当前用户的角色是否是管理员
     * @return
     */
    public String getCurrentRoleIsManange(){
        try {
            String userAgent = request.getHeader("userAgent");
            if (StringUtils.isEmpty(userAgent)) {
                userAgent = request.getHeader("User-Agent");
            }
            JSONObject json = new JSONObject(userAgent);
            return json.getJSONObject("currentUserRole").getString("isManage");
        } catch (Exception e) {
            return null;
        }
    }
    public void error(Exception e) {
        logger.error(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss")+":"+getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void warn(Exception e) {
        logger.warn(getClass().getName() + ":", e.getMessage());
        e.printStackTrace();
    }
    public void infoMessage(String message) {
        logger.info(message);
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 接口处理成功
     *
     * @param msg
     * @return
     */
    public String success(String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", 200);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONObject value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value,String key2, JSONObject value2) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            json.put(key2, value2);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param total 总数
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, int total, String key, JSONArray value) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            json.put("total", total);
            json.put(key, value);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, int total, String key, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            map.put("status", code);
            map.put("msg", msg);
            map.put("total", total);
            map.put(key, list);
            String s = mapper.writeValueAsString(map);
            return s;
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            // 是否为第一页
            map.put("isFirst", list.isFirst());
            // 是否为最后一页
            map.put("isLast", list.isLast());
            // 总条数
            map.put("total", list.getTotalElements());
            // 总页数
            map.put("totalPages", list.getTotalPages());
            map.put(key, list.getContent());
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, Page<?> page, JSONArray array) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", page == null ? false : page.isFirst());
            // 是否为最后一页
            json.put("isLast", page == null ? true : page.isLast());
            // 总条数
            json.put("total", page == null ? 0 : page.getTotalElements());
            // 总页数
            json.put("totalPages", page == null ? 0 : page.getTotalPages());
            json.put(key, array);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Map<?, ?> value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, String value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, String key, IdEntity entity) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("status", code);
            map.put("msg", msg);
            map.put(key, entity);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String write(int code, String msg, boolean isFirst, boolean isLast, long total, int totalPages, String key, Object values) {
        try {
            JSONObject json = new JSONObject();
            json.put("status", code);
            json.put("msg", msg);
            // 是否为第一页
            json.put("isFirst", isFirst);
            // 是否为最后一页
            json.put("isLast", isLast);
            // 总条数
            json.put("total", total);
            // 总页数
            json.put("totalPages", totalPages);
            json.put(key, values);
            return json.toString();
        } catch (Exception e) {
            logger.error("BaseController:", e.getMessage());
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public String trimEnd(String param, String trimChars) {
        if (param.endsWith(trimChars)) {
            param = param.substring(0, param.length() - trimChars.length());
        }
        return param;
    }
    /**
     * 无效用户消息返回
     *
     * @param e
     * @param defaultCode
     * @param defaultMsg
     * @return
     */
    public String invalidUserException(Exception e, int defaultCode, String defaultMsg) {
        try {
            // if (e instanceof UndeclaredThrowableException) {
            // UndeclaredThrowableException ute = (UndeclaredThrowableException) e;
            // InvalidUserException iue = (InvalidUserException) ute.getUndeclaredThrowable();
            // if (iue != null) {
            // return error(iue.getCode(), iue.getMsg());
            // }
            // }
            return error(defaultCode, defaultMsg);
        } catch (Exception e2) {
            return null;
        }
    }
    public List<Map<String, Object>> copyBeans(Collection<? extends Object> beans, String... propertyNames) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Object bean : beans) {
            result.add(copyBeanProperties(bean, propertyNames));
        }
        return result;
    }
    /**
     * 复制特定属性。
     *
     * @param bean
     * @param propertyNames
     * @return
     */
    public Map<String, Object> copyBeanProperties(Object bean, String... propertyNames) {
        Map<String, Object> simplifiedBean = new HashMap<>();
        for (String propertyName : propertyNames) {
            Field field = ReflectionUtils.findField(bean.getClass(), propertyName);
            if (field != null) {
                field.setAccessible(true);
                Object value = ReflectionUtils.getField(field, bean);
                simplifiedBean.put(propertyName, value == null ? "" : value);
            } else {
                simplifiedBean.put(propertyName, "");
            }
        }
        return simplifiedBean;
    }
    /**
     * 数据保留两位小数,**.0 去掉小数点
     * @param obj
     * @return
     */
    public String getNumberFormat(Object obj){
        if(obj != null){
            Double d = Double.valueOf(obj.toString());
            NumberFormat df = NumberFormat.getInstance();
            df.setGroupingUsed(false);
            df.setMaximumFractionDigits(2);
            return df.format(d);
        }else {
            return "";
        }
    }
    public String write(int code, String errorMsg, int page, int rows, long total, List<?> list) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("successFlg", code == 0);
            map.put("errorMsg", errorMsg);
            // 是否为第一页
            map.put("errorCode", code);
            // 是否为最后一页
            map.put("currPage", page);
            // 分页大小
            map.put("pageSize", rows);
            // 总条数
            map.put("totalCount", total);
            // 总页数
            map.put("totalPage", Math.ceil((double)total/(rows)));
            // 结果集
            map.put("detailModelList", list);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    
    /**
     * 判断是否是观察者模式
     * @return
     */
    public boolean getObserverStatus () {
    
        String userAgent = request.getHeader("userAgent");
        if (StringUtils.isEmpty(userAgent)) {
            userAgent = request.getHeader("User-Agent");
        }
        logger.debug("userAgent:" + userAgent);
        JSONObject json = new JSONObject(userAgent);
        String observer = json.has("observer") ? json.getString("observer") : "";
        //如果是观察者直接返回true
        if (!org.springframework.util.StringUtils.isEmpty(observer) && observer.equals("1")) {
            return true;
        }else{
            return false;
        }
    }
    //获取ip地址
    public String getIpAddr() {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
    //获取手机型号
    public String getPhoneType(){
        String userAgent = request.getHeader("User-Agent");
        Pattern pattern = Pattern.compile(";\\s?(\\S*?\\s?\\S*?)\\s?(Build)?/");
        Matcher matcher = pattern.matcher(userAgent);
        String model = null;
        if (matcher.find()) {
            model = matcher.group(1).trim();
        }else{
            model = "未知型号";
        }
        return model;
    }
}

+ 8 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/endpoint/WeixinBaseController.java

@ -0,0 +1,8 @@
package com.yihu.jw.care.endpoint;
public class WeixinBaseController extends BaseController {
}

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

@ -0,0 +1,53 @@
package com.yihu.jw.care.endpoint.device;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.DeviceService;
import com.yihu.jw.entity.care.device.Device;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/common/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "设备管理")
public class DeviceController extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @ApiOperation("获取设备列表")
    @RequestMapping(value = "DeviceList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceList(@ApiParam(name = "category_code", value = "设备类型代码", defaultValue = "1")
                                @RequestParam(value = "category_code", required = true) String categoryCode) {
        try {
            List<Device> list = deviceService.findDeviceByCategory(categoryCode);
            return write(200, "获取设备列表成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "获取设备列表失败!");
        }
    }
    @ApiOperation("获取设备信息")
    @RequestMapping(value = "DeviceInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceInfo(@ApiParam(name = "id", value = "设备ID", defaultValue = "19")
                                @RequestParam(value = "id", required = true) String id) {
        try {
            Device device = deviceService.findById(id);
            return write(200, "查询成功", "data", device);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}

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

@ -0,0 +1,128 @@
package com.yihu.jw.care.endpoint.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.DeviceDetailService;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.util.CommonUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
/**
 * 医生端:设备管理控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "doctor/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "患者设备管理--医生端", description = "患者设备管理--医生端")
public class DoctorDeviceController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(DoctorDeviceController.class);
	@Autowired
	private PatientDeviceService patientDeviceService;
	@Autowired
	private DeviceDetailService deviceDetailService;
	@Autowired
	private BasePatientDao patientDao;
	@Autowired
	private BaseDoctorDao doctorDao;
	@Autowired
	private CommonUtil commonUtil;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JmsTemplate jmsTemplate;
	private ObjectMapper  objectMapper=new ObjectMapper();
	@ApiOperation("患者设备列表获取--医生端")
	@RequestMapping(value = "PatientDeviceList",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceByPatient(
			@ApiParam(name="patient",value="患者code",defaultValue = "5f84f2f0f32c45e0977e3a1ea9f2d77c")
			@RequestParam(value="patient",required = true) String patient,
			@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.findByDoctor(patient, getUID(),page, pagesize);
			return write(200, "查询成功", "data", list);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("获取患者设备信息")
	@RequestMapping(value = "PatientDeviceInfo",method = RequestMethod.GET)
	@ResponseBody
	public String getPatientDeviceInfo(@ApiParam(name="id",value="患者设备ID",defaultValue = "34")
									   @RequestParam(value="id",required = true) String id) {
		try {
			PatientDevice device = patientDeviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况")
	@RequestMapping(value = "PatientDeviceIdcard",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceUser(
			@ApiParam(name="patient",value="患者code",defaultValue = "915cca0a-5b1d-11e6-8344-fa163e8aee56")
			@RequestParam(value="patient",required = true) String patient,
			@ApiParam(name="type",value="设备类型",defaultValue = "1")
			@RequestParam(value="type",required = true) String type,
			@ApiParam(name="device_sn",value="设备SN码",defaultValue = "15L000002")
			@RequestParam(value="device_sn",required = true) String deviceSn) {
		try {
			List<Map<String,String>> list = patientDeviceService.getDeviceUser(patient,deviceSn,type);
			return write(200, "获取设备绑定信息成功!", "data",list);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况(管理端)")
	@RequestMapping(value = "getListByDeviceSn",method = RequestMethod.GET)
	@ResponseBody
	public String getDeviceBindUser(@ApiParam(name="type",value="设备类型",defaultValue = "1")
									@RequestParam(value="type",required = true) String type,
									@ApiParam(name="deviceSn",value="设备SN码",defaultValue = "15L000002")
									@RequestParam(value="deviceSn",required = true) String deviceSn){
			JSONArray objects = patientDeviceService.getDeviceByDeviceSn(deviceSn,type);
			return write(200, "获取设备成功!", "data",objects);
	}
}

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

@ -0,0 +1,214 @@
package com.yihu.jw.care.endpoint.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.endpoint.BaseController;
import com.yihu.jw.care.service.device.DeviceDetailService;
import com.yihu.jw.care.service.device.PatientDeviceService;
import com.yihu.jw.care.service.device.PatientHealthIndexService;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 患者端:设备管理控制类
 *
 * @author George
 */
@Controller
@RequestMapping(value = "patient/device")
@Api(value = "患者设备管理", description = "患者设备管理")
public class PatientDeviceController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(PatientDeviceController.class);
    @Autowired
    private PatientDeviceService patientDeviceService;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private PatientHealthIndexService patientHealthIndexService;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private BasePatientDao patientDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    @ApiOperation("获取居民标准体征预警值")
    @RequestMapping(value = "getDeviceStandard", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceStandard(@ApiParam(name = "type", value = "类型1血糖,2血压", defaultValue = "1")
                                    @RequestParam(value = "type", required = true) Integer type){
        try {
            JSONObject json = patientHealthIndexService.getealthStandard(type,getRepUID());
            return write(200,"获取成功","data",json);
        } catch (Exception ex) {
            error(ex);
            return error(-1,"获取失败");
        }
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    @ResponseBody
    public String saveDevice(@ApiParam(name = "json", value = "设备数据json", defaultValue = "{\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"7052169111\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
                             @RequestParam(value = "json", required = true) String json) {
        try {
            PatientDevice device = objectMapper.readValue(json, PatientDevice.class);
            // 设置患者标识
            device.setUser(getRepUID());
            //患者和设备是否首绑
            Map<String,Object> checkMap = patientDeviceService.checkBindingFirstAndType(device);
            boolean flag = (Boolean)checkMap.get("flag");
            int code = (Integer)checkMap.get("code");
            if (code==-30000){
                return write(-1,"设备不存在或者数据存在错误!");
            }
            BasePatientDO patient = patientDao.findById(getRepUID());
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
                device.setAgentName(patient.getName());
            }
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                patientDeviceService.saveDevice(device);
            }
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            return success("设备保存成功!");
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceByPatient(@ApiParam(name = "id", value = "分页起始id", defaultValue = "0")
                                     @RequestParam(value = "id", required = true) long id,
                                     @ApiParam(name = "pagesize", value = "每页条数", defaultValue = "10")
                                     @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            Page<PatientDevice> list = patientDeviceService.findByPatient(getRepUID(), id, pagesize);
            return write(200, "查询成功", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    //要增加时间段信息展示
    @ApiOperation("获取患者设备信息")
    @RequestMapping(value = "PatientDeviceInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getPatientDeviceInfo(@ApiParam(name = "id", value = "患者设备ID", defaultValue = "146")
                                       @RequestParam(value = "id", required = true) String id) {
        try {
            Map mapList = new HashMap();
            PatientDevice device = patientDeviceService.findById(id);
            mapList.put("device", device);
            return write(200, "查询成功", "data", mapList);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 通过sn码获取设备绑定情况
     */
    @ApiOperation("通过sn码获取设备绑定情况")
    @RequestMapping(value = "PatientDeviceIdcard", method = RequestMethod.GET)
    @ResponseBody
    public String getDeviceUser(@ApiParam(name = "type", value = "设备类型", defaultValue = "1")
                                @RequestParam(value = "type", required = true) String type,
                                @ApiParam(name = "device_sn", value = "设备SN码", defaultValue = "15L000002")
                                @RequestParam(value = "device_sn", required = true) String deviceSn) {
        try {
            if (deviceDetailService.findByDeviceSn(deviceSn)==null){
                return write(-1,"设备不存在!");
            }
            List<Map<String, String>> list = patientDeviceService.getDeviceUser(getRepUID(), deviceSn, type);
            return write(200, "获取设备绑定信息成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    
    /**
     * 设备删除
     */
    @ApiOperation("设备删除")
    @RequestMapping(value = "DeletePatientDevice",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            PatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getRepUID());
                //全部解绑后去判断就更新设备表中是否绑定字段
                deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
                return success("设备已删除!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @ApiOperation("获取居民的设备任务信息")
    @RequestMapping(value = "getPatientDeviceTaskInfo",method = RequestMethod.POST)
    @ResponseBody
    public String getPatientDeviceTaskInfo(@ApiParam(name = "patientCode",value = "患者code")@RequestParam(value = "patientCode",required = true)String patientCode){
        try {
            return write(200,"执行成功","data",patientDeviceService.getPatientDeviceTaskInfo(patientCode));
        }catch (Exception e){
            return write(-1,"执行失败!");
        }
    }
}

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

@ -0,0 +1,185 @@
package com.yihu.jw.care.service.device;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
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.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
 * 设备管理(device库)
 * zd
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class DeviceDetailService extends BaseJpaService<DeviceDetail, DeviceDetailDao> {
	@Autowired
	private DeviceDetailDao deviceDetailDao;
	@Autowired
	private DeviceDao deviceDao;
	@Autowired
	private BasePatientDao patientDao;
	@Autowired
	private BaseDoctorDao doctorDao;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**
	 * 绑定时更新设备表中的信息
	 * @param patientDevice
	 * @param grantTime
	 * @param isFirst
	 * @throws Exception
	 */
	@Transactional
	public void updateAfterBinding(PatientDevice patientDevice, Date grantTime, boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		int bind = deviceDetail.getIsBinding();
		long adminTeam=0L;
		String hospital = "";
		String isFirstBind = "";
		String hospitalName = "";
		String doctorCode ="";
		String doctorName="";
		String keyType = "1";
		if ("2".equals(patientDevice.getUserType())){
			keyType="2";
		}
		//设备表没有数据则插入一条数据
		if (deviceDetail==null){
			insertDevice(patientDevice,String.valueOf(adminTeam),hospitalName,hospital,"",doctorCode,doctorName,1);
			deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		}
		isFirstBind = deviceDetail.getBindingCount();
		if (StringUtils.isNotBlank(isFirstBind)){
			JSONObject jsonObject = JSON.parseObject(isFirstBind);
			int bindCount = Integer.valueOf(String.valueOf(jsonObject.get(keyType)));
			jsonObject.replace(keyType,bindCount+1+"");
			isFirstBind = jsonObject.toJSONString();
		}
		if (isFirst){
			String updateFirstSql ="update wlyy_devices dd set dd.is_grant=1,dd.grant_admin_team=?,dd.grant_org_code=?,dd.binding_count=?,dd.grant_time = ?,dd.org_name=?,dd.grant_doctor=?,dd.grant_doctor_name=?,dd.is_binding=1 where dd.device_code=?";
			jdbcTemplate.update(updateFirstSql,new Object[]{String.valueOf(adminTeam),hospital,isFirstBind,grantTime,hospitalName,doctorCode, doctorName,patientDevice.getDeviceSn()});
		}else {
			List<PatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(patientDevice.getDeviceSn());
			int patientDeviceSize = patientDeviceList.size();
			String updateSql = "";
			if (bind == 0){
				updateSql ="update wlyy_devices dd set dd.is_grant=1,dd.grant_admin_team=?,dd.grant_org_code=?,dd.binding_count=?,dd.is_binding=?,dd.org_name=?,dd.grant_doctor=?,dd.grant_doctor_name=?  where dd.device_code=?";
				jdbcTemplate.update(updateSql,new Object[]{String.valueOf(adminTeam),hospital,isFirstBind,patientDeviceSize,hospitalName,doctorCode,doctorName,patientDevice.getDeviceSn()});
			}else if (bind>0){
				updateSql ="update wlyy_devices dd set dd.is_grant=1,dd.binding_count=?,dd.is_binding=? where dd.device_code=?";
				jdbcTemplate.update(updateSql,new Object[]{isFirstBind,patientDeviceSize,patientDevice.getDeviceSn()});
			}
		}
	}
	/**
	 * 绑定时设备表如果没有数据则插入一条数据
	 * @param patientDevice
	 * @param adminTeam
	 * @param orgName
	 * @param orgCode
	 * @param bindCount
	 * @param isBind 0未绑定  1已绑定
	 * @throws Exception
	 */
	public void insertDevice(PatientDevice patientDevice, String adminTeam, String orgName, String orgCode,String bindCount,String doctorCode,String doctorName,int isBind)throws Exception{
		//获取原始数据
		DeviceDetail deviceDetail = new DeviceDetail();
		BasePatientDO patient = patientDao.findById(patientDevice.getUser());
		BaseDoctorDO doctor = doctorDao.findById(patientDevice.getDoctor());
		Device device = deviceDao.findOne(patientDevice.getDeviceId());
		//添加数据到具体字段
		deviceDetail.setDeviceCode(patientDevice.getDeviceSn());
		deviceDetail.setDeviceName(patientDevice.getDeviceName());
		deviceDetail.setSim(patientDevice.getSim());
		deviceDetail.setGrantAdminTeam(adminTeam);
		deviceDetail.setGrantOrgCode(orgCode);
		deviceDetail.setGrantTime(patientDevice.getCzrq());
		deviceDetail.setApplyDate(DateUtil.getStringDate("yyyy-MM-dd HH:mm:ss"));
		deviceDetail.setOrgName(orgName);
		deviceDetail.setGrantDoctor(doctorCode);
		deviceDetail.setGrantDoctorName(doctorName);
		if (isBind>0){
			deviceDetail.setIsGrant(1);
			deviceDetail.setIsBinding(1);
		}else {
			deviceDetail.setIsGrant(0);
			deviceDetail.setIsBinding(0);
		}
		if (device!=null){
			deviceDetail.setDeviceModel(device.getModel());
		}
		if (StringUtils.isNotEmpty(bindCount)){
			deviceDetail.setBindingCount(bindCount);
		}else {
			if (Integer.valueOf(patientDevice.getUserType())>0){
				deviceDetail.setBindingCount("{\"1\":\"0\",\"2\":\"0\"}");
			}else {
				deviceDetail.setBindingCount("{\"1\":\"0\"}");
			}
		}
		if (patient!=null){
			deviceDetail.setLinkman(patient.getName());
			deviceDetail.setTel(patient.getPhone());
		}
		if (doctor!=null){
			deviceDetail.setApplicantName(doctor.getName());
			deviceDetail.setApplicantIdentity(doctor.getIdcard());
			deviceDetail.setApplicantTel(doctor.getMobile());
			deviceDetail.setApplicantMail(doctor.getMobile());
		}
		deviceDetailDao.save(deviceDetail);
	}
	/**
	 * 全部解绑后设备表更新为未绑定
	 * @param deviceSn
	 */
	public void unBindUpdateIsBinding(String deviceSn)throws Exception{
		List<PatientDevice> 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});
			//deviceDetailDao.updateUnbindAll(0,deviceSn);
		}
		if (patientDeviceList.size()==1){
			jdbcTemplate.update(sql,new Object[]{1,deviceSn});
			//deviceDetailDao.updateUnbindAll(1,deviceSn);
		}
		if (patientDeviceList.size()>1){
			jdbcTemplate.update(sql,new Object[]{2,deviceSn});
			//deviceDetailDao.updateUnbindAll(2,deviceSn);
		}
	}
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
}

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

@ -0,0 +1,38 @@
package com.yihu.jw.care.service.device;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * 设备管理
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class DeviceService extends BaseJpaService<Device, DeviceDao> {
	@Autowired
	private DeviceDao deviceDao;
	/**
	 * 查询设备信息
	 */
	public List<Device> findDeviceByCategory(String categoryCode) {
		return deviceDao.findByCategoryCode(categoryCode);
	}
	/**
	 * 获取设备信息
     */
	public Device findById(String id)
	{
		return deviceDao.findOne(Long.valueOf(id));
	}
}

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

@ -0,0 +1,656 @@
package com.yihu.jw.care.service.device;
import com.yihu.jw.care.dao.device.DeviceDao;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.service.wechat.WeiXinAccessTokenUtils;
import com.yihu.jw.care.util.ConcealUtil;
import com.yihu.jw.care.util.MyJdbcTemplate;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
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.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;
import javax.annotation.PostConstruct;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceService extends BaseJpaService<PatientDevice, PatientDeviceDao> {
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private PatientHealthIndexService healthIndexService;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private MyJdbcTemplate myJdbcTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    WeiXinAccessTokenUtils tokenUtils;
    //健康问题 高血压
    private static final String gxy = "HP0093";
    //健康问题 糖尿病
    private static final String tnb = "HP0047";
    Map<Integer, String> relations = new HashMap<>();
    @Value("${es.index.Statistics}")
    private String esIndex;
    @PostConstruct
    public void init() {
        relations.put(0, "其他");
        relations.put(1, "父亲");
        relations.put(2, "母亲");
        relations.put(3, "老公");
        relations.put(4, "老婆");
        relations.put(5, "儿子");
        relations.put(6, "女儿");
        relations.put(7, "未知");
        relations.put(8, "免疫关联");
    }
    /**
     * 验证sn码 先调总部接口 未注册才查询本地数据库,如果也没有才不能绑定
     * 屏蔽总部调总部接口,直接本地数据库验证,modify by Hmf on 2020.1.15
     * @param deviceSn
     * @return
     * @throws Exception
     */
    public Boolean checkDeviceSn(String deviceSn) throws Exception{
        Boolean flag = false;
        DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
        if(deviceDetail != null){
            flag = true;
        }
        return flag;
    }
    /**
     * 保存患者设备
     */
    public boolean saveDevice(PatientDevice patientDevice) throws Exception {
        //判断sn码是否被使用
        String sn = patientDevice.getDeviceSn();
        String type = patientDevice.getCategoryCode();
        Long deviceId = patientDevice.getDeviceId();
        String userType = patientDevice.getUserType();
        if (userType == null) {
            userType = "-1";
            patientDevice.setUserType("-1");
        }
        boolean needVerify = true;
        //修改操作
        if (patientDevice.getId() != null) {
            PatientDevice deviceOld = patientDeviceDao.findOne(patientDevice.getId());
            if (deviceOld != null) {
                if (deviceOld.getDeviceSn().equals(sn)) {
                    needVerify = false;
                }
            } else {
                throw new Exception("不存在该条记录!");
            }
        }
        //校验sn码是否被使用
        if (needVerify) {
            PatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
            if (device != null && !device.getId().equals(patientDevice.getId())) {
                throw new Exception("sn码" + sn + "已被使用!");
            }
        }
        patientDevice.setCzrq(new Date());
        patientDevice.setDel(0);
        //当前用户的身份证
        BasePatientDO patient = patientDao.findById(patientDevice.getUser());
        patientDevice.setUserIdcard(patient.getIdcard());
        if(checkDeviceSn(sn)){
            patientDeviceDao.save(patientDevice);
        }else {
            String message = "设备不存在";
            throw new Exception(message);
        }
        return true;
    }
    public void deleteDevices(String deviceSn, String type, String uuid) {
        List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (patientDevices == null || patientDevices.size() == 0) {
            throw new RuntimeException("设备未被绑定!");
        }
        for (PatientDevice patientDevice : patientDevices) {
            patientDeviceDao.delete(patientDevice);
        }
    }
    /**
     * 删除患者设备
     */
    public List<com.alibaba.fastjson.JSONObject> deleteDevice(String id, String uuid) {
        PatientDevice device = patientDeviceDao.findOne(Long.valueOf(id));
        patientDeviceDao.delete(device);
        List<PatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(device.getDeviceSn(), device.getCategoryCode());
        List<com.alibaba.fastjson.JSONObject> objects = new ArrayList<>();
        for (PatientDevice patientDevice : patientDevices) {
            String json = com.alibaba.fastjson.JSONObject.toJSONString(patientDevice) ;
            com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parseObject(json) ;
            BasePatientDO patient = patientDao.findById(patientDevice.getUser());
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.add(object);
        }
        return objects;
    }
    /**
     * 患者设备列表接口(分页)
     */
    public Page<PatientDevice> findByPatient(String patientCode, long id, int pageSize) {
        if (id < 0) {
            id = 0;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pageSize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("patient", new SearchFilter("user", Operator.EQ, patientCode));
        //filters.put("del", new SearchFilter("del", Operator.EQ, 0));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<PatientDevice> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientDevice.class);
        return patientDeviceDao.findAll(spec, pageRequest);
    }
    /**
     * 患者设备列表接口--医生端
     */
    public List<Map<String, Object>> findByDoctor(String patientCode, String doctorCode, int page, int pagesize) {
        List<Map<String, Object>> re = new ArrayList<>();
        if (page <= 0) {
            page = 1;
        }
        if (pagesize <= 0) {
            pagesize = 10;
        }
        PageRequest pageRequest = new PageRequest(page - 1, pagesize);
        List<PatientDevice> list = new ArrayList<>();
        list = patientDeviceDao.findByUser(patientCode, pageRequest);
        if (list != null) {
            //获取设备路径,医生姓名
            List<Device> deviceList = deviceDao.findAll();
            BaseDoctorDO self = doctorDao.findById(doctorCode);
            for (PatientDevice item : list) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(item.getDoctor())) {
                    if (StringUtils.equals(item.getDoctor(), doctorCode)) {
                        map.put("role", 1);//可解绑自己绑定的
                    } else {
                    }
                } else {
                    map.put("role", 0);//患者自己绑定无法解绑
                }
                map.put("id", item.getId());
                map.put("deviceId", item.getDeviceId());
                map.put("deviceSn", item.getDeviceSn());
                map.put("user", item.getUser());
                map.put("categoryCode", item.getCategoryCode());
                map.put("userType", item.getUserType());
                map.put("applyStatus", item.getApplyStatus());
                map.put("applyReason", item.getApplyReason());
                map.put("userIdcard", item.getUserIdcard());
                map.put("czrq", DateUtil.dateToStrLong(item.getCzrq()));
                String deviceDoctor = item.getDoctor();
                if (deviceDoctor == null) {
                    map.put("doctor", "");
                    map.put("doctorName", "");
                } else {
                    map.put("doctor", deviceDoctor);
                    if (deviceDoctor.equals(doctorCode)) {
                        map.put("doctorName", self.getName());
                    } else {
                        BaseDoctorDO doctor = doctorDao.findById(deviceDoctor);
                        if (doctor != null) {
                            map.put("doctorName", doctor.getName());
                        } else {
                            map.put("doctorName", "");
                        }
                    }
                }
                //获取设备路径
                for (Device de : deviceList) {
                    if (de.getId().equals(item.getDeviceId())) {
                        map.put("deviceName", de.getName());
                        map.put("devicePhoto", de.getPhoto());
                        map.put("deviceBrands", de.getBrands());
                        break;
                    }
                }
                re.add(map);
            }
        }
        re.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if (o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) > 0) {
                    return -1;
                }
                if (o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) < 0) {
                    return 1;
                }
                return 0;
            }
        });
        return re;
    }
    /**
     * 查询患者已拥有的设备
     *
     * @param patient
     * @return
     */
    public Iterator<PatientDevice> findPatientHave(String patient) {
        return patientDeviceDao.findByUser(patient).iterator();
    }
    /**
     * 获取患者设备信息
     **/
    public PatientDevice findById(String id) {
        return patientDeviceDao.findOne(Long.valueOf(id));
    }
    /**
     * 通过sn码获取设备绑定情况
     **/
    public List<Map<String, String>> getDeviceUser(String user, String deviceSn, String type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        List<PatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (list != null) {
            for (PatientDevice item : list) {
                Map<String, String> map = new HashMap<>();
                map.put("type", item.getUserType());
                String code = item.getUser();
                if (code.equals(user)) {
                    map.put("others", "0");
                } else {
                    map.put("others", "1");
                }
                //获取姓名
                BasePatientDO patient = patientDao.findById(code);
                if (patient != null) {
                    map.put("name", patient.getName());
                } else {
                    map.put("name", code);
                }
                re.add(map);
            }
        }
        return re;
    }
    public JSONArray getDeviceByDeviceSn(String deviceSn, String type) {
        List<PatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        JSONArray objects = new JSONArray();
        for (PatientDevice patientDevice : list) {
            JSONObject object = new JSONObject(patientDevice);
            BasePatientDO patient = patientDao.findById(patientDevice.getUser());
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.put(object);
        }
        return objects;
    }
    /**
     * 根据user,deviceSN更换绑定血糖仪
     *
     * @param user
     * @param deviceSN
     * @param newDeviceSN
     * @throws Exception
     */
    public int updatePatientDevice(String user, String deviceSN, String newDeviceSN, String userType,String sim,String hospital,String hospitalName,String checkDoctorName) throws Exception {
        int rows = patientDeviceDao.updatePatientDevice(user, deviceSN, newDeviceSN, userType,sim,hospital,hospitalName,checkDoctorName);
        return rows;
    }
    /**
     * 个人信息
     * @param patientCode
     */
    public com.alibaba.fastjson.JSONObject deviceInfo(String deviceSn,String patientCode){
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        List<PatientDevice> device = patientDeviceDao.findByDeviceSn(deviceSn);
        jsonObject.put("sim",device.get(0).getSim());
        jsonObject.put("deviceSn",device.get(0).getDeviceSn());
        jsonObject.put("categoryCode",device.get(0).getCategoryCode());
        jsonObject.put("deviceName",device.get(0).getDeviceName());
        BasePatientDO patient = patientDao.findById(patientCode);
        //个人信息
        jsonObject.put("sex",patient.getSex());//性別,1男,2女
        jsonObject.put("name",null==patient.getName()?"": ConcealUtil.nameOrAddrConceal(patient.getName()));
            jsonObject.put("doctorName","");//全科医生
            jsonObject.put("doctorHealthName","");//全科医生
            jsonObject.put("hospitalName","");//社区
        jsonObject.put("address",null==patient.getAddress()?"":ConcealUtil.nameOrAddrConceal(patient.getAddress()));
        jsonObject.put("idCard",ConcealUtil.idCardConceal(patient.getIdcard()));
        jsonObject.put("age", IdCardUtil.getAgeByIdcardOrBirthday(patient.getIdcard(),patient.getBirthday()));
        return jsonObject;
    }
    /**
     * 设备使用数据
     * @param page
     * @param pageSize
     * @param deviceSn
     * @return
     */
    public com.alibaba.fastjson.JSONObject deviceUseData(Integer page,Integer pageSize,String deviceSn){
        StringBuffer sql = new StringBuffer("SELECT DATE_FORMAT(h.record_date,'%Y-%m-%d %H:%i:%S') recodeDate,h.type,h.value1,h.value2,h.value3,p.name ");
        sql.append("from device.wlyy_patient_health_index h LEFT JOIN wlyy_patient p on h.user=p.code ");
        if(StringUtils.isNoneBlank(deviceSn)){
            sql.append("where h.device_sn = '"+deviceSn+"' and h.type in (1,2) ");
        }
        sql.append(" ORDER BY record_date desc limit ?,?");
        List<com.alibaba.fastjson.JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),new Object[]{(page-1)*pageSize,pageSize});
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("list",list);
        StringBuffer sqlTotal = new StringBuffer("SELECT count(h.id) c ");
        sqlTotal.append("from wlyy_patient_health_index h LEFT JOIN wlyy_patient p on h.user=p.code ");
        if(StringUtils.isNoneBlank(deviceSn)){
            sqlTotal.append("where h.device_sn = '"+deviceSn+"' ");
        }
        List<com.alibaba.fastjson.JSONObject> list2 = myJdbcTemplate.queryJson(sqlTotal.toString(),new Object[]{});
        if(list2.size()>0){
            json.put("total",list2.get(0).getInteger("c"));
        }else{
            json.put("total",0);
        }
        return json;
    }
    /**
     * 居民 医生搜索
     * @param name
     * @param page
     * @param pageSize
     */
    public List<com.alibaba.fastjson.JSONObject> searchPatient(String name,Integer page,Integer pageSize,String idcards){
        Object o[] = null;
        StringBuffer sql = new StringBuffer("SELECT p.code,p.name,p.address,p.idcard,p.sex,GROUP_CONCAT(label_name) labelName,t.doctor_name doctorName ");
        sql.append("FROM ( SELECT DISTINCT f.* FROM wlyy_patient_device d, wlyy_sign_family f ");
        sql.append("WHERE f.`status` > 0 AND f.patient = d.`user` ) t, wlyy_patient p LEFT JOIN ");
        sql.append("wlyy_sign_patient_label_info l on  p. CODE = l.patient and l.`status`=1 ");
        sql.append("AND l.label_type = 3 and (l.label=2 or l.label=1) WHERE t.patient = p. CODE ");
        if(StringUtils.isNotBlank(name)){
            sql.append(" and (p.`name` like '%"+name+"%' or t.doctor_name like '%"+name+"%') ");
        }
        if(StringUtils.isNotBlank(idcards)){
            idcards = "'"+idcards.replaceAll(",","','")+"'";
            sql.append(" and p.idcard in ("+idcards+") ");
            sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex ");
            o = new Object[]{};
        }else {
            sql.append("GROUP BY p.code,p.name,p.address,p.idcard,p.sex LIMIT ?,? ");
            o = new Object[]{(page-1)*pageSize,pageSize};
        }
        List<com.alibaba.fastjson.JSONObject> list = myJdbcTemplate.queryJson(sql.toString(),o);
        list.forEach(json->{
            json.put("age", IdCardUtil.getAgeForIdcard(String.valueOf(json.get("idcard"))));
            json.put("address", null==json.get("address")?"":ConcealUtil.nameOrAddrConceal(json.get("address").toString()));
            json.put("name", null==json.get("name")?"":ConcealUtil.nameOrAddrConceal(json.get("name").toString()));
            json.put("idcard", null==json.get("idcard")?"":ConcealUtil.idCardConceal(json.get("idcard").toString()));
        });
        return list;
    }
    /**
     * 判断当前值是否在区间内
     */
    private String checkHealthIndex(Double current, Double max) {
        if (current > max ) {
            return "偏高";
        }
        return "偏低";
    }
    /**
     * 名字转换
     * @param type
     * @param value
     * @return
     */
    private String getTypeName(String type,String value){
        String name = "";
        //1早餐前、2早餐后、3午餐前、4午餐后、5晚餐前 6晚餐后 7睡前)
        if ("1".equals(type)){
            switch (value){
                case "1":
                    name = "早餐前";
                    break;
                case "2":
                    name = "早餐后";
                    break;
                case "3":
                    name = "午餐前";
                    break;
                case "4":
                    name = "午餐后";
                    break;
                case "5":
                    name = "晚餐前";
                    break;
                case "6":
                    name = "晚餐后";
                    break;
                default:
                    name = "睡前";
                    break;
            }
        }else if("3".equals(type)){
            name = "收缩压";
        }else {
            name = "舒张压";
        }
        return name;
    }
    public Map<String,Object> getDeviceByDeviceSn(String deviceSn)throws Exception {
        Map<String,Object> map  = new HashedMap();
        String sql = "SELECT d.id,d.device_name deviceName,d.device_model deviceMode,d.sim,CAST(e.is_multi_user AS UNSIGNED INTEGER) isMultiUser,e.category_code as deviceType,e.multi_user multiUser,e.id as device_id FROM wlyy_devices d LEFT JOIN wlyy.dm_device e ON d.device_model = e.model WHERE d.device_code='"+deviceSn+"'";
        List<Map<String,Object>> mapSqlList = jdbcTemplate.queryForList(sql);
        if (mapSqlList!=null && mapSqlList.size()>0){
            map = mapSqlList.get(0);
        }
        List<PatientDevice> list = patientDeviceDao.findByDeviceSn(deviceSn);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (PatientDevice patientDevice : list) {
            Map<String,Object> infoMap = new HashedMap();
            BasePatientDO patient = patientDao.findById(patientDevice.getUser());
            if (patient!=null){
                infoMap.put("patientDeviceId",patientDevice.getId());
                infoMap.put("userCode",patient.getId());
                infoMap.put("userName",patient.getName());
                infoMap.put("idCard",patient.getIdcard());
                infoMap.put("userType",patientDevice.getUserType());
            }
            mapList.add(infoMap);
        }
        map.put("bindingInfo",mapList);
        return map;
    }
    public Map<String,Object> checkBindingFirstAndType(PatientDevice patientDevice)throws Exception{
        Map<String,Object> resultMap = new HashedMap();
        boolean flag = true;
        int code = 200;
        String msg = "";
        String deviceSn = patientDevice.getDeviceSn();
        String userType = patientDevice.getUserType();
        //设备是否是第一次被绑定
        String keyType = "1";
        if("2".equals(userType)){
            keyType = "2";
        }
        DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
        if (deviceDetail!=null && StringUtils.isNotEmpty(deviceDetail.getBindingCount())){
            JSONObject jsonObject =new JSONObject(String.valueOf(deviceDetail.getBindingCount()));
            if (jsonObject.getInt(keyType)>0){
                flag=false;
                msg="设备不是首次绑定";
                code = -20000;
            }
        }
        resultMap.put("flag",flag);
        resultMap.put("msg",msg);
        resultMap.put("code",code);
        return resultMap;
    }
    public Map<String,Object> getPatientDeviceTaskInfo(String patientCode)throws Exception{
        Map<String,Object> resultMap = new HashedMap();
        String sql = "SELECT d.binding_count,pd.user_type FROM wlyy_patient_device pd LEFT JOIN wlyy_devices d ON pd.device_sn = d.device_code where pd.del=0 and pd.user='"+patientCode+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        int count = 0;
        //查询一共绑定了多少个设备
        for (Map<String,Object> map : list){
            if (map.get("binding_count")!=null){
                JSONObject jsonObject =  new JSONObject(String.valueOf(map.get("binding_count")));
                Set<String> keyset = jsonObject.keySet();
                for (String key : keyset){
                    if (key.equals(String.valueOf(map.get("user_type"))) && jsonObject.getInt(key)==1){
                        count++;
                    }
                }
            }
        }
        resultMap.put("deviceCount",count);
        //体征上传表查询是否有今天的数据
        int healthBp = 0;
        int healthBs = 0;
        int resultHealty= 0;
        boolean hasUploadHealth = false;
        String today = DateUtil.dateToStr(DateUtil.getDateShort(new Date()),"yyyy-MM-dd");
        String healthSql ="SELECT type as healtyType,device_sn deviceSn FROM wlyy_patient_health_index where record_date >'"+today+" 00:00:00' and record_date <='"+today+" 23:59:59' and  status = 0 and  del = 1 and user = '"+patientCode+"'";
        List<Map<String,Object>>  maps =jdbcTemplate.queryForList(healthSql);
        for (Map<String,Object> map : maps){
            if (map.get("type")!=null && String.valueOf(map.get("Type")).equals("1")){
                //血糖
                healthBs=1;
            }
            if (map.get("type")!=null && String.valueOf(map.get("Type")).equals("2")){
                //血压
                healthBp=1;
            }
        }
        if (healthBp==1 && healthBs ==0){
            resultHealty =1;
        }
        if (healthBs ==1 && healthBp==0){
            resultHealty = 2;
        }
        if (healthBp ==1 && healthBs ==1){
            resultHealty = 3;
        }
        resultMap.put("resultHealty",resultHealty);
        return resultMap;
    }
    /**
     * 根据设备sn及居民code获取居民有效的设备绑定数据
     * @param deviceSn 设备sn码
     * @return
     */
    public List<PatientDevice> findByDeviceSn(String deviceSn){
       return  patientDeviceDao.findByDeviceSn(deviceSn);
    }
}

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

@ -0,0 +1,1599 @@
package com.yihu.jw.care.service.device;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.care.dao.device.DeviceDetailDao;
import com.yihu.jw.care.dao.device.DevicePatientHealthIndexDao;
import com.yihu.jw.care.dao.device.PatientDeviceDao;
import com.yihu.jw.care.util.CommonUtil;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.care.device.PatientDevice;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthIndexService extends BaseJpaService<DevicePatientHealthIndex, DevicePatientHealthIndexDao> {
    private Logger logger = LoggerFactory.getLogger(PatientHealthIndexService.class);
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    // 血糖餐前最小值
    public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;
    // 血糖餐前最大值
    public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;
    // 血糖餐后最小值
    public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;
    // 血糖餐后最大值
    public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;
    // 舒张压最小值
    public static final double HEALTH_STANDARD_SZY_MIN = 60;
    // 舒张压最大值
    public static final double HEALTH_STANDARD_SZY_MAX = 90;
    // 收缩压最小值
    public static final double HEALTH_STANDARD_SSY_MIN = 90;
    // 收缩压最大值
    public static final double HEALTH_STANDARD_SSY_MAX = 140;
    /**
     * 获取居民标准预警值
     *
     * @param type
     * @param patientCode
     * @return
     */
    public JSONObject getealthStandard(Integer type, String patientCode) {
        //血糖校验
        JSONObject json = new JSONObject();
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            Double maxValueBefore = HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = HEALTH_STANDARD_ST_MIN_AFTER;
            json.put("maxValueAfter", maxValueAfter);
            json.put("maxValueBefore", maxValueBefore);
            json.put("minValueBefore", minValueBefore);
            json.put("minValueAfter", minValueAfter);
        }
        //血压校验
        else if (type == 2) {
            // 血压记录,查询患者血压预警值
            Double maxValueSSY = HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = HEALTH_STANDARD_SZY_MIN;
            json.put("minValueSZY", minValueSZY);
            json.put("maxValueSZY", maxValueSZY);
            json.put("minValueSSY", minValueSSY);
            json.put("maxValueSSY", maxValueSSY);
            
        }
        return json;
        
    }
    
    
    //更改接口(包括手动记录的修改和所有的删除)
    public void modify(long id, String recordDate, String value1, String value2, String value3, String value4) throws Exception {
        
        DevicePatientHealthIndex result = patientHealthIndexDao.findOne(id);
        if (result != null) {
            //字段值均为空为删除
            if (StringUtils.isEmpty(value1) && StringUtils.isEmpty(value2) && StringUtils.isEmpty(value3) && StringUtils.isEmpty(value4)) {
                result.setDel("0");
            } else {
                if (StringUtils.isNotEmpty(recordDate)) {
                    result.setRecordDate(DateUtil.strToDate(recordDate));
                } else {
                    throw new Exception("Record date can not be null!");
                }
                
                result.setDel("1");
                if (StringUtils.isNotEmpty(value1)) {
                    result.setValue1(value1);
                }
                if (StringUtils.isNotEmpty(value2)) {
                    result.setValue2(value2);
                }
                if (StringUtils.isNotEmpty(value3)) {
                    result.setValue3(value3);
                }
                if (StringUtils.isNotEmpty(value4)) {
                    result.setValue4(value4);
                }
            }
            patientHealthIndexDao.save(result);
            if ("1".equals(result.getType()) || "2".equals(result.getType())) {
                verifyHealthIndex(result.getId());
            }
        } else {
            throw new Exception("Result not exit!");
        }
        
    }
    
    /**
     * 获取居民最新各类健康记录
     */
    public Map findDataByPatient(String patient, int type) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sql = "SELECT " +
                " * " +
                " FROM " +
                "  device.wlyy_patient_health_index a " +
                " WHERE " +
                " a. USER = ? " +
                " AND a.type = ? " +
                " AND a.del = 1 " +
                " ORDER BY " +
                " a.record_date DESC " +
                "LIMIT 0,1 ";
        List<Map<String, Object>> devicePatient = findDataByPatient(sql, patient, type);
        Map<String, Object> map = new HashMap<>();
        for (Map<String, Object> device : devicePatient) {
            String time = device.get("record_date") == null ? null : device.get("record_date").toString();
            String deviceSN = device.get("device_sn") == null ? "0" : "1";
            String value1 = device.get("value1") == null ? null : device.get("value1").toString();
            String value2 = device.get("value2") == null ? null : device.get("value2").toString();
            String value3 = device.get("value3") == null ? null : device.get("value3").toString();
            String value4 = device.get("value4") == null ? null : device.get("value4").toString();
            String value5 = device.get("value5") == null ? null : device.get("value5").toString();
            String value6 = device.get("value6") == null ? null : device.get("value6").toString();
            String value7 = device.get("value7") == null ? null : device.get("value7").toString();
            map.put("isDevice", deviceSN);
            if (StringUtils.isNotEmpty(time)) {
                Date date = sdf.parse(time);
                time = sdf.format(date);
                map.put("time", time);
            }
            if (StringUtils.isNotEmpty(value1)) {
                map.put("value1", value1);
            }
            if (StringUtils.isNotEmpty(value2)) {
                map.put("value2", value2);
                
            }
            if (StringUtils.isNotEmpty(value3)) {
                map.put("value3", value3);
            }
            if (StringUtils.isNotEmpty(value4)) {
                map.put("value4", value4);
            }
            if (StringUtils.isNotEmpty(value5)) {
                map.put("value5", value5);
            }
            if (StringUtils.isNotEmpty(value6)) {
                map.put("value6", value6);
            }
            if (StringUtils.isNotEmpty(value7)) {
                map.put("value7", value7);
            }
        }
        return map;
    }
    
    
    /**
     * 判断当前值是否在区间内
     */
    private boolean checkHealthIndex(Double current, Double max, Double min) {
        if (current > max || current < min || current < 0) {
            return false;
        }
        return true;
    }
    /**
     * 判断当前指标偏高或偏低
     */
    private int checkHealthIndexDetail(Double current, Double max, Double min) {
        if (current > max ) {
            return 1;
        }else if(current < min || current < 0){
            return 2;
        }
        return 0;
    }
    
    
    /**
     * 获取患者某天血糖值
     *
     * @return
     */
    private com.alibaba.fastjson.JSONObject getPatientXT_Json(String patient, String dateString) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("user", patient);
        boolean hadData = false;
        Date date = DateUtil.strToDateShort(dateString);
        /***************** 按时间排序 ***************************/
        
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",record_date" +
                ",sort_date" +
                ",czrq as createDate" +
                ",min(czrq) czrq " +
                " from device.wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type = 1" +
                " and DATE_FORMAT(record_date,'%Y-%m-%d') = '" + dateString + "'" +
                " and del = '1' " +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date,id desc ";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,dateString);
        if (list != null && list.size() > 0) {
            obj.put("type", 1);
            obj.put("czrq", date);
            obj.put("recordDate", date);
            obj.put("sortDate", date);
            for (Map<String, Object> item : list) {
                String data = item.get("value1").toString();
                String dataType = item.get("value2").toString();
                String deviceSn = item.get("device_sn") == null ? "" : item.get("device_sn").toString();
                Date recordDate = (Date)item.get("record_date");
                Long id = Long.parseLong(item.get("id") + "");
                Date createDate = (Date)item.get("createDate");
                
                String recordTime = DateUtil.dateToStr(recordDate,DateUtil.YYYY_MM_DD);
                String createTime = DateUtil.dateToStr(createDate,DateUtil.YYYY_MM_DD);
                
                if (data != null && dataType != null) {
                    if (dataType.equals("1")) {
                        obj.put("value1", data);
                        obj.put("time1", recordDate);
                        obj.put("id1", id);
                        obj.put("deviceSn1", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("2")) {
                        obj.put("value2", data);
                        obj.put("time2", recordDate);
                        obj.put("id2", id);
                        obj.put("deviceSn2", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("3")) {
                        obj.put("value3", data);
                        obj.put("time3", recordDate);
                        obj.put("id3", id);
                        obj.put("deviceSn3", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("4")) {
                        obj.put("value4", data);
                        obj.put("time4", recordDate);
                        obj.put("id4", id);
                        obj.put("deviceSn4", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("5")) {
                        obj.put("value5", data);
                        obj.put("time5", recordDate);
                        obj.put("id5", id);
                        obj.put("deviceSn5", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("6")) {
                        obj.put("value6", data);
                        obj.put("time6", recordDate);
                        obj.put("id6", id);
                        obj.put("deviceSn6", deviceSn);
                        hadData = true;
                    } else if (dataType.equals("7")) {
                        obj.put("value7", data);
                        obj.put("time7", recordDate);
                        obj.put("id7", id);
                        obj.put("deviceSn7", deviceSn);
                        hadData = true;
                    }
                    
                    //是否为补传数据(设备上传且测量时间和创建时间不匹配)
                    judgeIsSupplement(obj,recordTime,createTime,deviceSn,dataType);
                    
                    obj.put("healthindexid", id);
                    obj.put("valuedata", data);
                    obj.put("dataType",dataType);
                }
            }
        }
        if (hadData) {
            return obj;
        } else {
            return null;
        }
    }
    
    
    /**
     * 是否为补传数据(设备上传且测量时间和创建时间不匹配)
     * @param obj
     * @param recordDate
     * @param createDate
     * @param deviceSn
     * @param num
     */
    private void judgeIsSupplement(com.alibaba.fastjson.JSONObject obj,String recordDate,String createDate,String deviceSn,String num){
        if ("".equals(deviceSn)){
            obj.put("isSupplement"+num,0);
        }else {
            if (recordDate.compareTo(createDate)==0){
                obj.put("isSupplement"+num,0);
            }else {
                obj.put("isSupplement"+num,1);
            }
        }
    }
    
    private com.alibaba.fastjson.JSONArray getPatientXT_Json1(String patient,Integer page,Integer pageSize) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("user", patient);
        boolean hadData = false;
        /***************** 按时间排序 ***************************/
        
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",DATE_FORMAT(record_date,'%Y-%m-%d') as record_date " +
                ",sort_date" +
                ",min(czrq) czrq " +
                " from device.wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type = 1" +
                " and del = '1' " +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date,id desc limit "+page+","+pageSize;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> item : list) {
                obj.put("type", 1);
                obj.put("czrq", item.get("czrq"));
                obj.put("recordDate", item.get("record_date"));
                obj.put("sortDate", item.get("sort_date"));
                String data = item.get("value1").toString();
                String dataType = item.get("value2").toString();
                String deviceSn = item.get("device_sn") == null ? "" : item.get("device_sn").toString();
                String recordDate = item.get("record_date").toString();
                Long id = Long.parseLong(item.get("id") + "");
                if (data != null && dataType != null) {
                    if (dataType.equals("1")) {
                        obj.put("value1", data);
                        obj.put("time1", recordDate);
                        obj.put("id1", id);
                        obj.put("deviceSn1", deviceSn);
                    } else if (dataType.equals("2")) {
                        obj.put("value2", data);
                        obj.put("time2", recordDate);
                        obj.put("id2", id);
                        obj.put("deviceSn2", deviceSn);
                        
                    } else if (dataType.equals("3")) {
                        obj.put("value3", data);
                        obj.put("time3", recordDate);
                        obj.put("id3", id);
                        obj.put("deviceSn3", deviceSn);
                        
                    } else if (dataType.equals("4")) {
                        obj.put("value4", data);
                        obj.put("time4", recordDate);
                        obj.put("id4", id);
                        obj.put("deviceSn4", deviceSn);
                    } else if (dataType.equals("5")) {
                        obj.put("value5", data);
                        obj.put("time5", recordDate);
                        obj.put("id5", id);
                        obj.put("deviceSn5", deviceSn);
                    } else if (dataType.equals("6")) {
                        obj.put("value6", data);
                        obj.put("time6", recordDate);
                        obj.put("id6", id);
                        obj.put("deviceSn6", deviceSn);
                    } else if (dataType.equals("7")) {
                        obj.put("value7", data);
                        obj.put("time7", recordDate);
                        obj.put("id7", id);
                        obj.put("deviceSn7", deviceSn);
                    }
                    obj.put("healthindexid", id);
                    obj.put("valuedata", data);
                    obj.put("dataType",dataType);
                    array.add(obj);
                }
            }
        }
        return array;
    }
    
    /**
     * 校验指标是否超标,发送消息
     */
    public void verifyHealthIndex(Long id) {
        //指标信息
        DevicePatientHealthIndex data = patientHealthIndexDao.findOne(id);
        String patientCode = data.getUser();
        //患者信息
        BasePatientDO patient = patientDao.findById(patientCode);
        
        int type = data.getType();
        String msgContent = "";
        String oldMsgContent = "";
        //血糖校验
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            Double maxValueBefore = HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = HEALTH_STANDARD_ST_MIN_AFTER;
            int index = Integer.valueOf(data.getValue2());
            String value1 = data.getValue1();
            // 餐后
            if (index % 2 == 0) {
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueAfter, minValueAfter)) {
                    oldMsgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                    if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueAfter ,minValueAfter)==1){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏高</span>";
                    }else if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueAfter ,minValueAfter)==2){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏低</span>";
                    }
                    //体征异常,更新体征数据状态
                    updateStatus(data);
                }
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    oldMsgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L)";
                    if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueBefore ,minValueBefore)==1){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏高</span>";
                    }else if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueBefore ,minValueBefore)==2){
                        msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血糖偏低</span>";
                    }
                    updateStatus(data);
                }
            }
        }
        //血压校验
        else if (type == 2) {
            String value1 = data.getValue1();
            String value2 = data.getValue2();
            // 血压记录,查询患者血压预警值
            Double maxValueSSY = HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = HEALTH_STANDARD_SZY_MIN;
            // 收缩压/舒张压校验
            if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY) || !checkHealthIndex(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)) {
                oldMsgContent = patient.getName() + "血压异常(舒张压 " + value2 + "mmHg、收缩压 " + value1 + "mmHg)";
                if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY)==1||checkHealthIndexDetail(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)==1){
                    msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血压偏高</span>";
                }else if(checkHealthIndexDetail(NumberUtils.toDouble(value1), maxValueSSY, minValueSSY)==2||checkHealthIndexDetail(NumberUtils.toDouble(value2), maxValueSZY, minValueSZY)==2){
                    msgContent = "<a>"+patient.getName()+"</a><span style=\"color: #FF4C4C;\">血压偏低</span>";
                }
                updateStatus(data);
            }
        }
    }
    
    /**
     * 修改体征异常状态
     * @param data
     */
    public void updateStatus(DevicePatientHealthIndex data){
        data.setStatus(1);
        patientHealthIndexDao.save(data);
    }
    
    /**
     * 查询最近的一条体征数据
     * @param sql
     * @param patient
     * @param type
     * @return
     */
    public List<Map<String, Object>> findDataByPatient(String sql,String patient,Integer type){
        return jdbcTemplate.queryForList(sql, patient, type);
    }
    
    /**
     * 患者最近填写的健康指标
     * @param patient
     * @return
     */
    public List<DevicePatientHealthIndex> findRecentByPatientIterable(String patient){
        return patientHealthIndexDao.findRecentByPatient(patient);
    }
    
    /**
     * 根据患者标志获取健康指标
     * @param patient
     * @param type
     * @return
     */
    public DevicePatientHealthIndex findLastByPatienIot(String patient,Integer type){
        return findLastByPatien(patient,type);
    }
    
    /**
     * 查询指标记录
     * @param patient
     * @param startDate
     * @param endDate
     * @param page
     * @param size
     * @return
     */
    public List<String> findDateListIot(String patient,int type,Date startDate,Date endDate, Integer page, Integer size,String start, String end){
        return patientHealthIndexDao.findDateList(patient,type,startDate,endDate,page,size);
    }
    
    
    public List<String> findDateListIot1(String patient,Date startDate,Date endDate, Integer page, Integer size,String start, String end){
        
        return patientHealthIndexDao.findDateList(patient,startDate,endDate,page,size);
    }
    
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @param type
     * @param size
     * @param gi_type
     * @param begin
     * @param end
     * @return
     */
    public List<Map<String, Object>> findByPatientAndTime(String sql,String patient,Integer type,Integer size,Integer gi_type, String begin, String end){
        return jdbcTemplate.queryForList(sql);
    }
    
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @param date
     * @return
     */
    public List<Map<String, Object>> getPatientXT_JsonIot(String sql,String patient, String date){
        return jdbcTemplate.queryForList(sql);
    }
    
    /**
     * 按时间查找
     * @param sql
     * @param patient
     * @return
     */
    public List<Map<String, Object>> getPatientXT_JsonIot(String sql,String patient,Integer type,Integer page,Integer size, String begin,String end){
        return jdbcTemplate.queryForList(sql);
    }
    
    /********************************************物联网 end***********************************************************/
    
    /**
     * 新增患者指标
     * 【血糖】{"time":"2016-09-09 17:00:00","gi":"血糖值(mmol/L)"}
     * 【血压】{"time":"2016-09-09 17:00:00","sys":"收缩压(mmHg)","dia":"舒张压(mmHg)","pul":"脉搏(次/分)","ano":"有无心率不齐0否 1是","user":"身份标识"}
     * 【体重/身高】{"time":"2016-09-09 17:00:00","weight":"体重值(kg)","height":"身高(cm)"}
     * 【腰围】{"time":"2016-09-09 17:00:00","waistline":"腰围值(cm)"}
     *
     * @return
     */
    public DevicePatientHealthIndex addPatientHealthIndex(String data, String type, String patientCode, String deviceSn) throws Exception {
        Map<String, String> map = (Map<String, String>) objectMapper.readValue(data, Map.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        DevicePatientHealthIndex obj = new DevicePatientHealthIndex();
        Date currentTime = new Date();
        obj.setCzrq(currentTime);
        obj.setDel("1");
        obj.setStatus(0);
        Date time = currentTime;
        if (map.containsKey("time")) {
            String da = map.get("time");
//            time = DateUtil.strToDate(da);
            time = sdf.parse(da);
        }
        obj.setRecordDate(time);    //记录时间
        obj.setSortDate(time);      //排序时间
        
        String idcard = "";
        BasePatientDO patient = null;
        if (deviceSn != null && deviceSn.length() > 0)   //设备数据
        {
            obj.setDeviceSn(deviceSn);
            String userType = "-1";
            if (map.containsKey("user")) { //存在身份标识 ,多用户
                userType = map.get("user");
            }
            //根据设备获取患者(不同厂家sn码一样的问题未解决!!)
            PatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
            if (device != null) {
                patientCode = device.getUser();
                patient = patientDao.findById(patientCode);
                idcard = device.getUserIdcard();
            }
            DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
        }
        //自输数据
        else {
            patient = patientDao.findById(patientCode);
            if (patient != null) {
                idcard = patient.getIdcard();
            }
        }
        
        //身份证不为空
        if (patient != null) {
            obj.setUser(patientCode);
            obj.setName(patient.getName());
            obj.setIdcard(idcard);
            
            String msgContent = "";
            // 1血糖 2血压 3体重 4腰围
            switch (type) {
                case "1": {
                    obj.setType(1);
                    String value1 = map.get("gi");  //血糖值
                    String gi_type = map.get("gi_type"); //血糖值类型对应1到7
                    String recordDate = map.get("recordDate");
                    obj.setValue1(value1);
                    obj.setValue2(gi_type);
                    if (StringUtils.isNotBlank(recordDate)) {
                        obj.setRecordDate(DateUtil.strToDateAppendNowTime(recordDate, DateUtil.YYYY_MM_DD_HH_MM_SS));
                    }
                    break;
                }
                case "2": {
                    obj.setType(2);
                    String value1 = map.get("sys");  //收缩压
                    String value2 = map.get("dia");  //舒张压
                    obj.setValue1(value1);
                    obj.setValue2(value2);
                    obj.setValue3(map.get("pul"));     //脉搏
                    obj.setValue4(map.get("ano"));     //有无心率不齐
                    break;
                }
                case "3": {
                    obj.setType(3);
                    
                    String weight = map.get("weight");
                    String height = map.get("height");
                    
                    obj.setValue1(weight); //体重
                    obj.setValue2(height); //身高
                    double bmi = commonUtil.getBMIByWeightAndHeight(map.get("weight"), map.get("height"));
                    DecimalFormat df1 = new DecimalFormat("###.00");
                    obj.setValue3(df1.format(bmi));
                    
                    double bmiMin = new Double("18.5");
                    double bmiMax = new Double("23.9");
                    
                    //设置BMI值
                    if (bmi < bmiMin) {
                        obj.setValue4("1");
                    } else if (bmi > bmiMax) {
                        obj.setValue4("-1");
                    } else {
                        obj.setValue4("0");
                    }
                    break;
                }
                case "4": {
                    obj.setType(4);
                    obj.setValue1(map.get("waistline"));  //腰围
                    obj.setValue2(map.get("hipline"));
                    break;
                }
                default: {
                    throw new Exception("暂不支持该指标!");
                }
            }
            patientHealthIndexDao.save(obj);
        } else {
            throw new Exception("不存在该患者!");
        }
        
        
        return obj;
    }
    
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @param patientCode
     * @param date
     * @return
     */
    public Iterable<DevicePatientHealthIndex> findByPatienDate(String patientCode, int type, Date date) {
        return patientHealthIndexDao.findByPatienDate(patientCode, type, date);
    }
    
    /**
     * 按时间段查询患者健康指标
     *
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
    public JSONArray findChartByPatient(String patient, int type, int gi_type, String begin, String end) {
        JSONArray re = new JSONArray();
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",record_date" +
                ",sort_date" +
                ",min(czrq) czrq " +
                " from device.wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type =" + type +
                " and record_date >= '" + begin + "'" +
                " and record_date <= '" + end + "' " +
                " and del = '1' ";
        String conditionApp = "";
        if (gi_type != 0) {
            conditionApp = " and value2 = '" + gi_type + "' ";
        }
        sql = sql + conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = findByPatientAndTime(sql,patient,type,1000,gi_type,begin,end);
        for (Map<String, Object> map : list) {
            JSONObject json = new JSONObject();
            json.put("id", map.get("id"));
            json.put("patient", map.get("user"));
            json.put("value1", map.get("value1"));
            json.put("value2", map.get("value2"));
            json.put("value3", map.get("value3"));
            json.put("value4", map.get("value4"));
            json.put("value5", map.get("value5"));
            json.put("value6", map.get("value6"));
            json.put("value7", map.get("value7"));
            json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
            json.put("type", map.get("type"));
            
            Date date = (Date) map.get("record_date");
            if (type == 2) {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
            } else {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
            }
            json.put("sortDate", map.get("sort_date"));
            json.put("czrq", map.get("czrq"));
            
            re.put(json);
        }
        return re;
    }
    
    /**
     * 按时间段查询患者健康指标
     *
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
    public com.alibaba.fastjson.JSONObject findChartByPatientIot(String patient, int type, int gi_type, String begin, String end,String time) {
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        com.alibaba.fastjson.JSONArray re = new com.alibaba.fastjson.JSONArray();
        int high = 0;//偏高
        int normal = 0;//正常
        int low = 0;//偏低
        boolean flag = false;//高危标志 true高危。
        
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",record_date" +
                ",sort_date" +
                ",min(czrq) czrq " +
                " from device.wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type =" + type +
                " and record_date >= '" + begin + "'" +
                " and record_date <= '" + end + "' " +
                " and del = '1' ";
        String conditionApp = "";
        if (gi_type != 0) {
            conditionApp = " and value2 = '" + gi_type + "' ";
        }
        sql = sql + conditionApp +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String, Object>> list = findByPatientAndTime(sql,patient,type,1000,gi_type,begin,end);
        for (Map<String, Object> map : list) {
            String value1 = map.get("value1").toString();
            String value2 = map.get("value2").toString();
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("id", map.get("id"));
            json.put("patient", map.get("user"));
            json.put("value1", value1);
            json.put("value2", value2);
            json.put("value3", map.get("value3"));
            json.put("value4", map.get("value4"));
            json.put("value5", map.get("value5"));
            json.put("value6", map.get("value6"));
            json.put("value7", map.get("value7"));
            json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
            json.put("type", map.get("type"));
            
            Date date = (Date) map.get("record_date");
            if (type == 2) {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
            } else {
                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
            }
            json.put("sortDate", map.get("sort_date"));
            json.put("czrq", map.get("czrq"));
            
            
            //统计加指标分析
            int returnInt = 0;
            if(type==1){
                //血糖
                Double maxValueBefore = HEALTH_STANDARD_ST_MAX_BEFORE;
                Double minValueBefore = HEALTH_STANDARD_ST_MIN_BEFORE;
                Double maxValueAfter = HEALTH_STANDARD_ST_MAX_AFTER;
                Double minValueAfter = HEALTH_STANDARD_ST_MIN_AFTER;
                int index = Integer.parseInt(value2);
                Double intVlue1 = NumberUtils.toDouble(value1);
                if(index % 2 == 0){
                    //餐后
                    returnInt = checkHealth(maxValueAfter,minValueAfter,intVlue1);
                    switch (returnInt){
                        case 0:
                            normal++;
                            break;
                        case 1:
                            high++;
                            break;
                        default:
                            low++;
                            break;
                    }
                    if(intVlue1>=maxValueAfter){
                        flag = true;
                    }
                }else {
                    //餐前
                    returnInt = checkHealth(maxValueBefore,minValueBefore,intVlue1);
                    switch (returnInt){
                        case 0:
                            normal++;
                            break;
                        case 1:
                            high++;
                            break;
                        default:
                            low++;
                            break;
                    }
                    if(intVlue1>=maxValueBefore){
                        flag = true;
                    }
                }
            }else if(type==2){
                //血压
                Double intVlue1 = NumberUtils.toDouble(value1);
                Double intVlue2 = NumberUtils.toDouble(value2);
                Double maxValueSSY = HEALTH_STANDARD_SSY_MAX;
                Double minValueSSY = HEALTH_STANDARD_SSY_MIN;
                Double maxValueSZY = HEALTH_STANDARD_SZY_MAX;
                Double minValueSZY = HEALTH_STANDARD_SZY_MIN;
                
                returnInt = checkHealth(maxValueSSY,minValueSSY,intVlue1);
                switch (returnInt){
                    case 0:
                        normal++;
                        break;
                    case 1:
                        high++;
                        if(intVlue1>=maxValueSSY){
                            flag = true;
                        }
                        break;
                    default:
                        low++;
                        break;
                }
                returnInt = checkHealth(maxValueSZY,minValueSZY,intVlue2);
                switch (returnInt){
                    case 0:
                        normal++;
                        break;
                    case 1:
                        high++;
                        if(intVlue2>=maxValueSSY){
                            flag = true;
                        }
                        break;
                    default:
                        low++;
                        break;
                }
            }
            
            re.add(json);
        }
        jsonObject.put("list",re);
        com.alibaba.fastjson.JSONObject total = new com.alibaba.fastjson.JSONObject();
        total.put("high",high);
        total.put("normal",normal);
        total.put("low",low);
        jsonObject.put("total",total);
        String content = "";
        if(high>0){
            content = "居民"+time+"内有"+high+"次指标偏高";
            if(low>0){
                content+=",有"+low+"次指标偏低";
            }else {
                content+="。";
            }
            if(flag){
                content+="居民"+time+"内控制不理想,可能伴有靶器官损害或其他并发症。建议由健管师进行电话随访不少于每月4次,至少每2周面对面随访一次,建议动员居民至医院全科医生就诊,特殊情况建议入户诊疗。病情严重建议转诊专科医师进行进一步治疗。";
            }else {
                content+="居民"+time+"内控制不理想但低于急危值,建议至少每2周面对面随访一次,建议动员居民至医院全科医生就诊,特殊情况建议入户诊疗。病情严重建议转诊专科医师进行进一步治疗。";
            }
        }else if(low>0){
            content = "居民"+time+"内有"+low+"次指标偏低。";
            content+="居民"+time+"内控制不理想但低于急危值,建议至少每2周面对面随访一次,建议动员居民至医院全科医生就诊,特殊情况建议入户诊疗。病情严重建议转诊专科医师进行进一步治疗。";
        }else {
            content = "居民"+time+"内指标没有异常。居民"+time+"内相对稳定,建议至少每周面对面随访一次,全科医生根据居民情况安排预约转诊专科医师,并跟踪治疗情况。";
        }
        jsonObject.put("content",content);
        
        return jsonObject;
    }
    
    /**
     * 指标验证
     * @param max
     * @param min
     * @param value
     * @return -1偏低,0正常,1偏高
     */
    private Integer checkHealth(Double max,Double min,Double value){
        if(max<value){
            return 1;
        }else if(min>value){
            return -1;
        }else {
            return 0;
        }
    }
    
    /**
     * 查询指标记录
     *
     * @param patient
     * @param type
     * @param start
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    public JSONArray findIndexByPatient(String patient, int type, String start, String end, int page, int pageSize) {
        JSONArray re = new JSONArray();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
        
        } else {
            // 排序
            Sort sort = new Sort(Direction.DESC, "recordDate");
            PageRequest pageRequest = new PageRequest(page, pageSize, sort);
            String sql = "SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",czrq as createDate" +
                    ",min(czrq) czrq " +
                    " from device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and record_date >= '" + start + "'" +
                    " and record_date <= '" + end + "' " +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
//            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> list = getPatientXT_JsonIot(sql,patient,type,pageRequest.getOffset(),pageRequest.getPageSize(),start,end);
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
                json.put("id", map.get("id"));
                json.put("healthindexid", map.get("id"));
                json.put("patient", map.get("user"));
                json.put("value1", map.get("value1"));
                json.put("value2", map.get("value2"));
                json.put("value3", map.get("value3"));
                json.put("value4", map.get("value4"));
                json.put("value5", map.get("value5"));
                json.put("value6", map.get("value6"));
                json.put("value7", map.get("value7"));
                json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
                json.put("type", map.get("type"));
                
                Date date = (Date) map.get("record_date");
                if (type == 2) {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
                } else {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
                }
                json.put("sortDate", map.get("sort_date"));
                json.put("czrq", map.get("czrq"));
                
                //是否为补传数据(设备上传且测量时间和创建时间不匹配)
                Date recordDate = (Date)map.get("record_date");
                Date createDate = (Date) map.get("createDate");
                String recordTime = DateUtil.dateToStr(recordDate,DateUtil.YYYY_MM_DD);
                String createTime = DateUtil.dateToStr(createDate,DateUtil.YYYY_MM_DD);
                if (map.get("device_sn") == null){
                    json.put("isSupplement",0);
                }else {
                    if (recordTime.compareToIgnoreCase(createTime)==0){
                        json.put("isSupplement",0);
                    }else {
                        json.put("isSupplement",1);
                    }
                }
                
                re.put(json);
            }
        }
        return re;
    }
    
    public JSONObject findIndexByPatient1(String patient, int type,int page, int pageSize) {
        JSONArray re = new JSONArray();
        JSONObject object = new JSONObject();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
        
        } else {
            // 排序
            Sort sort = new Sort(Direction.DESC, "recordDate");
            PageRequest pageRequest = new PageRequest(page, pageSize, sort);
            String sql = "SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
            String sqlCount = "select count(1) as total from (SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc) phi ";
//            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String,Object>> rstotal2 = jdbcTemplate.queryForList(sqlCount);
            Long taskCount = 0L;
            if(rstotal2!=null&&rstotal2.size()>0){
                Object object1 = rstotal2.get(0).get("total");
                if (object1 != null ){
                    taskCount = Long.parseLong(object1.toString());
                }
            }
            object.put("totalCount",taskCount);
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
                json.put("id", map.get("id"));
                json.put("healthindexid", map.get("id"));
                json.put("patient", map.get("user"));
                json.put("value1", map.get("value1"));
                json.put("value2", map.get("value2"));
                json.put("value3", map.get("value3"));
                json.put("value4", map.get("value4"));
                json.put("value5", map.get("value5"));
                json.put("value6", map.get("value6"));
                json.put("value7", map.get("value7"));
                json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
                json.put("type", map.get("type"));
                
                Date date = (Date) map.get("record_date");
                if (type == 2) {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
                } else {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
                }
                json.put("sortDate", map.get("sort_date"));
                json.put("czrq", map.get("czrq"));
                
                re.put(json);
            }
        }
        object.put("pageSize",pageSize);
        object.put("currPage",page+1);
        object.put("detailModelList",re);
        return object;
    }
    
    
    /**
     * 查询指标记录
     *
     * @param patient
     * @param type
     * @param start
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    public List<Object> findIndexByPatient2(String patient, int type, String start, String end, int page, int pageSize) {
        List<Object> re = new ArrayList<>();
        if (page > 0) {
            page = page - 1;
        }
        
        Date startDate = DateUtil.strToDate(start, DateUtil.YYYY_MM_DD_HH_MM_SS);
        Date endDate = DateUtil.strToDate(end, DateUtil.YYYY_MM_DD_HH_MM_SS);
        if (type == 1)   //血糖特殊处理
        {
            PageRequest pageRequest = new PageRequest(page, pageSize);
            //根据时间过滤排序
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            List<String> dateList = findDateListIot(patient,type, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize(), start, end);
            if (dateList != null && dateList.size() > 0) {
                for (String dateString : dateList) {
                    com.alibaba.fastjson.JSONObject obj = getPatientXT_Json(patient, dateString);
                    if (obj != null) {
                        re.add(obj);
                    }
                }
            }
        } else {
            // 排序
            
        }
        return re;
    }
    
    
    public JSONObject findIndexByPatient3(String patient, int type,int page, int pageSize) {
        List<Object> re = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        if (page > 0) {
            page = page - 1;
        }
        
        if (type == 1)   //血糖特殊处理
        {
            PageRequest pageRequest = new PageRequest(page, pageSize);
            jsonObject.put("currPage",page+1);
            com.alibaba.fastjson.JSONArray array = getPatientXT_Json1(patient, pageRequest.getOffset(), pageRequest.getPageSize());
            jsonObject.put("detailModelList",array);
            //根据时间过滤排序
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            String sql = "select count(1) as total from (SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type = 1" +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date,id desc ) phi";
            List<Map<String,Object>> rstotal2 = jdbcTemplate.queryForList(sql);
            Long taskCount = 0L;
            if(rstotal2!=null&&rstotal2.size()>0){
                Object object1 = rstotal2.get(0).get("total");
                if (object1 != null ){
                    taskCount = Long.parseLong(object1.toString());
                }
            }
            jsonObject.put("totalCount",taskCount);
            
        } else {
            // 排序
            
        }
        
        jsonObject.put("pageSize",pageSize);
        
        return jsonObject;
    }
    
    /**
     * 查询患者最近填写的血糖、血压等记录
     *
     * @param patient
     * @return
     */
    public JSONArray findRecentByPatient(String patient) {
        JSONArray array = new JSONArray();
        List<DevicePatientHealthIndex> iterable = patientHealthIndexDao.findRecentByPatient(patient);
        if (iterable != null) {
            Iterator<DevicePatientHealthIndex> iterator = iterable.iterator();
            while (iterator != null && iterator.hasNext()) {
                DevicePatientHealthIndex phi = iterator.next();
                if (phi == null) {
                    continue;
                }
                JSONObject json = new JSONObject();
                // 设置健康指标类型(1血糖,2血压,3体重,4腰围)
                json.put("type", phi.getType());
                if (1 == phi.getType() && StringUtils.isNotBlank(phi.getValue2())) {
                    int gi_type = Integer.parseInt(phi.getValue2());
                    switch (gi_type) {
                        case 1:
                            // 设置血糖/收缩压/体重/腰围/早餐前空腹
                            json.put("value1", phi.getValue1());
                            json.put("time1", phi.getRecordDate());
                            break;
                        case 2:
                            // 设置舒张压/早餐后血糖
                            json.put("value2", phi.getValue2());
                            json.put("time2", phi.getRecordDate());
                            break;
                        case 3:
                            // 设置午餐前血糖
                            json.put("value3", phi.getValue3());
                            json.put("time3", phi.getRecordDate());
                            break;
                        case 4:
                            // 设置午餐后血糖
                            json.put("value4", phi.getValue4());
                            json.put("time4", phi.getRecordDate());
                            break;
                        case 5:
                            // 设置晚餐前血糖
                            json.put("value5", phi.getValue5());
                            json.put("time5", phi.getRecordDate());
                            break;
                        case 6:
                            // 设置晚餐后血糖
                            json.put("value6", phi.getValue6());
                            json.put("time6", phi.getRecordDate());
                            break;
                        case 7:
                            // 设置睡前血糖
                            json.put("value7", phi.getValue7());
                            json.put("time7", phi.getRecordDate());
                            break;
                    }
                } else {
                    json.put("value1", phi.getValue1());
                    json.put("value2", phi.getValue2());
                    // 设置午餐前血糖
                    json.put("value3", phi.getValue3());
                    // 设置午餐后血糖
                    json.put("value4", phi.getValue4());
                    // 设置晚餐前血糖
                    json.put("value5", phi.getValue5());
                    // 设置晚餐后血糖
                    json.put("value6", phi.getValue6());
                    // 设置睡前血糖
                    json.put("value7", phi.getValue7());
                }
                
                
                json.put("date", DateUtil.dateToStrShort(phi.getRecordDate()));
                array.put(json);
            }
        }
        return array;
    }
    
    /**
     * 根据患者标志获取健康指标
     *
     * @param patientCode 患者标志
     * @return 健康指标列表
     */
    public DevicePatientHealthIndex findLastByPatien(String patientCode, int type) {
        //最新血糖指标
        if (type == 1) {
            DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode, 1);
            return obj;
        } else if (type == 2) {  //其他指标
            return patientHealthIndexDao.findLastData(patientCode, 2);
        } else {
            return patientHealthIndexDao.findLastData(patientCode, type);
        }
    }
    
    /**
     * 获取患者健康指标历史记录
     * 1血糖,2血压,3体重,4腰围
     */
    public List<Map<String, String>> getHealthIndexHistory(String patientCode, int type, int page, int pagesize) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        
        // 排序
        Sort sort = new Sort(Direction.DESC, "recordDate");
        PageRequest pageRequest = new PageRequest(page, pagesize, sort);
        List<DevicePatientHealthIndex> list = patientHealthIndexDao.findIndexByPatient(patientCode, type, pageRequest);
        
        if (list != null && list.size() > 0) {
            for (DevicePatientHealthIndex item : list) {
                Map<String, String> map = new HashMap<>();
                if (type == 1)    //血糖
                {
                    String gi = item.getValue1();
                    String giType = item.getValue2();
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("gi", gi); //  血糖值
                    map.put("gi_type", giType); //  血糖值类型
                    String text = gi + " mmol/L";
                    if ("1".equals(giType)) {
                        text += "(早餐前)";
                    } else if ("2".equals(giType)) {
                        text += "(早餐后)";
                    } else if ("3".equals(giType)) {
                        text += "(午餐前)";
                    } else if ("4".equals(giType)) {
                        text += "(午餐后)";
                    } else if ("5".equals(giType)) {
                        text += "(晚饭前)";
                    } else if ("6".equals(giType)) {
                        text += "(晚饭后)";
                    } else if ("7".equals(giType)) {
                        text += "(睡前)";
                    }
                    map.put("text", text); //  展示
                    re.add(map);
                } else if (type == 2) //血压
                {
                    String sys = item.getValue1();   //收缩压
                    String dia = item.getValue2();    //舒张压
                    String pul = item.getValue3();    //脉搏
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("sys", sys);
                    map.put("dia", dia);
                    map.put("pul", pul);
                    re.add(map);
                } else if (type == 3) //体重
                {
                    String weight = item.getValue1();   //体重
                    String height = item.getValue2();   //身高
                    String bmi = item.getValue3();      //BMI
                    map.put("time", DateUtil.dateToStrShort(item.getRecordDate()));
                    map.put("weight", weight);
                    map.put("height", height);
                    map.put("bmi", bmi);
                    map.put("text", weight + " kg");
                    re.add(map);
                }
            }
        }
        
        return re;
    }
    
    public List<Map<String, String>> getHealthIndexByPatientAndDate(String patientCode, String deviceSn, String choseDate,int type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        
        // 排序
        Sort sort = new Sort(Direction.DESC, "recordDate");
        List<DevicePatientHealthIndex> list = new ArrayList<>();
        
        if(choseDate.length() == 7){
            list = patientHealthIndexDao.findByDateMonthAndType(type,patientCode,choseDate,deviceSn);
        }else{
            list = patientHealthIndexDao.findByDateAndType(type,patientCode,choseDate,deviceSn);
        }
        
        if (list != null && list.size() > 0) {
            for (DevicePatientHealthIndex item : list) {
                Map<String, String> map = new HashMap<>();
                if (type == 1)    //血糖
                {
                    String gi = item.getValue1();
                    String giType = item.getValue2();
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("gi", gi); //  血糖值
                    map.put("gi_type", giType); //  血糖值类型
                    String text = gi + " mmol/L";
                    if ("1".equals(giType)) {
                        text += "(早餐前)";
                    } else if ("2".equals(giType)) {
                        text += "(早餐后)";
                    } else if ("3".equals(giType)) {
                        text += "(午餐前)";
                    } else if ("4".equals(giType)) {
                        text += "(午餐后)";
                    } else if ("5".equals(giType)) {
                        text += "(晚饭前)";
                    } else if ("6".equals(giType)) {
                        text += "(晚饭后)";
                    } else if ("7".equals(giType)) {
                        text += "(睡前)";
                    }
                    map.put("text", text); //  展示
//                    re.add(map);
                } else if (type == 2) //血压
                {
                    String sys = item.getValue1();   //收缩压
                    String dia = item.getValue2();    //舒张压
                    String pul = item.getValue3();    //脉搏
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("sys", sys);
                    map.put("dia", dia);
                    map.put("pul", pul);
//                    re.add(map);
                } else if (type == 3) //体重
                {
                    String weight = item.getValue1();   //体重
                    String height = item.getValue2();   //身高
                    String bmi = item.getValue3();      //BMI
                    map.put("time", DateUtil.dateToStrShort(item.getRecordDate()));
                    map.put("weight", weight);
                    map.put("height", height);
                    map.put("bmi", bmi);
                    map.put("text", weight + " kg");
//                    re.add(map);
                }else if(type == 4){
                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
                    map.put("value1", item.getValue1());
                    map.put("value2", item.getValue2());
                }
                map.put("type", item.getType().toString());
                re.add(map);
            }
        }
        
        return re;
    }
    public DevicePatientHealthIndex getHealthIndexById(Long id) {
        return patientHealthIndexDao.findOne(id);
    }
}

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

@ -0,0 +1,211 @@
package com.yihu.jw.care.util;
import it.sauronsoftware.jave.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
@Component
public class CommonUtil {
    private Logger logger = LoggerFactory.getLogger(CommonUtil.class);
    public String getIdcardEncode(String idcard) {
        if (idcard != null) {
            if (idcard.length() == 18) {
                return idcard.substring(0, 9) + "*******" + idcard.substring(16, 18);
            } else if (idcard.length() == 15) {
                return idcard.substring(0, 8) + "***" + idcard.substring(11, 15);
            }
        }
        return idcard;
    }
    /**
     * 对象转数组
     *
     * @param obj
     * @return
     */
    public byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }
    /**
     * 数组转对象
     *
     * @param bytes
     * @return
     */
    public Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
    /**
     * double转字符串,在转int
     * double*100转int 有bug 34.3会会变成3429
     *
     * @param d
     * @return
     */
    public static Integer doubleToInt(Double d) {
        if (d == null) {
            return 0;
        }
        String currency = String.valueOf(d);
        int index = currency.indexOf(".");
        int length = currency.length();
        Integer amLong = 0;
        if (index == -1) {
            amLong = Integer.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Integer.valueOf((currency.substring(0, index + 3)).replace(".", ""));
            if (length - index > 3) {
                if (Integer.valueOf(currency.substring(index + 3, index + 4)) >= 5) {
                    amLong++;
                }
            }
        } else if (length - index == 2) {
            amLong = Integer.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Integer.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong;
    }
    /**
     * 校验健康指标是否正常
     *
     * @param curValue    当前值
     * @param standardMax 最大标准值
     * @param standardMin 最小标准值
     * @return 0正常,1高,-1低
     */
    public double checkHealthIndex(double curValue, double standardMax, double standardMin) {
        if (curValue <= 0) {
            return 0;
        }
        if (standardMax > 0 && curValue > standardMax) {
            return curValue;
        }
        return 0;
    }
    public void changeToMp3(String sourcePath, String targetPath) {
        File source = new File(sourcePath);
        File target = new File(targetPath);
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }
    /**
     * 传入身高体重,计算BMI值
     *
     * @param weightStr 体重
     * @param heightStr 身高
     * @return
     */
    public double getBMIByWeightAndHeight(String weightStr, String heightStr) {
        DecimalFormat df2 = new DecimalFormat("###.00");
        double weight = Double.parseDouble(weightStr);
        Integer heightCM = Integer.parseInt(heightStr);
        heightStr = df2.format(heightCM / 100d);
        double height = Double.parseDouble(heightStr);
        double bmi = weight / (height * height);
        return bmi;
    }
    public String request(String remote_url, MultipartFile file, String type) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        logger.info(file.getOriginalFilename());
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            if (!org.springframework.util.StringUtils.isEmpty(type)) {
                builder.addTextBody("type", type); //发送类型
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

+ 143 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/ConcealUtil.java

@ -0,0 +1,143 @@
package com.yihu.jw.care.util;
/**
 * 数据脱敏工具
 * Created by zdm on 2019/4/2.
 */
public class ConcealUtil {
    private static final int SIZE = 6;
    private static final String SYMBOL = "*";
    /**
     * 电话号码脱敏,达到保密效果
     *
     * @param userName 用户名
     * @return 替换后的用户名
     */
    public static String phoneConceal(String userName) {
        String userNameAfterReplaced = "";
        if (userName == null) {
            userName = "";
        }
        int nameLength = userName.length();
        if (nameLength <= 1) {
            userNameAfterReplaced = "*";
        } else if (nameLength == 2) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{0})\\d(?=\\d{1})");
        } else if (nameLength >= 3 && nameLength <= 6) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{1})\\d(?=\\d{1})");
        } else if (nameLength >= 7 && nameLength <= 10) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{3})\\d(?=\\d{3})");
        } else if (nameLength >= 11) {
            userNameAfterReplaced = replaceAction(userName, "(?<=\\d{3})\\d(?=\\d{4})");
        }
        return userNameAfterReplaced;
    }
    /**
     * 实际替换动作
     *
     * @param username username
     * @param regular  正则
     * @return
     */
    private static String replaceAction(String username, String regular) {
        return username.replaceAll(regular, "*");
    }
    /**
     * 身份证号替换,保留前四位和后四位
     * <p>
     * 如果身份证号为空 或者 null ,返回null ;否则,返回替换后的字符串;
     *
     * @param idCard 身份证号
     * @return
     */
    public static String idCardConceal(String idCard) {
        if (idCard.isEmpty() || idCard == null) {
            return null;
        } else {
            return replaceAction(idCard, "(?<=\\d{6})\\d(?=\\d{4})");
        }
    }
    /**
     * 银行卡替换,保留后四位
     * <p>
     * 如果银行卡号为空 或者 null ,返回null ;否则,返回替换后的字符串;
     *
     * @param bankCard 银行卡号
     * @return
     */
    public static String bankCardConceal(String bankCard) {
        if (bankCard.isEmpty() || bankCard == null) {
            return null;
        } else {
            return replaceAction(bankCard, "(?<=\\d{0})\\d(?=\\d{4})");
        }
    }
    /**
     * 姓名及地址脱敏
     * @param value
     * @return
     */
    public static String nameOrAddrConceal(String value) {
        if (null == value || "".equals(value)) {
            return value;
        }
        int len = value.length();
        int pamaone = len / 2;
        int pamatwo = pamaone - 1;
        int pamathree = len % 2;
        StringBuilder stringBuilder = new StringBuilder();
        if (len <= 2) {
            if (pamathree == 1) {
                return SYMBOL;
            }
            stringBuilder.append(value.charAt(0));
            stringBuilder.append(SYMBOL);
        } else {
            if (pamatwo <= 0) {
                stringBuilder.append(value.substring(0, 1));
                stringBuilder.append(SYMBOL);
                stringBuilder.append(value.substring(len - 1, len));
            } else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
                int pamafive = (len - SIZE) / 2;
                stringBuilder.append(value.substring(0, pamafive));
                for (int i = 0; i < SIZE; i++) {
                    stringBuilder.append(SYMBOL);
                }
                if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) {
                    stringBuilder.append(value.substring(len - pamafive, len));
                } else {
                    stringBuilder.append(value.substring(len - (pamafive + 1), len));
                }
            } else {
                int pamafour = len - 2;
                stringBuilder.append(value.substring(0, 1));
                for (int i = 0; i < pamafour; i++) {
                    stringBuilder.append(SYMBOL);
                }
                stringBuilder.append(value.substring(len - 1, len));
            }
        }
        return stringBuilder.toString();
    }
/*    public static void main(String[] args) throws IOException {
        String strName= nameOrAddrConceal("张三");
        System.out.println(strName);
        String addr= nameOrAddrConceal("厦门市");
        System.out.println(addr);
        String idcard= idCardConceal("350825199012033283");
        System.out.println(idcard);
        String phone= phoneConceal("17689202624");
        System.out.println(phone);
    }*/
}

+ 81 - 0
svr/svr-cloud-care/src/main/java/com/yihu/jw/care/util/MyJdbcTemplate.java

@ -0,0 +1,81 @@
package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * @author yeshijie on 2018/2/12.
 */
@Component
public class MyJdbcTemplate {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * jdbc查询返回json
     * @param sql
     * @param args
     * @return
     * @throws DataAccessException
     */
    public List<JSONObject> queryJson(String sql, Object[] args) throws DataAccessException {
        return jdbcTemplate.query(sql, args, new ResultSetExtractor<List<JSONObject>>() {
            @Override
            public List<JSONObject> extractData(ResultSet rs) throws SQLException, DataAccessException {
                ResultSetMetaData rsd = rs.getMetaData();
                int clength = rsd.getColumnCount();
                List<JSONObject> li = new ArrayList<JSONObject>();
                try {
                    while (rs.next()) {
                        JSONObject jo = new JSONObject();
                        for (int i = 0; i < clength; i++) {
                            String columnName = rsd.getColumnLabel(i + 1);
                            jo.put(columnName, rs.getObject(i + 1));
                        }
                        li.add(jo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return li;
            }
        });
    }
    public List<JSONObject> queryJson(String sql) throws DataAccessException {
        return jdbcTemplate.query(sql, new ResultSetExtractor<List<JSONObject>>() {
            @Override
            public List<JSONObject> extractData(ResultSet rs) throws SQLException, DataAccessException {
                ResultSetMetaData rsd = rs.getMetaData();
                int clength = rsd.getColumnCount();
                List<JSONObject> li = new ArrayList<JSONObject>();
                try {
                    while (rs.next()) {
                        JSONObject jo = new JSONObject();
                        for (int i = 0; i < clength; i++) {
                            String columnName = rsd.getColumnLabel(i + 1);
                            jo.put(columnName, rs.getObject(i + 1));
                        }
                        li.add(jo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return li;
            }
        });
    }
}