LAPTOP-KB9HII50\70708 1 éve
szülő
commit
f7ffd5c8c2
12 módosított fájl, 5136 hozzáadás és 3 törlés
  1. 373 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorDeviceController.java
  2. 691 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorHealthController.java
  3. 454 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java
  4. 564 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientHealthController.java
  5. 189 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java
  6. 51 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceService.java
  7. 93 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceWxMessageService.java
  8. 129 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceLogService.java
  9. 652 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java
  10. 1933 0
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientHealthIndexService.java
  11. 3 2
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java
  12. 4 1
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationGuidanceService.java

+ 373 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorDeviceController.java

@ -0,0 +1,373 @@
package com.yihu.jw.hospital.module.health.controller;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceDetailService;
import com.yihu.jw.hospital.module.health.service.DeviceWxMessageService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceLogService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.base.device.DeviceWxMessageDTO;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
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.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
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.RestController;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 医生端:设备管理控制类
 * @author George
 *
 */
@RestController
@RequestMapping(value = "doctor/device")
@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 WechatTemplateConfigDao templateConfigDao;
	@Autowired
	private PushMsgTask pushMsgTask;
	@Autowired
	private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
	@Autowired
	private BasePatientDao patientDao;
	@Autowired
	private BaseDoctorDao doctorService;
	@Autowired
	private PatientDeviceLogService patientDeviceLogService;
	@Autowired
	private CommonUtil commonUtil;
	@Autowired
	private DeviceWxMessageService deviceWxMessageService;
	@Autowired
	private PatientDeviceDao patientDeviceDao;
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private JmsTemplate jmsTemplate;
	@Value("${activemq.queue.deviceMeasurementRemindingQueue}")
	private String devcieChannelName;
	private ObjectMapper  objectMapper=new ObjectMapper();
	@ApiOperation("设备保存接口--医生端")
	@RequestMapping(value = "SavePatientDevice",method = RequestMethod.POST)
	public String saveDevice(@ApiParam(name="data",value="设备数据json",defaultValue = "{\"user\":\"915cca0a-5b1d-11e6-8344-fa163e8aee56\",\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"16C000337\",\"categoryCode\": \"1\",\"userType\": \"-1\"}")
							  @RequestParam(value="data",required = true) String data) {
		try {
			DevicePatientDevice device = objectMapper.readValue(data,DevicePatientDevice.class);
			if(StringUtils.isBlank(device.getDeviceSn())){
				return write(-1,"sn码不能为空!");
			}
			// 设置操作医生标识
			device.setDoctor(getUID());
			BaseDoctorDO doctor = doctorService.findByIdAndDel(getUID());
			if (doctor!=null){
				device.setDoctorName(doctor.getName());
			}
			//首绑和设备类型判断  判断是否可以增加积分
			Map<String,Object> checkMap = patientDeviceService.checkBindingFirstAndType(device);
			boolean flag = (Boolean)checkMap.get("flag");
			//绑定
			patientDeviceService.saveDevice(device);
			patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),1,1);
			//修改设备表中{"1":"0", "2":"0"}绑定次数 和其他绑定信息,
			deviceDetailService.updateAfterBinding(device,new Date(),flag);
			return success("设备保存成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("设备保存接口并且添加积分--医生端")
	@RequestMapping(value = "SavePatientDeviceAndCredit",method = RequestMethod.POST)
	public String SavePatientDeviceAndCredit(@ApiParam(name="data",value="设备数据json",defaultValue = "{\"user\":\"915cca0a-5b1d-11e6-834 4-fa163e8aee56\",\"deviceId\": \"3\",\"deviceName\": \"血压计-优瑞恩\",\"deviceSn\": \"16C000337\",\"categoryCode\": \"1\",\"userType\": \"-1\"}") @RequestParam(value="data",required = true) String data,
											 @ApiParam(name = "agreementPhoto",value = "协议图片临时路径")@RequestParam(value = "agreementPhoto",required = false)String agreementPhoto) {
		try {
			DevicePatientDevice device = objectMapper.readValue(data,DevicePatientDevice.class);
			// 设置操作医生标识
			device.setDoctor(getUID());
			BaseDoctorDO doctor = doctorService.findByIdAndDel(getUID());
			if (doctor!=null){
				device.setDoctorName(doctor.getName());
			}
			if (StringUtils.isNotEmpty(agreementPhoto)){
				device.setAgreementPhoto(commonUtil.copyTempImage(agreementPhoto));
			}
			/*if ("1".equals(device.getCategoryCode())){
				device.setUserType("-1");
			}*/
			//首绑和设备类型判断  判断是否可以增加积分
			Map<String,Object> checkMap = patientDeviceService.checkBindingFirstAndType(device);
			boolean flag = (Boolean)checkMap.get("flag");
			//绑定
			patientDeviceService.saveDevice(device);
			patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),1,1);
			//修改设备表中{"1":"0", "2":"0"}绑定次数 和其他绑定信息,
			deviceDetailService.updateAfterBinding(device,new Date(),flag);
			return success("设备保存成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("患者设备列表获取--医生端")
	@RequestMapping(value = "PatientDeviceList",method = RequestMethod.GET)
	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) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除--医生端")
	@RequestMapping(value = "DeletePatientDevice",method = {RequestMethod.POST,RequestMethod.GET})
	public String delete(@ApiParam(name="id",value="删除设备关联ID")
						 @RequestParam(value="id",required = true) String id) {
		try {
			DevicePatientDevice pd = patientDeviceService.findById(id);
			if(pd!=null)
			{
				//2019-08-06 1.6.0版本医生解绑不用判断权限
				List<JSONObject> objects = patientDeviceService.deleteDevice(id,getUID());
				patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),1,2);
				deviceDetailService.unBindUpdateIsBinding(pd.getDeviceSn());
				//设置解绑申请消息为已处理
//				messageDao.updateMessageByRelationCode(pd.getId() + "", 302);
				//发送设备审核消息
				patientDeviceService.sendWxMessage(pd, 1);
				return write(200,"","data",objects);
			}
			else{
				return error(-1, "不存在该设备!");
			}
		} catch (Exception ex) {
			return invalidUserException(ex, -1,ex.getMessage());
		}
	}
	/**
	 * 设备删除
	 */
	@ApiOperation("设备删除--管理端")
	@RequestMapping(value = "unbindDevice",method = {RequestMethod.POST,RequestMethod.GET})
	public String deleteByAdmin(@ApiParam(name="deviceSn",value="设备SN")
						 @RequestParam(value="deviceSn",required = true) String deviceSn,
						@ApiParam(name="type",value="设备类型")
						@RequestParam(value="type",required = true) String type) {
		try{
			List<DevicePatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
			DevicePatientDevice patientDevice = new DevicePatientDevice();
			if (patientDevices!=null && patientDevices.size()>0){
				patientDevice = patientDevices.get(0);
			}
			patientDeviceService.deleteDevices(deviceSn,type,getUID());
			//全部解绑后去判断就更新设备表中是否绑定字段
			patientDeviceLogService.savePatientDeviceLog(patientDevice,deviceSn,1,2);
			deviceDetailService.unBindUpdateIsBinding(deviceSn);
			return write(200,"解绑成功!");
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception e){
			return errorResult(e);
		}
	}
	@ApiOperation("获取患者设备信息")
	@RequestMapping(value = "PatientDeviceInfo",method = RequestMethod.GET)
	public String getPatientDeviceInfo(@ApiParam(name="id",value="患者设备ID",defaultValue = "34")
									   @RequestParam(value="id",required = true) String id) {
		try {
			DevicePatientDevice device = patientDeviceService.findById(id);
			return write(200, "查询成功", "data", device);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况")
	@RequestMapping(value = "PatientDeviceIdcard",method = RequestMethod.GET)
	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) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@ApiOperation("通过sn码获取设备绑定情况(管理端)")
	@RequestMapping(value = "getListByDeviceSn",method = RequestMethod.GET)
	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);
	}
	@ApiOperation("根据sn码获取设备的信息和绑定信息")
	@RequestMapping(value = "/getDeviceInfoByDeviceSn",method = RequestMethod.GET)
	public String getDeviceInfoByDeviceSn(@ApiParam(name="deviceSn",value="设备SN码",defaultValue = "15L000002")
														  @RequestParam(value="deviceSn",required = true) String deviceSn){
		try{
			Map<String,Object> checkMap = patientDeviceService.checkBindingDeviceSn(deviceSn);
			boolean checkFlag = (Boolean)checkMap.get("flag");
			if (!checkFlag){
				return write(-1,String.valueOf(checkMap.get("message")));
			}
			return write(200, "获取设备成功!", "data",patientDeviceService.getDeviceByDeviceSn(deviceSn));
		}catch (Exception e){
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/checkIsBinding",method = RequestMethod.POST)
	@ApiOperation(value = "根据sn码查询设备是否已经绑定和存在",notes = "绑定设备前的判断")
	public String findDeviceAndBindingBySn(@ApiParam(name = "deviceSn", value = "", defaultValue = "") @RequestParam(value = "deviceSn")String deviceSn){
		if (org.springframework.util.StringUtils.isEmpty(deviceSn)){
			return write(-1,"参数格式错误!");
		}
		try{
			Map<String,Object> map = patientDeviceService.checkBindingDeviceSn(deviceSn);
			return  write(200,String.valueOf(map.get("message")),"data",(Boolean)map.get("flag"));
		}catch (Exception e){
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/getDevicesList",method = RequestMethod.GET)
	@ApiOperation(value = "医生端-设备管理中设备列表",notes = "设备列表")
	public String getDevicesList(@ApiParam(value = "未测量天数(1今日为测量 2七天未测量 3本月未测量 4超过一个月未测量)", name = "noGaugeDay") @RequestParam(value = "noGaugeDay",required = false)String noGaugeDay,
								 @ApiParam(value = "是否绑定(1绑定 2解绑)", name = "isBinding") @RequestParam(value = "isBinding",required = false)String isBinding,
								 @ApiParam(value = "设备类型(1血糖仪 2血压计,4智能手表)", name = "categoryCode") @RequestParam(value = "categoryCode",required = false)String categoryCode,
								 @ApiParam(value = "今日是否发送消息(1未发送 2已发送)", name = "isSend") @RequestParam(value = "isSend",required = false)String isSend,
								 @ApiParam(name="page",value="第几页",defaultValue = "1") @RequestParam(value="page",required = true) String page,
								 @ApiParam(name="pageSize",value="",defaultValue = "10") @RequestParam(value="pageSize",required = true) String pageSize) {
		if (StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}
		try {
			return  write(200,"查找成功!","data",patientDeviceLogService.getDevicesList(getUID(),noGaugeDay,isBinding,categoryCode,isSend,Integer.valueOf(page),Integer.valueOf(pageSize)));
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	@RequestMapping(value = "/sendDeviceWxMessage",method = RequestMethod.POST)
	@ApiOperation("给没有测量的居民发送微信消息提醒")
	public String sendDevcieWxMessage(@ApiParam(name = "data",value = "[{\"patient\":\"1\",\"deviceName\":\"同学1\",\"deviceSn\":\"123\",\"categoryCode\":\"1\"}]")
									  @RequestParam(value = "data",required = true)String data){
		try {
			List<DeviceWxMessageDTO> deviceWxMessageDTOList = deviceWxMessageService.batchSaveAndSendActiveMq(data);
			sender(deviceWxMessageDTOList);
			return write(200,"提醒成功!");
		}catch (Exception e){
			return errorResult(e);
		}
	}
	public void sender(List<DeviceWxMessageDTO> deviceWxMessageList){
		//发送到队列
        try{
            deviceWxMessageList.stream().forEach(one->{
                jmsTemplate.send(devcieChannelName, new MessageCreator() {
                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        TextMessage textMessage = session.createTextMessage();
                        textMessage.setText(net.sf.json.JSONObject.fromObject(one).toString());
                        return textMessage;
                    }
                });
            });
        }catch (Exception e){
            e.printStackTrace();
        }
	}
	
	
	@ApiOperation("拒绝居民设备解绑申请")
	@RequestMapping(value = "refusePatientDeviceApply",method = RequestMethod.POST)
	public String refusePatientDeviceApply(
			@ApiParam(name = "id", value = "删除设备关联ID")
			@RequestParam(value = "id", required = true) String id,
			@ApiParam(name = "reason", value = "拒绝原因")
			@RequestParam(value = "reason", required = true) String reason){
		try {
			DevicePatientDevice pd = patientDeviceService.findById(id);
			pd.setApplyStatus(2);
			pd.setRefuseReason(reason);
			patientDeviceDao.save(pd);
			//发送设备审核模板消息
			patientDeviceService.sendWxMessage(pd, 2);
			return write(200,"执行成功");
		}catch (Exception e){
			return errorResult(e);
		}
	}
}

+ 691 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorHealthController.java

@ -0,0 +1,691 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.contant.DeviceHealthContant;
import com.yihu.jw.entity.base.device.DoctorHealthStandard;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping(value = "/doctor/health_index")
@Api(description = "医生端-患者指标")
public class DoctorHealthController extends BaseController {
	@Autowired
	private PatientHealthIndexService healthIndexService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@RequestMapping(value = "recent",method = RequestMethod.GET)
	@ApiOperation("患者最近填写的健康指标")
	public String recent(@ApiParam("患者代码")
						  @RequestParam String patient) {
		try {
			JSONArray array = healthIndexService.findRecentByPatient(patient);
			if (array != null) {
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			return errorResult(e);
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者标识
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标(图表)")
	public String getHealthIndexChartByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "eb0b478fbe9245428ecf63cd7517206f")
												   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="gi_type",value="就餐类型",defaultValue = "1")
												   @RequestParam(value = "gi_type",required = false) int gi_type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2017-05-22 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2017-06-02 00:00:00")
												   @RequestParam(value="end",required = true) String end) {
		try {
			JSONArray jsonArray = healthIndexService.findChartByPatient(patient,type,gi_type,begin,end);
			List<Map<String,Object>> maps = new ArrayList<>();
			if (type==1){
				JSONArray array = new JSONArray();
				Set<String> list = new HashSet<>();
				for (int i=0;i<maps.size();i++){
					JSONObject jsonObject = new JSONObject();
					Map<String,Object> map = maps.get(i);
					if (array!=null&&array.length()!=0){
						for (int j=0;j<array.length();j++){
							JSONObject object = array.getJSONObject(j);
							if (list.contains(map.get("mid").toString())){
								if (object.getString("mid").equalsIgnoreCase(map.get("mid").toString())){
									if (map.get("code").toString().equalsIgnoreCase("BloodSugar")){
										object.put("mid",map.get("mid"));
										object.put("date",map.get("measure_time").toString());
										object.put("device_sn",map.get("sn").toString());
										object.put("flag","xiaowu");
										object.put("value1",map.get("value"));
										object.put("valuedata",map.get("value"));
									}else if (map.get("code").toString().equalsIgnoreCase("BloodsugarType")){
										object.put("mid",map.get("mid"));
										object.put("date",map.get("measure_time").toString());
										object.put("device_sn",map.get("sn").toString());
										object.put("flag","xiaowu");
										object.put("value2",map.get("value"));
									}
								}
							}else {
								if (map.get("code").toString().equalsIgnoreCase("BloodSugar")){
									jsonObject.put("mid",map.get("mid"));
									jsonObject.put("date",map.get("measure_time").toString());
									jsonObject.put("device_sn",map.get("sn").toString());
									jsonObject.put("flag","xiaowu");
									jsonObject.put("value1",map.get("value"));
									jsonObject.put("valuedata",map.get("value"));
									array.put(jsonObject);
									list.add(map.get("mid").toString());
								}else if (map.get("code").toString().equalsIgnoreCase("BloodsugarType")){
									jsonObject.put("mid",map.get("mid"));
									jsonObject.put("date",map.get("measure_time").toString());
									jsonObject.put("device_sn",map.get("sn").toString());
									jsonObject.put("flag","xiaowu");
									jsonObject.put("value2",map.get("value"));
									array.put(jsonObject);
									list.add(map.get("mid").toString());
								}
							}
						}
					}else {
						if (map.get("code").toString().equalsIgnoreCase("BloodSugar")){
							jsonObject.put("mid",map.get("mid"));
							jsonObject.put("date",map.get("measure_time").toString());
							jsonObject.put("device_sn",map.get("sn").toString());
							jsonObject.put("flag","xiaowu");
							jsonObject.put("value1",map.get("value"));
							jsonObject.put("valuedata",map.get("value"));
							array.put(jsonObject);
							list.add(map.get("mid").toString());
						}else if (map.get("code").toString().equalsIgnoreCase("BloodsugarType")){
							jsonObject.put("mid",map.get("mid"));
							jsonObject.put("date",map.get("measure_time").toString());
							jsonObject.put("device_sn",map.get("sn").toString());
							jsonObject.put("flag","xiaowu");
							jsonObject.put("value2",map.get("value"));
							array.put(jsonObject);
							list.add(map.get("mid").toString());
						}
					}
				}
				for (int z=0;z<array.length();z++){
					JSONObject object = array.getJSONObject(z);
					jsonArray.put(object);
				}
			}else if (type==2){
			}else if (type==3){
			}
			if (jsonArray.length()==0) {
				return success("查询成功!");
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者标识
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart_new",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标(图表)-展会")
	public String getHealthIndexChartByPatient_new(@ApiParam(name="patient",value="患者代码",defaultValue = "eb0b478fbe9245428ecf63cd7517206f")
											   @RequestParam(value="patient",required = true) String patient,
											   @ApiParam(name="type",value="指标类型",defaultValue = "1")
											   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="gi_type",value="就餐类型",defaultValue = "1")
											   @RequestParam(value = "gi_type",required = false) int gi_type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2017-05-22 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2017-06-02 00:00:00")
											   @RequestParam(value="end",required = true) String end) {
		try {
			JSONArray jsonArray = healthIndexService.findChartByPatient(patient,type,gi_type,begin,end);
			if (jsonArray.length()==0) {
				return success("查询成功!");
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
											  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
											  @RequestParam(value="begin",required = true) String begin,
										  @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
											  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
											  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONObject jsonObject2 = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			if (type == 1) {
				List<Object> list = healthIndexService.findIndexByPatient2(patient, type, begin, end, page, pagesize);
				jsonObject2.put("data",list);
			}else {
				jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
				jsonObject2.put("data", jsonArray);
			}
			return write(200, "查询成功", "list", jsonObject2);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list_new",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标-展会")
	public String getHealthIndexByPatient_new(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
										  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="begin",value="开始时间",defaultValue = "2016-07-23 00:00:00")
										  @RequestParam(value="begin",required = true) String begin,
										  @ApiParam(name="end",value="开始时间",defaultValue = "2016-08-23 00:00:00")
										  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
										  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONArray jsonArray = new JSONArray();
			if (type == 1) {
				List<Object> list = healthIndexService.findIndexByPatient2(patient, type, begin, end, page, pagesize);
				jsonArray = new JSONArray(list);
			}else{
				jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 根据患者标志获取健康指标
	 * @param patient 患者指标
	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
	 * @return 操作结果
	 */
	@RequestMapping(value = "list1",method = RequestMethod.POST)
	@ApiOperation("根据患者标志获取健康指标")
	public String getHealthIndexByPatient1(@ApiParam(name="patient",value="患者代码",defaultValue = "P20160901001")
										  @RequestParam(value="patient",required = true) String patient,
										  @ApiParam(name="type",value="指标类型",defaultValue = "1")
										  @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
										  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			JSONObject jsonObject = new JSONObject();
			if (type == 1) {
				jsonObject = healthIndexService.findIndexByPatient3(patient, type, page, pagesize);
			}else{
				jsonObject = healthIndexService.findIndexByPatient1(patient, type, page, pagesize);
			}
			return write(200, "查询成功", "list", jsonObject);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 *
	 * @param patient 患者标识
	 * @return
	 */
	@RequestMapping(value = "standard",method = RequestMethod.GET)
	@ApiOperation("患者健康指标预警值查询")
	public String standard(@ApiParam("患者代码") @RequestParam String patient) {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(patient);
			Iterator<PatientHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					PatientHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型:1血糖,2血压,3体重,4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	@RequestMapping(value = "standard_save",method = RequestMethod.POST)
	@ApiOperation("保存患者健康指标预警值")
	public String standardSave(@ApiParam("患者代码") @RequestParam String patient,
							    @ApiParam("预警值Json") @RequestParam String json) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(patient) || array == null || array.length() == 0) {
				return error(-1, "保存失败!");
			}
				String[] pcodeArray = new String[1];
				if(patient.contains(",")){
					pcodeArray = patient.split(",");
				}else{
					pcodeArray = new String[]{patient};
				}
				if(pcodeArray != null && pcodeArray.length > 0){
					// 生成数据对象
					List<PatientHealthStandard> list = new ArrayList<>();
					//保存患者的数据时,同时医生的预警值方案
					List<DoctorHealthStandard> doclist = new ArrayList<>();
					for (int i = 0; i < array.length(); i++) {
						JSONObject obj = array.getJSONObject(i);
						if (obj == null) {
							continue;
						}
						for (String patientCode: pcodeArray) {
							PatientHealthStandard standard = new PatientHealthStandard();
							standard.setDoctor(getUID());
							standard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
							standard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
							standard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
							standard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
							standard.setType(obj.getInt("type"));
							standard.setPatient(patientCode);
							standard.setCzrq(new Date());
							list.add(standard);
						}
					}
					if (list.size() == 0) {
						return error(-1, "保存失败!");
					}
					// 保存数据库
					Iterable<PatientHealthStandard> iterable = healthIndexService.saveStandard(list, patient);
					if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
						return error(-1, "保存失败!");
					}
				}
			return write(200, "保存成功");
		} catch (Exception e) {
			return invalidUserException(e, -1, "保存失败!");
		}
	}
	@RequestMapping(value = "last",method = RequestMethod.GET)
	@ApiOperation("患者最新健康指标信息")
	public String getHealthIndexByPatient(@ApiParam(name="patient",value="患者代码",defaultValue = "")
										   @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
			if (xt != null) {
				map.put("xt", xt);
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
			if (xy != null) {
				map.put("xy", xy);
			}
			DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
			if (tz != null) {
				map.put("tz", tz);
			}
			DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
			if (sg != null) {
				map.put("sg", sg);
			}
			DevicePatientHealthIndex xl = healthIndexService.findLastByPatienIot(patient, 5);
			if (xl != null) {
				map.put("xl", xl);
			}
			return write(200, "查询成功", "data", map);
		} catch (ServiceException se) {
			return write(-1,se.getMessage());
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "last_new",method = RequestMethod.GET)
	@ApiOperation("患者最新健康指标信息-展会")
	public String getHealthIndexByPatient_new(@ApiParam(name="patient",value="患者代码",defaultValue = "")
										  @RequestParam(value="patient",required = true) String patient) {
		try {
			Map<String,Object> map = new HashMap<>();
			DevicePatientHealthIndex xt = healthIndexService.findLastByPatien(patient,1);
			if(xt!=null)
			{
				map.put("xt",xt);
			}
			DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient,2);
			if(xy!=null)
			{
				map.put("xy",xy);
			}
			DevicePatientHealthIndex tz = healthIndexService.findLastByPatien(patient,3);
			if(tz != null){
				map.put("tz",tz);
			}
			DevicePatientHealthIndex sg = healthIndexService.findLastByPatien(patient,4);
			if(sg != null){
				map.put("sg",sg);
			}
			DevicePatientHealthIndex xl = healthIndexService.findLastByPatien(patient,5);
			if(xl != null){
				map.put("xl",xl);
			}
			return write(200, "查询成功", "data", map);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "getHealthIndexHistory",method = RequestMethod.GET)
	@ApiOperation("获取患者健康指标历史记录")
	public String getHealthIndexHistory(@ApiParam(name="patient",value="患者代码",defaultValue = "P20161008001")
										 @RequestParam(value="patient",required = true) String patient,
										 @ApiParam(name="type",value="指标类型1血糖,2血压,3体重,4腰围",defaultValue = "1")
										 @RequestParam(value="type",required = true) int type,
										 @ApiParam(name="page",value="第几页",defaultValue = "0")
										 @RequestParam(value="page",required = true) int page,
										 @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										 @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<Map<String,String>> list = healthIndexService.getHealthIndexHistory(patient, type, page, pagesize);
			return write(200, "获取患者健康指标历史记录成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@RequestMapping(value = "doctorstandard",method = RequestMethod.GET)
	@ApiOperation("医生健康指标预警值方案查询")
	public String doctorstandard(@ApiParam("医生") @RequestParam String doctor) {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			if(StringUtils.isBlank(doctor)){
				doctor = getUID();
			}
			Iterable<DoctorHealthStandard> iterable = healthIndexService.findDoctorStandardByDoctor(doctor);
			if(iterable == null){
				//如果获取不到,则获取系统默认方案
				iterable = healthIndexService.findDoctorStandardByDoctor("default");
			}
			Iterator<DoctorHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置,返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖(餐前,餐后二小时)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
			// 默认血压(收缩压,舒张压)
			sb.append("{min_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ DeviceHealthContant.HEALTH_STANDARD_SSY_MAX +", " +
					"min_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ DeviceHealthContant.HEALTH_STANDARD_SZY_MAX +", type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					DoctorHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围\BMI)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围\BMI)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压\步数)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压\步数)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型:1血糖,2血压,3BMI,4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			return invalidUserException(e, -1, "查询失败!");
		}
	}
	@RequestMapping(value = "savastandbyteamcode",method = RequestMethod.POST)
	@ApiOperation("医生保存团队下所有居民的预警方案")
	public String doctorSaveStandardByTeamCode(
			@ApiParam("团队代码") @RequestParam String teamcode,
			@ApiParam("预警值Json") @RequestParam String json) {
		try {
			JSONArray array = new JSONArray(json);
			if (StringUtils.isEmpty(teamcode) || array == null || array.length() == 0) {
				return error(-1, "保存失败!");
			}
			List<BasePatientDO> patients = new ArrayList<>();
			if(!patients.isEmpty()){
				// 生成数据对象
				List<PatientHealthStandard> list = new ArrayList<>();
				//保存患者的数据时,同时医生的预警值方案
				List<DoctorHealthStandard> doclist = new ArrayList<>();
				for (int i = 0; i < array.length(); i++) {
					JSONObject obj = array.getJSONObject(i);
					if (obj == null) {
						continue;
					}
					for (BasePatientDO patient: patients) {
						PatientHealthStandard standard = new PatientHealthStandard();
						standard.setDoctor(getUID());
						standard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
						standard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
						standard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
						standard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
						standard.setType(obj.getInt("type"));
						standard.setPatient(patient.getId());
						standard.setCzrq(new Date());
						list.add(standard);
					}
					DoctorHealthStandard doctorHealthStandard = new DoctorHealthStandard();
					doctorHealthStandard.setDoctor(getUID());
					doctorHealthStandard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
					doctorHealthStandard.setMaxValue2(obj.has("max_value2") ? NumberUtils.toDouble(obj.getString("max_value2"), 0) : 0);
					doctorHealthStandard.setMinValue1(obj.has("min_value1") ? NumberUtils.toDouble(obj.getString("min_value1"), 0) : 0);
					doctorHealthStandard.setMinValue2(obj.has("min_value2") ? NumberUtils.toDouble(obj.getString("min_value2"), 0) : 0);
					doctorHealthStandard.setType(obj.getInt("type"));
					doctorHealthStandard.setCzrq(new Date());
					doclist.add(doctorHealthStandard);
				}
				if (list.size() == 0) {
					return error(-1, "保存失败!");
				}
				// 保存数据库
				Iterable<PatientHealthStandard> iterable = healthIndexService.saveStandardPatients(list, patients);
				if (iterable == null || iterable.iterator() == null || !iterable.iterator().hasNext()) {
					return error(-1, "保存失败!");
				}
				Iterable<DoctorHealthStandard> dociterable = healthIndexService.saveDocStandard(doclist, getUID());
				if (dociterable == null || dociterable.iterator() == null || !dociterable.iterator().hasNext()) {
					return error(-1, "保存失败!");
				}
			}
			return write(200, "保存成功");
		} catch (Exception e) {
			return invalidUserException(e, -1, "操作失败!");
		}
	}
	@RequestMapping(value = "/getHealthDateAll",method = RequestMethod.GET)
	@ApiOperation("医生端--查询所有有数据的日期")
	public String getHealthDateAll(@ApiParam(value = "居民code)", name = "patientCode") @RequestParam(value = "patientCode",required = true)String patientCode,
								   @ApiParam(value = "设备sn码", name = "deviceSn") @RequestParam(value = "deviceSn",required = true)String deviceSn,
								   @ApiParam(value = "时间(month:yyyy-MM)", name = "choseMonth") @RequestParam(value = "choseMonth",required = true)String choseMonth,
								   @ApiParam(value = "健康指标类型(1血糖,2血压,3体重,4腰围)",name = "type")@RequestParam(value = "type",required = true)int type){
		try{
			String sql = "select DISTINCT(DATE_FORMAT(a.record_date,'%Y-%m-%d')) result from wlyy_patient_health_index a where a.type="+type+" and a.`user` = '"+patientCode+"' and DATE_FORMAT(a.record_date,'%Y-%m') = '"+choseMonth+"' and a.device_sn = '"+deviceSn+"' and a.del = '1' order by a.record_date,a.id";
			List<Map<String,Object>> reusltList = jdbcTemplate.queryForList(sql);
			List<String> list = new ArrayList<>();
			for (Map<String,Object> map : reusltList){
				list.add(String.valueOf(map.get("result")));
			}
			return write(200, "获取健康指标记录日期成功", "data", list);
		}catch (Exception e){
			return invalidUserException(e, -1, e.getMessage());
		}
	}
	@RequestMapping(value = "/patientHealthIndexByDateAndDeviceSn",method = RequestMethod.GET)
	@ApiOperation("医生端--根据时间和设备sn码查询某个居民的体征记录")
	public String patientHealthIndexByDateAndDeviceSn(@ApiParam(value = "居民code)", name = "patientCode") @RequestParam(value = "patientCode",required = true)String patientCode,
													  @ApiParam(value = "设备sn码", name = "deviceSn") @RequestParam(value = "deviceSn",required = true)String deviceSn,
													  @ApiParam(value = "日期", name = "choseDay") @RequestParam(value = "choseDay",required = true)String choseDay,
													  @ApiParam(value = "健康指标类型(1血糖,2血压,3体重,4腰围)",name = "type")@RequestParam(value = "type",required = true)int type){
		try {
			List<Map<String,String>> list = healthIndexService.getHealthIndexByPatientAndDate(patientCode,deviceSn,choseDay,type);
			return write(200, "获取健康指标历史记录成功", "data", list);
		} catch (Exception ex) {
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}
	@GetMapping(value = "/getDataByType")
	@ApiOperation(value = "体征类型查询数据", notes = "体征类型查询数据")
	public String getDataByType(
			@ApiParam(name = "patient",value = "居民code",required = true) @RequestParam String patient,
			@ApiParam(name = "type", value = "体征类型", required = true) @RequestParam String type,
			@ApiParam(name = "page", value = "页", required = true) @RequestParam(defaultValue = "1") int page,
			@ApiParam(name = "size", value = "数量", required = true) @RequestParam(defaultValue = "15") int size,
			@ApiParam(name = "beginTime", value = "开始时间", required = false) @RequestParam String beginTime,
			@ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam String endTime
	) throws Exception {
		return write(200, "查询成功", "data", new ArrayList<>());
	}
	@RequestMapping(value = "getHealthIndexById",method = RequestMethod.GET)
	@ApiOperation("根据体征记录id获取体征记录详情")
	public String getHealthIndexById(@ApiParam("体征记录id")
						 @RequestParam Long id) {
		try {
			DevicePatientHealthIndex patientHealthIndex = healthIndexService.getHealthIndexById(id);
			return write(200, "查询成功", "data", patientHealthIndex);
		} catch (Exception e) {
			return errorResult(e);
		}
	}
}

+ 454 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientDeviceController.java

@ -0,0 +1,454 @@
package com.yihu.jw.hospital.module.health.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.device.dao.PatientHealthTimeDao;
import com.yihu.jw.entity.base.device.PatientHealthTime;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.wechat.WechatTemplateConfig;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.DeviceDetailService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceLogService;
import com.yihu.jw.hospital.module.health.service.PatientDeviceService;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.hospital.module.wx.dao.WechatTemplateConfigDao;
import com.yihu.jw.hospital.task.PushMsgTask;
import com.yihu.jw.hospital.utils.WeiXinAccessTokenUtils;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
 * 患者端:设备管理控制类
 *
 * @author George
 */
@RestController
@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 PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private PatientHealthIndexService patientHealthIndexService;
    @Autowired
    private DeviceDetailService deviceDetailService;
    @Autowired
    private BasePatientDao patientService;
    @Autowired
    private WechatTemplateConfigDao templateConfigDao;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    private PatientDeviceLogService patientDeviceLogService;
    @Autowired
    private MessageDao messageDao;
    private ObjectMapper objectMapper = new ObjectMapper();
    @ApiOperation("获取居民标准体征预警值")
    @RequestMapping(value = "getDeviceStandard", method = RequestMethod.GET)
    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,"获取失败");
        }
    }
    /**
     * 设置及修改血糖仪时间段
     * 默认时间段如下
     * fasting: 00:00-07:59
     * afterBreakfast: 08:00-09:59
     * beforeLunch: 10:00-11:59
     * afterLunch: 12:00-13:59
     * beforeDinner: 14:00-17:59
     * afterDinner: 18:00-19:59
     * beforeSleep: 20:00-23:59
     */
    @ApiOperation("设置修改血糖仪时间段")
    @RequestMapping(value = "/setBloodTime", method = RequestMethod.GET)
    public String setBloodTime(@RequestParam(required = false) String fastingStart,
                               @RequestParam(required = false) String fastingEnd,
                               @RequestParam(required = false) String afterBreakfastStart,
                               @RequestParam(required = false) String afterBreakfastEnd,
                               @RequestParam(required = false) String beforeLunchStart,
                               @RequestParam(required = false) String beforeLunchEnd,
                               @RequestParam(required = false) String afterLunchStart,
                               @RequestParam(required = false) String afterLunchEnd,
                               @RequestParam(required = false) String beforeDinnerStart,
                               @RequestParam(required = false) String beforeDinnerEnd,
                               @RequestParam(required = false) String afterDinnerStart,
                               @RequestParam(required = false) String afterDinnerEnd,
                               @RequestParam(required = false) String beforeSleepStart,
                               @RequestParam(required = false) String beforeSleepEnd,
                               @RequestParam(required = false) String sim,
                               @RequestParam String deviceSN,
                               @RequestParam String categoryCode,
                               @RequestParam String userType,
                               @RequestParam(required = false) String newDeviceSN,
                               @RequestParam(required = false) String hospital,
                               @RequestParam(required = false) String hospitalName,
                               @RequestParam(required = false) String checkDoctorName) {
        try {
//            String user = getUID();
            String user = getRepUID();
            if (StringUtils.isNotEmpty(newDeviceSN)) {
//                校验新的sn码 1.是否被占用 2.是否是真的设备码
                if(!newDeviceSN.equals(deviceSN)){
                    //有改sn码
                    DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(newDeviceSN, userType);
                    if (device != null) {
                        throw new Exception("sn码" + newDeviceSN + "已被使用!");
                    }
                    if(!patientDeviceService.checkDeviceSn(newDeviceSN)){
                        return error(-1,"设备不存在");
                    }
                }
                if ("1".equals(categoryCode)) {
//                        先修改患者设备绑定表
                    int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType,sim,hospital,hospitalName,checkDoctorName);
                    if (rows != 0) {
                        //                只更换设备编码,不更改时间值
//                1.先查询是否自定义时间段,没有则新增,有则修改
                        PatientHealthTime healthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
                        if (healthTime == null) {
                            patientDeviceService.setBloodTime(user, newDeviceSN, "null", "null", "null", "null", "null", "null",
                                    "null", "null", "null", "null", "null", "null", "null", "null");
                        } else {
                            patientDeviceService.updateDeviceSN(user, deviceSN, newDeviceSN);
                        }
                    }
                }else {
                    int rows = patientDeviceService.updatePatientDevice(user, deviceSN, newDeviceSN,userType,sim,hospital,hospitalName,checkDoctorName);
                }
                return write(200, "更改sv码成功!");
            }
            patientDeviceService.setBloodTime(user, deviceSN, fastingStart, fastingEnd, afterBreakfastStart, afterBreakfastEnd, beforeLunchStart, beforeLunchEnd,
                    afterLunchStart, afterLunchEnd, beforeDinnerStart, beforeDinnerEnd, afterDinnerStart, afterDinnerEnd, beforeSleepStart, beforeSleepEnd);
            return write(200, "设置成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, e.getMessage());
        }
    }
    /**
     * 设备保存接口  ---增加血糖时间段保存 Reece v1.3.3
     */
    @ApiOperation("设备保存接口")
    @RequestMapping(value = "SavePatientDevice", method = RequestMethod.POST)
    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 {
            DevicePatientDevice device = objectMapper.readValue(json, DevicePatientDevice.class);
            if(StringUtils.isBlank(device.getDeviceSn())){
                return write(-1,"sn码不能为空!");
            }
            // 设置患者标识
            device.setUser(getRepUID());
//            device.setUser(getUID());
            //患者和设备是否首绑
            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 = patientService.findById(getRepUID()).orElse(null);
            if(!getUID().equals(getRepUID())&&device.getId()==null){
                device.setAgent(getRepUID());
                device.setAgentName(patient.getName());
            }
            String sn = device.getDeviceSn();
            synchronized (sn.intern()){
                patientDeviceService.saveDevice(device);
                patientDeviceLogService.savePatientDeviceLog(device,device.getDeviceSn(),2,1);
            }
            //修改设备表中{"1":"0", "2":"0"}的绑定次数 和其他绑定信息
            deviceDetailService.updateAfterBinding(device,new Date(),flag);
            String flagStr ="";
            if ("1".equals(device.getCategoryCode())){
                flagStr="GLU_BIND";
            }else if ("2".equals(device.getCategoryCode())){
                flagStr="BP_BIND";
            }
            //活动的活跃度
            if (flag){
                com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                jsonObject.put("patientId",patient.getId());
                jsonObject.put("taskCode",flagStr);
            }
            if(!"11".equals(device.getCategoryCode())){
                try {
                    String openId = patient.getOpenid();
                    String name = patient.getName();
                    JSONObject sendJson = new JSONObject();
                    String first = "";
                    String remark = "";
                    String deviceName = device.getDeviceName();
                    WechatTemplateConfig templateConfig = templateConfigDao.findByScene("template_patient_bind_device","bdsb");
                    first = templateConfig.getFirst();
                    first = first.replace("key1",(deviceName==null?"":deviceName));
                    remark = templateConfig.getRemark();
                    sendJson.put("keyword1", deviceName);
                    sendJson.put("keyword2", DateUtil.dateToStrLong(device.getCzrq()));
                    sendJson.put("keyword3", templateConfig.getKeyword3());
                    sendJson.put("first", first);
                    sendJson.put("remark", remark);
                    sendJson.put("url", templateConfig.getUrl());//带参数的模板跳转链接
                    System.out.println(sendJson.toString());
                    pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 22, openId, name, sendJson);
                }catch (Exception e){
                    logger.info("设备绑定微信模板消息发送失败:"+e.getMessage());
                }
            }
            return success("设备保存成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备列表获取
     *
     * @return 操作结果
     */
    @ApiOperation("患者设备列表获取")
    @RequestMapping(value = "PatientDeviceList", method = RequestMethod.GET)
    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<DevicePatientDevice> 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)
    public String getPatientDeviceInfo(@ApiParam(name = "id", value = "患者设备ID", defaultValue = "146")
                                       @RequestParam(value = "id", required = true) String id) {
        try {
            Map mapList = new HashMap();
            DevicePatientDevice device = patientDeviceService.findById(id);
            String deviceSN = device.getDeviceSn();
            String user = device.getUser();
            if(!device.getCategoryCode().equals("4")) {
                Map map = patientDeviceService.getBloodSuggerTime(user, deviceSN);
                mapList.put("time", map);
            }
            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)
    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 (!"11".equals(type)&&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 = "sendDeviceReviewMessage",method = RequestMethod.POST)
    public String sendDeviceReviewMessage(@ApiParam(name = "id", value = "删除设备关联ID")
                                              @RequestParam(value = "id", required = true) String id,
                                          @ApiParam(name = "reson", value = "解绑理由")
                                          @RequestParam(value = "reson", required = true) String reson){
        try {
            DevicePatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
//                if (!StringUtils.equals(pd.getUser(), getUID())) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                //居民自主解绑设备时发送消息给医生
                BasePatientDO patient = patientService.findById(getRepUID()).orElse(null);
                String messageContent =  "您的居民"+patient.getName()+"申请解绑智能设备:"+pd.getDeviceName()+",请及时处理";
//                if ("1".equals(pd.getCategoryCode())){
//                    messageContent +="血糖仪,点击下方查看居民详情";
//                }else if ("2".equals(pd.getCategoryCode())){
//                    messageContent +="血压计,点击下方查看居民详情";
//                }else if ("4".equals(pd.getCategoryCode())){
//                    messageContent +="智能手表,点击下方查看居民详情";
//                }
                
                JSONObject contentObj = new JSONObject();
                contentObj.put("reason",reson);
                contentObj.put("messageContent",messageContent);
                contentObj.put("patientName",patient.getName());
                
/*                Message message = new Message();
                message.setCzrq(new Date());
                message.setCreateTime(new Date());
                message.setContent(contentObj.toString());
                message.setRead(1);//设置未读
                message.setReceiver(signFamily.getDoctor());//设置接受医生的code
                message.setSender("admin");//设置发送的用户
                message.setSenderName("系统");
                message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
                message.setSenderPhoto("");
                message.setTitle("解绑设备审核消息");
                message.setType(302);//解绑设备消息
                message.setReadonly(1);//是否只读消息
                message.setSex(1);
                message.setRelationCode(id);
                message.setOver("1");//未处理
                message.setData("");
                message.setDel("1");
                messageDao.save(message);*/
    
                pd.setApplyStatus(1);//审核中
                pd.setApplyReason(reson);
                patientDeviceDao.save(pd);
                
                return success("申请成功!");
            } else {
                return error(-1, "不存在该设备!");
            }
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    /**
     * 设备删除
     */
    @ApiOperation("设备删除")
    @RequestMapping(value = "DeletePatientDevice",method = {RequestMethod.GET,RequestMethod.POST})
    public String delete(@ApiParam(name = "id", value = "删除设备关联ID")
                         @RequestParam(value = "id", required = true) String id) {
        try {
            DevicePatientDevice pd = patientDeviceService.findById(id);
            if (pd != null) {
//                if (!StringUtils.equals(pd.getUser(), getUID())) {
                if (!StringUtils.equals(pd.getUser(), getRepUID())) {
                    return error(-1, "只允许删除自己的设备!");
                }
                // 删除设备
                patientDeviceService.deleteDevice(id, getRepUID());
//                patientDeviceService.deleteDevice(id, getUID());
                //居民自主解绑设备时发送消息给医生
                BasePatientDO patient = patientService.findById(getRepUID()).orElse(null);
                String messageContent =  "您的居民"+patient.getName()+"解绑了";
                if ("1".equals(pd.getCategoryCode())){
                    messageContent +="血糖仪,点击下方查看居民详情";
                }else if ("2".equals(pd.getCategoryCode())){
                    messageContent +="血压计,点击下方查看居民详情";
                }else if ("4".equals(pd.getCategoryCode())){
                    messageContent +="智能手表,点击下方查看居民详情";
                }
/*                Message message = new Message();
                message.setCzrq(new Date());
                message.setCreateTime(new Date());
                message.setContent(messageContent);
                message.setRead(1);//设置未读
                message.setReceiver(signFamily.getDoctor());//设置接受医生的code
                message.setSender("admin");//设置发送的用户
                message.setSenderName("系统");
                message.setCode(UUID.randomUUID().toString().replaceAll("-", ""));
                message.setSenderPhoto("");
                message.setTitle("解绑设备消息");
                message.setType(301);//解绑设备消息
                message.setReadonly(1);//是否只读消息
                message.setSex(1);
                message.setRelationCode(patient.getCode());
                message.setOver("1");//未处理
                message.setData("");
                message.setDel("1");
                messageDao.save(message);*/
                //全部解绑后去判断就更新设备表中是否绑定字段
                patientDeviceLogService.savePatientDeviceLog(pd,pd.getDeviceSn(),2,2);
                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)
    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,"执行失败!");
        }
    }
}

+ 564 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/PatientHealthController.java

@ -0,0 +1,564 @@
package com.yihu.jw.hospital.module.health.controller;
import com.yihu.jw.entity.base.device.PatientHealthStandard;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.hospital.module.common.BaseController;
import com.yihu.jw.hospital.module.health.service.PatientHealthIndexService;
import com.yihu.jw.util.entity.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping(value = "/patient/health_index")
@Api(description = "患者指标")
public class PatientHealthController extends BaseController {
    @Autowired
    private PatientHealthIndexService healthIndexService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 更改接口(包括手动记录的修改和所有的删除)
     * 血糖  value1 血糖值 value2 1234567血糖时间段
     * 血压  value1 高压 value2 低压 value3脉搏 value4心率不齐(0否 1是)
     * 体重 value1 体重值
     * 腰围 value1 腰围值
     *  @param recordDate 记录时间
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ApiOperation("更改接口(包括手动记录的修改和所有的删除)")
    public String modify(@RequestParam long id,
                         @RequestParam(required = false) String recordDate,
                         @RequestParam(required = false) String value1,
                         @RequestParam(required = false) String value2,
                         @RequestParam(required = false) String value3,
                         @RequestParam(required = false) String value4) {
        try {
            healthIndexService.modify(id,recordDate, value1, value2, value3, value4);
            return write(200, "更改成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "更改失败!");
        }
    }
    @RequestMapping(value = "/getRecentData", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("患者最近的各项健康信息")
    public String getRecentData() {
        try {
            List list = new ArrayList();
            String patient = getRepUID();
//            String patient = getUID();
//            健康指标类型(1血糖,2血压,3体重,4腰围)
            Map map = healthIndexService.findDataByPatient(patient, 1);
            Map map1 = healthIndexService.findDataByPatient(patient, 2);
            Map map2 = healthIndexService.findDataByPatient(patient, 3);
            Map map3 = healthIndexService.findDataByPatient(patient, 4);
//            血糖各个时间段取值
            if (map.size() != 0) {
                Map sugar = new HashMap();
                Object time = map.get("time");
                String isDevice = map.get("isDevice").toString();
                Object value1 = map.get("value1");
                Object value2 = map.get("value2");
                Object value3 = map.get("value3");
                Object value4 = map.get("value4");
                Object value5 = map.get("value5");
                Object value6 = map.get("value6");
                Object value7 = map.get("value7");
                sugar.put("type", 1);
                sugar.put("isDevice", isDevice);
                if (time != null) {
                    sugar.put("time", time);
                }
                if (value1 != null) {
                    sugar.put("value1", value1);
                }
                if (value2 != null) {
                    sugar.put("value2", value2);
                }
                if (value3 != null) {
                    sugar.put("value3", value3);
                }
                if (value4 != null) {
                    sugar.put("value4", value4);
                }
                if (value5 != null) {
                    sugar.put("value5", value5);
                }
                if (value6 != null) {
                    sugar.put("value6", value6);
                }
                if (value7 != null) {
                    sugar.put("value7", value7);
                }
                list.add(sugar);
            }
//            血压  value1高压 value2低压 value3脉搏 value4心率不齐
            if (map1.size() != 0) {
                Map pa = new HashMap();
                Object time = map1.get("time");
                String isDevice = map1.get("isDevice").toString();
                Object value1 = map1.get("value1");
                Object value2 = map1.get("value2");
                Object value3 = map1.get("value3");
                Object value4 = map1.get("value4");
                Object value5 = map1.get("value5");
                Object value6 = map1.get("value6");
                Object value7 = map1.get("value7");
                pa.put("type", 2);
                pa.put("isDevice", isDevice);
                if (time != null) {
                    pa.put("time", time);
                }
                if (value1 != null) {
                    pa.put("value1", value1);
                }
                if (value2 != null) {
                    pa.put("value2", value2);
                }
                if (value3 != null) {
                    pa.put("value3", value3);
                }
                if (value4 != null) {
                    pa.put("value4", value4);
                }
                if (value5 != null) {
                    pa.put("value5", value5);
                }
                if (value6 != null) {
                    pa.put("value6", value6);
                }
                if (value7 != null) {
                    pa.put("value7", value7);
                }
                list.add(pa);
            }
//            体重 value1 体重
            if (map2.size() != 0) {
                Map weight = new HashMap();
                Object time = map2.get("time");
                String isDevice = map2.get("isDevice").toString();
                Object value1 = map2.get("value1");
                Object value2 = map2.get("value2");
                Object value3 = map2.get("value3");
                Object value4 = map2.get("value4");
                Object value5 = map2.get("value5");
                Object value6 = map2.get("value6");
                Object value7 = map2.get("value7");
                weight.put("type", 3);
                weight.put("isDevice", isDevice);
                if (time != null) {
                    weight.put("time", time);
                }
                if (value1 != null) {
                    weight.put("value1", value1);
                }
                if (value2 != null) {
                    weight.put("value2", value2);
                }
                if (value3 != null) {
                    weight.put("value3", value3);
                }
                if (value4 != null) {
                    weight.put("value4", value4);
                }
                if (value5 != null) {
                    weight.put("value5", value5);
                }
                if (value6 != null) {
                    weight.put("value6", value6);
                }
                if (value7 != null) {
                    weight.put("value7", value7);
                }
                list.add(weight);
            }
//            腰围 value1腰围
            if (map3.size() != 0) {
                Map waist = new HashMap();
                Object time = map3.get("time");
                String isDevice = map3.get("isDevice").toString();
                Object value1 = map3.get("value1");
                Object value2 = map3.get("value2");
                Object value3 = map3.get("value3");
                Object value4 = map3.get("value4");
                Object value5 = map3.get("value5");
                Object value6 = map3.get("value6");
                Object value7 = map3.get("value7");
                waist.put("type", 4);
                waist.put("isDevice", isDevice);
                if (time != null) {
                    waist.put("time", time);
                }
                if (value1 != null) {
                    waist.put("value1", value1);
                }
                if (value2 != null) {
                    waist.put("value2", value2);
                }
                if (value3 != null) {
                    waist.put("value3", value3);
                }
                if (value4 != null) {
                    waist.put("value4", value4);
                }
                if (value5 != null) {
                    waist.put("value5", value5);
                }
                if (value6 != null) {
                    waist.put("value6", value6);
                }
                if (value7 != null) {
                    waist.put("value7", value7);
                }
                list.add(waist);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "recent", method = RequestMethod.GET)
    @ApiOperation("患者最近填写的健康指标")
    public String recent() {
        try {
            JSONArray array = healthIndexService.findRecentByPatient(getRepUID());
            if (array != null) {
                return write(200, "查询成功", "list", array);
            } else {
                return error(-1, "查询失败");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "last", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation("获取患者最后填写的健康指标(新)")
    public String last() {
        try {
            Map<String, Object> map = new HashMap<>();
            String patient = getRepUID();
            DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
            if (xt != null) {
                map.put("xt", xt);
            }
            DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
            if (xy != null) {
                map.put("xy", xy);
            }
            DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
            if (tz != null) {
                map.put("tz", tz);
            }
            DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
            if (sg != null) {
                map.put("sg", sg);
            }
            DevicePatientHealthIndex xl = healthIndexService.findLastByPatienIot(patient, 5);
            if (xl != null) {
                map.put("xl", xl);
            }
            return write(200, "查询成功", "data", map);
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "last_new", method = RequestMethod.GET)
    @ApiOperation("获取患者最后填写的健康指标(新)-展会")
    public String last_new() {
        try {
            Map<String, Object> map = new HashMap<>();
            String patient = getRepUID();
            DevicePatientHealthIndex xt = healthIndexService.findLastByPatienIot(patient, 1);
            if (xt != null) {
                map.put("xt", xt);
            }
            DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
            if (xy != null) {
                map.put("xy", xy);
            }
            DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
            if (tz != null) {
                map.put("tz", tz);
            }
            DevicePatientHealthIndex sg = healthIndexService.findLastByPatienIot(patient, 4);
            if (sg != null) {
                map.put("sg", sg);
            }
            DevicePatientHealthIndex xl = healthIndexService.findLastByPatienIot(patient, 5);
            if (xl != null) {
                map.put("xl", xl);
            }
            return write(200, "查询成功", "data", map);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "addPatientHealthIndex", method = RequestMethod.POST)
    @ApiOperation("新增患者指标")
    public String addPatientHealthIndex(@ApiParam(name = "data", value = "指标数据", defaultValue = "{\"gi\":\"5.5\",\"gi_type\":\"1\"}")
                                        @RequestParam(value = "data", required = true) String data,
                                        @ApiParam(name = "type", value = "指标类型", defaultValue = "1")
                                        @RequestParam(value = "type", required = true) String type,
                                        @ApiParam(name = "patient", value = "patient", defaultValue = "1")
                                        @RequestParam(value = "patient", required = false) String patient) {
        try {
            if(StringUtils.isBlank(patient)){
                patient = getRepUID();
            }
            DevicePatientHealthIndex obj = healthIndexService.addPatientHealthIndex(data, type, patient, null);
            
            //血糖和血压需要校验
            if (type.equals("1") || type.equals("2")) {
                healthIndexService.verifyHealthIndex(obj.getId());
            }
            //判断居民的体征预警状态
//            healthIndexService.handlePatientStandarStatus(obj);
            return success("新增患者指标成功!");
        } catch (ServiceException se) {
            return write(-1,se.getMessage());
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "verifyPatientHealthIndex", method = RequestMethod.POST)
    @ApiOperation("校验患者指标")
    public String verifyPatientHealthIndex(@ApiParam(name = "id", value = "指标id", defaultValue = "")
                                           @RequestParam(value = "id", required = true) Long id) {
        try {
            healthIndexService.verifyHealthIndex(id);
            return success("校验患者指标成功!");
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
    @RequestMapping(value = "chart", method = RequestMethod.POST)
    @ApiOperation("根据患者标志获取健康指标(图表)")
    public String getHealthIndexChartByPatient(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重,4腰围)", defaultValue = "1")
                                               @RequestParam(value = "type", required = true) int type,
                                               @ApiParam(name = "gi_type", value = "就餐类型0全部", defaultValue = "1")
                                               @RequestParam(value = "gi_type", required = false) int gi_type,
                                               @ApiParam(name = "begin", value = "开始时间", defaultValue = "2017-05-22 00:00:00")
                                               @RequestParam(value = "begin", required = true) String begin,
                                               @ApiParam(name = "end", value = "结束时间", defaultValue = "2017-06-02 00:00:00")
                                               @RequestParam(value = "end", required = true) String end) {
        try {
            JSONArray jsonArray = healthIndexService.findChartByPatient(getRepUID(), type, gi_type, begin, end);
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "chart_new", method = RequestMethod.POST)
    @ApiOperation("根据患者标志获取健康指标(图表)-展会")
    public String getHealthIndexChartByPatient_new(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重,4腰围)", defaultValue = "1")
                                               @RequestParam(value = "type", required = true) int type,
                                               @ApiParam(name = "gi_type", value = "就餐类型0全部", defaultValue = "1")
                                               @RequestParam(value = "gi_type", required = false) int gi_type,
                                               @ApiParam(name = "begin", value = "开始时间", defaultValue = "2017-05-22 00:00:00")
                                               @RequestParam(value = "begin", required = true) String begin,
                                               @ApiParam(name = "end", value = "结束时间", defaultValue = "2017-06-02 00:00:00")
                                               @RequestParam(value = "end", required = true) String end) {
        try {
            JSONArray jsonArray = healthIndexService.findChartByPatient(getRepUID(), type, gi_type, begin, end);
            if (jsonArray.length()==0) {
                return success("查询成功!");
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiOperation("患者获取健康指标")
    public String getHealthIndexByPatient(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重/身高,4腰围)", defaultValue = "1")
                                          @RequestParam(value = "type", required = true) int type,
                                          @ApiParam(name = "start", value = "开始时间", defaultValue = "2016-07-23 00:00:00")
                                          @RequestParam(value = "start", required = true) String start,
                                          @ApiParam(name = "end", value = "结束时间", defaultValue = "2016-08-23 00:00:00")
                                          @RequestParam(value = "end", required = true) String end,
                                          @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                          @RequestParam(value = "page", required = true) int page,
                                          @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                          @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            JSONObject jsonObject2 = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            if (type == 1) {
                List<Object> list = healthIndexService.findIndexByPatient2(getRepUID(), type, start, end, page, pagesize);
                jsonObject2.put("data",list);
            } else {
                jsonArray = healthIndexService.findIndexByPatient(getRepUID(), type, start, end, page, pagesize);
                JSONArray jsonArray1 = new JSONArray();
                jsonObject2.put("data",jsonArray);
            }
            return write(200, "查询成功", "list", jsonObject2);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "list_new", method = RequestMethod.POST)
    @ApiOperation("患者获取健康指标-展会")
    public String getHealthIndexByPatient_new(@ApiParam(name = "type", value = "指标类型(1血糖,2血压,3体重/身高,4腰围)", defaultValue = "1")
                                          @RequestParam(value = "type", required = true) int type,
                                          @ApiParam(name = "start", value = "开始时间", defaultValue = "2016-07-23 00:00:00")
                                          @RequestParam(value = "start", required = true) String start,
                                          @ApiParam(name = "end", value = "结束时间", defaultValue = "2016-08-23 00:00:00")
                                          @RequestParam(value = "end", required = true) String end,
                                          @ApiParam(name = "page", value = "第几页", defaultValue = "1")
                                          @RequestParam(value = "page", required = true) int page,
                                          @ApiParam(name = "pagesize", value = "每页几行", defaultValue = "10")
                                          @RequestParam(value = "pagesize", required = true) int pagesize) {
        try {
            JSONArray jsonArray = new JSONArray();
            if (type == 1) {
                List<Object> list = healthIndexService.findIndexByPatient2(getRepUID(), type, start, end, page, pagesize);
                jsonArray = new JSONArray(list);
            } else {
                jsonArray = healthIndexService.findIndexByPatient(getRepUID(), type, start, end, page, pagesize);
            }
            return write(200, "查询成功", "list", jsonArray);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    @RequestMapping(value = "standard", method = RequestMethod.GET)
    @ApiOperation("患者健康指标预警值查询")
    public String standard() {
        try {
            JSONArray standardArray = new JSONArray();
            JSONArray userArray = new JSONArray();
            Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(getRepUID());
            Iterator<PatientHealthStandard> iterator = null;
            if (iterable != null) {
                iterator = iterable.iterator();
            }
            // 预警值未设置,返回默认值
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            // 默认血糖(餐前,餐后二小时)
            sb.append("{min_value_1:3.9, max_value_1:6.1, min_value_2:4.4, max_value_2:7.8, type:1},");
            // 默认血压(收缩压,舒张压)
            sb.append("{min_value_1:90, max_value_1:139, min_value_2:60, max_value_2:89, type:2}");
            sb.append("]");
            standardArray = new JSONArray(sb.toString());
            if (iterator != null) {
                while (iterator.hasNext()) {
                    PatientHealthStandard phs = iterator.next();
                    if (phs == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // 最低安全值(血糖餐前\收缩压\体重\腰围)
                    json.put("min_value_1", phs.getMinValue1());
                    // 最高安全值(血糖餐前\收缩压\体重\腰围)
                    json.put("max_value_1", phs.getMaxValue1());
                    // 最低安全值(血糖餐后\舒张压)
                    json.put("min_value_2", phs.getMinValue2());
                    // 最高安全值(血糖餐后\舒张压)
                    json.put("max_value_2", phs.getMaxValue2());
                    // 健康指标类型:1血糖,2血压,3体重,4腰围
                    json.put("type", phs.getType());
                    userArray.put(json);
                }
            }
            JSONObject json = new JSONObject();
            json.put("standard", standardArray);
            json.put("custom", userArray);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 奕拓小屋查询体征数据,根据体征类型查询
     *
     * @param type
     * @param page
     * @param size
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping(value = "/getDataByType")
    @ApiOperation(value = "体征类型查询数据", notes = "体征类型查询数据")
    public String getDataByType(
            @ApiParam(name = "type", value = "体征类型", required = true) @RequestParam String type,
            @ApiParam(name = "page", value = "页", required = true) @RequestParam(defaultValue = "1") int page,
            @ApiParam(name = "size", value = "数量", required = true) @RequestParam(defaultValue = "15") int size,
            @ApiParam(name = "beginTime", value = "开始时间", required = false) @RequestParam String beginTime,
            @ApiParam(name = "endTime", value = "结束时间", required = false) @RequestParam String endTime
    ) throws Exception {
        return write(200, "查询成功", "data", new ArrayList<>());
    }
    /**
     * 奕拓小屋查询体征数据,根据设备记录id查询详情
     *
     * @param mid
     * @return
     */
    @GetMapping(value = "/getDataDetailById")
    @ApiOperation(value = "根据设备id查询详情", notes = "数据详情")
    public String getDataDetailById(
            @ApiParam(name = "mid", value = "设备测试记录id", required = true) @RequestParam String mid,
            @ApiParam(name = "t'y'pe", value = "体征类型", required = true) @RequestParam String type
    ) throws Exception {
        return write(200, "查询成功", "data", new ArrayList<>());
    }
}

+ 189 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceDetailService.java

@ -0,0 +1,189 @@
package com.yihu.jw.hospital.module.health.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.device.dao.DeviceDetailDao;
import com.yihu.jw.device.dao.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.DevicePatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
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 {
	@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(DevicePatientDevice patientDevice, Date grantTime, boolean isFirst)throws Exception{
		DeviceDetail deviceDetail = deviceDetailDao.findBySn(patientDevice.getDeviceSn());
		int bind = deviceDetail.getIsBinding();
//		SignFamily signFamily = signFamilyDao.findByIdcard(patientDevice.getUserIdcard());
		long adminTeam=0L;
		String hospital = "";
		String isFirstBind = "";
		String hospitalName = "";
		String doctorCode ="";
		String doctorName="";
		String keyType = "1";
		if ("2".equals(patientDevice.getUserType())){
			keyType="2";
		}
//		if (signFamily!=null){
//			adminTeam = signFamily.getAdminTeamId();
//			hospital = signFamily.getHospital();
//			hospitalName = signFamily.getHospitalName();
//			doctorCode = signFamily.getDoctor();
//			doctorName = signFamily.getDoctorName();
//		}
		//设备表没有数据则插入一条数据
		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, "",patientDevice.getDeviceSn()});
		}else {
			List<DevicePatientDevice> 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,"",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(DevicePatientDevice 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()).orElse(null);
		BaseDoctorDO doctor = doctorDao.findByIdAndDel(patientDevice.getDoctor());
		Device device = deviceDao.findById(patientDevice.getDeviceId()).orElse(null);
		//添加数据到具体字段
		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<DevicePatientDevice> patientDeviceList = patientDeviceDao.findByDeviceSn(deviceSn);
		String sql = "update wlyy_devices dd set dd.is_binding=? where dd.device_code=?";
		if (patientDeviceList.size()==0){
			jdbcTemplate.update(sql,new Object[]{0,deviceSn});
		}
		if (patientDeviceList.size()==1){
			jdbcTemplate.update(sql,new Object[]{1,deviceSn});
		}
		if (patientDeviceList.size()>1){
			jdbcTemplate.update(sql,new Object[]{2,deviceSn});
		}
	}
	public DeviceDetail findByDeviceSn(String deviceSn){
		return deviceDetailDao.findBySn(deviceSn);
	}
}

+ 51 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceService.java

@ -0,0 +1,51 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.DeviceCategoryDao;
import com.yihu.jw.device.dao.DeviceDao;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceCategory;
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 {
	@Autowired
	private DeviceCategoryDao deviceCategoryDao;
	@Autowired
	private DeviceDao deviceDao;
	/**
	 * 查询所有的设备类型
	 * @return
	 */
	public List<DeviceCategory> findAllCategory() {
		return deviceCategoryDao.findAll();
	}
	/**
	 * 查询设备信息
	 */
	public List<Device> findDeviceByCategory(String categoryCode) {
		return deviceDao.findByCategoryCode(categoryCode);
	}
	/**
	 * 获取设备信息
     */
	public Device findById(String id)
	{
		return deviceDao.findById(Long.valueOf(id)).orElse(null);
	}
}

+ 93 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/DeviceWxMessageService.java

@ -0,0 +1,93 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.DeviceWxMessageDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.base.device.DeviceWxMessage;
import com.yihu.jw.restmodel.base.device.DeviceWxMessageDTO;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONArray;
import org.json.JSONObject;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@Transactional(rollbackFor = Exception.class)
public class DeviceWxMessageService{
    @Autowired
    private DeviceWxMessageDao deviceWxMessageDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<DeviceWxMessageDTO> batchSaveAndSendActiveMq(String data)throws Exception{
        JSONArray jsonArray = new JSONArray(data);
        List<DeviceWxMessage> messageList = new ArrayList<>();
        for (int i=0;i<jsonArray.length();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            DeviceWxMessage deviceWxMessage = new DeviceWxMessage();
            deviceWxMessage.setPatient(jsonObject.getString("patient"));
            deviceWxMessage.setCategoryCode(jsonObject.getString("categoryCode"));
            deviceWxMessage.setDeviceName(jsonObject.getString("deviceName"));
            deviceWxMessage.setDeviceSn(jsonObject.getString("deviceSn"));
            deviceWxMessage.setCzrq(new Date());
            messageList.add(deviceWxMessage);
        }
        //批量插入数据
        deviceWxMessageDao.saveAll(messageList);
        //放入队列的数据集(相同用户不同设备各发一条  相同设备发一条)
        Map<String,List<String>> map = new HashedMap();
        for (DeviceWxMessage deviceWxMessage : messageList) {
            List<String> deviceTypeList = null;
            if (map.containsKey(deviceWxMessage.getPatient())){
                deviceTypeList = map.get(deviceWxMessage.getPatient());
                if (deviceTypeList==null){
                    deviceTypeList = new ArrayList<>();
                    deviceTypeList.add(deviceWxMessage.getCategoryCode());
                    map.put(deviceWxMessage.getPatient(),deviceTypeList);
                }else {
                    boolean flag = false;
                    if (!deviceTypeList.contains(deviceWxMessage.getCategoryCode())){
                        flag=true;
                    }
                    if (flag){
                        deviceTypeList.add(deviceWxMessage.getCategoryCode());
                        map.put(deviceWxMessage.getPatient(),deviceTypeList);
                    }
                }
            }else {
                deviceTypeList = new ArrayList<>();
                deviceTypeList.add(deviceWxMessage.getCategoryCode());
                map.put(deviceWxMessage.getPatient(),deviceTypeList);
            }
         }
        List<DeviceWxMessageDTO> deviceWxMessageDTOS = new ArrayList<>();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
            String patient = entry.getKey();
            List<String> list = entry.getValue();
            for (String deviceType : list){
                DeviceWxMessageDTO deviceWxMessageDTO =  new DeviceWxMessageDTO();
                deviceWxMessageDTO.setPatient(patient);
                deviceWxMessageDTO.setDeviceType(Integer.valueOf(deviceType));
                deviceWxMessageDTO.setCzrq(DateUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
                deviceWxMessageDTOS.add(deviceWxMessageDTO);
            }
        }
        return deviceWxMessageDTOS;
    }
}

+ 129 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceLogService.java

@ -0,0 +1,129 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.device.dao.PatientDeviceLogDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.patient.PatientDeviceLog;
import com.yihu.jw.patient.dao.BasePatientDao;
import org.apache.commons.collections.map.HashedMap;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceLogService {
    @Autowired
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BasePatientDao patientDao;
    /**
     * 绑定和解绑的时候会保存一条数据
     * @param patientDevice
     * @param role
     * @param operateCode
     * @throws Exception
     */
    @Transactional
    public void savePatientDeviceLog(DevicePatientDevice patientDevice, String deviceSn, int role, int operateCode)throws Exception{
       if (patientDevice==null){
           patientDevice = patientDeviceDao.findByDeviceSn(deviceSn).get(0);
       }
        PatientDeviceLog patientDeviceLog = new PatientDeviceLog();
        patientDeviceLog.setDeviceId(patientDevice.getDeviceId());
        patientDeviceLog.setPatient(patientDevice.getUser());
        patientDeviceLog.setCategoryCode(patientDevice.getCategoryCode());
        patientDeviceLog.setDeviceName(patientDevice.getDeviceName());
        patientDeviceLog.setDeviceSn(patientDevice.getDeviceSn());
        patientDeviceLog.setRole(role);
        patientDeviceLog.setOperateCode(operateCode);
        patientDeviceLog.setAgreementPhoto(patientDevice.getAgreementPhoto());
        patientDeviceLog.setHospital(patientDevice.getHospital());
        patientDeviceLog.setHospitalName(patientDevice.getHospitalName());
        patientDeviceLog.setCheckDoctorName(patientDevice.getCheckDoctorName());
        if (role==1){
            patientDeviceLog.setOperatorName(patientDevice.getDoctorName());
            patientDeviceLog.setOperator(patientDevice.getDoctor());
        }else if (role==2){
            if(StringUtils.isEmpty(patientDevice.getAgent())){
                BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
                if (patient!=null){
                    patientDeviceLog.setOperatorName(patient.getName());
                    patientDeviceLog.setOperator(patient.getId());
                }
            }else {
                patientDeviceLog.setOperatorName(patientDevice.getAgentName());
                patientDeviceLog.setOperator(patientDevice.getAgent());
            }
        }
        patientDeviceLog.setCreateTime(new Date());
        patientDeviceLog.setIsDel(1);
        patientDeviceLogDao.save(patientDeviceLog);
    }
    public Map<String,Object> getDevicesList(String doctor,String noGaugeDay,String isBinding,String categoryCode,String isSend,int pageNo,int pageSize){
        List<Map<String,Object>> resultList =  new ArrayList<>();
        Map<String,Object> resultMap = new HashedMap();
        int start = (pageNo-1)*pageSize;
        String sql ="SELECT b.*,dd.photo FROM (SELECT a.* FROM (" +
                "  SELECT sf.name, pd.* FROM wlyy_patient_device_log pd" +
                "  LEFT JOIN wlyy_sign_family sf ON pd.patient = sf.patient" +
                "  WHERE" +
                "  pd.is_del = 1 and sf.doctor= '"+doctor+"'  and sf.`status`>0"+
                "  ORDER BY" +
                "  pd.create_time DESC) a" +
                " GROUP BY a.device_sn,a.patient) b" +
                " LEFT JOIN dm_device dd ON b.device_id = dd.id where 1=1 ";
        resultList = jdbcTemplate.queryForList(sql);
        resultMap.put("tatalCount",resultList.size());
        //筛选条件--是否绑定
        if (!StringUtils.isEmpty(isBinding)){
            sql += " and b.operate_code= "+isBinding;
        }
        //筛选条件--设备类型
        if (!StringUtils.isEmpty(categoryCode)){
            sql += " and b.category_code= "+categoryCode;
        }
        //筛选条件--今日未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("1",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE TO_DAYS(record_date)=TO_DAYS(NOW()))";
        }
        //筛选条件--七天内未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("2",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= DATE(record_date))";
        }
        //筛选条件--一个月内未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("3",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE DATE_SUB(CURDATE(), INTERVAL 1 MONTH) <= DATE(record_date))";
        }
        //筛选条件--超过一个月未测量
        if (!StringUtils.isEmpty(noGaugeDay) && StringUtils.equals("4",noGaugeDay)){
            sql += " and b.patient NOT IN (SELECT user FROM wlyy_patient_health_index WHERE  DATE_SUB(DATE_SUB(CURDATE(), INTERVAL 1 MONTH),INTERVAL 1 DAY) <= DATE(record_date))";
        }
        //发送消息要筛选未发送消息的设备
        if (StringUtils.isNotEmpty(isSend)){
            sql += " and b.device_sn NOT IN (SELECT device_sn FROM wlyy_device_wx_message WHERE TO_DAYS(czrq) = TO_DAYS(NOW()))";
        }
        sql += " limit ?,?";
        resultList = jdbcTemplate.queryForList(sql,new Object[]{start,pageSize});
        resultMap.put("data",resultList);
        return resultMap;
    }
}

+ 652 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientDeviceService.java

@ -0,0 +1,652 @@
package com.yihu.jw.hospital.module.health.service;
import com.yihu.jw.device.dao.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.device.PatientBloodSugger;
import com.yihu.jw.entity.base.device.PatientHealthTime;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.entity.care.device.Device;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.patient.PatientDeviceLog;
import com.yihu.jw.message.service.WxMessageUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.persistence.criteria.Predicate;
import java.util.*;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientDeviceService  {
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private PatientBloodSuggerDao patientBloodSuggerDao;
    @Autowired
    private PatientHealthTimeDao patientHealthTimeDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDeviceLogDao patientDeviceLogDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    /**
     * 验证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(DevicePatientDevice 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) {
            DevicePatientDevice deviceOld = patientDeviceDao.findById(patientDevice.getId()).orElse(null);
            if (deviceOld != null) {
                if (deviceOld.getDeviceSn().equals(sn)) {
                    needVerify = false;
                }
            } else {
                throw new ServiceException("不存在该条记录!");
            }
        }
        //校验sn码是否被使用
        if (needVerify) {
            DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndUserType(sn, userType);
            if (device != null && !device.getId().equals(patientDevice.getId())) {
                throw new ServiceException("sn码" + sn + "已被使用!");
            }
        }
        patientDevice.setCzrq(new Date());
        patientDevice.setDel(0);
        //当前用户的身份证
        BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
        patientDevice.setUserIdcard(patient.getIdcard());
        if(checkDeviceSn(sn)){
            savePatientDevice(patientDevice);
        }else {
            String message = "设备不存在";
            throw new ServiceException(message);
        }
        return true;
    }
    /**
     * 设备绑定
     * @param patientDevice
     */
    public void savePatientDevice(DevicePatientDevice patientDevice){
        patientDeviceDao.save(patientDevice);
    }
    public void deleteDevices(String deviceSn, String type, String uuid) {
        List<DevicePatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (patientDevices == null || patientDevices.size() == 0) {
            throw new ServiceException("设备未被绑定!");
        }
        for (DevicePatientDevice patientDevice : patientDevices) {
            patientDeviceDao.delete(patientDevice);
        }
    }
    /**
     * 删除患者设备
     */
    public List<com.alibaba.fastjson.JSONObject> deleteDevice(String id, String uuid) {
        DevicePatientDevice device = patientDeviceDao.findById(Long.valueOf(id)).orElse(null);
        patientDeviceDao.delete(device);
        List<DevicePatientDevice> patientDevices = patientDeviceDao.findByDeviceSnAndCategoryCode(device.getDeviceSn(), device.getCategoryCode());
        List<com.alibaba.fastjson.JSONObject> objects = new ArrayList<>();
        for (DevicePatientDevice 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()).orElse(null);
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.add(object);
        }
        return objects;
    }
    /**
     * 患者设备列表接口(分页)
     */
    public Page<DevicePatientDevice> findByPatient(String patientCode,final Long id, int pageSize) {
        if (pageSize <= 0) {
            pageSize = 10;
        }
        // 排序
        Sort sort = Sort.by(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = PageRequest.of(0, pageSize, sort);
        Specification<DevicePatientDevice> specification = (root, criteriaQuery, criteriaBuilder) -> {
            //增加筛选条件
            Predicate predicate = criteriaBuilder.conjunction();
            predicate.getExpressions().add(criteriaBuilder.equal(root.get("user"), patientCode));
            predicate.getExpressions().add(criteriaBuilder.lt(root.get("id"), id));
            return predicate;
        };
        return patientDeviceDao.findAll(specification, 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 = PageRequest.of(page - 1, pagesize);
        List<DevicePatientDevice> list = new ArrayList<>();
        list = patientDeviceDao.findByUser(patientCode, pageRequest);
        if (list != null) {
            //获取设备路径,医生姓名
            List<Device> deviceList = deviceDao.findAll();
            BaseDoctorDO self = doctorDao.findByIdAndDel(doctorCode);
            for (DevicePatientDevice item : list) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isNotBlank(item.getDoctor())) {
                    if (StringUtils.equals(item.getDoctor(), doctorCode)) {
                        map.put("role", 1);//可解绑自己绑定的
                    } else {
                        map.put("role", 0);//不同行政团队不可解绑
                    }
                } 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.findByIdAndDel(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<DevicePatientDevice> findPatientHave(String patient) {
        return patientDeviceDao.findByUser(patient).iterator();
    }
    /**
     * 获取患者设备信息
     **/
    public DevicePatientDevice findById(String id) {
        return patientDeviceDao.findById(Long.valueOf(id)).orElse(null);
    }
    /**
     * 通过sn码获取设备绑定情况
     **/
    public List<Map<String, String>> getDeviceUser(String user, String deviceSn, String type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        List<DevicePatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        if (list != null) {
            for (DevicePatientDevice 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).orElse(null);
                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<DevicePatientDevice> list = patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn, type);
        JSONArray objects = new JSONArray();
        for (DevicePatientDevice patientDevice : list) {
            JSONObject object = new JSONObject(patientDevice);
            BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
            if (patient != null) {
                object.put("userName", patient.getName());
            }
            objects.put(object);
        }
        return objects;
    }
    /**
     * 获取血糖仪各个时间段(无参为默认时间段)
     *
     * @param user
     * @param deviceSN
     * @return
     */
    public Map getBloodSuggerTime(String user, String deviceSN) {
        Map map = new HashMap();
        PatientBloodSugger bloodSugger = null;
        PatientHealthTime patientHealthTime = null;
        if (!StringUtils.isEmpty(user) && !StringUtils.isEmpty(deviceSN)) {
            patientHealthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
        }
        String fastingStart = null;
        String fastingEnd = null;
        String afterBreakFastStart = null;
        String afterBreakFastEnd = null;
        String beforeLunchStart = null;
        String beforeLunchEnd = null;
        String afterLunchStart = null;
        String afterLunchEnd = null;
        String beforeDinnerStart = null;
        String beforeDinnerEnd = null;
        String afterDinnerStart = null;
        String afterDinnerEnd = null;
        String beforeSleepStart = null;
        String beforeSleepEnd = null;
        if (patientHealthTime == null) {
            bloodSugger = patientBloodSuggerDao.findRecent();
            fastingStart = bloodSugger.getFastingStart();
            fastingEnd = bloodSugger.getFastingEnd();
            afterBreakFastStart = bloodSugger.getAfterBreakfastStart();
            afterBreakFastEnd = bloodSugger.getAfterBreakfastEnd();
            beforeLunchStart = bloodSugger.getBeforeLunchStart();
            beforeLunchEnd = bloodSugger.getBeforeLunchEnd();
            afterLunchStart = bloodSugger.getAfterLunchStart();
            afterLunchEnd = bloodSugger.getAfterLunchEnd();
            beforeDinnerStart = bloodSugger.getBeforeDinnerStart();
            beforeDinnerEnd = bloodSugger.getBeforeDinnerEnd();
            afterDinnerStart = bloodSugger.getAfterDinnerStart();
            afterDinnerEnd = bloodSugger.getAfterDinnerEnd();
            beforeSleepStart = bloodSugger.getBeforeSleepStart();
            beforeSleepEnd = bloodSugger.getBeforeSleepEnd();
        } else {
            fastingStart = patientHealthTime.getFastingStart();
            fastingEnd = patientHealthTime.getFastingEnd();
            afterBreakFastStart = patientHealthTime.getAfterBreakfastStart();
            afterBreakFastEnd = patientHealthTime.getAfterBreakfastEnd();
            beforeLunchStart = patientHealthTime.getBeforeLunchStart();
            beforeLunchEnd = patientHealthTime.getBeforeLunchEnd();
            afterLunchStart = patientHealthTime.getAfterLunchStart();
            afterLunchEnd = patientHealthTime.getAfterLunchEnd();
            beforeDinnerStart = patientHealthTime.getBeforeDinnerStart();
            beforeDinnerEnd = patientHealthTime.getBeforeDinnerEnd();
            afterDinnerStart = patientHealthTime.getAfterDinnerStart();
            afterDinnerEnd = patientHealthTime.getAfterDinnerEnd();
            beforeSleepStart = patientHealthTime.getBeforeSleepStart();
            beforeSleepEnd = patientHealthTime.getBeforeSleepEnd();
        }
        map.put("fasting", fastingStart + " - " + fastingEnd);
        map.put("afterBreakFast", afterBreakFastStart + " - " + afterBreakFastEnd);
        map.put("beforeLunch", beforeLunchStart + " - " + beforeLunchEnd);
        map.put("afterLunch", afterLunchStart + " - " + afterLunchEnd);
        map.put("beforeDinner", beforeDinnerStart + " - " + beforeDinnerEnd);
        map.put("afterDinner", afterDinnerStart + " - " + afterDinnerEnd);
        map.put("beforeSleep", beforeSleepStart + " - " + beforeSleepEnd);
        return map;
    }
    /**
     * 用户自定义血糖仪各个时间段
     */
    public void setBloodTime(String user, String deviceSN, String fastingStart, String fastingEnd, String afterBreakfastStart, String afterBreakfastEnd, String beforeLunchStart, String beforeLunchEnd,
                             String afterLunchStart, String afterLunchEnd, String beforeDinnerStart, String beforeDinnerEnd, String afterDinnerStart, String afterDinnerEnd,
                             String beforeSleepStart, String beforeSleepEnd) throws Exception {
        if (StringUtils.isEmpty(fastingStart) && StringUtils.isEmpty(fastingEnd) && StringUtils.isEmpty(afterBreakfastStart) && StringUtils.isEmpty(afterBreakfastEnd) && StringUtils.isEmpty(beforeLunchStart)
                && StringUtils.isEmpty(beforeLunchEnd) && StringUtils.isEmpty(afterLunchStart) && StringUtils.isEmpty(afterLunchEnd) && StringUtils.isEmpty(beforeDinnerStart) && StringUtils.isEmpty(beforeDinnerEnd) && StringUtils.isEmpty(afterDinnerStart)
                && StringUtils.isEmpty(afterDinnerEnd) && StringUtils.isEmpty(beforeSleepStart) && StringUtils.isEmpty(beforeSleepEnd)) {
            patientHealthTimeDao.deleteByUserAndSN(user, deviceSN);
            return;
        }
        PatientHealthTime healthTime = patientHealthTimeDao.findByUserAndSN(user, deviceSN);
        if (healthTime == null) {
            PatientHealthTime patientHealthTime = new PatientHealthTime();
            patientHealthTime.setUser(user);
            patientHealthTime.setDeviceSN(deviceSN);
            patientHealthTime.setFastingStart(fastingStart);
            patientHealthTime.setFastingEnd(fastingEnd);
            patientHealthTime.setAfterBreakfastStart(afterBreakfastStart);
            patientHealthTime.setAfterBreakfastEnd(afterBreakfastEnd);
            patientHealthTime.setBeforeLunchStart(beforeLunchStart);
            patientHealthTime.setBeforeLunchEnd(beforeLunchEnd);
            patientHealthTime.setAfterLunchStart(afterLunchStart);
            patientHealthTime.setAfterLunchEnd(afterLunchEnd);
            patientHealthTime.setBeforeDinnerStart(beforeDinnerStart);
            patientHealthTime.setBeforeDinnerEnd(beforeDinnerEnd);
            patientHealthTime.setAfterDinnerStart(afterDinnerStart);
            patientHealthTime.setAfterDinnerEnd(afterDinnerEnd);
            patientHealthTime.setBeforeSleepStart(beforeSleepStart);
            patientHealthTime.setBeforeSleepEnd(beforeSleepEnd);
            patientHealthTime.setDel(1);
            patientHealthTime.setCzrq(new Date());
            patientHealthTimeDao.save(patientHealthTime);
        } else {
            int rows = patientHealthTimeDao.modifyByUserAndSN(fastingStart, fastingEnd, afterBreakfastStart, afterBreakfastEnd, beforeLunchStart, beforeLunchEnd,
                    afterLunchStart, afterLunchEnd, beforeDinnerStart, beforeDinnerEnd, afterDinnerStart, afterDinnerEnd, beforeSleepStart, beforeSleepEnd, user, deviceSN);
            int str = rows;
        }
    }
    /**
     * 根据user,deviceSN修改血糖时间段
     *
     * @param user
     * @param deviceSN
     * @param newDeviceSN
     * @throws Exception
     */
    public void updateDeviceSN(String user, String deviceSN, String newDeviceSN) throws Exception {
        patientHealthTimeDao.updateDeviceSN(user, deviceSN, newDeviceSN);
    }
    /**
     * 根据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;
    }
    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 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<DevicePatientDevice> list = patientDeviceDao.findByDeviceSn(deviceSn);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (DevicePatientDevice patientDevice : list) {
            Map<String,Object> infoMap = new HashedMap();
            BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
            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(DevicePatientDevice 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();
        //判断患者是否第一次绑定设备
        List<PatientDeviceLog> patientDeviceLogList = patientDeviceLogDao.findByPatientAndCategoryCode(patientDevice.getUser(),patientDevice.getCategoryCode());
        if (patientDeviceLogList!=null && patientDeviceLogList.size()>0){
            flag=false;
            msg="已经绑定过同样类型的设备了";
            code=-10000;
        }
        //设备是否是第一次被绑定
        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;
    }
    /**
     * 验证sn码 先调总部接口 未注册才查询本地数据库,如果也没有才不能绑定
     * @param deviceSn
     * @return
     * @throws Exception
     */
    public Map<String,Object> checkBindingDeviceSn(String deviceSn) throws Exception{
        Boolean flag = false;
        String message = "设备不存在!";
        Integer resultCode = 200;
        Map<String, String> params = new HashMap<>();
        params.put("deviceSn", deviceSn);
        Map<String,Object> map1 = new HashedMap();
        map1.put("code",resultCode);
        map1.put("message",message);
        map1.put("flag",flag);
        return map1;
    }
    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;
        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;
    }
    /**
     * 发送设备审核消息
     * @param patientDevice
     * @param type 1同意解绑,2不同意
     */
    public void sendWxMessage(DevicePatientDevice patientDevice, int type) {
        BasePatientDO patient = patientDao.findById(patientDevice.getUser()).orElse(null);
        WxTemplateConfigDO templateConfig = null;
        //判断是同意解绑还是拒绝解绑
        if(type == 1){
            templateConfig = wxMessageUtil.findByWechatIdAndTemplateNameAndSceneAndStatus(null,"template_process_feedback","unbind",1);
        }else if(type == 2) {
            templateConfig = wxMessageUtil.findByWechatIdAndTemplateNameAndSceneAndStatus(null,"template_process_feedback", "refuse",1);
        }
        WxTemplateConfigDO newConfig = new WxTemplateConfigDO();
        BeanUtils.copyProperties(templateConfig,newConfig);
        String first = newConfig.getFirst();
        first = first.replace("key1", patientDevice.getDeviceName());
        String keyword2 = newConfig.getKeyword2();
        if(keyword2.contains("key2")){
            keyword2 = keyword2.replace("key2", patientDevice.getRefuseReason());
        }
        newConfig.setFirst(first);
        newConfig.setKeyword2(keyword2);
        newConfig.setKeyword1(DateUtil.dateToStrShort(new Date()));
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("deviceId", patientDevice.getCategoryCode());
        json.put("id", patientDevice.getId());
        if(patient != null && StringUtils.isNotBlank(patient.getOpenid())) {
            wxMessageUtil.putWxMsg(null,  patient.getOpenid(),newConfig, 33, json);
        }
    }
}

+ 1933 - 0
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/service/PatientHealthIndexService.java

@ -0,0 +1,1933 @@
package com.yihu.jw.hospital.module.health.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.contant.DeviceHealthContant;
import com.yihu.jw.device.dao.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.device.*;
import com.yihu.jw.entity.base.im.ConsultTeamDo;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DeviceDetail;
import com.yihu.jw.entity.care.device.DevicePatientDevice;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.im.dao.ConsultTeamDao;
import com.yihu.jw.im.util.ImUtil;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.message.service.WxMessageUtil;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.common.CommonUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.entity.ServiceException;
import org.apache.commons.collections.map.HashedMap;
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 {
    private Logger logger = LoggerFactory.getLogger(PatientHealthIndexService.class);
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private BaseDoctorDao doctorDao;
    @Autowired
    private DevicePatientHealthIndexDao patientHealthIndexDao;
    @Autowired
    private PatientHealthStandardDao patientHealthStandardDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private WxMessageUtil wxMessageUtil;
    @Autowired
    private PatientAimSportsDao patientAimSportsDao;
    @Autowired
    private DoctorHealthStandardDao doctorHealthStandardDao;
    @Autowired
    private ImUtil imUtil;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private PatientAimBloodSuggerDao patientAimBloodSuggerDao;
    @Autowired
    private PatientAimBloodPressureDao patientAimBloodPressureDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    public DevicePatientHealthIndex getHealthIndexById(Long id) {
        return patientHealthIndexDao.findById(id).orElse(null);
    }
    /**
     * 获取居民标准预警值
     *
     * @param type
     * @param patientCode
     * @return
     */
    public JSONObject getealthStandard(Integer type, String patientCode) {
        //血糖校验
        JSONObject json = new JSONObject();
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueBefore = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueBefore = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueAfter = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueAfter = standard.getMinValue2();
                }
            }
            json.put("maxValueAfter", maxValueAfter);
            json.put("maxValueBefore", maxValueBefore);
            json.put("minValueBefore", minValueBefore);
            json.put("minValueAfter", minValueAfter);
        }
        //血压校验
        else if (type == 2) {
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            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 = 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 ServiceException("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);
                }
            }
            
            update(result);
            if ("1".equals(result.getType()) || "2".equals(result.getType())) {
                verifyHealthIndex(result.getId());
            }
        } else {
            throw new ServiceException("Result not exit!");
        }
        
    }
    
    /**
     * 获取居民最新各类健康记录
     */
    public Map findDataByPatient(String patient, int type) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sql = "SELECT " +
                " * " +
                " FROM " +
                "  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;
    }
    
    /**
     * 推送信息
     */
//    private void sendMessage(String content, BasePatientDO patient, DevicePatientHealthIndex model, String oldMsgContent) {
//        String patientCode = patient.getId();
//        String patientName = patient.getName();
//        // 消息接收者
//        List<String> receivers = new ArrayList<String>();
//        // 查询病人家庭签约的健康管理师
//        SignFamily signFamily = signFamilyDao.findByjiatingPatientYes(patientCode);
//        String healthDoctorFamily = "";
//        String doctorFamily = "";
//        /*String doctorName = "";
//        String doctorOpenID = "";*/
//        if (signFamily != null) {
//            healthDoctorFamily = signFamily.getDoctorHealth();
//            doctorFamily = signFamily.getDoctor();
//            if (StringUtils.isNotEmpty(healthDoctorFamily) && StringUtils.isNotEmpty(doctorFamily)){
//                // 添加到消息接收人列表
//                if (doctorFamily.equals(healthDoctorFamily)){
//                    System.out.println("-------------健管师和家医同一个人-------------");
//                    receivers.add(healthDoctorFamily);
//                }else {
//                    System.out.println("-------------健管师和家医不是同一个人-------------");
//                    receivers.add(healthDoctorFamily);
//                    receivers.add(doctorFamily);
//                }
//            }else if (StringUtils.isNotEmpty(healthDoctorFamily) && StringUtils.isEmpty(doctorFamily)){
//                System.out.println("-------------家医为空-------------");
//                receivers.add(healthDoctorFamily);
//            }else if (StringUtils.isNotEmpty(doctorFamily) && StringUtils.isEmpty(healthDoctorFamily)){
//                System.out.println("-------------健管师为空-------------");
//                receivers.add(doctorFamily);
//            }
//        }
//
//        List<Message> messages = new ArrayList<Message>();
//        JSONArray array = new JSONArray();
//        //判断是否是今日测量数据,如果不是则不进行体征干预
//        if(model.getRecordDate().compareTo(DateUtil.getNowDateShort()) > -1) {
//            for (String receiver : receivers) {
//                if (StringUtils.isEmpty(receiver)) {
//                    continue;
//                }
//                // 保存异常消息
//                Message message = new Message();
//                message.setCode(getCode());
//                message.setCzrq(new Date());
//                message.setCreateTime(new Date());
//                message.setRead(1);
//                message.setOver("1");
//                message.setReceiver(receiver);
//                message.setSender(patientCode);
//                message.setSex(patient.getSex());
//                message.setSenderName(patient.getName());
//                message.setSenderPhoto(patient.getPhoto());
//                message.setTitle("预警值信息");
//                message.setContent(content);
//                message.setType(2);
//                message.setDel("1");
//                message.setValue1(Double.valueOf(model.getValue1()));
//                message.setValue2(Double.valueOf(model.getValue2()));
//                message.setTzCode(String.valueOf(model.getId()));//消息关联的体征id
//                message.setTzType(String.valueOf(model.getType()));//体征类别 (1血糖,2血压,3体重,4腰围)
//                messages.add(message);
//
//                if (messageService.getMessageNoticeSettingByMessageType(receiver, "1", MessageNoticeSetting.MessageTypeEnum.healthSignSwitch.getValue())) {
//                    // 异常通知
//                    JSONObject json = new JSONObject();
//                    json.put("receiver", receiver);
//                    json.put("type", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.D_HI_01.name());
//                    json.put("title", MessageType.MESSAGE_TYPE_DOCTOR_HEALTH_INDEX.体征指标.name());
//                    json.put("msg", oldMsgContent);
//                    json.put("data", "");
//                    array.put(json);
//                }
//            }
//            // 批量保存消息
//            messageDao.save(messages);
//            for (String receiver : receivers) {
//                if (StringUtils.isEmpty(receiver)) {
//                    continue;
//                }
//
//            }
//            // 推送消息给医生
//            pushMsgTask.put(array);
//        }
//    }
    
    /**
     * 获取患者某天血糖值
     *
     * @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 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 = 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,Long 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 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 = findOne(id);
        String patientCode = data.getUser();
        //患者信息
        BasePatientDO patient = patientDao.findById(patientCode).orElse(null);
        
        int type = data.getType();
        String msgContent = "";
        String oldMsgContent = "";
        //血糖校验
        if (type == 1) {
            // 血糖记录,查询患者血糖预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 1);
            Double maxValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_AFTER;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueBefore = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueBefore = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueAfter = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueAfter = standard.getMinValue2();
                }
            }
            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();
            // 血压记录,查询患者血压预警值
            PatientHealthStandard standard = patientHealthStandardDao.findByPatientType(patientCode, 2);
            Double maxValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MIN;
            if (standard != null) {
                if (standard.getMaxValue1() > 0) {
                    maxValueSSY = standard.getMaxValue1();
                }
                if (standard.getMinValue1() > 0) {
                    minValueSSY = standard.getMinValue1();
                }
                if (standard.getMaxValue2() > 0) {
                    maxValueSZY = standard.getMaxValue2();
                }
                if (standard.getMinValue2() > 0) {
                    minValueSZY = standard.getMinValue2();
                }
            }
            // 收缩压/舒张压校验
            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);
            }
        }
        
        //超标则发送消息
        if (msgContent != null && msgContent.length() > 0) {
//            sendMessage(msgContent, patient, data,oldMsgContent);
        }
    }
    
    /********************************************物联网 start***********************************************************/
    /**
     * 修改体征异常状态
     * @param data
     */
    public void updateStatus(DevicePatientHealthIndex data){
        data.setStatus(1);
        patientHealthIndexDao.save(data);
    }
    
    /**
     * 按id查找体征记录
     * @param id
     * @return
     */
    public DevicePatientHealthIndex findOne(Long id){
        return patientHealthIndexDao.findById(id).orElse(null);
    }
    
    /**
     * 体征保存
     * @param data
     * @return
     */
    public DevicePatientHealthIndex save(DevicePatientHealthIndex data){
        return patientHealthIndexDao.save(data);
    }
    
    /**
     * 体征修改
     * @param data
     * @return
     */
    public DevicePatientHealthIndex update(DevicePatientHealthIndex data){
        return 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, Long page, Integer size){
        return patientHealthIndexDao.findDateList(patient,type,startDate,endDate,page,size);
    }
    
    
    public List<String> findDateListIot1(String patient,Date startDate,Date endDate, Long page, Integer size){
        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);
    }
    
    /**
     * 转map
     * @param index
     * @return
     */
    private Map<String, Object> indexToMap(DevicePatientHealthIndex index){
        Map<String, Object> map = new HashedMap();
        map.put("value1",index.getValue1());
        map.put("value2",index.getValue2());
        map.put("value3",index.getValue3());
        map.put("value4",index.getValue4());
        map.put("value5",index.getValue5());
        map.put("value6",index.getValue6());
        map.put("value7",index.getValue7());
        map.put("device_sn",index.getDeviceSn());
        map.put("record_date",index.getRecordDate());
        return map;
    }
    
    
    
    /********************************************物联网 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码一样的问题未解决!!)
            DevicePatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
            if (device != null) {
                patientCode = device.getUser();
                patient = patientDao.findById(patientCode).orElse(null);
                idcard = device.getUserIdcard();
            }
            DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
            if(deviceDetail!=null){
                obj.setHospital(deviceDetail.getGrantOrgCode());
                obj.setHospitalName(deviceDetail.getOrgName());
            }
        }
        //自输数据
        else {
            patient = patientDao.findById(patientCode).orElse(null);
            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); //身高
                    
                    PatientAimSports patientAimSports = new PatientAimSports();
                    patientAimSports = patientAimSportsDao.getPatientAimSportsByPatientCode(patientCode);
                    //如果该患者没有设置运动目标,则获取预置数据
                    if (patientAimSports == null || StringUtils.isBlank(patientAimSports.getCode())) {
                        patientAimSports = patientAimSportsDao.findByCode("default");
                    }
                    
                    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");
                    
                    if (patientAimSports != null && StringUtils.isNoneEmpty(patientAimSports.getCode())) {
                        bmiMin = Double.parseDouble(patientAimSports.getBmiMin());
                        bmiMax = Double.parseDouble(patientAimSports.getBmiMax());
                    }
                    
                    //设置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 ServiceException("暂不支持该指标!");
                }
            }
            
            obj = save(obj);
            
            //判断是否有未结束的续方咨询,发送消息给对应的医生
            sendPrescriptionHealthIndexMsgresult(obj,patient);
        } else {
            throw new ServiceException("不存在该患者!");
        }
        
        
        return obj;
    }
    
    /**
     * 判断是否有未结束的续方咨询,发送消息给对应的医生
     * @param result
     * @param patient
     */
    private void sendPrescriptionHealthIndexMsgresult(DevicePatientHealthIndex result, BasePatientDO patient) {
        
        List<ConsultTeamDo> consultTeams = consultTeamDao.findUnfinishedConsultPrescription(patient.getId());
        
        for (ConsultTeamDo consultTeam:consultTeams) {
            if(consultTeam.getHealthindexType() != null){
                JSONObject contentPatient = new JSONObject();
                //患者发送的消息
                contentPatient.put("title", "【本消息为系统提醒】:");
                if(1 == result.getType()){
                    contentPatient.put("tzMsg", "体征记录:血糖 "+result.getValue1()+" mmol/L");
                    contentPatient.put("type",2);
                }else if(2 == result.getType()){
                    contentPatient.put("tzMsg", "体征记录:血压 "+result.getValue1()+"/"+result.getValue2()+" mmHg");
                    contentPatient.put("type",1);
                }else{}
                
                contentPatient.put("tzTime", "检测时间:"+DateUtil.dateToStrLong(result.getRecordDate()));
                contentPatient.put("tzAlert","温馨提示:本条体征为居民上传的健康体征数据,您可以");
                contentPatient.put("needUpload","false");
                contentPatient.put("healthindexid",result.getId());//体征记录 ID
                
                //患者发送Im消息
                imUtil.sendTopicIM(patient.getId(), patient.getName(), consultTeam.getConsult(), "16", contentPatient.toString(), null);
            }
        }
    }
    
    /**
     * 设置默认监控方案
     * @param patient
     * @return
     */
    public String setDefaultAim(String patient){
        PatientAimBloodSugger patientAimBloodSugger = patientAimBloodSuggerDao.findByPatientcode(patient);
        PatientAimBloodPressure patientAimBloodPressure =  patientAimBloodPressureDao.findByPatientcode(patient);
        if(patientAimBloodSugger==null){
            PatientAimBloodSugger pa = new PatientAimBloodSugger();
            pa.setPatientcode(patient);
            pa.setCode(CommonUtil.getCode());
            pa.setCreateTime(new Date());
            pa.setUnit("mmol/L");
            pa.setFbg("7.0");
            pa.setHpg("11.1");
            pa.setFbgMin("4.0");
            pa.setHpgMin("4.0");
            patientAimBloodSuggerDao.save(pa);
        }
        if(patientAimBloodPressure==null){
            PatientAimBloodPressure pa = new PatientAimBloodPressure();
            pa.setPatientcode(patient);
            pa.setCode(CommonUtil.getCode());
            pa.setCreateTime(new Date());
            pa.setSbp("140");
            pa.setSbpMin("90");
            pa.setDbp("90");
            pa.setDbpMin("60");
            pa.setUnit("mmHg");
            patientAimBloodPressureDao.save(pa);
        }
        return "1";
    }
    /**
     * 按录入时间和患者标识查询健康记录
     *
     * @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 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 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 = 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 = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_BEFORE;
                Double minValueBefore = DeviceHealthContant.HEALTH_STANDARD_ST_MIN_BEFORE;
                Double maxValueAfter = DeviceHealthContant.HEALTH_STANDARD_ST_MAX_AFTER;
                Double minValueAfter = DeviceHealthContant.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 = DeviceHealthContant.HEALTH_STANDARD_SSY_MAX;
                Double minValueSSY = DeviceHealthContant.HEALTH_STANDARD_SSY_MIN;
                Double maxValueSZY = DeviceHealthContant.HEALTH_STANDARD_SZY_MAX;
                Double minValueSZY = DeviceHealthContant.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 = Sort.by(Direction.DESC, "recordDate");
            PageRequest pageRequest = PageRequest.of(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 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);
            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 = Sort.by(Direction.DESC, "recordDate");
            PageRequest pageRequest = PageRequest.of(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 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 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>> 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 = PageRequest.of(page, pageSize);
            //根据时间过滤排序
            List<String> dateList = findDateListIot(patient,type, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            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 = PageRequest.of(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 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 Iterable<PatientHealthStandard> findStandardByPatient(String patient) {
        return patientHealthStandardDao.findByPatient(patient);
    }
    
    /**
     * 保存患者健康指标预警值
     *
     * @param list
     */
    public Iterable<PatientHealthStandard> saveStandard(List<PatientHealthStandard> list, String patient) {
        // 先删除
        patientHealthStandardDao.deleteByPatient(patient);
        return patientHealthStandardDao.saveAll(list);
    }
    
    /**
     * 查询患者最近填写的血糖、血压等记录
     *
     * @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 = Sort.by(Direction.DESC, "recordDate");
        PageRequest pageRequest = PageRequest.of(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;
    }
    
    /**
     * 保存医生预警值方案
     *
     * @param doclist
     * @param uid
     * @return
     */
    public Iterable<DoctorHealthStandard> saveDocStandard(List<DoctorHealthStandard> doclist, String uid) throws Exception {
        // 先删除
        doctorHealthStandardDao.deleteByDoctor(uid);
        return doctorHealthStandardDao.saveAll(doclist);
    }
    
    /**
     * 查询患者健康指标预警值
     *
     * @param code
     * @return
     */
    public Iterable<DoctorHealthStandard> findDoctorStandardByDoctor(String code) {
        return doctorHealthStandardDao.findByDoctor(code);
    }
    
    /**
     * 批量保存患者预警方案
     *
     * @param list
     * @param patients
     * @return
     */
    public Iterable<PatientHealthStandard> saveStandardPatients(List<PatientHealthStandard> list, List<BasePatientDO> patients) {
        
        for (BasePatientDO patient : patients) {
            patientHealthStandardDao.deleteByPatient(patient.getId());
        }
        return patientHealthStandardDao.saveAll(list);
    }
    
    public List<Map<String, String>> getHealthIndexByPatientAndDate(String patientCode, String deviceSn, String choseDate,int type) throws Exception {
        List<Map<String, String>> re = new ArrayList<>();
        
        // 排序
        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;
    }
}

+ 3 - 2
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/controller/RehabilitationManageController.java

@ -364,13 +364,14 @@ public class RehabilitationManageController extends EnvelopRestEndpoint {
                                         @RequestParam(value = "article", required = false) String article,
                                         @ApiParam(name = "doctor", value = "医生code", required = false)
                                         @RequestParam(value = "doctor", required = false) String doctor,
                                         @ApiParam(name = "relationCode", value = "执行计划id", required = false)
                                         @RequestParam(value = "relationCode", required = false) String relationCode,
                                         @ApiParam(name = "page", value = "页码", required = false)
                                         @RequestParam(value = "page", required = false) Integer page,
                                         @ApiParam(name = "pagesize", value = "每页大小", required = false)
                                         @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        try {
            return rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,article,page,pagesize);
            return rehabilitationGuidanceService.selectPatientGuidances(patient,doctor,article,relationCode,page,pagesize);
        } catch (Exception e) {
            e.printStackTrace();
            return Envelop.getError("查询失败");

+ 4 - 1
svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/rehabilitation/service/RehabilitationGuidanceService.java

@ -176,7 +176,7 @@ public class RehabilitationGuidanceService {
    }
    public PageEnvelop selectPatientGuidances(String patient, String doctor, String article, Integer page, Integer pagesize) {
    public PageEnvelop selectPatientGuidances(String patient, String doctor, String article,String relationCode, Integer page, Integer pagesize) {
        if (page >= 1) {
            page--;
        }
@ -204,6 +204,9 @@ public class RehabilitationGuidanceService {
        if (StringUtils.isNoneBlank(doctor)) {
            filters.put("doctor", new SearchFilter("doctor", SearchFilter.Operator.EQ, doctor));
        }
        if (StringUtils.isNoneBlank(relationCode)) {
            filters.put("relationCode", new SearchFilter("relationCode", SearchFilter.Operator.EQ, relationCode));
        }
        Specification<RehabilitationguidancePatientDO> spec = DynamicSpecifications.bySearchFilter(filters.values(), RehabilitationguidancePatientDO.class);
        Page<RehabilitationguidancePatientDO> rehabilitationguidancePatientDOS = rehabilitationGuidancePatientDao.findAll(spec, pageRequest);
        for (RehabilitationguidancePatientDO rehabilitationguidancePatientDO : rehabilitationguidancePatientDOS) {