Browse Source

Merge branch 'dev' of yeshijie/patient-co-management into dev

yeshijie 7 years ago
parent
commit
b2e5435b7a

+ 29 - 0
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/common/dao/SystemDictDao.java

@ -0,0 +1,29 @@
package com.yihu.hos.device.common.dao;
import com.yihu.hos.device.model.SystemDict;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2016/8/13.
 */
public interface SystemDictDao extends PagingAndSortingRepository<SystemDict, Long>, JpaSpecificationExecutor<SystemDict> {
    @Query("from SystemDict s where s.dictName=?1 order by sort asc ")
    List<SystemDict> findByDictName(String name);
    @Query("select s.value from SystemDict s where s.dictName=?1 and s.code =?2")
    String findByDictNameAndCode(String dictName, String code);
    @Query(" from SystemDict s where s.dictName=?1 and s.value =?2")
    SystemDict findByDictNameAndValue(String dictName, String value);
    @Query("select s from SystemDict s where s.value like ?1 ")
    List<SystemDict> findByLikeName(String name);
    @Query("select s from SystemDict s where s.dictName like ?1 ")
    List<SystemDict> findByLikeDictName(String name);
}

+ 100 - 0
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/model/SystemDict.java

@ -0,0 +1,100 @@
package com.yihu.hos.device.model;
import javax.persistence.*;
/**
 * SystemDict entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "system_dict")
public class SystemDict implements java.io.Serializable {
	// Fields
	private String dictName;
	private String code;
	private String value;
	private String pyCode;
	private Integer sort;
	private Integer id;
	// Constructors
	/** default constructor */
	public SystemDict() {
	}
	/** minimal constructor */
	public SystemDict(String dictName, String code, String value) {
		this.dictName = dictName;
		this.code = code;
		this.value = value;
	}
	// Property accessors
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	/** full constructor */
	public SystemDict(String dictName, String code, String value,
                      String pyCode, Integer sort) {
		this.dictName = dictName;
		this.code = code;
		this.value = value;
		this.pyCode = pyCode;
		this.sort = sort;
	}
	@Column(name = "dict_name", nullable = false, length = 50)
	public String getDictName() {
		return this.dictName;
	}
	public void setDictName(String dictName) {
		this.dictName = dictName;
	}
	@Column(name = "code", nullable = false, length = 50)
	public String getCode() {
		return this.code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	@Column(name = "value", nullable = false, length = 50)
	public String getValue() {
		return this.value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	@Column(name = "py_code", length = 50)
	public String getPyCode() {
		return this.pyCode;
	}
	public void setPyCode(String pyCode) {
		this.pyCode = pyCode;
	}
	@Column(name = "sort")
	public Integer getSort() {
		return this.sort;
	}
	public void setSort(Integer sort) {
		this.sort = sort;
	}
}

+ 25 - 106
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/DeviceService.java

@ -35,8 +35,8 @@ public class DeviceService extends BaseService{
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientHealthIndexDao patientHealthIndexDao;
//    @Autowired
//    private PatientHealthIndexDao patientHealthIndexDao;
    /*@Autowired
    private BloodSuggerConfiguration bloodSuggerConfiguration;*/
    @Autowired
@ -79,6 +79,8 @@ public class DeviceService extends BaseService{
    private PatientAimBloodSuggerDao patientAimBloodSuggerDao;
    @Autowired
    private PatientAimBloodPressureDao patientAimBloodPressureDao;
    @Autowired
    private IotDeviceService iotDeviceService;
    private ObjectMapper objectMapper = new ObjectMapper();
    private Integer aStart;
@ -507,8 +509,10 @@ public class DeviceService extends BaseService{
            List<PatientHealthIndex> bloodPressurepatientHealthIndices = new ArrayList<>();
            List<PatientHealthIndex> bloodSuggurpatientHealthIndices = new ArrayList<>();
            bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,2);
            bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,1);
//            bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,2);
//            bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,1);
            bloodPressurepatientHealthIndices = iotDeviceService.findByPatientAndTypeByPage(patientCode,2);
            bloodSuggurpatientHealthIndices = iotDeviceService.findByPatientAndTypeByPage(patientCode,1);
            if(!bloodPressurepatientHealthIndices.isEmpty()){
                stdbloodPressureBbnormalCount = bloodPressurepatientHealthIndices.size();
@ -538,7 +542,8 @@ public class DeviceService extends BaseService{
                Date end = new Date();
                Date start = DateUtil.setDateTime(end,-7);
                //计算血糖或者血压一周内的异常记录数量
                int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start,end,1,patientCode);
//                int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start,end,1,patientCode);
                int errorCount = iotDeviceService.getCountByTimeAndStatus(start,end,1,patientCode);
                if(errorCount >= 5){//超过5次,记为预警状态
                    patient.setStandardStatus(1);
                    //1.4.2加入重点关注逻辑
@ -776,7 +781,8 @@ public class DeviceService extends BaseService{
                    value1 = value[0];     //收缩压
                }
            }
            List<PatientHealthIndex> list = patientHealthIndexDao.findByType(device.getUser(),deviceSn,value1,Integer.parseInt(type),time);
//            List<PatientHealthIndex> list = patientHealthIndexDao.findByType(device.getUser(),deviceSn,value1,Integer.parseInt(type),time);
            List<PatientHealthIndex> list = iotDeviceService.findByType(device.getUser(),deviceSn,value1,Integer.parseInt(type),time);
            if(list!=null&&list.size()>0){
                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setDeviceData(json.toString());
@ -833,7 +839,8 @@ public class DeviceService extends BaseService{
                default:
                    throw new Exception("Can not support the metric!");
            }
            obj = patientHealthIndexDao.save(obj);
//            obj = patientHealthIndexDao.save(obj);
            obj = iotDeviceService.save(obj);
            return obj;
        } else {
            DeviceInfo deviceInfo = new DeviceInfo();
@ -909,7 +916,8 @@ public class DeviceService extends BaseService{
            throw new Exception("This device is not relate patient!");
        }
        patientHealthIndexDao.save(obj);
//        patientHealthIndexDao.save(obj);
        iotDeviceService.save(obj);
        return obj;
    }
@ -956,16 +964,18 @@ public class DeviceService extends BaseService{
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L),请处理";
                    //体征异常,更新体征数据状态
                    data.setStatus(1);
                    patientHealthIndexDao.save(data);
//                    data.setStatus(1);
//                    patientHealthIndexDao.save(data);
                    iotDeviceService.updateStatus(data);
                }
            } else { //餐前
                if (!checkHealthIndex(NumberUtils.toDouble(value1), maxValueBefore, minValueBefore)) {
                    msgContent += patient.getName() + "血糖异常(" + value1 + "mmol/L),请处理";
                    //体征异常,更新体征数据状态
                    data.setStatus(1);
                    patientHealthIndexDao.save(data);
//                    data.setStatus(1);
//                    patientHealthIndexDao.save(data);
                    iotDeviceService.updateStatus(data);
                }
            }
        }
@ -998,8 +1008,9 @@ public class DeviceService extends BaseService{
                msgContent = patient.getName() + "血压异常(舒张压 " + value2 + "mmHg、收缩压 " + value1 + "mmHg),请处理";
                //体征异常,更新体征数据状态
                data.setStatus(1);
                patientHealthIndexDao.save(data);
//                data.setStatus(1);
//                patientHealthIndexDao.save(data);
                iotDeviceService.updateStatus(data);
            }
        }
@ -1205,96 +1216,4 @@ public class DeviceService extends BaseService{
        }
    }
    /******************************体征上传 start**************************************************/
    private String bloodSugarUnit = "mmol/L";
    private String bloodPressureUnit = "mmHg";
    private String pulseUnit = "bpm";
    private String heightUnit = "cm";
    private String weightUnit = "kg";
    private String bmiUnit = "kg/m^2";
    private String waistUnit = "cm";
    public void upload(PatientDevice patientDevice,PatientHealthIndex obj,String userType){
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        if(patientDevice!=null){
            //未绑定居民
            Patient patient = patientDao.findByCode(patientDevice.getUser());
            json.put("idcard",patient.getIdcard());
            json.put("username",patient.getName());
            json.put("usercode",patient.getCode());
            json.put("device_name",patientDevice.getDeviceName());
            json.put("device_model",patientDevice.getDeviceName());
        }
        json.put("sn",obj.getDeviceSn());
        json.put("ext_code",userType);
        com.alibaba.fastjson.JSONArray jsonArray = new com.alibaba.fastjson.JSONArray();
        com.alibaba.fastjson.JSONObject js = new com.alibaba.fastjson.JSONObject();
        js.put("measure_time",obj.getRecordDate());
        switch (obj.getType()){
            case 1:
                //血糖
                js.put("blood_sugar",obj.getValue1());
                js.put("blood_sugar_unit",bloodSugarUnit);
                js.put("blood_sugar_result",obj.getValue2());
                break;
            case 2:
                //血压
                js.put("systolic",obj.getValue1());
                js.put("systolic_unit",bloodPressureUnit);
                js.put("diastolic",obj.getValue2());
                js.put("diastolic_unit",bloodPressureUnit);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    js.put("pulse",obj.getValue3());
                    js.put("pulse_unit",pulseUnit);
                }
                break;
            case 3:
                //体重/身高/BMI
                js.put("height",obj.getValue1());
                js.put("height_unit",heightUnit);
                js.put("weight",obj.getValue2());
                js.put("weight_unit",weightUnit);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    js.put("bmi",obj.getValue3());
                    js.put("bmi_unit",bmiUnit);
                }
                break;
            case 4:
                //腰围
                js.put("waist",obj.getValue1());
                js.put("waist_unit",waistUnit);
                break;
            default:
                break;
        }
        jsonArray.add(js);
        json.put("data",jsonArray);
        try {
            String url = wlyyService + "/iot/upload";
            Map<String, Object> params = new HashedMap();
            params.put("jsonStr", json.toString());
            HttpResponse response = httpHelper.post(url, params);
            if (response != null && response.getStatusCode() == 200) {
                JSONObject jsonObject = JSONObject.fromObject(response.getBody());
                if (!"200".equals(jsonObject.optString("status"))) {
                    throw new Exception(jsonObject.optString("msg"));
                }
            } else {
                throw new Exception("接口调用错误!" + response.getBody());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /******************************体征上传 end****************************************************/
}

+ 270 - 0
patient-co-service/wlyy_device/src/main/java/com/yihu/hos/device/service/IotDeviceService.java

@ -0,0 +1,270 @@
package com.yihu.hos.device.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.device.common.dao.PatientDao;
import com.yihu.hos.device.common.dao.PatientHealthIndexDao;
import com.yihu.hos.device.common.dao.SystemDictDao;
import com.yihu.hos.device.common.http.HttpHelper;
import com.yihu.hos.device.common.http.HttpResponse;
import com.yihu.hos.device.common.util.DateUtil;
import com.yihu.hos.device.model.PatientHealthIndex;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * @author yeshijie on 2018/1/26.
 */
@Service
public class IotDeviceService extends BaseService{
    private static Logger logger = LoggerFactory.getLogger(IotDeviceService.class);
    @Value("${systemConfig.server_url}")
    private String wlyyService;
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private PatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private HttpHelper httpHelper;
    @Autowired
    private PatientDao patientDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 判断是否数据上传到物联网
     * @return
     */
    public Boolean isUploadIot(){
        String value = systemDictDao.findByDictNameAndCode("SYSTEM_PARAMS","DEVICE_UPLOAD_IOT");
        return "1".equals(value)?true:false;
    }
    /**
     * 修改体征异常状态
     * @param data
     */
    public void updateStatus(PatientHealthIndex data){
        if(isUploadIot()){
            //物联网更新
            updateStatus(data.getId(),"1");
        }else {
            data.setStatus(1);
            patientHealthIndexDao.save(data);
        }
    }
    /**
     * 按id查找体征记录
     * @param id
     * @return
     */
    public PatientHealthIndex findOne(Long id){
        if(isUploadIot()){
            return getById(id);
        }else {
            return patientHealthIndexDao.findOne(id);
        }
    }
    /**
     * 体征保存
     * @param data
     * @return
     */
    public PatientHealthIndex save(PatientHealthIndex data){
        if(isUploadIot()){
            return saveDevice(data);
        }else {
            return patientHealthIndexDao.save(data);
        }
    }
    /**
     * 按类型查找最近5次的体征记录
     * @param patientCode
     * @param type
     * @return
     */
    public List<PatientHealthIndex> findByPatientAndTypeByPage(String patientCode, Integer type){
        if(isUploadIot()){
            return findByPatientAndType(patientCode,type);
        }else {
            return patientHealthIndexDao.findByPatientAndTypeByPage(patientCode,type);
        }
    }
    /**
     * 统计时间段内的体征异常次数
     * @param start
     * @param end
     * @param status
     * @param patientCode
     * @return
     */
    public int getCountByTimeAndStatus(Date start,Date end,Integer status,String patientCode){
        if(isUploadIot()){
            return getCountByTimeAndStatusAndPatient(start,end,status,patientCode);
        }else {
            return patientHealthIndexDao.getCountByTimeAndStatus(start,end,status,patientCode);
        }
    }
    /**
     * 查找重复数据
     * @param user
     * @param deviceSn
     * @param value1
     * @param type
     * @param time
     * @return
     */
    public List<PatientHealthIndex> findByType(String user,String deviceSn,String value1,Integer type,Date time){
        if(isUploadIot()){
            return findRepeat(user,deviceSn,value1,type,time);
        }else {
            return  patientHealthIndexDao.findByType(user,deviceSn,value1,type,time);
        }
    }
    private List<PatientHealthIndex> findRepeat(String user,String deviceSn,String value1,Integer type,Date time){
        List<PatientHealthIndex> list = null;
        try {
            String url = wlyyService + "/iot/findRepeat";
            Map<String, Object> params = new HashedMap();
            params.put("user", user);
            params.put("deviceSn", deviceSn);
            params.put("value1", value1);
            params.put("type", user);
            params.put("time", DateUtil.dateToStrLong(time));
            String re = transfor(url,params);
            JSONObject json = JSONObject.parseObject(re);
            JSONArray jsonArray = json.getJSONObject("data").getJSONArray("obj");
            if(jsonArray!=null){
                list = new ArrayList<>(jsonArray.size());
                for (Object o:jsonArray) {
                    PatientHealthIndex index = new PatientHealthIndex();
                    list.add(index);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }
    private int getCountByTimeAndStatusAndPatient(Date start,Date end,Integer status,String patientCode){
        try {
            String url = wlyyService + "/iot/getCountByTimeAndStatusAndPatient";
            Map<String, Object> params = new HashedMap();
            params.put("start", DateUtil.dateToStrLong(start));
            params.put("end", DateUtil.dateToStrLong(end));
            params.put("status", status);
            params.put("patientCode", patientCode);
            String response = transfor(url,params);
            JSONObject json = JSONObject.parseObject(response);
            if(json.getInteger("status")==200){
                return json.getInteger("data");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return 0;
    }
    private List<PatientHealthIndex> findByPatientAndType(String patientCode, Integer type){
        return null;
    }
    /**
     * 更新状态
     * @param id
     */
    private void updateStatus(Long id,String status){
        try {
            String url = wlyyService + "/iot/updateStatus";
            Map<String, Object> params = new HashedMap();
            params.put("id", id);
            params.put("status", status);
            transfor(url,params);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 保存体征数据
     * @param obj
     */
    private PatientHealthIndex saveDevice(PatientHealthIndex obj){
        PatientHealthIndex index = null;
        try {
            String url = wlyyService + "/iot/upload";
            Map<String, Object> params = new HashedMap();
            params.put("jsonStr", JSONObject.toJSONString(obj));
            String re = transfor(url,params);
            JSONObject json = JSONObject.parseObject(re);
            index = objectMapper.readValue(json.getJSONObject("obj").toString(), PatientHealthIndex.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return index;
    }
    /**
     * 查询单条
     * @param id
     * @return
     */
    private PatientHealthIndex getById(Long id){
        return null;
    }
    /**
     * 结果处理
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    private String transfor(String url,Map<String, Object> params) throws Exception{
        String re = null;
        HttpResponse response = httpHelper.post(url, params);
        if (response != null && response.getStatusCode() == 200) {
            JSONObject jsonObject = JSONObject.parseObject(response.getBody());
            if (jsonObject.getInteger("status")!=null) {
                throw new Exception(jsonObject.getString("msg"));
            }
            re = response.getBody();
        } else {
            throw new Exception("接口调用错误!" + response.getBody());
        }
        return re;
    }
}

+ 1 - 1
patient-co-service/wlyy_device/src/main/resources/application.yml

@ -5,7 +5,7 @@ spring:
    name: hos-device
  jpa:
      database: MYSQL
      show-sql: true
      show-sql: false
      hibernate:
        ddl-auto: update
        naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy

+ 1 - 1
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/app/health/PatientHealthIndexService.java

@ -593,7 +593,7 @@ public class PatientHealthIndexService extends BaseService {
    public void updateStatus(DevicePatientHealthIndex data){
        if(iotDeviceService.isUploadIot()){
            //物联网更新
            iotDeviceService.updateStatus(data.getId());
            iotDeviceService.updateStatus(data.getId(),"1");
        }else {
            data.setStatus(1);
            patientHealthIndexDao.save(data);

+ 271 - 118
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/service/third/iot/IotDeviceService.java

@ -40,7 +40,7 @@ public class IotDeviceService {
    private Logger logger = LoggerFactory.getLogger(IotDeviceService.class);
//    @Value("${}")
    private String baseUrl = "http://192.168.131.24:8080/svr-iot-ysj/";
    private String baseUrl = "http://192.168.131.24:8088/svr-iot/";
    private String grantType = "client_credentials";
    private String clientId = "Va5yQRHlA4Fq4eR3LT0vuXV4";
    private String clientSecret = "0rDSjzQ20XUj5itV7WRtznPQSzr5pVw2";
@ -75,7 +75,7 @@ public class IotDeviceService {
        return "1".equals(value)?true:false;
    }
    public JSONObject test(){
    public JSONObject testUpload(){
//        String sql = "select response from wlyy_http_log_detail where id = 1";
//        List<String> list = jdbcTemplate.queryForList(sql,String.class);
        String sql = "SELECT i.id,i.user,i.value1,i.value2,i.value3,i.value4,i.type,i.record_date,i.device_sn,i.status,i.del,d.device_name,d.user_type,p.name,p.idcard " +
@ -108,6 +108,17 @@ public class IotDeviceService {
        if(list.size()>0){
            JSONObject one = list.get(0);
            String response = initUpload(one);
            JSONObject re = JSONObject.parseObject(response);
            if(re.getInteger("status")!=200){
                logger.error("id:"+one.getInteger("id")+" "+re.getString("errorMsg"));
            }else {
                //保存映射关系
                DeviceHealthyInfoMapping info = new DeviceHealthyInfoMapping();
                info.setCreateTime(new Date());
                info.setIndexId(one.getLong("id"));
                info.setRid(re.getJSONObject("obj").getJSONArray("rid").getString(0));
                deviceHealthyInfoMappingDao.save(info);
            }
            return JSONObject.parseObject(response);
        }
        return null;
@ -156,51 +167,115 @@ public class IotDeviceService {
     */
    public String findRepeat(String user,String deviceSn,String value1,String value2,String type,String time){
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonUser = new JSONObject();
        jsonUser.put("andOr","and");
        jsonUser.put("filed","usercode");
        jsonUser.put("condition","=");
        jsonUser.put("value",user);
        jsonArray.add(jsonUser);
        JSONObject jsonSn = new JSONObject();
        jsonSn.put("andOr","and");
        jsonSn.put("filed","sn");
        jsonSn.put("condition","=");
        jsonSn.put("value",deviceSn);
        jsonArray.add(jsonSn);
        field("and","usercode","=",user,jsonArray);
        field("and","sn","=",deviceSn,jsonArray);
        if("1".equals(type)){
            //血糖
            JSONObject jsonValue1 = new JSONObject();
            jsonValue1.put("andOr","and");
            jsonValue1.put("filed","blood_sugar");
            jsonValue1.put("condition","=");
            jsonValue1.put("value",value1);
            jsonArray.add(jsonValue1);
            field("and","blood_sugar","=",value1,jsonArray);
        }else {
            //血压
            JSONObject jsonValue1 = new JSONObject();
            jsonValue1.put("andOr","and");
            jsonValue1.put("filed","systolic");
            jsonValue1.put("condition","=");
            jsonValue1.put("value",value1);
            JSONObject jsonValue2 = new JSONObject();
            jsonValue2.put("andOr","and");
            jsonValue2.put("filed","diastolic");
            jsonValue2.put("condition","=");
            jsonValue2.put("value",value2);
            jsonArray.add(jsonValue1);
            jsonArray.add(jsonValue2);
            field("and","systolic","=",value1,jsonArray);
            field("and","diastolic","=",value2,jsonArray);
        }
        JSONObject jsonTime = new JSONObject();
        jsonTime.put("andOr","and");
        jsonTime.put("filed","measure_time");
        jsonTime.put("condition","=");
        jsonTime.put("value",time);
        String url = baseUrl+"/findById";
        String response = httpClientUtil.iotPostBody(url, jsonArray.toString());
        field("and","measure_time","=",time,jsonArray);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        String url = baseUrl+"/dataSearch/findById";
        String response = httpClientUtil.iotPostBody(url, jsonObject.toString());
        return response;
    }
    /**
     * 按条件统计数量
     * @param start
     * @param end
     * @param status
     * @param patientCode
     * @return
     */
    public int getCountByTimeAndStatusAndPatient(String start,String end,Integer status,String patientCode){
        int re = 0;
        JSONArray jsonArray = new JSONArray();
        field("and","usercode","=",patientCode,jsonArray);
        field("and","status","=",String.valueOf(status),jsonArray);
        field("and","del","=","1",jsonArray);
        field("and","measure_time",">=",start,jsonArray);
        field("and","measure_time","<=",end,jsonArray);
        field("and","type",">=","1",jsonArray);
        field("and","type","<=","2",jsonArray);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        String url = baseUrl+"/dataSearch/findById";
        String response = httpClientUtil.iotPostBody(url, jsonObject.toString());
        JSONObject json = JSONObject.parseObject(response);
        JSONArray ja = json.getJSONArray("obj");
        if(ja!=null){
            re = ja.size();
        }
        return re;
    }
    /**
     *
     * @param patient
     * @param type
     * @return
     */
    public List<DevicePatientHealthIndex> findByPatientAndType(String patient,Integer type){
        List<DevicePatientHealthIndex> list = new ArrayList<>();
        JSONArray jsonArray = new JSONArray();
        field("and","usercode","=",patient,jsonArray);
        field("and","del","=","1",jsonArray);
        field("and","type","=",String.valueOf(type),jsonArray);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        jsonObject.put("page","1");
        jsonObject.put("size","5");
        JSONArray sort = new JSONArray();
        sort(sort,"measure_time","desc");
        jsonObject.put("sort",sort);
        String url = baseUrl+"/dataSearch/findById";
        String response = httpClientUtil.iotPostBody(url, jsonObject.toString());
        return list;
    }
    /**
     * 添加条件
     * 参数格式:[{"andOr":"and|or","condition":">|=|<|>=|<=|?","field":"<field>","value":"<value>"},<{...}>]
     * @param andOr
     * @param field
     * @param condition
     * @param value
     * @param jsonArray
     */
    private void field(String andOr,String field,String condition,String value,JSONArray jsonArray){
        JSONObject json = new JSONObject();
        json.put("andOr",andOr);
        json.put("field",field);
        json.put("condition",condition);
        json.put("value",value);
        jsonArray.add(json);
    }
    /**
     * 排序[{"key1":{"order":"asc|desc"}},{"key2":{"order":"asc|desc"}}]
     * @param jsonArray
     * @param key
     * @param order
     */
    private void sort(JSONArray jsonArray,String key,String order){
        JSONObject json = new JSONObject();
        json.put("order",order);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key,json);
        jsonArray.add(json);
    }
    /**
     * 查询单条
@ -209,11 +284,10 @@ public class IotDeviceService {
     */
    public String getById(String rid){
        JSONObject json = new JSONObject();
        json.put("andOr","and");
        json.put("filed","rid");
        json.put("condition","=");
        json.put("value",rid);
        String url = baseUrl+"/getById";
        JSONArray filters = new JSONArray();
        field("and","rid","=",rid,filters);
        json.put("filter",filters);
        String url = baseUrl+"/dataSearch/getById";
        String response = httpClientUtil.iotPostBody(url, json.toString());
        return response;
    }
@ -221,15 +295,17 @@ public class IotDeviceService {
    /**
     * 查询
     * filter
     * - 参数格式:[{"andOr":"and|or","condition":">|=|<|>=|<=|?","field":"<filed>","value":"<value>"},<{...}>]
     * - 参数格式:[{"andOr":"and|or","condition":">|=|<|>=|<=|?","field":"<field>","value":"<value>"},<{...}>]
     * - 参数说明:andOr跟数据库的中的AND和OR相似;condition指条件匹配程度,?相当于数据库中的like;filed指检索的字段;value为检索的值
     * page - 参数说明:页码
     * size - 参数说明:分页大小
     * sort - 参数格式:排序,key要排序的字段,order固定,取值asc或desc,不需要排序,传""
     *  排序[{"key1":{"order":"asc|desc"}},{"key2":{"order":"asc|desc"}}]
     * @param json
     * @return
     */
    public String searchList(JSONObject json){
        String url = baseUrl+"/searchList";
        String url = baseUrl+"/dataSearch/searchList";
        String response = httpClientUtil.iotPostBody(url, json.toString());
        return response;
    }
@ -240,7 +316,7 @@ public class IotDeviceService {
     * @return
     */
    public String listPage(JSONObject json){
        String url = baseUrl+"/listPage";
        String url = baseUrl+"/dataSearch/listPage";
        String response = httpClientUtil.iotPostBody(url, json.toString());
        return response;
    }
@ -254,7 +330,7 @@ public class IotDeviceService {
    public String recent5(JSONObject json,JSONObject sort){
        json.put("access_token",accessToken);
        String url = baseUrl+"/recent5";
        String url = baseUrl+"/dataSearch/recent5";
        String response = httpClientUtil.iotPostBody(url, json.toString());
        return response;
    }
@ -268,7 +344,7 @@ public class IotDeviceService {
    public String recent1(JSONObject json,JSONObject sort){
        json.put("access_token",accessToken);
        String url = baseUrl+"/recent1";
        String url = baseUrl+"/dataSearch/recent1";
        String response = httpClientUtil.iotPostBody(url, json.toString());
        return response;
    }
@ -313,14 +389,14 @@ public class IotDeviceService {
            list.stream().forEach(one->{
                String response = initUpload(one);
                JSONObject re = JSONObject.parseObject(response);
                String errorMsg = re.getString("errorMsg");//错误信息(请求失败才有错误消息)
                if(StringUtils.isNotBlank(errorMsg)){
                    logger.error("id:"+one.getInteger("id")+" "+errorMsg);
                if(re.getInteger("status")!=200){
                    logger.error("id:"+one.getInteger("id")+" "+re.getString("errorMsg"));
                }else {
                    //保存映射关系
                    DeviceHealthyInfoMapping info = new DeviceHealthyInfoMapping();
                    info.setCreateTime(new Date());
                    info.setIndexId(one.getLong("id"));
                    info.setRid(one.getJSONObject("obj").getJSONArray("rid").getString(0));
                    infos.add(info);
                }
            });
@ -356,7 +432,8 @@ public class IotDeviceService {
//        js.put("id",String.valueOf(jsonObject.getInteger("id")));
        js.put("measure_time",subStringTime(jsonObject.getString("record_date")));
        js.put("del",StringUtils.trimToEmpty(jsonObject.getString("del")));
        js.put("status",StringUtils.trimToEmpty(jsonObject.getString("status")));
        js.put("status",getStatus(jsonObject.getString("status")));
        js.put("type",String.valueOf(type));
        switch (type){
            case 1:
                //血糖
@ -405,14 +482,17 @@ public class IotDeviceService {
     * 更新状态
     * @param id
     */
    public void updateStatus(Long id){
    public void updateStatus(Long id,String status){
        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(id,id);
        if(mapping == null){
            logger.info("未找到映射关系,id:"+id);
            logger.error("未找到映射关系,id:"+id);
        }else {
            JSONObject json = new JSONObject();
            String url = baseUrl+"/dataInput/updateRecord";
            json.put("rid",mapping.getRid());
            json.put("status",status);
            String url = baseUrl+"/dataSearch/update";
            String response = httpClientUtil.iotPostBody(url, json.toString());
            JSONObject res = JSONObject.parseObject(response);
        }
    }
@ -424,13 +504,62 @@ public class IotDeviceService {
    public DevicePatientHealthIndex getById(Long id){
        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(id,id);
        if(mapping == null){
            logger.info("未找到映射关系,id:"+id);
            logger.error("未找到映射关系,id:"+id);
            return null;
        }else {
            return transforOne(getById(mapping.getRid()),id);
        }
    }
    /**
     * 更新
     * @param obj
     * @return
     */
    public DevicePatientHealthIndex update(DevicePatientHealthIndex obj){
        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(obj.getId(),obj.getId());
        if(mapping == null){
            logger.error("未找到映射关系,id:"+obj.getId());
        }else {
            JSONObject json = new JSONObject();
            json.put("rid",mapping.getRid());
            json.put("del",obj.getDel());
            transforIot(obj,json);
            String url = baseUrl+"/dataSearch/update";
            String response = httpClientUtil.iotPostBody(url, json.toString());
            JSONObject res = JSONObject.parseObject(response);
        }
        return obj;
    }
    /**
     * 删除
     * @param id
     */
    public void delete(Long id){
        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(id,id);
        if(mapping == null){
            logger.error("未找到映射关系,id:"+id);
        }else {
            JSONObject json = new JSONObject();
            json.put("rid",mapping.getRid());
            json.put("del","0");
            String url = baseUrl+"/dataSearch/delete";
            String response = httpClientUtil.iotPostBody(url, json.toString());
            JSONObject res = JSONObject.parseObject(response);
            if("true".equals(res.getString("obj"))){
                logger.info("删除成功!");
            }else {
                logger.error("删除失败,id="+id+",rid="+mapping.getRid()+",msg="+res.getString("errorMsg"));
            }
        }
    }
    /**
     * 体征上传
     * @param obj
@ -457,43 +586,11 @@ public class IotDeviceService {
        JSONArray jsonArray = new JSONArray();
        JSONObject js = new JSONObject();
        js.put("measure_time",obj.getRecordDate());
        switch (obj.getType()){
            case 1:
                //血糖
                js.put("blood_sugar",obj.getValue1());
                js.put("blood_sugar_unit",bloodSugarUnit);
                js.put("blood_sugar_result",obj.getValue2());
                break;
            case 2:
                //血压
                js.put("systolic",obj.getValue1());
                js.put("systolic_unit",bloodPressureUnit);
                js.put("diastolic",obj.getValue2());
                js.put("diastolic_unit",bloodPressureUnit);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    js.put("pulse",obj.getValue3());
                    js.put("pulse_unit",pulseUnit);
                }
                break;
            case 3:
                //体重/身高/BMI
                js.put("height",obj.getValue1());
                js.put("height_unit",heightUnit);
                js.put("weight",obj.getValue2());
                js.put("weight_unit",weightUnit);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    js.put("bmi",obj.getValue3());
                    js.put("bmi_unit",bmiUnit);
                }
                break;
            case 4:
                //腰围
                js.put("waist",obj.getValue1());
                js.put("waist_unit",waistUnit);
                break;
            default:
                break;
        }
        transforIot(obj,js);
        js.put("status","0");
        js.put("del","1");
        js.put("type",String.valueOf(obj.getType()));
        jsonArray.add(js);
        json.put("data",jsonArray);
        //上传
@ -514,15 +611,6 @@ public class IotDeviceService {
        return obj;
    }
    /**
     * 更新
     * @param obj
     * @return
     */
    public DevicePatientHealthIndex update(DevicePatientHealthIndex obj){
        return obj;
    }
    /************************************i健康业务相关 end  ************************************************************/
@ -537,7 +625,7 @@ public class IotDeviceService {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        if(jsonObject.getString("errorMsg")!=null){
        if(jsonObject.getInteger("status")!=200||jsonObject.getJSONArray("obj").size()==0){
            logger.error(jsonObject.getString("errorMsg"));
            return null;
        }
@ -547,25 +635,34 @@ public class IotDeviceService {
        index.setDeviceSn(obj.getString("sn"));
        index.setUser(obj.getString("usercode"));
        index.setIdcard(obj.getString("idcard"));
        index.setRecordDate(DateUtil.strToDate(obj.getString("measure_time")));
        //{"errorCode":null,"errorMsg":null,"successMsg":"search success","status":200,"pageSize":10,"currPage":0,"totalPage":0,"totalCount":0,"detailModelList":null,
        // "obj":[{"access_token":"test","data_source":"iHealth","sn":"867967022337804","ext_code":"","device_name":"","device_model":"",
        // "data":[{"rid":"lwKBG349zj/XBIJOP8CpyoFxFKl0xyxLLzxpN/l9+1U=","del":1,"measure_time":"2016-08-26 12:32:04","systolic":"115.00","systolic_unit":"mmHg","diastolic":"105.00","pulse":"105.00","pulse_unit":"bpm"}],
        // "idCard":"350122198601145513","username":"谢挺盛","usercode":"443a196ef8744536a531260eb26c05d7"}]}
        JSONObject data = obj.getJSONArray("data").getJSONObject(0);
        index.setRecordDate(DateUtil.strToDate(data.getString("measure_time")));
        index.setSortDate(index.getRecordDate());
        if(obj.getString("blood_sugar")==null){
        index.setDel(data.getString("del"));
        index.setStatus(data.getInteger("status"));
        if(data.getString("blood_sugar")!=null){
            index.setType(1);
            index.setValue1(obj.getString("blood_sugar"));
            index.setValue2(obj.getString("blood_sugar_result"));
        }else if(obj.getString("systolic")==null){
            index.setValue1(data.getString("blood_sugar"));
            index.setValue2(data.getString("blood_sugar_result"));
        }else if(data.getString("systolic")!=null){
            index.setType(2);
            index.setValue1(obj.getString("systolic"));
            index.setValue2(obj.getString("diastolic"));
            index.setValue3(obj.getString("pulse"));
        }else if(obj.getString("height")==null){
            index.setValue1(data.getString("systolic"));
            index.setValue2(data.getString("diastolic"));
            index.setValue3(data.getString("pulse"));
        }else if(data.getString("height")!=null){
            index.setType(3);
            index.setValue1(obj.getString("height"));
            index.setValue2(obj.getString("weight"));
            index.setValue3(obj.getString("bmi"));
        }else if(obj.getString("waist")==null){
            index.setValue1(data.getString("height"));
            index.setValue2(data.getString("weight"));
            index.setValue3(data.getString("bmi"));
        }else if(data.getString("waist")!=null){
            index.setType(4);
            index.setValue1(obj.getString("waist"));
            index.setValue1(data.getString("waist"));
        }
        return index;
    }
@ -605,6 +702,62 @@ public class IotDeviceService {
        return StringUtils.isBlank(time)? "":time.substring(0,19);
    }
    /**
     * 状态默认值
     * @param status
     * @return
     */
    private String getStatus(String status){
        return StringUtils.isBlank(status)?"0":status;
    }
    /**
     * 转化成物联网格式
     * @param obj
     * @param json
     * @return
     */
    public JSONObject transforIot(DevicePatientHealthIndex obj,JSONObject json){
        switch (obj.getType()){
            case 1:
                //血糖
                json.put("blood_sugar",obj.getValue1());
                json.put("blood_sugar_unit",bloodSugarUnit);
                json.put("blood_sugar_result",obj.getValue2());
                break;
            case 2:
                //血压
                json.put("systolic",obj.getValue1());
                json.put("systolic_unit",bloodPressureUnit);
                json.put("diastolic",obj.getValue2());
                json.put("diastolic_unit",bloodPressureUnit);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    json.put("pulse",obj.getValue3());
                    json.put("pulse_unit",pulseUnit);
                }
                break;
            case 3:
                //体重/身高/BMI
                json.put("height",obj.getValue1());
                json.put("height_unit",heightUnit);
                json.put("weight",obj.getValue2());
                json.put("weight_unit",weightUnit);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    json.put("bmi",obj.getValue3());
                    json.put("bmi_unit",bmiUnit);
                }
                break;
            case 4:
                //腰围
                json.put("waist",obj.getValue1());
                json.put("waist_unit",waistUnit);
                break;
            default:
                break;
        }
        return json;
    }
    /*****************************************工具方法 end  ************************************************************/
}

+ 86 - 5
patient-co/patient-co-wlyy/src/main/java/com/yihu/wlyy/web/third/iot/IotDeviceController.java

@ -4,11 +4,13 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.device.entity.DevicePatientHealthIndex;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.service.third.iot.IotDeviceService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
@ -27,6 +29,8 @@ public class IotDeviceController extends BaseController{
    @Autowired
    private IotDeviceService iotDeviceService;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private PatientHealthIndexService indexService;
    @RequestMapping(value = "/registedevice",method = RequestMethod.POST)
    @ApiOperation("注册设备")
@ -73,11 +77,11 @@ public class IotDeviceController extends BaseController{
        }
    }
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ApiOperation("test")
    @RequestMapping(value = "/testUpload",method = RequestMethod.GET)
    @ApiOperation("testUpload")
    public String upload(){
        try {
            return write(200, "test成功!", "data", iotDeviceService.test());
            return write(200, "test成功!", "data", iotDeviceService.testUpload());
        }catch (Exception e){
            error(e);
            return error(-1, e.getMessage());
@ -110,7 +114,7 @@ public class IotDeviceController extends BaseController{
    @RequestMapping(value = "/getById",method = RequestMethod.GET)
    @ApiOperation("按id查询")
    public String getById(@ApiParam(name = "id",value = "id",defaultValue = "123")
    public String getById(@ApiParam(name = "id",value = "id",defaultValue = "100000")
                           @RequestParam(name="id",required = true) Long id){
        try {
            return write(200,"查询成功","data",iotDeviceService.getById(id));
@ -120,7 +124,52 @@ public class IotDeviceController extends BaseController{
        }
    }
    @RequestMapping(value = "/findRepeat",method = RequestMethod.GET)
    @RequestMapping(value = "/delHealthIndex",method = RequestMethod.POST)
    @ApiOperation("删除体征数据")
    public String delHealthIndex(@ApiParam(name = "id",value = "id",defaultValue = "100000")
                          @RequestParam(name="id",required = true) Long id){
        try {
            iotDeviceService.delete(id);
            return success("删除成功");
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "/updateHealthIndex",method = RequestMethod.POST)
    @ApiOperation("更新体征数据")
    public String updateHealthIndex(@ApiParam(name = "id",value = "id",defaultValue = "1")
                                 @RequestParam(name="id",required = true) Long id){
        try {
            DevicePatientHealthIndex index = indexService.findOne(id);
            DevicePatientHealthIndex newIndex = new DevicePatientHealthIndex();
            BeanUtils.copyProperties(index,newIndex);
            newIndex.setId(100000L);
            iotDeviceService.update(newIndex);
            return success("更新成功");
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "/updateStatus",method = RequestMethod.POST)
    @ApiOperation("更新成功")
    public String getById(@ApiParam(name = "id",value = "id",defaultValue = "100000")
                          @RequestParam(name="id",required = true) Long id,
                          @ApiParam(name = "status",value = "status",defaultValue = "1")
                          @RequestParam(name="status",required = true) String status){
        try {
            iotDeviceService.updateStatus(id,status);
            return success("更新成功");
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "/findRepeat",method = RequestMethod.POST)
    @ApiOperation("查找重复数据")
    public String findRepeat(@ApiParam(name = "user",value = "user",defaultValue = "aduiojdajkdlsd")
                             @RequestParam(name="user",required = true) String user,
@ -142,4 +191,36 @@ public class IotDeviceController extends BaseController{
        }
    }
    @RequestMapping(value = "getCountByTimeAndStatusAndPatient",method = RequestMethod.POST)
    @ApiOperation("按条件查找数量")
    public String getCountByTimeAndStatusAndPatient(@ApiParam(name="patientCode",value = "居民code")
                                                    @RequestParam(name="patientCode",required = true)String patientCode,
                                                    @ApiParam(name="status",value = "状态")
                                                    @RequestParam(name="status",required = true)Integer status,
                                                    @ApiParam(name="start",value = "开始时间")
                                                    @RequestParam(name="start",required = true)String start,
                                                    @ApiParam(name="end",value = "结束时间")
                                                    @RequestParam(name="end",required = true)String end){
        try {
            return write(200,"","data",iotDeviceService.getCountByTimeAndStatusAndPatient(start, end, status, patientCode));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
    @RequestMapping(value = "findByPatientAndType",method = RequestMethod.POST)
    @ApiOperation("按类型查找最近5次的体征记录")
    public String findByPatientAndType(@ApiParam(name="patientCode",value = "居民code")
                                                    @RequestParam(name="patientCode",required = true)String patientCode,
                                                    @ApiParam(name="type",value = "类型")
                                                    @RequestParam(name="type",required = true)Integer type){
        try {
            return write(200,"","data",iotDeviceService.findByPatientAndType(patientCode,type));
        }catch (Exception e){
            error(e);
            return error(-1,e.getMessage());
        }
    }
}