Browse Source

慢病管理

suqinyi 1 year ago
parent
commit
205a622f1c
41 changed files with 15152 additions and 5 deletions
  1. 13 0
      business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java
  2. 36 0
      business/base-service/src/main/java/com/yihu/jw/health/service/FoodCompService.java
  3. 127 0
      business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleDoctorService.java
  4. 99 0
      business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleLabelService.java
  5. 81 0
      business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleOpHistoryService.java
  6. 184 0
      business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticlePatientService.java
  7. 256 0
      business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleService.java
  8. 57 0
      business/base-service/src/main/java/com/yihu/jw/health/service/HealthNewsService.java
  9. 278 0
      business/base-service/src/main/java/com/yihu/jw/health/service/IotService.java
  10. 429 0
      business/base-service/src/main/java/com/yihu/jw/health/service/PatientHealthGuidanceService.java
  11. 2452 0
      business/base-service/src/main/java/com/yihu/jw/health/service/PatientHealthIndexService.java
  12. 403 0
      business/base-service/src/main/java/com/yihu/jw/health/service/PatientHealthRecordService.java
  13. 1478 0
      business/base-service/src/main/java/com/yihu/jw/iot/IotDeviceService.java
  14. 2151 0
      business/base-service/src/main/java/com/yihu/jw/scheme/DoctorSchemeService.java
  15. 14 0
      business/base-service/src/main/java/com/yihu/jw/scheme/DoctorSwitchDao.java
  16. 31 0
      business/base-service/src/main/java/com/yihu/jw/scheme/DoctoreSchemeBloodPressureDao.java
  17. 33 0
      business/base-service/src/main/java/com/yihu/jw/scheme/DoctrorSchemeBloodSuggerDao.java
  18. 30 0
      business/base-service/src/main/java/com/yihu/jw/scheme/PatientSchemeListDao.java
  19. 19 0
      business/base-service/src/main/java/com/yihu/jw/scheme/TrackPatientDao.java
  20. 9 0
      business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java
  21. 45 0
      common/common-entity/src/db/2024.sql
  22. 44 0
      common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceHealthyInfoMapping.java
  23. 223 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/DoctorSchemeBloodPressure.java
  24. 269 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/DoctorSchemeBloodSugger.java
  25. 62 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/DoctorSwitch.java
  26. 86 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/PatientSchemeList.java
  27. 108 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/TrackPatient.java
  28. 52 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/vo/DoctorSchemeBloodPressureVO.java
  29. 52 0
      common/common-entity/src/main/java/com/yihu/jw/entity/scheme/vo/DoctorSchemeBloodSuggerVO.java
  30. 212 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/conf/SystemConf.java
  31. 446 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/patient/PatientVO.java
  32. 1218 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthController.java
  33. 601 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthEduArticleController.java
  34. 299 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthGuidanceController.java
  35. 380 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthRecordController.java
  36. 2403 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/vo/MedicalDetailVo.java
  37. 44 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/vo/MedicalQvo.java
  38. 46 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/vo/MedicalVo.java
  39. 340 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/manbing/ChronicDiseaseController.java
  40. 38 0
      svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java
  41. 4 5
      svr/svr-visit-behind/src/main/java/com/yihu/jw/hospital/module/health/controller/DoctorHealthController.java

+ 13 - 0
business/base-service/src/main/java/com/yihu/jw/device/dao/DevicePatientHealthIndexDao.java

@ -11,4 +11,17 @@ import java.util.List;
public interface DevicePatientHealthIndexDao
		extends PagingAndSortingRepository<DevicePatientHealthIndex, Long>, JpaSpecificationExecutor<DevicePatientHealthIndex> {
	@Query(value= " select * from device.wlyy_patient_health_index where type in (1,2) and record_date BETWEEN ?1 AND ?2  AND user in (select p.code from wlyy.wlyy_patient p INNER JOIN wlyy.wlyy_sign_family s on s.patient = p.code RIGHT JOIN wlyy.wlyy_sign_patient_label_info sp on sp.patient = p.code where  s.status > 0 AND s.admin_team_code = ?3 and (s.doctor = ?4 or s.doctor_health =?4) and sp.status = 1 and sp.label_type = 3 and (sp.label = 1 or sp.label = 2))",nativeQuery = true)
	List<DevicePatientHealthIndex> findByTeamcodeAndRecordDate(Date start, Date end,String teamcode,String doctorcode);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from device.wlyy_patient_health_index a where a.user = ?1 and a.record_date >= ?2 and a.record_date <= ?3 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?4 ,?5",nativeQuery = true)
	List<String> findDateList(String patient,Date start ,Date end,int currentSize,int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from device.wlyy_patient_health_index a where a.user = ?1 and a.type=?2 and a.record_date >= ?3 and a.record_date <= ?4 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?5 ,?6",nativeQuery = true)
	List<String> findDateList(String patient,int type,Date start ,Date end,int currentSize,int pageSize);
	@Query(value = "select DATE_FORMAT(a.record_date,'%Y-%m-%d') from device.wlyy_patient_health_index a where a.user = ?1 and a.del = '1' group by DATE_FORMAT(a.record_date,'%Y-%m-%d') order by DATE_FORMAT(a.record_date,'%Y-%m-%d') desc limit ?2 ,?3",nativeQuery = true)
	List<String> findDateList1(String patient,int currentSize,int pageSize);
}

+ 36 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/FoodCompService.java

@ -0,0 +1,36 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.FoodComp;
//import com.yihu.wlyy.repository.education.FoodCompDao;
//import com.yihu.wlyy.service.BaseService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.List;
//
///**
// * 食物健康热量服务类
// * @author George
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class FoodCompService extends BaseService {
//
//	@Autowired
//	private FoodCompDao foodCompDao;
//
//	public List<FoodComp> getByPid(Long pid){
//		return foodCompDao.findByPid(pid);
//	}
//
//	public FoodComp getById(Long id){
//		return foodCompDao.findById(id);
//	}
//
//	public List<FoodComp> getByName(String name){
//		return foodCompDao.findByName("%"+name+"%");
//	}
//
//}

+ 127 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleDoctorService.java

@ -0,0 +1,127 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.HealthEduArticleDoctor;
//import com.yihu.wlyy.repository.education.HealthEduArticleDoctorDao;
//import com.yihu.wlyy.service.BaseService;
//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.List;
//import java.util.Map;
//
///**
// * 健康教育患者业务逻辑类
// * @author linz
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class HealthEduArticleDoctorService extends BaseService {
//
//	@Autowired
//	private HealthEduArticleDoctorDao healthEduArticleDoctorDao;
//
//	@Autowired
//	private HealthEduArticleLabelService healthEduArticleLabelService;
//
//	@Autowired
//	private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
//
//	@Autowired
//	private JdbcTemplate jdbcTemplate;
//	/**
//	 * 根据文章标示获取数据
//	 * @param article
//	 * @return
//	 *
//	 */
//	public HealthEduArticleDoctor findByArticle(String article,String doctor) {
//		return healthEduArticleDoctorDao.findByArticleAndDoctor(article, doctor);
//	}
//
//	/**
//	 * 根据文章删除
//	 * @param article
//	 * @return
//	 *
//	 */
//	public int delete(String article,String doctor) {
//		//删除收藏统计
//		healthEduArticleOpHistoryService.delCollectAmount(article,doctor);
//		return healthEduArticleDoctorDao.deleteByArticleAndDoctor(article, doctor);
//	}
//
//	/**
//	 * 保存
//	 * @param healthEduArticleDoctor
//	 * @return
//	 */
//	public HealthEduArticleDoctor save(HealthEduArticleDoctor healthEduArticleDoctor){
//		return this.healthEduArticleDoctorDao.save(healthEduArticleDoctor);
//	}
//
//	/**
//	 * 根据文章id获取数据
//	 * @param id
//	 * @return
//	 */
//	public HealthEduArticleDoctor findById(Long id) {
//		return healthEduArticleDoctorDao.findOne(id);
//	}
//
//	/**
//	 * 查询收藏的文章
//	 * @param page 第几页
//	 * @param pagesize 分页大小
//	 * @return
//	 */
//	public List<Map<String, Object>> list(int page, int pagesize,String filter,String doctor,String patient,Integer wheaType) {
//		if (pagesize <= 0) {
//			pagesize = 10;
//		}
//		if(page<=0){
//			page = 1;
//		}
//		page = page-1;
//		List<Object> params = new ArrayList<Object>();
//		StringBuffer sql = new StringBuffer();
//		sql.append("select a.id,a.article,a.doctor,a.title,a.url,a.czrq,b.summary content,b.keyword,b.whea_type");
//		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.article and c.status = 1) as readAmount");
//		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.article and c.status = 2) as collectionAmount");
//		sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.article and c.status = 3) as repeatAmount");
//		if(StringUtils.isNotBlank(patient)) {
//			params.add(doctor);
//			params.add(patient);
//			sql.append(",(select count(1) from wlyy_health_edu_article_patient c where c.article = a.article and c.doctor=? and c.patient = ?) as send");
//		}
//		sql.append(" from wlyy_health_edu_article_doctor a left join wlyy_health_edu_article b on a.article = b.code ");//内联取文章内容
//		String where = " where a.doctor = ?";
//		if(wheaType>-1){
//			where += " and  whea_type ="+wheaType;
//		}
//		params.add(doctor);
//		if(StringUtils.isNotBlank(filter)){
//			//记录搜索记录
//			healthEduArticleLabelService.saveOrUpdateLabel(filter,doctor);
//			filter="%"+filter+"%";
//			params.add(filter);
//			params.add(filter);
//			where+=" and ( a.title like ? or b.keyword like ? )";
//		}
//		int start = page * pagesize;
//
//		String pageInfo = " limit "+start+","+pagesize;
//
//		String orderBy = " order by a.czrq,a.id desc";
//
//		sql.append(where).append(orderBy).append(pageInfo);
//		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString(),params.toArray());
//		return result;
//	}
//
//
//}

+ 99 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleLabelService.java

@ -0,0 +1,99 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.HealthEduArticleLabel;
//import com.yihu.wlyy.repository.education.HealthEduArticleLabelDao;
//import com.yihu.wlyy.service.BaseService;
//import com.yihu.wlyy.util.DateUtil;
//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.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springside.modules.persistence.DynamicSpecifications;
//import org.springside.modules.persistence.SearchFilter;
//
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * 健康教育患者业务逻辑类
// * @author linz
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class HealthEduArticleLabelService extends BaseService {
//
//	@Autowired
//	private HealthEduArticleLabelDao healthEduArticleLabelDao;
//
//	/**
//	 * 更新标签
//	 * @param keyword 关键字
//	 * @param user 人员
//	 * @return
//	 *
//	 */
//	public void saveOrUpdateLabel(String keyword,String user) {
//		 HealthEduArticleLabel healthEduArticleLabel =  healthEduArticleLabelDao.findByPublicKeyword(keyword);
//		 if(healthEduArticleLabel==null){//公共标签不存在则添加
//			 HealthEduArticleLabel publicLabel = new HealthEduArticleLabel();
//			 publicLabel.setAmount(1);
//			 publicLabel.setCreater("public");
//			 publicLabel.setKeyword(keyword);
//			 publicLabel.setCzrq(DateUtil.getNow());
//			 this.healthEduArticleLabelDao.save(publicLabel);
//		 }else{//存在更新次数
//			 int amount = healthEduArticleLabel.getAmount();
//			 healthEduArticleLabel.setAmount(amount+1);
//			 healthEduArticleLabel.setCzrq(DateUtil.getNow());
//			 this.healthEduArticleLabelDao.save(healthEduArticleLabel);
//		 }
//		HealthEduArticleLabel userLabel =  healthEduArticleLabelDao.findByKeywordAndCreater(keyword, user);
//		if(userLabel==null){//个人标签
//			userLabel = new HealthEduArticleLabel();
//			userLabel.setAmount(1);
//			userLabel.setCreater(user);
//			userLabel.setKeyword(keyword);
//			userLabel.setCzrq(DateUtil.getNow());
//			this.healthEduArticleLabelDao.save(userLabel);
//		}else{//存在更新次数
//			int amount = userLabel.getAmount();
//			userLabel.setAmount(amount+1);
//			userLabel.setCzrq(DateUtil.getNow());
//			this.healthEduArticleLabelDao.save(userLabel);
//		}
//	}
//
//	/**
//	 * 获取文章列表
//	 * @param page 页码
//	 * @param pagesize 分页大小
//	 * @return 列表
//	 */
//	public Page<HealthEduArticleLabel> findAll(int page, int pagesize, int type, String user) {
//		if (pagesize <= 0) {
//			pagesize = 10;
//		}
//		if(page<0){
//			page = 0;
//		}
//		// 排序
//		Sort sort = new Sort(Direction.DESC,"amount","czrq");
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(page, pagesize, sort);
//		// 设置查询条件
//		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//		if(type==1){
//			filters.put("creater", new SearchFilter("creater", SearchFilter.Operator.EQ, "public"));
//		}else if(type==2){
//			filters.put("creater", new SearchFilter("creater", SearchFilter.Operator.EQ, user));
//		}
//		Specification<HealthEduArticleLabel> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthEduArticleLabel.class);
//		return healthEduArticleLabelDao.findAll(spec, pageRequest);
//	}
//
//}

+ 81 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleOpHistoryService.java

@ -0,0 +1,81 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
//import com.yihu.wlyy.repository.education.HealthEduArticleOpHistoryDao;
//import com.yihu.wlyy.service.BaseService;
//import com.yihu.wlyy.util.DateUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
///**
// * 健康教育患者业务逻辑类
// * @author linz
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class HealthEduArticleOpHistoryService extends BaseService {
//
//	@Autowired
//	private HealthEduArticleOpHistoryDao healthEduArticleOpHistoryDao;
//
//	/**
//	 * 汇总阅读量
//	 * @param code
//	 * @return
//	 */
//	public  int countReadAmount(String code){
//		return healthEduArticleOpHistoryDao.countByCodeStatus(code,HealthEduArticleOpHistory.READ_STATUS);
//	}
//
//
//
//	/**
//	 * 汇总转发量
//	 * @param code
//	 * @return
//	 */
//	public int countRepeatAmount(String code){
//		return healthEduArticleOpHistoryDao.countByCodeStatus(code,HealthEduArticleOpHistory.REPEAT_STATUS);
//	}
//
//	/**
//	 * 获取收藏量
//	 * @param code
//	 * @return
//	 */
//	public  int countCollectionAmount(String code){
//		return healthEduArticleOpHistoryDao.countByCodeStatus(code,HealthEduArticleOpHistory.COLLECTION_STATUS);
//	}
//
//	public int delCollectAmount(String code,String user){
//		return healthEduArticleOpHistoryDao.deleteByCodeAndStatusAndCreater(code,HealthEduArticleOpHistory.COLLECTION_STATUS,user);
//	}
//
//	public int countByUserStatus(String user,String status){
//		return healthEduArticleOpHistoryDao.countByCodeStatus(user,status);
//	}
//
//	/**
//	 *
//	 * @param status 状态
//	 * @param code 文章编号
//	 * @param title 文章标题
//	 * @param user 操作人
//	 * @return
//	 */
//	public HealthEduArticleOpHistory saveByStatus(String status,String code,String title,String user){
//
//		HealthEduArticleOpHistory healthEduArticleOpHistory = new HealthEduArticleOpHistory();
//		healthEduArticleOpHistory.setCode(code);
//		healthEduArticleOpHistory.setCreatedTime(DateUtil.getNow());
//		healthEduArticleOpHistory.setStatus(status);
//		healthEduArticleOpHistory.setTitle(title);
//		healthEduArticleOpHistory.setCreater(user);
//		healthEduArticleOpHistory.setId(0L);
//		healthEduArticleOpHistoryDao.save(healthEduArticleOpHistory);
//		return healthEduArticleOpHistory;
//	}
//
//}

+ 184 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticlePatientService.java

@ -0,0 +1,184 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
//import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
//import com.yihu.wlyy.service.BaseService;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.jdbc.core.BeanPropertyRowMapper;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.List;
//import java.util.Map;
//
///**
// * 健康教育患者业务逻辑类
// *
// * @author linz
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class HealthEduArticlePatientService extends BaseService {
//
//    @Autowired
//    private HealthEduArticlePatientDao healthEduArticlePatientDao;
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//
//    /**
//     * 根据文章标示获取数据
//     *
//     * @param article
//     * @return
//     */
//    @Deprecated
//    public HealthEduArticlePatient findByArticle(String article) {
//        return healthEduArticlePatientDao.findByArticle(article);
//    }
//
//    /**
//     * 根据文章id获取数据
//     *
//     * @param id
//     * @return
//     */
//    public HealthEduArticlePatient findById(Long id) {
//        return healthEduArticlePatientDao.findOne(id);
//    }
//
//    public List<HealthEduArticlePatient> findByArticleAndPatient(String article, String patient) {
//        return healthEduArticlePatientDao.findByArticleAndPatient(article, patient);
//    }
//
//
//    /**
//     * 查询患者文章
//     *
//     * @param patient  患者标识
//     * @param pagesize 分页大小
//     * @return
//     */
//    public List<HealthEduArticlePatient> findByPatient(String patient,int wheaType, int pageIndex, int pagesize) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        String sql = "select " +
//                "    a.id" +
//                "    ,a.patient" +
//                "    ,a.article" +
//                "    ,a.doctor" +
//                "    ,a.doctor_name as doctorName" +
//                "    ,b.title" +
//                "    ,b.url" +
//                "    ,b.summary as content" +
//                "    ,a.is_read as 'read'" +
//                "    ,a.czrq" +
//                "    ,a.attached_content" +
//                "    ,b.id as article_id" +
//                " from" +
//                "     wlyy_health_edu_article_patient a" +
//                "     , wlyy_health_edu_article b" +
//                " where" +
//                "      a.article = b.code" +
//                " and ( a.send_type =1 or a.send_type is null or a.send_type = '') "+  //添加类型判断是集美的推送还是三师原来的推送
//                " and a.patient = ?" +
//                (wheaType > 0 ? " and a.wheaType = ? " : "") +
//                " order by a.id desc limit "+pageIndex+"," + pagesize;
//        Object params[] = null;
//        if(wheaType>-1){
//            params = new Object[]{patient,wheaType};
//        }else{
//            params = new Object[]{patient};
//        }
//        List<HealthEduArticlePatient> list = jdbcTemplate.query(sql,params, new BeanPropertyRowMapper(HealthEduArticlePatient.class));
//        return list;
//    }
//
//
//    /**
//     * 查询患者文章
//     *
//     * @param doctor  医生标识
//     * @param  page 第几页
//     * @param pagesize 分页大小
//     * @return
//     */
//    public List<Map<String,Object>> findByDoctor(String doctor,int page, int pagesize) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        if(page<=0){
//            page = 1 ;
//        }
//        int start = (page-1) * pagesize;
//        String sql ="select a.article,b.title,b.summary,a.attached_content, a.czrq,count( distinct a.patient) as amount,GROUP_CONCAT( distinct p.name) as  patients,a.batch_no from "+
//        " wlyy_health_edu_article_patient a, "+
//        " wlyy_health_edu_article b,"+
//        " wlyy_patient p"+
//        " where"+
//        " a.article = b.code"+
//        " and ( a.send_type =1 or a.send_type is null or a.send_type = '') "+  //添加类型判断是集美的推送还是三师原来的推送
//        " and a.patient = p.code"+
//        " and a.doctor =? "+
//        " group BY a.batch_no,a.article,a.attached_content,b.summary,a.doctor order by a.czrq desc  limit ?,? ";
//        Object params[] = new Object[]{doctor,start,pagesize};
//        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,params);
//        return list;
//    }
//
//    /**
//     * 查询批次号相关的文章及成员信息
//     * @param doctor
//     * @param article
//     * @param batchNo
//     * @return
//     */
//    public List<Map<String,Object>> findByBatchNo(String doctor,String article, String  batchNo) {
//        String sql ="select a.article,b.title,b.content,a.attached_content,b.url, a.czrq as send_time,b.czrq,a.batch_no,sum(a.is_read) as no_read from "+
//                " wlyy_health_edu_article_patient a, "+
//                " wlyy_health_edu_article b,"+
//                " wlyy_patient p"+
//                " where"+
//                " a.article = b.code"+
//                " and a.patient = p.code"+
//                " and ( a.send_type =1 or a.send_type is null or a.send_type = '') "+  //添加类型判断是集美的推送还是三师原来的推送
//                " and a.doctor =? "+
//                " and a.article =? "+
//                (StringUtils.isNotBlank(batchNo)?" and a.batch_no =? ":"and a.batch_no is null ")+
//                " group BY a.batch_no,a.article,b.content,b.summary,a.doctor,b.title";
//        Object params[] =  (StringUtils.isNotBlank(batchNo)?new Object[]{doctor,article,batchNo}:new Object[]{doctor,article});
//        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,params);
//        for(Map<String,Object> dataMap :list){
//            String patientListSql ="select a.patient,p.name,a.is_read "+
//            " from wlyy_health_edu_article_patient a,wlyy_health_edu_article b,wlyy_patient p"+
//            " where "+
//            " a.article = b.code " +
//            " and a.doctor=? and  a.article =?"+
//            (StringUtils.isNotBlank(batchNo)?" and a.batch_no =? ":" and a.batch_no is null ")+
//            " and a.patient = p.code " +
//            " group BY a.batch_no,a.article,b.content,a.attached_content,a.patient,b.title";
//            List<Map<String,Object>> patientList = jdbcTemplate.queryForList(patientListSql,params);
//            dataMap.put("patients",patientList);
//            dataMap.put("read_amount",patientList.size()-Integer.parseInt(dataMap.get("no_read").toString()));
//            dataMap.put("amount",patientList.size());
//        }
//        return list;
//    }
//
//
//
//
//    /**
//     * 文章更新为已读
//     *
//     * @param patient
//     * @param article
//     * @return
//     */
//    public int updateRead(String patient, String article) {
//        return healthEduArticlePatientDao.updateRead(patient, article);
//    }
//
//}

+ 256 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/HealthEduArticleService.java

@ -0,0 +1,256 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.HealthEduArticle;
//import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
//import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
//import com.yihu.wlyy.repository.education.HealthEduArticleDao;
//import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
//import com.yihu.wlyy.service.BaseService;
//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.Iterator;
//import java.util.List;
//import java.util.Map;
//
///**
// * 健康教育业务控制类
// *
// * @author George
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class HealthEduArticleService extends BaseService {
//
//    @Autowired
//    private HealthEduArticleDao healthEduArticleDao;
//    @Autowired
//    private HealthEduArticlePatientDao healthEduArticlePatientDao;
//    @Autowired
//    private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
//    @Autowired
//    private HealthEduArticleLabelService healthEduArticleLabelService;
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//
//
//    /**
//     * 查询文章信息
//     *
//     * @param code
//     * @return
//     */
//    public HealthEduArticle findArticleByCode(String code) {
//        return healthEduArticleDao.findByCode(code);
//    }
//
//    public HealthEduArticle findArticleById(Long id) {
//        return healthEduArticleDao.findOne(id);
//    }
//
//    /**
//     * 获取文章列表
//     *
//     * @param page     页码
//     * @param pagesize 分页大小
//     * @return 列表
//     */
//    public List<Map<String, Object>> findAll(int page, int pagesize, String filter, String doctor, String patient,int wheaType) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        if (page <=0) {
//            page = 1;
//        }
//        page = page-1;
//        List<Object> params = new ArrayList<Object>();
//        StringBuffer sql = new StringBuffer();
//        sql.append("select a.id,a.code,a.title,a.url,a.czrq,a.summary content,a.keyword");
//        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 1) as readAmount");
//        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 2) as collectionAmount");
//        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 3) as repeatAmount");
//        sql.append(",(select count(1) from wlyy_health_edu_article_doctor c where c.article = a.code and c.doctor =?) as collection");
//        params.add(doctor);
//        if (StringUtils.isNotBlank(patient)) {
//            sql.append(",(select count(1) from wlyy_health_edu_article_patient c where c.article = a.code and c.doctor = ? and c.patient= ? ) as send");
//            params.add(doctor);
//            params.add(patient);
//        }
//        sql.append(" from wlyy_health_edu_article a  ");//内联取文章内容
//        String where = " where 1=1 ";
//        if (StringUtils.isNotBlank(filter)) {
//            //记录搜索记录
//            healthEduArticleLabelService.saveOrUpdateLabel(filter, doctor);
//            filter = "%" + filter + "%";
//            where += " and  ( a.title like ? or a.keyword like ? )";
//            params.add(filter);
//            params.add(filter);
//        }
//        if(wheaType>=0){
//            where += " and  ( a.whea_type = ? )";
//            params.add(wheaType);
//        }
//        int start = page * pagesize;
//        String pageInfo = " limit " + start + "," + pagesize;
//        String orderBy = " order by a.czrq desc";
//        sql.append(where).append(orderBy).append(pageInfo);
//        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString(), params.toArray());
//        return result;
//    }
//
//    /**
//     * 查询给患者发送的健康教育文章
//     *
//     * @param patient
//     * @param teamCode
//     * @param page
//     * @param pageSize
//     * @return
//     */
//    public List<Map<String, Object>> findByPatientAndTeam(String patient, long teamCode, int page, int pageSize) {
//        List<Object> params = new ArrayList<Object>();
//        String sql = "select " +
//                "    a.article" +
//                "    ,b.title" +
//                "    ,b.url" +
//                "    ,a.czrq" +
//                "    ,b.summary content" +
//                "    ,d.code" +
//                "    ,d.name" +
//                "    ,d.photo" +
//                "    ,a.admin_team_code" +
//                "    ,a.is_read" +
//                "    ,a.attached_content" +
//                "  from" +
//                "    wlyy_health_edu_article_patient a" +
//                "    ,wlyy_health_edu_article b" +
//                "    ,wlyy_doctor d" +
//                "  where" +
//                "    a.article = b.code " +
//                "    and a.doctor = d.code " +
//                "   and ( a.send_type =1 or a.send_type is null or a.send_type = '') "+  //添加类型判断是集美的推送还是三师原来的推送
//                "    and a.patient = ?" +
//                "    and a.admin_team_code = ?" +
//                "  order by a.czrq desc limit " + page*pageSize + "," + pageSize;
//
//        List<Map<String,Object>> result = jdbcTemplate.queryForList(sql,new Object[]{patient,teamCode});
//        return result;
//    }
//
//    /**
//     * 文章更新为已读
//     *
//     * @param patient
//     * @param article
//     * @return
//     */
//    public int updateRead(String patient, String article) {
//        return healthEduArticlePatientDao.updateRead(patient, article);
//    }
//
//    /**
//     * 对当前用户的所有未读文章设置为已读
//     *
//     * @param patient
//     * @return
//     */
//    public int readAllArticle(String patient) {
//        return healthEduArticlePatientDao.readAllArticle(patient);
//    }
//
//    /**
//     * 发送文章列表
//     *
//     * @param list
//     * @return
//     */
//    public int send(List<HealthEduArticlePatient> list) {
//        Iterable<HealthEduArticlePatient> iterable = healthEduArticlePatientDao.save(list);
//        //记录转发量
//        for (HealthEduArticlePatient healthEduArticlePatient : list) {
//            healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.REPEAT_STATUS, healthEduArticlePatient.getArticle(), healthEduArticlePatient.getTitle(), healthEduArticlePatient.getDoctor());
//        }
//        Iterator<HealthEduArticlePatient> iterator = iterable.iterator();
//        if (iterator.hasNext()) {
//            return 1;
//        } else {
//            return 0;
//        }
//
//    }
//
//    public List<Map<String,Object>> zyfindAll(int page, int pagesize, String titlefilter, String keywordfilter, String contentfilter) {
//        if (pagesize <= 0) {
//            pagesize = 10;
//        }
//        if (page <=0) {
//            page = 1;
//        }
//        page = page-1;
//        List<Object> params = new ArrayList<Object>();
//        StringBuffer sql = new StringBuffer();
//        sql.append("select a.id,a.code,a.title,a.url,a.czrq,a.summary content,a.keyword");
//        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 1) as readAmount");
//        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 2) as collectionAmount");
//        sql.append(",(select count(1) from wlyy_health_edu_article_op_history c where c.code = a.code and c.status = 3) as repeatAmount");
//        sql.append(" from wlyy_health_edu_article a  ");//内联取文章内容
//        String where = " where 1=1 ";
//        if (StringUtils.isNotBlank(titlefilter) ||
//                StringUtils.isNotBlank(keywordfilter)||
//                    StringUtils.isNotBlank(contentfilter)) {
//            where += " and  ( ";
//
//            boolean need_or = false;
//
//            //文章标题关键字搜索
//            if(StringUtils.isNotBlank(titlefilter)){
//                titlefilter = "%" + titlefilter + "%";
//                where +="a.title like ?";
//
//                need_or = true;
//                params.add(titlefilter);
//            }
//
//            //关键字搜索
//            if(StringUtils.isNotBlank(keywordfilter)){
//                keywordfilter = "%" + keywordfilter + "%";
//
//                if(need_or){
//                    where +=" or a.keyword like ?";
//                }else{
//                    where +="a.keyword like ?";
//                    need_or = true;
//                }
//                params.add(keywordfilter);
//            }
//
//            //文章内容搜索
//            if(StringUtils.isNotBlank(contentfilter)){
//                contentfilter = "%" + contentfilter + "%";
//
//                if(need_or){
//                    where +=" or a.content like ?";
//                }else{
//                    where +="a.content like ?";
//                }
//                params.add(contentfilter);
//            }
//
//            where += " )";
//        }
////        if(wheaType>=0){
////            where += " and  ( a.whea_type = ? )";
////            params.add(wheaType);
////        }
//        int start = page * pagesize;
//        String pageInfo = " limit " + start + "," + pagesize;
//        String orderBy = " order by a.czrq desc";
//        sql.append(where).append(orderBy).append(pageInfo);
//        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString(), params.toArray());
//        return result;
//    }
//}

+ 57 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/HealthNewsService.java

@ -0,0 +1,57 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.education.HealthNews;
//import com.yihu.wlyy.repository.education.HealthNewsDao;
//import com.yihu.wlyy.service.BaseService;
//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.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springside.modules.persistence.DynamicSpecifications;
//import org.springside.modules.persistence.SearchFilter;
//import org.springside.modules.persistence.SearchFilter.Operator;
//
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * 健康资讯业务处理类
// * @author George
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class HealthNewsService extends BaseService {
//
//	@Autowired
//	private HealthNewsDao healthNewsDao;
//
//	/**
//	 * 获取文章列表
//	 * @param page 页码
//	 * @param pagesize 分页大小
//	 * @return 列表
//	 */
//	public Page<HealthNews> findAll(long id, int pagesize) {
//		if (pagesize <= 0) {
//			pagesize = 10;
//		}
//		// 排序
//		Sort sort = new Sort(Direction.DESC, "id");
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
//		// 设置查询条件
//		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//		if (id > 0) {
//			filters.put("id", new SearchFilter("id", Operator.LT, id));
//		}
//		// 未作废
//		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//		Specification<HealthNews> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthNews.class);
//		return healthNewsDao.findAll(spec, pageRequest);
//	}
//}

+ 278 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/IotService.java

@ -0,0 +1,278 @@
//package com.yihu.jw.health.service;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.yihu.iot.entity.entity.WlyyIotD;
//import com.yihu.iot.entity.entity.WlyyIotM;
//import com.yihu.iot.entity.entity.WlyyIotTzDict;
//import com.yihu.mysql.query.BaseJpaService;
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.iot.repository.repository.WlyyIotDDao;
//import com.yihu.wlyy.iot.repository.repository.WlyyIotMDao;
//import com.yihu.wlyy.iot.repository.repository.WlyyIotTzDictDao;
//import com.yihu.wlyy.repository.patient.PatientDao;
//import org.apache.commons.lang3.StringUtils;
//import org.apache.http.client.utils.DateUtils;
//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.beans.factory.annotation.Value;
//import org.springframework.data.domain.PageRequest;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.CollectionUtils;
//
//import javax.annotation.PostConstruct;
//import java.util.*;
//import java.util.stream.Collectors;
//
///**
// * 物联网服务类-健康小屋体征数据
// * @author George
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class IotService extends BaseJpaService<WlyyIotD, WlyyIotDDao> {
//	private Logger logger = LoggerFactory.getLogger(IotService.class);
//
//	private Map<String,Object> codeNameMap = new HashMap<>();
//
//	@Autowired
//	private WlyyIotDDao wlyyIotDDao;
//
//	@Autowired
//	private WlyyIotMDao wlyyIotMDao;
//
//	@Autowired
//	private WlyyIotTzDictDao wlyyIotTzDictDao;
//
//    @Autowired
//    private PatientDao patientDao;
//
//    @Autowired
//    private ObjectMapper objectMapper;
//	@Value("${testPattern.sign}")
//	private String isClose;
//
//	@PostConstruct
//	public void init() {
//		if (codeNameMap.isEmpty()&&!"1".equals(isClose)) {
//
//			Iterable<WlyyIotTzDict> iterable = wlyyIotTzDictDao.findAll();
//
//			iterable.forEach(
//					oneElement -> {
//						codeNameMap.put(oneElement.getCode(), oneElement.getName());
//					}
//			);
//		}
//	}
//
//	/**
//	 * 根据体征类型获取数据
//	 * @return
//	 */
//	public JSONArray getDataByType(String uid, String type, int page, int size, String beginTime, String endTime){
//        Patient patient = patientDao.findByCode(uid);
//        if( patient == null ){
//            logger.error("根据体征类型查询数据失败:当前居民不存在" );
//            return null;
//        }
//
//		if(StringUtils.isEmpty(type)){
//            logger.error("根据体征类型查询数据失败:类型不可为空" );
//            return null;
//		}
//		logger.info("size==="+size+",page===="+page+", beginTime==="+beginTime);
//		// 先查找出测量设备
//		List<WlyyIotM> iotMList = new ArrayList<>();
//		if(StringUtils.isEmpty(beginTime) && StringUtils.isEmpty(endTime)){
//			iotMList = wlyyIotMDao.queryByIdCardNoOrderByMeasureTimeDesc(patient.getIdcard(),new PageRequest(page-1,size));
//		}else if(!StringUtils.isEmpty(beginTime)){
//			if(StringUtils.isEmpty(endTime)){
//				endTime = DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
//			}
//			iotMList = wlyyIotMDao.queryByIdCardNoAndMeasureTimeBetweenOrderByMeasureTimeDesc(patient.getIdcard(),beginTime,endTime,new PageRequest(page-1,size));
//		}
//
//		if(CollectionUtils.isEmpty(iotMList)){
//			logger.error("当前居民没有体征数据测量记录");
//			return new JSONArray();
//		}
//
//		Map<String,WlyyIotM> iotMId2Map = new HashMap<>();
//		iotMList.forEach(wlyyIotM -> iotMId2Map.put(wlyyIotM.getId(),wlyyIotM));
//
//		List<WlyyIotD> iotDList = new ArrayList<>();
//		try{
//			iotDList = wlyyIotDDao.queryByMidInAndType(iotMId2Map.keySet(),type);
//		}catch (Exception e){
//			logger.error("根据体征类型查询数据失败:" + e.getMessage());
//            return null;
//		}
//        Map<String,List<WlyyIotD>> groupIotDataMapList = iotDList.stream().collect(Collectors.groupingBy(oneData -> oneData.getMid()));
//
//		JSONArray jsonArray = new JSONArray();
//		groupIotDataMapList.keySet().forEach(
//				oneKey -> {
//					JSONObject result = new JSONObject();
//					groupIotDataMapList.get(oneKey).forEach(
//							iotD -> {
//								iotD.setCh_name(String.valueOf(codeNameMap.get(iotD.getCode())));
//								if ((iotD.getType().equalsIgnoreCase("MinFat")&&iotD.getCode().equalsIgnoreCase("Shape"))||(iotD.getType().equalsIgnoreCase("MinFat")&&iotD.getCode().equalsIgnoreCase("Physique"))||
//										(iotD.getType().equalsIgnoreCase("BloodSugar")&&iotD.getCode().equalsIgnoreCase("BloodsugarType"))){
//									iotD.setValue(wlyyIotTzDictDao.selectByCodeAndValue(iotD.getType()+"_"+iotD.getCode(),iotD.getValue()));
//								}
//								if(StringUtils.equalsIgnoreCase("result",iotD.getCode())){
//									JSONObject resultElement = null;
//									try {
//										resultElement = new JSONObject(objectMapper.writeValueAsString(iotD));
//									} catch (JsonProcessingException e) {
//										e.printStackTrace();
//									}
//									WlyyIotM iotM = iotMId2Map.get(oneKey);
//									resultElement.put("measureTime",iotM.getMeasureTime());
//									resultElement.put("device_name",iotM.getDeviceName());
//									resultElement.put("device_sn",iotM.getSn());
//									resultElement.put("valueName",wlyyIotTzDictDao.selectByCodeAndValue(iotD.getType()+"_"+iotD.getCode(),iotD.getValue()));
//									result.put("result",resultElement);
//								}else {
//									JSONObject resultElement = new JSONObject();
//									WlyyIotM iotM = iotMId2Map.get(oneKey);
//									resultElement.put("measureTime",iotM.getMeasureTime());
//									resultElement.put("device_name",iotM.getDeviceName());
//									resultElement.put("device_sn",iotM.getSn());
//									resultElement.put("mid",iotM.getId());
//									resultElement.put("valueName","");
//									result.put("result",resultElement);
//								}
//							}
//					);
//					result.put("data",groupIotDataMapList.get(oneKey));
//					jsonArray.put(result);
//				}
//		);
//		return jsonArray;
//	}
//
//
//	public JSONArray getDataByTypeNoPage(String uid, String type, String beginTime, String endTime){
//		Patient patient = patientDao.findByCode(uid);
//		if( patient == null ){
//			logger.error("根据体征类型查询数据失败:当前居民不存在" );
//			return null;
//		}
//
//		if(StringUtils.isEmpty(type)){
//			logger.error("根据体征类型查询数据失败:类型不可为空" );
//			return null;
//		}
//		// 先查找出测量设备
//		List<WlyyIotM> iotMList = new ArrayList<>();
//		if(StringUtils.isEmpty(beginTime) && StringUtils.isEmpty(endTime)){
//			iotMList = wlyyIotMDao.queryByIdCardNoOrderByMeasureTimeDesc(patient.getIdcard());
//		}else if(!StringUtils.isEmpty(beginTime)){
//			if(StringUtils.isEmpty(endTime)){
//				endTime = DateUtils.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
//			}
//			iotMList = wlyyIotMDao.queryByIdCardNoAndMeasureTimeBetweenOrderByMeasureTimeDesc(patient.getIdcard(),beginTime,endTime);
//		}
//
//		if(CollectionUtils.isEmpty(iotMList)){
//			logger.error("当前居民没有体征数据测量记录");
//			return new JSONArray();
//		}
//
//		Map<String,WlyyIotM> iotMId2Map = new HashMap<>();
//		iotMList.forEach(wlyyIotM -> iotMId2Map.put(wlyyIotM.getId(),wlyyIotM));
//
//		List<WlyyIotD> iotDList = new ArrayList<>();
//		try{
//			iotDList = wlyyIotDDao.queryByMidInAndType(iotMId2Map.keySet(),type);
//		}catch (Exception e){
//			logger.error("根据体征类型查询数据失败:" + e.getMessage());
//			return null;
//		}
//		Map<String,List<WlyyIotD>> groupIotDataMapList = iotDList.stream().collect(Collectors.groupingBy(oneData -> oneData.getMid()));
//
//		JSONArray jsonArray = new JSONArray();
//		groupIotDataMapList.keySet().forEach(
//				oneKey -> {
//					JSONObject result = new JSONObject();
//					groupIotDataMapList.get(oneKey).forEach(
//							iotD -> {
//								iotD.setCh_name(String.valueOf(codeNameMap.get(iotD.getCode())));
//								if ((iotD.getType().equalsIgnoreCase("MinFat")&&iotD.getCode().equalsIgnoreCase("Shape"))||(iotD.getType().equalsIgnoreCase("MinFat")&&iotD.getCode().equalsIgnoreCase("Physique"))||
//										(iotD.getType().equalsIgnoreCase("BloodSugar")&&iotD.getCode().equalsIgnoreCase("BloodsugarType"))){
//									iotD.setValue(wlyyIotTzDictDao.selectByCodeAndValue(iotD.getType()+"_"+iotD.getCode(),iotD.getValue()));
//								}
//								if(StringUtils.equalsIgnoreCase("result",iotD.getCode())){
//									JSONObject resultElement = null;
//									try {
//										resultElement = new JSONObject(objectMapper.writeValueAsString(iotD));
//									} catch (JsonProcessingException e) {
//										e.printStackTrace();
//									}
//									WlyyIotM iotM = iotMId2Map.get(oneKey);
//									resultElement.put("measureTime",iotM.getMeasureTime());
//									resultElement.put("device_name",iotM.getDeviceName());
//									resultElement.put("device_sn",iotM.getSn());
//									resultElement.put("valueName",wlyyIotTzDictDao.selectByCodeAndValue(iotD.getType()+"_"+iotD.getCode(),iotD.getValue()));
//									result.put("result",resultElement);
//								}else {
//									JSONObject resultElement = new JSONObject();
//									WlyyIotM iotM = iotMId2Map.get(oneKey);
//									resultElement.put("measureTime",iotM.getMeasureTime());
//									resultElement.put("device_name",iotM.getDeviceName());
//									resultElement.put("device_sn",iotM.getSn());
//									result.put("result",resultElement);
//								}
//							}
//					);
//					result.put("data",groupIotDataMapList.get(oneKey));
//					jsonArray.put(result);
//				}
//		);
//		return jsonArray;
//	}
//
//	/**
//	 * 健康小屋血糖数据查询(1餐前、2餐后、3随机)
//	 * @param uid
//	 * @param type
//	 * @param value
//	 * @param beginTime
//	 * @param endTime
//	 * @return
//	 */
//	public List<Map<String,Object>> selectByTypeAndCode(String uid, String type,Integer value,String beginTime,String endTime){
//		Patient patient = patientDao.findByCode(uid);
//		StringBuffer buffer = new StringBuffer();
//		if (value!=null){
//			buffer.append(" and m.id in (SELECT DISTINCT d1.mid FROM xmiot.wlyy_iot_d d1 WHERE d1.`value`="+value+" and d1.code='BloodsugarType' and d1.type='"+type+"')");
//		}
//		String sql = "SELECT d.mid,d.type,d.`code`,d.`value`,d.unit,m.sn,m.device_model,m.device_name,m.measure_time " +
//				" FROM xmiot.wlyy_iot_d d,xmiot.wlyy_iot_m m WHERE m.id = d.mid  and m.id_card_no = '" +patient.getIdcard()+
//				"'and m.measure_time >= '"+beginTime+"' and m.measure_time <= '"+endTime+"'  and d.type = '"+type+"' "+buffer+" ORDER BY m.measure_time DESC ";
//		List<Map<String,Object>> mapList = jdbcTemplate.queryForList(sql);
//		return mapList;
//	}
//
//
//	/**
//	 * 根据体征设备测量记录Id获取数据详情
//	 * @return
//	 */
//	public List getDataDetailById(String mid,String type){
//		List<WlyyIotD> result = new ArrayList<>();
//		if(org.springframework.util.StringUtils.isEmpty(mid) || org.springframework.util.StringUtils.isEmpty(type)){
//			return result;
//		}
//		return wlyyIotDDao.queryByMidAndType(mid,type);
//	}
//
//
//}

+ 429 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/PatientHealthGuidanceService.java

@ -0,0 +1,429 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.util.TransforSqlUtl;
//import com.yihu.wlyy.entity.doctor.profile.Doctor;
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
//import com.yihu.wlyy.entity.patient.PatientHealthGuidanceRecord;
//import com.yihu.wlyy.entity.patient.SignFamily;
//import com.yihu.wlyy.repository.doctor.DoctorDao;
//import com.yihu.wlyy.repository.patient.PatientDao;
//import com.yihu.wlyy.repository.patient.PatientHealthGuidanceDao;
//import com.yihu.wlyy.repository.patient.PatientHealthGuidanceRecordDao;
//import com.yihu.wlyy.repository.patient.SignFamilyDao;
//import com.yihu.wlyy.repository.wechat.WechatTemplateConfigDao;
//import com.yihu.wlyy.service.BaseService;
//import com.yihu.wlyy.service.ServiceException;
//import com.yihu.wlyy.service.common.SqlReplaceService;
//import com.yihu.wlyy.service.common.account.PatientService;
//import com.yihu.wlyy.task.PushMsgTask;
//import com.yihu.wlyy.util.DateUtil;
//import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
//import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.json.JSONArray;
//import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.Page;
//import org.springframework.data.domain.PageRequest;
//import org.springframework.data.domain.Pageable;
//import org.springframework.data.domain.Sort;
//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;
//import java.util.Map;
//
///**
// * 健康指导业务处理类
// * @author George
// *
// */
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class PatientHealthGuidanceService extends BaseService {
//
//	@Autowired
//	private DoctorDao doctorDao;
//	@Autowired
//	private PatientDao patientDao;
//	@Autowired
//	private PatientHealthGuidanceDao patientHealthGuidanceDao;
//	@Autowired
//	SignFamilyDao signFamilyDao;
//	@Autowired
//    JdbcTemplate jdbcTemplate;
//	@Autowired
//	WeiXinOpenIdUtils weiXinOpenIdUtils;
//	@Autowired
//	private PatientService patientService;
//	@Autowired
//	private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
//
//	@Autowired
//	private PushMsgTask pushMsgTask;
//	@Autowired
//	private WechatTemplateConfigDao templateConfigDao;
//	@Autowired
//	private PatientHealthGuidanceRecordDao patientHealthGuidanceRecordDao;
//	@Autowired
//	private SqlReplaceService sqlReplaceService;
//
//	public JSONObject findById(Long id){
//		PatientHealthGuidance guidance = patientHealthGuidanceDao.findOne(id);
//
//		if(guidance != null){
//			JSONObject obj = new JSONObject(guidance);
//			Doctor doc = doctorDao.findByCode(guidance.getDoctor());
//			Patient p = patientDao.findByCode(guidance.getPatient());
//
//			obj.put("doctorName",doc.getName());
//			obj.put("photo",doc.getPhoto());
//			obj.put("name",doc.getName());
//			obj.put("level",doc.getLevel());
//			obj.put("patientName",p.getName());
//			obj.put("czrq",guidance.getCzrq()!= null ? DateUtil.dateToStr(guidance.getCzrq(),DateUtil.YYYY_MM_DD_HH_MM) :"");
//			return obj;
//		}else{
//			return null;
//		}
//	}
//
//	/**
//	 * 更改健康指导阅读状态
//	 * @param id
//	 * @return
//	 */
//	public void modifyStatus(String id,String type) {
//		if("1".equals(type)){
////            一键设置居民未读指导
//			String sql = "UPDATE wlyy_patient_health_guidance wphg " +
//					"SET wphg .read_status = 1  "+
//					"WHERE wphg.patient = ?";
//			jdbcTemplate.update(sql,id);
//		}else {
//			String sql = "UPDATE wlyy_patient_health_guidance wphg " +
//					"SET wphg .read_status = 1  " +
//					"WHERE wphg.id = ?";
//			jdbcTemplate.update(sql, id);
//		}
//	}
//
//	/**
//	 * 保存健康指导
//	 * @param guidance
//	 * @param modelName
//	 * @return
//	 */
//	public PatientHealthGuidance add(PatientHealthGuidance guidance, String accessToken, String tzCode, String modelName) throws Exception {
//		Doctor doctor = doctorDao.findByCode(guidance.getDoctor());
//		Patient patient = patientDao.findByCode(guidance.getPatient());
//		//家庭医生
//		SignFamily signFamily = signFamilyDao.findByjiatingPatient(guidance.getPatient());
//		//家庭医生不存在
//		if(signFamily == null){
//			 return null;
//		}
//
//		guidance.setCzrq(new Date());
//		guidance.setCreateTime(new Date());
//		guidance.setDel("1");
//		guidance.setAdminTeamCode(signFamily.getAdminTeamId());
//		guidance.setSignType(2);
//		//保存签约CODE
//		guidance.setSignCode(patientService.getSignCodeByPatient(patient.getCode()));
//		guidance = patientHealthGuidanceDao.save(guidance);
//
//		String openId = null;
////		String name = null;
//		JSONObject json = new JSONObject();
//
//		//判定openId是否为空空,如果为空,查找他家人的openId
//		if(StringUtils.isNotBlank(patient.getOpenid())){
//			json.put("first", "健康指导提醒");
//			//name = patient.getName();
//			openId = patient.getOpenid();
//		}
////		else{
////			JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
////			Patient member = (Patient)j.get("member");
////			openId = member.getOpenid();
////			//name = member.getName();
////			if (StringUtils.isNotEmpty(openId)) {
////				json.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()) + "健康指导提醒");
////			}
////		}
//		if (guidance != null ) {
//			json.put("toUser", patient.getCode());
//			json.put("represented",patient.getCode());//被代理人
//			json.put("id", guidance.getId());
//			json.put("date", DateUtil.getStringDate());
//			json.put("orgName", doctor.getHospitalName());
//			json.put("doctorName", doctor.getName());
////			json.put("content", "您好!医生给您发来了一份新的健康指导。");
//			json.put("content", "《" + modelName + "》");
//			json.put("remark", "请点击查看");
//			if(StringUtils.isNotEmpty(openId)){
//				//保存健康指导推送记录
//				PatientHealthGuidanceRecord guidanceRecord = new PatientHealthGuidanceRecord();
//				guidanceRecord.setCode(getCode());
//				guidanceRecord.setPatient(patient.getCode());
//				guidanceRecord.setPatientOpenid(openId);
//				guidanceRecord.setDoctor(doctor.getCode());
//				guidanceRecord.setContent(guidance.getContent());
//				guidanceRecord.setDel(1);
//				guidanceRecord.setImages(guidance.getImages());
//				guidanceRecord.setVoice(guidance.getVoice());
//				guidanceRecord.setReadStatus(0);
//				guidanceRecord.setAdminTeamCode(signFamily.getAdminTeamId());
//				guidanceRecord.setCreateTime(new Date());
//				patientHealthGuidanceRecordDao.save(guidanceRecord);
//
//				// 推送消息到微信端
//				pushMsgTask.putWxMsg(accessToken, 4, openId, patient.getName(), json);
//			}else {
//				//发送代理人
//				JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(), patient.getOpenid());
//				if (jsonArray != null && jsonArray.length() > 0) {
//					for (int i = 0; i < jsonArray.length(); i++) {
//						JSONObject j = jsonArray.getJSONObject(i);
//						Patient member = (Patient) j.get("member");
//						//保存健康指导推送记录
//						PatientHealthGuidanceRecord guidanceRecord = new PatientHealthGuidanceRecord();
//						guidanceRecord.setCode(getCode());
//						guidanceRecord.setPatient(patient.getCode());
//						guidanceRecord.setPatientOpenid(member.getOpenid());
//						guidanceRecord.setDoctor(doctor.getCode());
//						guidanceRecord.setContent(guidance.getContent());
//						guidanceRecord.setDel(1);
//						guidanceRecord.setImages(guidance.getImages());
//						guidanceRecord.setVoice(guidance.getVoice());
//						guidanceRecord.setReadStatus(0);
//						guidanceRecord.setAdminTeamCode(signFamily.getAdminTeamId());
//						guidanceRecord.setCreateTime(new Date());
//						patientHealthGuidanceRecordDao.save(guidanceRecord);
//
//						JSONObject data = json;
//						data.remove("toUser");
//						data.put("toUser", member.getCode());
//						//String first = (String) json.get("first");
//						data.remove("first");
//						data.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()) + "健康指导提醒");
//						pushMsgTask.putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 4, member.getOpenid(), patient.getName(), data);
//					}
//				}
//			}
//		}
//		if(StringUtils.isNotEmpty(tzCode)&&!"undefined".equals(tzCode)){
//			String sql = " select * from device.wlyy_patient_health_index i where id in ("+tzCode+")";
//			sql = TransforSqlUtl.wlyy_patient_health_index(sql);
//
//			List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//			long h24 = 1000*60*60*24+10;
//			for(Map<String, Object> one :list){
//				if(one.get("manage_result")!=null&&((Integer)one.get("manage_result")==1||(Integer)one.get("manage_result")==2))continue;
//				String tempSql="";
//				Date temp =(Date)one.get("czrq");
//				if(new Date().getTime()-temp.getTime()<=h24){//有效干预
//					tempSql = "update device.wlyy_patient_health_index set manage_result=1 where id="+one.get("id");
//				}else{//无效干预
//					tempSql = "update device.wlyy_patient_health_index set manage_result=2 where id="+one.get("id");
//				}
//				jdbcTemplate.execute(tempSql);
//			}
//			String tempSql="update wlyy.wlyy_message a set a.has_read = 0,a.over='0' where a.tz_code in ("+tzCode+") and a.type=2 ";
//			jdbcTemplate.execute(tempSql);
//		}
//
//		return guidance;
//	}
//
//	/**
//	 * 查询医生为患者添加的健康指导
//	 * @param doctor 医生标识
//	 * @param patient 患者标识
//	 * @param id
//	 * @param pagesize 分页大小
//	 * @return
//	 */
//	public JSONArray findPatientGuidanceByDoctor(String doctor, String patient, String beginStr, String endStr, long id, int pagesize) {
//		Date begin = DateUtil.strToDateLong(beginStr);
//		Date end = DateUtil.strToDateLong(endStr);
//		JSONArray array = new JSONArray();
//		Page<Object> page = null;
//		PageRequest pageRequest = new PageRequest(0, pagesize);
//		if (id > 0) {
//			if (StringUtils.isNotEmpty(patient)) {
//				if (begin != null && end != null) {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, begin, end, id, pageRequest);
//				} else {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, id, pageRequest);
//				}
//			} else {
//				if (begin != null && end != null) {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, begin, end, id, pageRequest);
//				} else {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, id, pageRequest);
//				}
//			}
//		} else {
//			if (StringUtils.isNotEmpty(patient)) {
//				if (begin != null && end != null) {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, begin, end, pageRequest);
//				} else {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, pageRequest);
//				}
//			} else {
//				if (begin != null && end != null) {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, begin, end, pageRequest);
//				} else {
//					page = patientHealthGuidanceDao.findByDoctor(doctor, pageRequest);
//				}
//			}
//		}
//		if (page != null) {
//			for (Object obj : page) {
//				Object[] temp = (Object[]) obj;
//				if (temp == null || temp.length != 5) {
//					continue;
//				}
//				JSONObject json = new JSONObject();
//				json.put("name", temp[0]);
//				json.put("photo", temp[1]);
//				json.put("id", temp[2]);
//				json.put("content", temp[3]);
//				json.put("czrq", DateUtil.dateToStrLong((Date) temp[4]));
//				array.put(json);
//			}
//		}
//		return array;
//	}
//
//	/**
//	 * 健康指导查询
//	 *
//	 * @param patient
//	 * @param teamCode
//	 * @param page
//	 * @param pageSize
//	 * @return
//	 */
//	public JSONArray findByPatientAndGuidanceAndTeam(String patient, long teamCode, int page, int pageSize){
//		Sort sort = new Sort(Sort.Direction.DESC,"createTime");
//		PageRequest pageRequest = new PageRequest(page, pageSize, sort);
//		Page<Object> result = patientHealthGuidanceDao.findByPatientAndTeamCode(patient,teamCode,pageRequest);
//		JSONArray array = new JSONArray();
//		if (result != null) {
//			for (Object obj : result) {
//				Object[] temp = (Object[]) obj;
//				JSONObject json = new JSONObject();
//				json.put("doctorCode", temp[6]);
//				json.put("doctorName", temp[0]);
//				json.put("doctorPhoto", temp[1]);
//				json.put("id", temp[2]);
//				json.put("content", temp[3]);
//				json.put("createTime", DateUtil.dateToStrLong((Date) temp[4]));
//				json.put("adminTeamCode", temp[7]);
//				json.put("readStatus", temp[8]);
//				json.put("total", result.getTotalElements());
//				array.put(json);
//			}
//		}
//		return array;
//	}
//
//	/**
//	 * 查询患者的健康指导
//	 * @param patient 患者标识
//	 * @param id
//	 * @param pagesize 分页大小
//	 * @return
//	 */
//	public JSONArray findGuidanceByPatient(String patient, long id, int pagesize) {
//
//		JSONArray array = new JSONArray();
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(0, pagesize);
//		Page<Object> page = null;
//		if (id > 0) {
//			page = patientHealthGuidanceDao.findByPatient(patient, id, pageRequest);
//		} else {
//			page = patientHealthGuidanceDao.findByPatient(patient, pageRequest);
//		}
//		if (page != null) {
//			for (Object obj : page) {
//				Object[] temp = (Object[]) obj;
//				if (temp == null || temp.length != 7) {
//					continue;
//				}
////				控制返回内容50字以内
//				String content = temp[3].toString();
//				String contain = "";
//				if(content.length()>50){
//					contain = content.substring(0,50);
//				}else {
//					contain = content.substring(0,content.length()-1);
//				}
//				JSONObject json = new JSONObject();
//				json.put("name", temp[0]);
//				json.put("photo", temp[1]);
//				json.put("id", temp[2]);
//				json.put("content", contain);
//				json.put("createTime", DateUtil.dateToStrLong((Date) temp[4]));
//				json.put("level", temp[5]);
//				json.put("readStatus", temp[6]);
//				array.put(json);
//			}
//		}
//		return array;
//	}
//
//	public Integer findGuidanceByPatient(String patientCode, String doctor) {
//		return patientHealthGuidanceDao.findbydoctorAndPatient(doctor,patientCode);
//	}
//
//	public JSONArray getPatientHealthGuidance(String idcard, String page, String pageSize) throws Exception {
//		Patient patient = patientDao.findByIdcard(idcard);
//
//		if(patient == null || StringUtils.isBlank(patient.getCode())){
//			throw new ServiceException("找不到该身份证号的居民!");
//		}
//
//		JSONArray array = new JSONArray();
//		// 分页信息,排序
//		Sort sort = new Sort(Sort.Direction.DESC,"createTime");
//		// 分页信息
//		Pageable pageRequest = new PageRequest(Integer.valueOf(page) - 1, Integer.valueOf(pageSize), sort);
//		Page<Object> pageObj = null;
//		pageObj = patientHealthGuidanceDao.findByPatient(patient.getCode(), pageRequest);
//		if (page != null) {
//			for (Object obj : pageObj) {
//				Object[] temp = (Object[]) obj;
//				if (temp == null || temp.length != 7) {
//					continue;
//				}
////				控制返回内容50字以内
//				String content = temp[3].toString();
//				String contain = "";
//				if(content.length()>50){
//					contain = content.substring(0,50);
//				}else {
//					contain = content.substring(0,content.length()-1);
//				}
//				JSONObject json = new JSONObject();
//				json.put("name", temp[0]);
//				json.put("photo", temp[1]);
//				json.put("id", temp[2]);
//				json.put("content", contain);
//				json.put("contentAll", content);
//				json.put("createTime", DateUtil.dateToStrLong((Date) temp[4]));
//				json.put("level", temp[5]);
//				json.put("readStatus", temp[6]);
//				array.put(json);
//			}
//		}
//		return array;
//	}
//}

+ 2452 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/PatientHealthIndexService.java

@ -0,0 +1,2452 @@
package com.yihu.jw.health.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.device.dao.*;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.device.DoctorHealthStandard;
import com.yihu.jw.entity.base.device.PatientAimBloodPressure;
import com.yihu.jw.entity.base.device.PatientAimBloodSugger;
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.entity.door.SignFamily;
import com.yihu.jw.entity.scheme.DoctorSwitch;
import com.yihu.jw.entity.scheme.TrackPatient;
import com.yihu.jw.entity.util.TransforSqlUtl;
import com.yihu.jw.iot.IotDeviceService;
import com.yihu.jw.message.dao.MessageDao;
import com.yihu.jw.message.service.MessageService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.conf.SystemConf;
import com.yihu.jw.scheme.DoctorSwitchDao;
import com.yihu.jw.scheme.TrackPatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.HttpClientUtil;
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.beans.factory.annotation.Value;
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.SimpleDateFormat;
import java.util.*;
//import org.springside.modules.utils.Clock;
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthIndexService {
    private Logger logger = LoggerFactory.getLogger(PatientHealthIndexService.class);
    //    private Clock clock = Clock.DEFAULT;
//
    @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 com.yihu.jw.util.common.CommonUtil CommonUtil;
    @Autowired
    private PatientAimSportsDao patientAimSportsDao;
    @Autowired
    private DoctorHealthStandardDao doctorHealthStandardDao;
//    @Value("${doctorAssistant.api}")
    private String doctorAssistant;
//    @Value("${doctorAssistant.target_url}")
    private String targetUrl;
//    @Autowired
//    private HttpClientUtil httpClientUtil;
//    @Autowired
//    private ImUtill ImUtill;
    @Autowired
    private MessageService messageService;
    @Autowired
    private DoctorSwitchDao doctorSwitchDao;
    @Autowired
    private TrackPatientDao trackPatientDao;
    @Autowired
    private PatientAimBloodSuggerDao patientAimBloodSuggerDao;
    @Autowired
    private PatientAimBloodPressureDao patientAimBloodPressureDao;
    @Autowired
    private DeviceDetailDao deviceDetailDao;
    @Autowired
    private IotDeviceService iotDeviceService;
//    @Autowired
//    private WlyyIotTzDictDao wlyyIotTzDictDao;
//    @Autowired
//    private SqlReplaceService sqlReplaceService;
//    @Autowired
//    private PushMsgTask pushMsgTask;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private DoctorWorkTimeService doctorWorkTimeService;
//    @Autowired
//    private ConsultTeamDao consultTeamDao;
    /**
     * 获取居民标准预警值
     *
     * @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 = SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
            Double minValueBefore = SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
            Double maxValueAfter = SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
            Double minValueAfter = SystemConf.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 = SystemConf.HEALTH_STANDARD_SSY_MAX;
            Double minValueSSY = SystemConf.HEALTH_STANDARD_SSY_MIN;
            Double maxValueSZY = SystemConf.HEALTH_STANDARD_SZY_MAX;
            Double minValueSZY = SystemConf.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 RuntimeException("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 RuntimeException("Result not exit!");
//        }
//
//    }
    /**
     * 获取居民最新各类健康记录
     */
//    public Map findDataByPatient(String patient, int type) throws Exception {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        String sql = "SELECT " +
//                " * " +
//                " FROM " +
//                "  device.wlyy_patient_health_index a " +
//                " WHERE " +
//                " a. USER = ? " +
//                " AND a.type = ? " +
//                " AND a.del = 1 " +
//                " ORDER BY " +
//                " a.record_date DESC " +
//                "LIMIT 0,1 ";
////        List<Map<String, Object>> devicePatient = jdbcTemplate.queryForList(sql, patient, type);
//
////        sql = TransforSqlUtl.wlyy_patient_health_index(sql);
//
//        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, Patient patient, DevicePatientHealthIndex model,String oldMsgContent) {
//        String patientCode = patient.getCode();
//        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)){
//                    //-------------健管师和家医同一个人-------------
//                    receivers.add(healthDoctorFamily);
//                }else {
//                    //-------------健管师和家医不是同一个人-------------
//                    receivers.add(healthDoctorFamily);
//                    receivers.add(doctorFamily);
//                }
//            }else if (StringUtils.isNotEmpty(healthDoctorFamily) && StringUtils.isEmpty(doctorFamily)){
//                //-------------家医为空-------------
//                receivers.add(healthDoctorFamily);
//            }else if (StringUtils.isNotEmpty(doctorFamily) && StringUtils.isEmpty(healthDoctorFamily)){
//                //-------------健管师为空-------------
//                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;
//                }
//                if (messageService.getMessageNoticeSettingByMessageType(receiver, "1", MessageNoticeSetting.MessageTypeEnum.healthSignSwitch.getValue())) {
//                    //            新增发送医生助手模板消息 v1.4.0 by wujunjie
//                    Doctor doctor = doctorDao.findByCode(receiver);
//                    if (doctor != null && StringUtils.isNotEmpty(doctor.getOpenid())) {
//                        List<Message> messagesList = messageDao.findUnreadHealthIndex(patientCode, receiver);
//                        if (messagesList != null && messagesList.size() > 0) {
//                            String url = doctorAssistant + "/wlyy/feldsher/sendDoctorTemplates";
//                            List<NameValuePair> params = new ArrayList<>();
//                            params.add(new BasicNameValuePair("type", "3"));
//                            params.add(new BasicNameValuePair("openId", doctor.getOpenid()));
//                            params.add(new BasicNameValuePair("url", targetUrl));
//                            params.add(new BasicNameValuePair("first", doctor.getName() + "医生,您的签约居民" + patientName +
//                                    "有" + messagesList.size() + "条未读的体征异常消息"));
//                            params.add(new BasicNameValuePair("remark", "请进入手机APP查看"));
//                            SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
//                            String date = format.format(new Date());
//                            String keywords = date + "," + patientName;
//                            params.add(new BasicNameValuePair("keywords", keywords));
//
//                            httpClientUtil.post(url, params, "UTF-8");
//                        }
//                    }
//                }
//            }
//            // 推送消息给医生
//            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 device.wlyy_patient_health_index " +
//                " WHERE `user` = '" + patient + "' " +
//                " and type = 1" +
//                " and DATE_FORMAT(record_date,'%Y-%m-%d') = '" + dateString + "'" +
//                " and del = '1' " +
//                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
//                " order by record_date,id desc ";
////        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        List<Map<String, Object>> list = getPatientXT_JsonIot(sql, patient, dateString);
//        if (list != null && list.size() > 0) {
//            obj.put("type", 1);
//            obj.put("czrq", date);
//            obj.put("recordDate", date);
//            obj.put("sortDate", date);
//            for (Map<String, Object> item : list) {
//                String data = item.get("value1").toString();
//                String dataType = item.get("value2").toString();
//                String deviceSn = item.get("device_sn") == null ? "" : item.get("device_sn").toString();
//                Date recordDate = (Date) item.get("record_date");
//                Long id = Long.parseLong(item.get("id") + "");
//                Date createDate = (Date) item.get("createDate");
//
//                String recordTime = DateUtil.dateToStr(recordDate, DateUtil.YYYY_MM_DD);
//                String createTime = DateUtil.dateToStr(createDate, DateUtil.YYYY_MM_DD);
//
//                if (data != null && dataType != null) {
//                    if (dataType.equals("1")) {
//                        obj.put("value1", data);
//                        obj.put("time1", recordDate);
//                        obj.put("id1", id);
//                        obj.put("deviceSn1", deviceSn);
//                        hadData = true;
//                    } else if (dataType.equals("2")) {
//                        obj.put("value2", data);
//                        obj.put("time2", recordDate);
//                        obj.put("id2", id);
//                        obj.put("deviceSn2", deviceSn);
//                        hadData = true;
//                    } else if (dataType.equals("3")) {
//                        obj.put("value3", data);
//                        obj.put("time3", recordDate);
//                        obj.put("id3", id);
//                        obj.put("deviceSn3", deviceSn);
//                        hadData = true;
//                    } else if (dataType.equals("4")) {
//                        obj.put("value4", data);
//                        obj.put("time4", recordDate);
//                        obj.put("id4", id);
//                        obj.put("deviceSn4", deviceSn);
//                        hadData = true;
//                    } else if (dataType.equals("5")) {
//                        obj.put("value5", data);
//                        obj.put("time5", recordDate);
//                        obj.put("id5", id);
//                        obj.put("deviceSn5", deviceSn);
//                        hadData = true;
//                    } else if (dataType.equals("6")) {
//                        obj.put("value6", data);
//                        obj.put("time6", recordDate);
//                        obj.put("id6", id);
//                        obj.put("deviceSn6", deviceSn);
//                        hadData = true;
//                    } else if (dataType.equals("7")) {
//                        obj.put("value7", data);
//                        obj.put("time7", recordDate);
//                        obj.put("id7", id);
//                        obj.put("deviceSn7", deviceSn);
//                        hadData = true;
//                    }
//
//                    //是否为补传数据(设备上传且测量时间和创建时间不匹配)
//                    judgeIsSupplement(obj, recordTime, createTime, deviceSn, dataType);
//
//                    obj.put("healthindexid", id);
//                    obj.put("valuedata", data);
//                    obj.put("dataType", dataType);
//                }
//            }
//        }
//        if (hadData) {
//            return obj;
//        } else {
//            return null;
//        }
//    }
    /**
     * 是否为补传数据(设备上传且测量时间和创建时间不匹配)
     *
     * @param obj
     * @param recordDate
     * @param createDate
     * @param deviceSn
     * @param num
     */
    private void judgeIsSupplement(com.alibaba.fastjson.JSONObject obj, String recordDate, String createDate, String deviceSn, String num) {
        if ("".equals(deviceSn)) {
            obj.put("isSupplement" + num, 0);
        } else {
            if (recordDate.compareTo(createDate) == 0) {
                obj.put("isSupplement" + num, 0);
            } else {
                obj.put("isSupplement" + num, 1);
            }
        }
    }
    private com.alibaba.fastjson.JSONArray getPatientXT_Json1(String patient, Integer page, Integer pageSize) {
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        obj.put("user", patient);
        boolean hadData = false;
        /***************** 按时间排序 ***************************/
        String sql = "SELECT " +
                "MIN(id) id" +
                ", user" +
                ",value1" +
                ",value2" +
                ",value3" +
                ",value4" +
                ",value5" +
                ",value6" +
                ",value7" +
                ",device_sn" +
                ",type" +
                ",DATE_FORMAT(record_date,'%Y-%m-%d') as record_date " +
                ",sort_date" +
                ",min(czrq) czrq " +
                " from device.wlyy_patient_health_index " +
                " WHERE `user` = '" + patient + "' " +
                " and type = 1" +
                " and del = '1' " +
                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                " order by record_date,id desc limit " + page + "," + pageSize;
//        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        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 = SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
//            Double minValueBefore = SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
//            Double maxValueAfter = SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
//            Double minValueAfter = SystemConf.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 = SystemConf.HEALTH_STANDARD_SSY_MAX;
//            Double minValueSSY = SystemConf.HEALTH_STANDARD_SSY_MIN;
//            Double maxValueSZY = SystemConf.HEALTH_STANDARD_SZY_MAX;
//            Double minValueSZY = SystemConf.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) {
//        if (iotDeviceService.isUploadIot()) {
//            //物联网更新
//            iotDeviceService.updateStatus(data.getId(), "1");
//        } else {
//            data.setStatus(1);
//            patientHealthIndexDao.save(data);
//        }
//    }
    /**
     * 按id查找体征记录
     *
     * @param id
     * @return
     */
//    public DevicePatientHealthIndex findOne(Long id) {
//        if (iotDeviceService.isUploadIot()) {
//            return iotDeviceService.getById(id);
//        } else {
//            return patientHealthIndexDao.findById(id).orElse(null);
//        }
//    }
    /**
     * 体征保存
     *
     * @param data
     * @return
     */
//    public DevicePatientHealthIndex save(DevicePatientHealthIndex data) {
//        if (iotDeviceService.isUploadIot()) {
//            return iotDeviceService.save(data);
//        } else {
//            //数据双写
//            try {
//                iotDeviceService.save(data);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return patientHealthIndexDao.save(data);
//        }
//    }
    /**
     * 体征修改
     *
     * @param data
     * @return
     */
//    public DevicePatientHealthIndex update(DevicePatientHealthIndex data) {
//        if (iotDeviceService.isUploadIot()) {
//            return iotDeviceService.update(data);
//        } else {
//            return patientHealthIndexDao.save(data);
//        }
//    }
    /**
     * 查询最近的一条体征数据
     *
     * @param sql
     * @param patient
     * @param type
     * @return
     */
//    public List<Map<String, Object>> findDataByPatient(String sql, String patient, Integer type) {
//        if (iotDeviceService.isUploadIot()) {
//            List<Map<String, Object>> re = new ArrayList<>();
//            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndType(patient, type, 1);
//            if (list != null && list.size() > 0) {
//                re.add(indexToMap(list.get(0)));
//            }
//            return re;
//        } else {
//            return jdbcTemplate.queryForList(sql, patient, type);
//        }
//    }
    /**
     * 患者最近填写的健康指标
     *
     * @param patient
     * @return
     */
//    public List<DevicePatientHealthIndex> findRecentByPatientIterable(String patient) {
//        if (iotDeviceService.isUploadIot()) {
//            return iotDeviceService.findByPatientAndType(patient, null, 1000);
//        } else {
//            return patientHealthIndexDao.findRecentByPatient(patient);
//        }
//    }
    /**
     * 根据患者标志获取健康指标
     * @param patient
     * @param type
     * @return
     */
//    public DevicePatientHealthIndex findLastByPatienIot(String patient,Integer type){
//        if(iotDeviceService.isUploadIot()){
//            DevicePatientHealthIndex index = null;
//            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndType(patient,type,1);
//            if(list!=null&&list.size()>0){
//                index = list.get(0);
//            }
//            return index;
//        }else {
//            return findLastByPatien(patient,type);
//        }
//    }
    /**
     *  获取小康小屋数据
     *
     * @param patientCode
     * @return
     * @throws Exception
     */
//    public List<Map<String,Object>> selectByXiaoWu(String patientCode) throws Exception {
//        Patient patient = patientDao.findByCode(patientCode);
//        if (patient == null){
//            throw new RuntimeException("该居民不存在!");
//        }
//        String idcard = patient.getIdcard();
//        String sql = "SELECT  *  FROM xmiot.wlyy_iot_d d RIGHT JOIN " +
//                "( SELECT  *  FROM xmiot.wlyy_iot_m m  " +
//                "WHERE m.id_card_no = '"+idcard+"' " +
//                "ORDER BY m.measure_time DESC LIMIT 0,1 ) m2 ON	m2.id = d.mid AND d.code = 'Result'";
//        List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);
//        for (Map<String,Object> map:maps){
//            map.put("typeName",wlyyIotTzDictDao.selectByCodeAndValue(map.get("type").toString(),map.get("type").toString()));
//            map.put("valueName",wlyyIotTzDictDao.selectByCodeAndValue(map.get("type").toString()+"_"+map.get("code").toString(),map.get("value").toString()));
//        }
//        return maps;
//
//    }
    /**
     * 血糖 、血压
     *
     * @param patientCode
     * @return
     * @throws Exception
     */
//    public List<Map<String, Object>> selectByTypeOfXiaoWu(String patientCode, String type) throws Exception {
//        BasePatientDO patient = patientDao.findById(patientCode).orElse(null);
//        if (patient == null) {
//            throw new RuntimeException("该居民不存在!");
//        }
//        String idcard = patient.getIdcard();
//        String sql = "SELECT * FROM xmiot.wlyy_iot_d d RIGHT JOIN ( " +
//                "SELECT * FROM xmiot.wlyy_iot_m m " +
//                "WHERE  m.id_card_no = '" + idcard + "' " +
//                "ORDER BY m.measure_time DESC LIMIT 0,1 ) m2 " +
//                "ON m2.id = d.mid AND d.type = '" + type + "'";
//        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
//        for (Map<String, Object> map : maps) {
//            if (map.get("code").toString().equalsIgnoreCase("Result")) {
//                map.put("typeName", wlyyIotTzDictDao.selectByCodeAndValue(map.get("type").toString(), map.get("type").toString()));
//                map.put("valueName", wlyyIotTzDictDao.selectByCodeAndValue(map.get("type").toString() + "_" + map.get("code").toString(), map.get("value").toString()));
//            }
//        }
//        return maps;
//
//    }
    /**
     * 查询指标记录
     *
     * @param patient
     * @param startDate
     * @param endDate
     * @param page
     * @param size
     * @return
     */
//    public List<String> findDateListIot(String patient, int type, Date startDate, Date endDate, Integer page, Integer size, String start, String end) {
//        if (iotDeviceService.isUploadIot()) {
//            List<String> re = new ArrayList<>();
//            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, null, page, size, null, start, end);
//            if (list != null && list.size() > 0) {
//                list.forEach(one -> {
//                    re.add(DateUtil.dateToStrShort(one.getRecordDate()));
//                });
//            }
//            return re;
//        } else {
//            return patientHealthIndexDao.findDateList(patient, type, startDate, endDate, page, size);
//        }
//    }
    public List<String> findDateListIot1(String patient, Date startDate, Date endDate, Integer page, Integer size, String start, String end) {
        return patientHealthIndexDao.findDateList(patient, startDate, endDate, page, size);
    }
    /**
     * 按时间查找
     *
     * @param sql
     * @param patient
     * @param type
     * @param size
     * @param gi_type
     * @param begin
     * @param end
     * @return
     */
//    public List<Map<String, Object>> findByPatientAndTime(String sql, String patient, Integer type, Integer size, Integer gi_type, String begin, String end) {
//        if (iotDeviceService.isUploadIot()) {
//            List<Map<String, Object>> re = new ArrayList<>();
//            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, type, 1, size, gi_type, begin, end);
//            if (list != null && list.size() > 0) {
//                list.forEach(one -> {
//                    re.add(indexToMap(one));
//                });
//            }
//            return re;
//        } else {
//            return jdbcTemplate.queryForList(sql);
//        }
//    }
    /**
     * 按时间查找
     *
     * @param sql
     * @param patient
     * @param date
     * @return
     */
//    public List<Map<String, Object>> getPatientXT_JsonIot(String sql, String patient, String date) {
//        String begin = date + " 00:00:00";
//        String end = date + " 23:59:59";
//        if (iotDeviceService.isUploadIot()) {
//            List<Map<String, Object>> re = new ArrayList<>();
//            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, 1, 1, 100, null, begin, end);
//            if (list != null && list.size() > 0) {
//                list.forEach(one -> {
//                    re.add(indexToMap(one));
//                });
//            }
//            return re;
//        } else {
//            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) {
//        if (iotDeviceService.isUploadIot()) {
//            List<Map<String, Object>> re = new ArrayList<>();
//            List<DevicePatientHealthIndex> list = iotDeviceService.findByPatientAndTime(patient, type, page, size, null, begin, end);
//            if (list != null && list.size() > 0) {
//                list.forEach(one -> {
//                    re.add(indexToMap(one));
//                });
//            }
//            return re;
//        } else {
//            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码一样的问题未解决!!)
//            PatientDevice device = patientDeviceDao.findByDeviceSnAndCategoryCodeAndUserType(deviceSn, type, userType);
//            if (device != null) {
//                patientCode = device.getUser();
//                patient = patientDao.findByCode(patientCode);
//                idcard = device.getUserIdcard();
//            }
//
//            DeviceDetail deviceDetail = deviceDetailDao.findBySn(deviceSn);
//            if(deviceDetail!=null){
//                obj.setHospital(deviceDetail.getGrantOrgCode());
//                obj.setHospitalName(deviceDetail.getOrgName());
//            }
//        }
//        //自输数据
//        else {
//            patient = patientDao.findByCode(patientCode);
//            if (patient != null) {
//                idcard = patient.getIdcard();
//            }
//        }
//
//        //身份证不为空
//        if (patient != null) {
//            obj.setUser(patientCode);
//            obj.setName(patient.getName());
//            obj.setIdcard(idcard);
//
//            String msgContent = "";
//            // 1血糖 2血压 3体重 4腰围
//            switch (type) {
//                case "1": {
//                    obj.setType(1);
//                    String value1 = map.get("gi");  //血糖值
//                    String gi_type = map.get("gi_type"); //血糖值类型对应1到7
//                    String recordDate = map.get("recordDate");
//                    obj.setValue1(value1);
//                    obj.setValue2(gi_type);
//                    if (StringUtils.isNotBlank(recordDate)) {
//                        obj.setRecordDate(DateUtil.strToDateAppendNowTime(recordDate, DateUtil.YYYY_MM_DD_HH_MM_SS));
//                    }
//                    break;
//                }
//                case "2": {
//                    obj.setType(2);
//                    String value1 = map.get("sys");  //收缩压
//                    String value2 = map.get("dia");  //舒张压
//                    obj.setValue1(value1);
//                    obj.setValue2(value2);
//                    obj.setValue3(map.get("pul"));     //脉搏
//                    obj.setValue4(map.get("ano"));     //有无心率不齐
//                    break;
//                }
//                case "3": {
//                    obj.setType(3);
//
//                    String weight = map.get("weight");
//                    String height = map.get("height");
//
//                    obj.setValue1(weight); //体重
//                    obj.setValue2(height); //身高
//
//                    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 RuntimeException("暂不支持该指标!");
//                }
//            }
//
//            obj = save(obj);
//
//            //判断是否有未结束的续方咨询,发送消息给对应的医生
//            sendPrescriptionHealthIndexMsgresult(obj,patient);
//
//            //保存完后上传基卫
////            new Thread(new HealthIndexUploadTask(String.valueOf(obj.getId()))).start();
//        } else {
//            throw new RuntimeException("不存在该患者!");
//        }
//
//
//        return obj;
//    }
    /**
     * 判断是否有未结束的续方咨询,发送消息给对应的医生
     * @param result
     * @param patient
     */
//    private void sendPrescriptionHealthIndexMsgresult(DevicePatientHealthIndex result, Patient patient) {
//
//        List<ConsultTeam> consultTeams = consultTeamDao.findUnfinishedConsultPrescription(patient.getCode());
//
//        for (ConsultTeam consultTeam:consultTeams) {
//            if(consultTeam.getHealthindexType() != null){
//                org.json.JSONObject contentPatient = new org.json.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消息
//                ImUtill.sendTopicIM(patient.getCode(), patient.getName(), consultTeam.getConsult(), "16", contentPatient.toString(), null);
//            }
//        }
//    }
    /**
     * 判断居民的体征预警状态
     *
     * @param obj
     */
//    public void handlePatientStandarStatus(DevicePatientHealthIndex obj) {
//        //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----START
//        String patientCode = obj.getUser();
//        //患者信息
//        BasePatientDO p = patientDao.findById(patientCode).orElse(null);
//
//        PatientVO patient = new PatientVO();
//        String patientsql = "select group_concat(label) disease from wlyy_sign_patient_label_info where label_type = 3 and status=1 and (label = 1 or label = 2) and patient = '"+p.getCode()+"' GROUP BY patient";
//
//        String patientdisease = "";
//        List<Map<String,Object>> diseases = jdbcTemplate.queryForList(patientsql);
//        if(diseases!=null&&diseases.size()>0){
//            patientdisease = (String)diseases.get(0).get("disease");
//        }
//
//        int bloodPressureBbnormalCount = 0;//血压异常次数
//        int bloodSuggurBbnormalCount = 0;//血糖异常次数
//        int stdbloodPressureBbnormalCount = 0;//血压次数
//        int stdbloodSuggurBbnormalCount = 0;//血糖次数
//
//        List<DevicePatientHealthIndex> bloodPressurepatientHealthIndices = new ArrayList<>();
//        List<DevicePatientHealthIndex> bloodSuggurpatientHealthIndices = new ArrayList<>();
//
//        bloodPressurepatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode, 2);
//        bloodSuggurpatientHealthIndices = patientHealthIndexDao.findByPatientAndTypeByPage(patientCode, 1);
//
//        if(!bloodPressurepatientHealthIndices.isEmpty()){
//            stdbloodPressureBbnormalCount = bloodPressurepatientHealthIndices.size();
//        }
//
//        if(!bloodSuggurpatientHealthIndices.isEmpty()){
//            stdbloodSuggurBbnormalCount = bloodSuggurpatientHealthIndices.size();
//        }
//
//        for (DevicePatientHealthIndex index1 : bloodPressurepatientHealthIndices) {
//            if (index1.getStatus() != null && 1 == index1.getStatus()) {
//                bloodPressureBbnormalCount++;
//            }
//        }
//
//        for (DevicePatientHealthIndex index2 : bloodSuggurpatientHealthIndices) {
//            if (index2.getStatus() != null && 1 == index2.getStatus()) {
//                bloodSuggurBbnormalCount++;
//            }
//        }
//
//
//        //连续3次异常,修改用户为预警状态
//        if ((bloodPressureBbnormalCount >= 3 || bloodSuggurBbnormalCount >= 3)) {
//            p.setStandardStatus(1);
//            //1.4.2加入重点关注逻辑
//            setTrackPatientByDoctor(patientCode);
//        } else {
//            Date end = new Date();
//            Date start = DateUtil.setDateTime(end, -7);
//            //计算血糖或者血压一周内的异常记录数量
//            int errorCount = patientHealthIndexDao.getCountByTimeAndStatus(start, end, 1, patientCode);
//            if (errorCount >= 5) {//超过5次,记为预警状态
//                p.setStandardStatus(1);
//                //1.4.2加入重点关注逻辑
//                setTrackPatientByDoctor(patientCode);
//            }
//        }
//
//        //连续5次正常,修改用户为非预警状态
//        if (StringUtils.isNotBlank(patientdisease)) {
//            if ("1".equals(patientdisease)) {
//                if (stdbloodPressureBbnormalCount==5&&0 == bloodPressureBbnormalCount) {
//                    p.setStandardStatus(0);
//                    //1.4.2加入重点关注逻辑
//                    cancalTrackPatientByDoctor(patientCode);
//                }
//            } else if ("2".equals(patientdisease)) {
//                if (stdbloodSuggurBbnormalCount==5&&0 == bloodSuggurBbnormalCount) {
//                    p.setStandardStatus(0);
//                    //1.4.2加入重点关注逻辑
//                    cancalTrackPatientByDoctor(patientCode);
//                }
//            } else if ("1,2".equals(patientdisease) || "2,1".equals(patientdisease)) {
//                if (stdbloodPressureBbnormalCount==5&&stdbloodSuggurBbnormalCount==5&&0 == bloodSuggurBbnormalCount && 0 == bloodPressureBbnormalCount) {
//                    p.setStandardStatus(0);
//                    //1.4.2加入重点关注逻辑
//                    cancalTrackPatientByDoctor(patientCode);
//                }
//            }
//        } else {
//            p.setStandardStatus(0);
//            //1.4.2加入重点关注逻辑
//            cancalTrackPatientByDoctor(patientCode);
//        }
//
//        patientDao.save(p);
//        //连续5次体征值正常,则修改为非预警状态;连续5次异常,修改为预警状态-----END
//    }
    /**
     * 设置默认监控方案
     *
     * @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(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(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 patient
     * @return
     */
//    public int setTrackPatientByDoctor(String patient) {
//        SignFamily signFamily = signFamilyDao.findByjiatingPatientYes(patient);
//        if (signFamily == null) {
//            return -1;
//        }
//        BasePatientDO p = patientDao.findById(patient).orElse(null);
//        if (p == null) {
//            return -1;
//        }
//        //医生是否自动追踪居民
//        DoctorSwitch sw = doctorSwitchDao.findByDoctor(signFamily.getDoctor());
//        DoctorSwitch swh = doctorSwitchDao.findByDoctor(signFamily.getDoctorHealth());
//
//        if (sw != null) {
//            if ("1".equals(sw.getAlertPatientSwitch())) {
//                //查询是否与医生建立重点跟踪关系,诺无关系则建立
//                TrackPatient trackPatient = trackPatientDao.findByDoctorCodeAndPatientCode(signFamily.getDoctor(), patient);
//
//                if (trackPatient == null) {
//                    TrackPatient t = new TrackPatient();
//                    t.setCreateTime(new Date());
//                    t.setDoctorCode(signFamily.getDoctor());
//                    t.setDoctorName(signFamily.getDoctorName());
//                    t.setIdcard(signFamily.getIdcard());
//                    t.setSsc(signFamily.getSsc());
//                    t.setTeamCode(signFamily.getAdminTeamId().intValue());
//                    t.setPatientCode(patient);
//                    t.setPatientName(p.getName());
//                    t.setDel("1");
//                    trackPatientDao.save(t);
//                    //设置默认控制目标
//                    setDefaultAim(patient);
//                } else {
//                    trackPatient.setDel("1");
//                    trackPatientDao.save(trackPatient);
//                }
//            }
//        }
//
//        if (swh != null) {
//            if ("1".equals(swh.getAlertPatientSwitch())) {
//                //查询是否与医生建立重点跟踪关系,诺无关系则建立
//                TrackPatient trackPatient = trackPatientDao.findByDoctorCodeAndPatientCode(signFamily.getDoctorHealth(), patient);
//                if (trackPatient == null) {
//                    TrackPatient t = new TrackPatient();
//                    t.setCreateTime(new Date());
//                    t.setDoctorCode(signFamily.getDoctorHealth());
//                    t.setDoctorName(signFamily.getDoctorHealthName());
//                    t.setIdcard(signFamily.getIdcard());
//                    t.setSsc(signFamily.getSsc());
//                    t.setTeamCode(signFamily.getAdminTeamId().intValue());
//                    t.setPatientCode(patient);
//                    t.setPatientName(p.getName());
//                    t.setDel("1");
//                    trackPatientDao.save(t);
//                    //设置默认控制目标
//                    setDefaultAim(patient);
//                } else {
//                    trackPatient.setDel("1");
//                    trackPatientDao.save(trackPatient);
//                }
//            }
//        }
//        return 1;
//    }
//    public int cancalTrackPatientByDoctor(String patient){
//        SignFamily signFamily = signFamilyDao.findByjiatingPatientYes(patient);
//        if(signFamily==null){
//            return -1;
//        }
//        BasePatientDO p = patientDao.findByCode(patient);
//        if(p==null){
//            return -1;
//        }
//        //医生是否自动追踪居民
//
//        DoctorSwitch sw =  doctorSwitchDao.findByDoctor(signFamily.getDoctor());
//        DoctorSwitch swh =  doctorSwitchDao.findByDoctor(signFamily.getDoctorHealth());
//
//        if(sw!=null){
//            if("1".equals(sw.getAlertPatientSwitch())){
//                //查询是否与医生建立重点跟踪关系,诺无关系则建立
//                TrackPatient trackPatient = trackPatientDao.findByDoctorCodeAndPatientCode(signFamily.getDoctor(),patient);
//
//                if(trackPatient == null){
//                    TrackPatient t = new TrackPatient();
//                    t.setCreateTime(new Date());
//                    t.setDoctorCode(signFamily.getDoctor());
//                    t.setDoctorName(signFamily.getDoctorName());
//                    t.setIdcard(signFamily.getIdcard());
//                    t.setSsc(signFamily.getSsc());
//                    t.setTeamCode(signFamily.getAdminTeamId().intValue());
//                    t.setPatientCode(patient);
//                    t.setPatientName(p.getName());
//                    t.setDel("0");
//                    trackPatientDao.save(t);
//                }else{
//                    trackPatient.setDel("0");
//                    trackPatientDao.save(trackPatient);
//                }
//            }
//        }
//
//        if(swh!=null){
//            if("1".equals(swh.getAlertPatientSwitch())){
//                //查询是否与医生建立重点跟踪关系,诺无关系则建立
//                TrackPatient trackPatient = trackPatientDao.findByDoctorCodeAndPatientCode(signFamily.getDoctorHealth(),patient);
//                if(trackPatient == null){
//                    TrackPatient t = new TrackPatient();
//                    t.setCreateTime(new Date());
//                    t.setDoctorCode(signFamily.getDoctorHealth());
//                    t.setDoctorName(signFamily.getDoctorHealthName());
//                    t.setIdcard(signFamily.getIdcard());
//                    t.setSsc(signFamily.getSsc());
//                    t.setTeamCode(signFamily.getAdminTeamId().intValue());
//                    t.setPatientCode(patient);
//                    t.setPatientName(p.getName());
//                    t.setDel("0");
//                    trackPatientDao.save(t);
//                }else{
//                    trackPatient.setDel("0");
//                    trackPatientDao.save(trackPatient);
//                }
//            }
//        }
//        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 begin 开始时间
     * @param end   结束时间
     * @return
     */
//    public List<DevicePatientHealthIndex> findChartByPatien(String patient, int type, String begin, String end) {
//        List<DevicePatientHealthIndex> re = new ArrayList<>();
//
//        Date startDate = DateUtil.strToDate(begin, DateUtil.YYYY_MM_DD_HH_MM_SS);
//        Date endDate = DateUtil.strToDate(end, DateUtil.YYYY_MM_DD_HH_MM_SS);
//        if (type == 1)   //血糖特殊处理
//        {
//            //根据时间过滤排序
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, null);
//            if (dateList != null && dateList.size() > 0) {
//                for (int i = dateList.size() - 1; i >= 0; i--) {
//                    String dateString = dateList.get(i);
//                    DevicePatientHealthIndex obj = getPatientXT(patient, dateString);
//                    if (obj != null) {
//                        re.add(obj);
//                    }
//                }
//            }
//        } else {
//            // 排序
//            Sort sort = new Sort(Direction.ASC, "recordDate");
//            PageRequest pageRequest = new PageRequest(0, 1000, sort);
//            re = patientHealthIndexDao.findIndexByPatient(patient, type, startDate, endDate, pageRequest).getContent();
//        }
//        return re;
//    }
    /**
     * 按时间段查询患者健康指标
     *
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
//    public JSONArray findChartByPatient(String patient, int type, int gi_type, String begin, String end) {
//        JSONArray re = new JSONArray();
//        String sql = "SELECT " +
//                "MIN(id) id" +
//                ", user" +
//                ",value1" +
//                ",value2" +
//                ",value3" +
//                ",value4" +
//                ",value5" +
//                ",value6" +
//                ",value7" +
//                ",device_sn" +
//                ",type" +
//                ",record_date" +
//                ",sort_date" +
//                ",min(czrq) czrq " +
//                " from device.wlyy_patient_health_index " +
//                " WHERE `user` = '" + patient + "' " +
//                " and type =" + type +
//                " and record_date >= '" + begin + "'" +
//                " and record_date <= '" + end + "' " +
//                " and del = '1' ";
//        String conditionApp = "";
//        if (gi_type != 0) {
//            conditionApp = " and value2 = '" + gi_type + "' ";
//        }
//        sql = sql + conditionApp +
//                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
//                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
////        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        List<Map<String, Object>> list = findByPatientAndTime(sql, patient, type, 1000, gi_type, begin, end);
//        for (Map<String, Object> map : list) {
//            JSONObject json = new JSONObject();
//            json.put("id", map.get("id"));
//            json.put("patient", map.get("user"));
//            json.put("value1", map.get("value1"));
//            json.put("value2", map.get("value2"));
//            json.put("value3", map.get("value3"));
//            json.put("value4", map.get("value4"));
//            json.put("value5", map.get("value5"));
//            json.put("value6", map.get("value6"));
//            json.put("value7", map.get("value7"));
//            json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
//            json.put("type", map.get("type"));
//
//            Date date = (Date) map.get("record_date");
//            if (type == 2) {
//                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
//            } else {
//                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
//            }
//            json.put("sortDate", map.get("sort_date"));
//            json.put("czrq", map.get("czrq"));
//
//            re.put(json);
//        }
//        return re;
//    }
    /**
     * 按时间段查询患者健康指标
     *
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
//    public com.alibaba.fastjson.JSONObject findChartByPatientIot(String patient, int type, int gi_type, String begin, String end, String time) {
//        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
//        com.alibaba.fastjson.JSONArray re = new com.alibaba.fastjson.JSONArray();
//        int high = 0;//偏高
//        int normal = 0;//正常
//        int low = 0;//偏低
//        boolean flag = false;//高危标志 true高危。
//
//        String sql = "SELECT " +
//                "MIN(id) id" +
//                ", user" +
//                ",value1" +
//                ",value2" +
//                ",value3" +
//                ",value4" +
//                ",value5" +
//                ",value6" +
//                ",value7" +
//                ",device_sn" +
//                ",type" +
//                ",record_date" +
//                ",sort_date" +
//                ",min(czrq) czrq " +
//                " from device.wlyy_patient_health_index " +
//                " WHERE `user` = '" + patient + "' " +
//                " and type =" + type +
//                " and record_date >= '" + begin + "'" +
//                " and record_date <= '" + end + "' " +
//                " and del = '1' ";
//        String conditionApp = "";
//        if (gi_type != 0) {
//            conditionApp = " and value2 = '" + gi_type + "' ";
//        }
//        sql = sql + conditionApp +
//                " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
//                " order by record_date desc ,sort_date desc limit " + 0 + " ," + 1000 + " ";
////        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//        List<Map<String, Object>> list = findByPatientAndTime(sql, patient, type, 1000, gi_type, begin, end);
//        for (Map<String, Object> map : list) {
//            String value1 = map.get("value1").toString();
//            String value2 = map.get("value2").toString();
//            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
//            json.put("id", map.get("id"));
//            json.put("patient", map.get("user"));
//            json.put("value1", value1);
//            json.put("value2", value2);
//            json.put("value3", map.get("value3"));
//            json.put("value4", map.get("value4"));
//            json.put("value5", map.get("value5"));
//            json.put("value6", map.get("value6"));
//            json.put("value7", map.get("value7"));
//            json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
//            json.put("type", map.get("type"));
//
//            Date date = (Date) map.get("record_date");
//            if (type == 2) {
//                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
//            } else {
//                json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
//            }
//            json.put("sortDate", map.get("sort_date"));
//            json.put("czrq", map.get("czrq"));
//
//
//            //统计加指标分析
//            int returnInt = 0;
//            if (type == 1) {
////                int age = 60;
////                Patient p = patientDao.findByCode(patient);
////                if(p!=null){
////                    age = IdCardUtil.getAgeForIdcard(p.getIdcard());
////                }
//                //血糖
//                Double maxValueBefore = SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE;
//                Double minValueBefore = SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE;
//                Double maxValueAfter = SystemConf.HEALTH_STANDARD_ST_MAX_AFTER;
//                Double minValueAfter = SystemConf.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 = SystemConf.HEALTH_STANDARD_SSY_MAX;
//                Double minValueSSY = SystemConf.HEALTH_STANDARD_SSY_MIN;
//                Double maxValueSZY = SystemConf.HEALTH_STANDARD_SZY_MAX;
//                Double minValueSZY = SystemConf.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 device.wlyy_patient_health_index " +
//                    " WHERE `user` = '" + patient + "' " +
//                    " and type =" + type +
//                    " and record_date >= '" + start + "'" +
//                    " and record_date <= '" + end + "' " +
//                    " and del = '1' " +
//                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
//                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
////            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
//            List<Map<String, Object>> list = getPatientXT_JsonIot(sql, patient, type, Integer.parseInt(String.valueOf(pageRequest.getOffset())), pageRequest.getPageSize(), start, end);
//            for (Map<String, Object> map : list) {
//                JSONObject json = new JSONObject();
//                json.put("id", map.get("id"));
//                json.put("healthindexid", map.get("id"));
//                json.put("patient", map.get("user"));
//                json.put("value1", map.get("value1"));
//                json.put("value2", map.get("value2"));
//                json.put("value3", map.get("value3"));
//                json.put("value4", map.get("value4"));
//                json.put("value5", map.get("value5"));
//                json.put("value6", map.get("value6"));
//                json.put("value7", map.get("value7"));
//                json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
//                json.put("type", map.get("type"));
//
//                Date date = (Date) map.get("record_date");
//                if (type == 2) {
//                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
//                } else {
//                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
//                }
//                json.put("sortDate", map.get("sort_date"));
//                json.put("czrq", map.get("czrq"));
//
//                //是否为补传数据(设备上传且测量时间和创建时间不匹配)
//                Date recordDate = (Date) map.get("record_date");
//                Date createDate = (Date) map.get("createDate");
//                String recordTime = DateUtil.dateToStr(recordDate, DateUtil.YYYY_MM_DD);
//                String createTime = DateUtil.dateToStr(createDate, DateUtil.YYYY_MM_DD);
//                if (map.get("device_sn") == null) {
//                    json.put("isSupplement", 0);
//                } else {
//                    if (recordTime.compareToIgnoreCase(createTime) == 0) {
//                        json.put("isSupplement", 0);
//                    } else {
//                        json.put("isSupplement", 1);
//                    }
//                }
//
//                re.put(json);
//            }
//        }
//        return re;
//    }
    public JSONObject findIndexByPatient1(String patient, int type, int page, int pageSize) {
        JSONArray re = new JSONArray();
        JSONObject object = new JSONObject();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
        } else {
            // 排序
            Sort sort =  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 device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc limit " + pageRequest.getOffset() + " ," + pageRequest.getPageSize() + " ";
            String sqlCount = "select count(1) as total from (SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type =" + type +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date desc ,sort_date desc) phi ";
//            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List<Map<String, Object>> rstotal2 = jdbcTemplate.queryForList(sqlCount);
            Long taskCount = 0L;
            if (rstotal2 != null && rstotal2.size() > 0) {
                Object object1 = rstotal2.get(0).get("total");
                if (object1 != null) {
                    taskCount = Long.parseLong(object1.toString());
                }
            }
            object.put("totalCount", taskCount);
            for (Map<String, Object> map : list) {
                JSONObject json = new JSONObject();
                json.put("id", map.get("id"));
                json.put("healthindexid", map.get("id"));
                json.put("patient", map.get("user"));
                json.put("value1", map.get("value1"));
                json.put("value2", map.get("value2"));
                json.put("value3", map.get("value3"));
                json.put("value4", map.get("value4"));
                json.put("value5", map.get("value5"));
                json.put("value6", map.get("value6"));
                json.put("value7", map.get("value7"));
                json.put("deviceSn", map.get("device_sn") == null ? "" : map.get("device_sn"));
                json.put("type", map.get("type"));
                Date date = (Date) map.get("record_date");
                if (type == 2) {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD_HH_MM_SS));
                } else {
                    json.put("date", DateUtil.dateToStr(date, DateUtil.YYYY_MM_DD));
                }
                json.put("sortDate", map.get("sort_date"));
                json.put("czrq", map.get("czrq"));
                re.put(json);
            }
        }
        object.put("pageSize", pageSize);
        object.put("currPage", page + 1);
        object.put("detailModelList", re);
        return object;
    }
    /**
     * 查询指标记录
     *
     * @param patient
     * @param type
     * @param start
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
//    public List<Object> findIndexByPatient2(String patient, int type, String start, String end, int page, int pageSize) {
//        List<Object> re = new ArrayList<>();
//        if (page > 0) {
//            page = page - 1;
//        }
//
//        Date startDate = DateUtil.strToDate(start, DateUtil.YYYY_MM_DD_HH_MM_SS);
//        Date endDate = DateUtil.strToDate(end, DateUtil.YYYY_MM_DD_HH_MM_SS);
//        if (type == 1)   //血糖特殊处理
//        {
//            PageRequest pageRequest = PageRequest.of(page, pageSize);
//            //根据时间过滤排序
////            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
//            List<String> dateList = findDateListIot(patient, type, startDate, endDate, Integer.parseInt(String.valueOf(pageRequest.getOffset())), pageRequest.getPageSize(), start, end);
//            if (dateList != null && dateList.size() > 0) {
//                for (String dateString : dateList) {
//                    com.alibaba.fastjson.JSONObject obj = getPatientXT_Json(patient, dateString);
//                    if (obj != null) {
//                        re.add(obj);
//                    }
//                }
//            }
//        } else {
//            // 排序
//
//        }
//        return re;
//    }
    public JSONObject findIndexByPatient3(String patient, int type, int page, int pageSize) {
        List<Object> re = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        if (page > 0) {
            page = page - 1;
        }
        if (type == 1)   //血糖特殊处理
        {
            PageRequest pageRequest = PageRequest.of(page, pageSize);
            jsonObject.put("currPage", page + 1);
            com.alibaba.fastjson.JSONArray array = getPatientXT_Json1(patient, Integer.parseInt(String.valueOf(pageRequest.getOffset())), pageRequest.getPageSize());
            jsonObject.put("detailModelList", array);
            //根据时间过滤排序
//            List<String> dateList = patientHealthIndexDao.findDateList(patient, startDate, endDate, pageRequest.getOffset(), pageRequest.getPageSize());
            String sql = "select count(1) as total from (SELECT " +
                    "MIN(id) id" +
                    ", user" +
                    ",value1" +
                    ",value2" +
                    ",value3" +
                    ",value4" +
                    ",value5" +
                    ",value6" +
                    ",value7" +
                    ",device_sn" +
                    ",type" +
                    ",record_date" +
                    ",sort_date" +
                    ",min(czrq) czrq " +
                    " from device.wlyy_patient_health_index " +
                    " WHERE `user` = '" + patient + "' " +
                    " and type = 1" +
                    " and del = '1' " +
                    " GROUP BY user,value1,value2,value3,value4,value5,value6,value7,type,record_date,sort_date " +
                    " order by record_date,id desc ) phi";
            List<Map<String, Object>> rstotal2 = jdbcTemplate.queryForList(sql);
            Long taskCount = 0L;
            if (rstotal2 != null && rstotal2.size() > 0) {
                Object object1 = rstotal2.get(0).get("total");
                if (object1 != null) {
                    taskCount = Long.parseLong(object1.toString());
                }
            }
            jsonObject.put("totalCount", taskCount);
        } else {
            // 排序
        }
        jsonObject.put("pageSize", pageSize);
        return jsonObject;
    }
    /**
     * 查询患者健康指标预警值
     *
     * @param patient
     * @return
     */
    public 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);
//        List<DevicePatientHealthIndex> iterable = findRecentByPatientIterable(patient);
//        if (iterable != null) {
//            Iterator<DevicePatientHealthIndex> iterator = iterable.iterator();
//            while (iterator != null && iterator.hasNext()) {
//                DevicePatientHealthIndex phi = iterator.next();
//                if (phi == null) {
//                    continue;
//                }
//                JSONObject json = new JSONObject();
//                // 设置健康指标类型(1血糖,2血压,3体重,4腰围)
//                json.put("type", phi.getType());
//                if (1 == phi.getType() && StringUtils.isNotBlank(phi.getValue2())) {
//                    int gi_type = Integer.parseInt(phi.getValue2());
//                    switch (gi_type) {
//                        case 1:
//                            // 设置血糖/收缩压/体重/腰围/早餐前空腹
//                            json.put("value1", phi.getValue1());
//                            json.put("time1", phi.getRecordDate());
//                            break;
//                        case 2:
//                            // 设置舒张压/早餐后血糖
//                            json.put("value2", phi.getValue2());
//                            json.put("time2", phi.getRecordDate());
//                            break;
//                        case 3:
//                            // 设置午餐前血糖
//                            json.put("value3", phi.getValue3());
//                            json.put("time3", phi.getRecordDate());
//                            break;
//                        case 4:
//                            // 设置午餐后血糖
//                            json.put("value4", phi.getValue4());
//                            json.put("time4", phi.getRecordDate());
//                            break;
//                        case 5:
//                            // 设置晚餐前血糖
//                            json.put("value5", phi.getValue5());
//                            json.put("time5", phi.getRecordDate());
//                            break;
//                        case 6:
//                            // 设置晚餐后血糖
//                            json.put("value6", phi.getValue6());
//                            json.put("time6", phi.getRecordDate());
//                            break;
//                        case 7:
//                            // 设置睡前血糖
//                            json.put("value7", phi.getValue7());
//                            json.put("time7", phi.getRecordDate());
//                            break;
//                    }
//                } else {
//                    json.put("value1", phi.getValue1());
//                    json.put("value2", phi.getValue2());
//                    // 设置午餐前血糖
//                    json.put("value3", phi.getValue3());
//                    // 设置午餐后血糖
//                    json.put("value4", phi.getValue4());
//                    // 设置晚餐前血糖
//                    json.put("value5", phi.getValue5());
//                    // 设置晚餐后血糖
//                    json.put("value6", phi.getValue6());
//                    // 设置睡前血糖
//                    json.put("value7", phi.getValue7());
//                }
//
//
//                json.put("date", DateUtil.dateToStrShort(phi.getRecordDate()));
//                array.put(json);
//            }
//        }
//        return array;
//    }
    /**
     * 根据患者标志获取健康指标
     *
     * @param patientCode 患者标志
     * @return 健康指标列表
     */
//    public DevicePatientHealthIndex findLastByPatien(String patientCode, int type) {
//        //最新血糖指标
//        if (type == 1) {
//            DevicePatientHealthIndex obj = patientHealthIndexDao.findLastData(patientCode, 1);
//            return obj;
//        } else if (type == 2) {  //其他指标
//            return patientHealthIndexDao.findLastData(patientCode, 2);
//        } else {
//            return patientHealthIndexDao.findLastData(patientCode, type);
//        }
//    }
    /**
     * 获取患者健康指标历史记录
     * 1血糖,2血压,3体重,4腰围
     */
//    public List<Map<String, String>> getHealthIndexHistory(String patientCode, int type, int page, int pagesize) throws Exception {
//        List<Map<String, String>> re = new ArrayList<>();
//
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "recordDate");
//        PageRequest pageRequest = new PageRequest(page, pagesize, sort);
//        List<DevicePatientHealthIndex> list = patientHealthIndexDao.findIndexByPatient(patientCode, type, pageRequest);
//
//        if (list != null && list.size() > 0) {
//            for (DevicePatientHealthIndex item : list) {
//                Map<String, String> map = new HashMap<>();
//                if (type == 1)    //血糖
//                {
//                    String gi = item.getValue1();
//                    String giType = item.getValue2();
//                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
//                    map.put("gi", gi); //  血糖值
//                    map.put("gi_type", giType); //  血糖值类型
//                    String text = gi + " mmol/L";
//                    if ("1".equals(giType)) {
//                        text += "(早餐前)";
//                    } else if ("2".equals(giType)) {
//                        text += "(早餐后)";
//                    } else if ("3".equals(giType)) {
//                        text += "(午餐前)";
//                    } else if ("4".equals(giType)) {
//                        text += "(午餐后)";
//                    } else if ("5".equals(giType)) {
//                        text += "(晚饭前)";
//                    } else if ("6".equals(giType)) {
//                        text += "(晚饭后)";
//                    } else if ("7".equals(giType)) {
//                        text += "(睡前)";
//                    }
//                    map.put("text", text); //  展示
//                    re.add(map);
//                } else if (type == 2) //血压
//                {
//                    String sys = item.getValue1();   //收缩压
//                    String dia = item.getValue2();    //舒张压
//                    String pul = item.getValue3();    //脉搏
//                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
//                    map.put("sys", sys);
//                    map.put("dia", dia);
//                    map.put("pul", pul);
//                    re.add(map);
//                } else if (type == 3) //体重
//                {
//                    String weight = item.getValue1();   //体重
//                    String height = item.getValue2();   //身高
//                    String bmi = item.getValue3();      //BMI
//                    map.put("time", DateUtil.dateToStrShort(item.getRecordDate()));
//                    map.put("weight", weight);
//                    map.put("height", height);
//                    map.put("bmi", bmi);
//                    map.put("text", weight + " kg");
//                    re.add(map);
//                }
//            }
//        }
//
//        return re;
//    }
    /**
     * 保存医生预警值方案
     *
     * @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.getCode());
            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<>();
//
//        // 排序
//        Sort sort = new Sort(Direction.DESC, "recordDate");
//        List<DevicePatientHealthIndex> list = new ArrayList<>();
//
//        if(choseDate.length() == 7){
//            list = patientHealthIndexDao.findByDateMonthAndType(type,patientCode,choseDate,deviceSn);
//        }else{
//            list = patientHealthIndexDao.findByDateAndType(type,patientCode,choseDate,deviceSn);
//        }
//
//        if (list != null && list.size() > 0) {
//            for (DevicePatientHealthIndex item : list) {
//                Map<String, String> map = new HashMap<>();
//                if (type == 1)    //血糖
//                {
//                    String gi = item.getValue1();
//                    String giType = item.getValue2();
//                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
//                    map.put("gi", gi); //  血糖值
//                    map.put("gi_type", giType); //  血糖值类型
//                    String text = gi + " mmol/L";
//                    if ("1".equals(giType)) {
//                        text += "(早餐前)";
//                    } else if ("2".equals(giType)) {
//                        text += "(早餐后)";
//                    } else if ("3".equals(giType)) {
//                        text += "(午餐前)";
//                    } else if ("4".equals(giType)) {
//                        text += "(午餐后)";
//                    } else if ("5".equals(giType)) {
//                        text += "(晚饭前)";
//                    } else if ("6".equals(giType)) {
//                        text += "(晚饭后)";
//                    } else if ("7".equals(giType)) {
//                        text += "(睡前)";
//                    }
//                    map.put("text", text); //  展示
////                    re.add(map);
//                } else if (type == 2) //血压
//                {
//                    String sys = item.getValue1();   //收缩压
//                    String dia = item.getValue2();    //舒张压
//                    String pul = item.getValue3();    //脉搏
//                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
//                    map.put("sys", sys);
//                    map.put("dia", dia);
//                    map.put("pul", pul);
////                    re.add(map);
//                } else if (type == 3) //体重
//                {
//                    String weight = item.getValue1();   //体重
//                    String height = item.getValue2();   //身高
//                    String bmi = item.getValue3();      //BMI
//                    map.put("time", DateUtil.dateToStrShort(item.getRecordDate()));
//                    map.put("weight", weight);
//                    map.put("height", height);
//                    map.put("bmi", bmi);
//                    map.put("text", weight + " kg");
////                    re.add(map);
//                }else if(type == 4){
//                    map.put("time", DateUtil.dateToStrLong(item.getRecordDate()));
//                    map.put("value1", item.getValue1());
//                    map.put("value2", item.getValue2());
//                }
//                map.put("type", item.getType().toString());
//                re.add(map);
//            }
//        }
//
//        return re;
//    }
//
//
//    public DevicePatientHealthIndex getHealthIndexById(Long id) {
//        return patientHealthIndexDao.findOne(id);
//    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

+ 403 - 0
business/base-service/src/main/java/com/yihu/jw/health/service/PatientHealthRecordService.java

@ -0,0 +1,403 @@
//package com.yihu.jw.health.service;
//
//import com.yihu.wlyy.entity.dict.Medicines;
//import com.yihu.wlyy.entity.education.FoodComp;
//import com.yihu.wlyy.entity.education.Sports;
//import com.yihu.wlyy.entity.education.SportsType;
//import com.yihu.wlyy.entity.kit.KitDrugDetail;
//import com.yihu.wlyy.entity.kit.KitDrugUseRecord;
//import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
//import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
//import com.yihu.wlyy.entity.patient.PatientHealthRecordSports;
//import com.yihu.wlyy.repository.dict.MedicinesDao;
//import com.yihu.wlyy.repository.education.FoodCompDao;
//import com.yihu.wlyy.repository.education.SportsDao;
//import com.yihu.wlyy.repository.education.SportsTypeDao;
//import com.yihu.wlyy.repository.kit.KitDrugDetailDao;
//import com.yihu.wlyy.repository.kit.KitDrugUseRecordDao;
//import com.yihu.wlyy.repository.patient.PatientHealthRecordDietDao;
//import com.yihu.wlyy.repository.patient.PatientHealthRecordMedicationDao;
//import com.yihu.wlyy.repository.patient.PatientHealthRecordSportsDao;
//import com.yihu.wlyy.service.BaseService;
//import com.yihu.wlyy.util.DateUtil;
//import org.apache.commons.lang3.StringUtils;
//import org.json.JSONObject;
//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.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//import org.springside.modules.persistence.DynamicSpecifications;
//import org.springside.modules.persistence.SearchFilter;
//import org.springside.modules.persistence.SearchFilter.Operator;
//
//import java.text.SimpleDateFormat;
//import java.util.*;
//
//@Component
//@Transactional(rollbackFor = Exception.class)
//public class PatientHealthRecordService extends BaseService {
//
//	@Autowired
//	private SportsTypeDao sportsTypeDao;
//
//	@Autowired
//	private SportsDao sportsDao;
//
//	@Autowired
//	private MedicinesDao medicinesDao;
//
//	@Autowired
//	private PatientHealthRecordMedicationDao patientHealthRecordMedicationDao;
//
//	@Autowired
//	private PatientHealthRecordDietDao patientHealthRecordDietDao;
//
//	@Autowired
//	private PatientHealthRecordSportsDao patientHealthRecordSportsDao;
//
//	@Autowired
//	private KitDrugUseRecordDao kitDrugUseRecordDao;
//
//	@Autowired
//	private KitDrugDetailDao kitDrugDetailDao;
//	@Autowired
//	private FoodCompDao foodCompDao;
//
//	/**
//	 * 更改保健记录(包括手动记录的修改和所有的删除)
//	 *
//	 * @param id
//	 * @param type   饮食1,运动2,用药3
//	 * @param value1 记录时间
//	 * @param value2 饮食内容CONTETN  时长 用药
//	 * @param value3 上传图片 强度
//	 * @param value4 运动项目
//	 */
//	public void modifyHealthCare(long id, int type, String value1, String value2, String value3, String value4) throws Exception {
//		//value类字段值均为空为删除
//		if (StringUtils.isEmpty(value1) && StringUtils.isEmpty(value2) && StringUtils.isEmpty(value3) && StringUtils.isEmpty(value4)) {
//			switch (type) {
//				case 1:
//					patientHealthRecordDietDao.deleteDiet(id);
//					break;
//				case 2:
//					patientHealthRecordSportsDao.deleteSports(id);
//					break;
//				case 3:
//					patientHealthRecordMedicationDao.deleteMedication(id);
//					break;
//			}
//		} else {
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			Date recordDate = sdf.parse(value1);
//			switch (type) {
//				case 1:
//					patientHealthRecordDietDao.modifyDiet(id, recordDate, value2, value3);
//					break;
//				case 2:
//					SportsType sportsType = sportsTypeDao.findByCode(value3);
//					String typeName = sportsType.getName();
//					Sports sport = sportsDao.findByCode(value4);
//					String sportName = sport.getName();
//					Double sportsTime = Double.parseDouble(value2);
//					patientHealthRecordSportsDao.modifySports(id, recordDate, sportsTime, value3, typeName, value4, sportName);
//					break;
//				case 3:
//					Medicines medicines = medicinesDao.findByCode(value2);
//					String medicinesName = medicines.getName();
//					patientHealthRecordMedicationDao.modifyMedication(id, recordDate, value2, medicinesName);
//					break;
//			}
//		}
//
//	}
//
//	/**
//	 * 添加运动记录
//	 * @param record 运动记录对象
//	 * @return
//	 */
//	public PatientHealthRecordSports addSports(PatientHealthRecordSports record, String sportsType, String sports) {
//		record.setCode(getCode());
//		record.setSportsType(sportsType);
//		record.setSportsTypeName(sportsTypeDao.findByCode(sportsType).getName());
//		record.setSports(sports);
//		record.setSportsName(sportsDao.findByCode(sports).getName());
//		return patientHealthRecordSportsDao.save(record);
//	}
//
//	/**
//	 * 添加用药记录
//	 * @param record 用药记录对象
//	 * @return
//	 */
//	public PatientHealthRecordMedication addMedication(PatientHealthRecordMedication record) {
//		record.setCode(getCode());
//		return patientHealthRecordMedicationDao.save(record);
//	}
//
//	/**
//	 * 添加饮食记录
//	 * @param record 饮食记录对象
//	 * @return
//	 */
//	public PatientHealthRecordDiet addDiet(PatientHealthRecordDiet record) {
//		record.setCode(getCode());
//		return	 patientHealthRecordDietDao.save(record);
//	}
//
//	/**
//	 * 按分类查询患者运动记录
//	 * @param patient 患者标识
//	 * @param
//	 * @param pageSize 分页大小
//	 * @return
//	 */
//	public Page<PatientHealthRecordSports> findSportsByPatient(String patient, Date sortDate, int pageSize) {
//		if (pageSize <= 0) {
//			pageSize = 10;
//		}
//		// 排序
//		Sort sort = new Sort(Direction.DESC, "sortDate");
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(0, pageSize, sort);
//
//		// 设置查询条件
//		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//		// 患者标志
//		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//		if(sortDate != null){
//			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
//		}
//		// 未作废
//		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//		Specification<PatientHealthRecordSports> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientHealthRecordSports.class);
//		return patientHealthRecordSportsDao.findAll(spec, pageRequest);
//	}
//
//	/**
//	 * 查询运动记录
//	 *
//	 * @param patient
//	 * @param start
//	 * @param end
//	 * @param page
//	 * @param pagesize
//	 * @return
//	 */
//	public Page<PatientHealthRecordSports> findSportsByPatientPage(String patient, String start, String end, int page, int pagesize){
//		if(page > 0) {
//			page = page -1;
//		}
//		PageRequest pageRequest = new PageRequest(page,pagesize);
//
//		return patientHealthRecordSportsDao.findSportsByPatient(patient, DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS)
//				,DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS),pageRequest);
//	}
//
//	/**
//	 * 查询用药记录
//	 *
//	 * @param patient
//	 * @param start
//	 * @param end
//	 * @param page
//	 * @param pagesize
//	 * @return
//	 */
//	public Page<PatientHealthRecordMedication> findMedicalByPatientPage(String patient, String start, String end, int page, int pagesize){
//		if(page > 0)
//		{
//			page = page -1;
//		}
//		PageRequest pageRequest = new PageRequest(page,pagesize);
//		return patientHealthRecordMedicationDao.findMedicalByPatient(patient, DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS)
//				,DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS),pageRequest);
//	}
//
//	/**
//	 * 查询饮食记录
//	 *
//	 * @param patient
//	 * @param start
//	 * @param end
//	 * @param page
//	 * @param pagesize
//	 * @return
//	 */
//	public Page<PatientHealthRecordDiet> findDietByPatientPage(String patient, String start, String end, int page, int pagesize){
//		if(page > 0) {
//			page = page -1;
//		}
//		PageRequest pageRequest = new PageRequest(page,pagesize);
//		return patientHealthRecordDietDao.findDietByPatient(patient, DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS)
//				,DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS),pageRequest);
//	}
//
//	/**
//	 * 按分类查询患者用药记录
//	 * @param patient 患者标识
//	 * @param pageSize 分页大小
//	 * @return
//	 */
//	public Page<PatientHealthRecordMedication> findMedicationByPatient(String patient, Date sortDate, Integer page, int pageSize) {
//		if(page==null){
//			page = 0;
//		}else if(page > 0)
//		{
//			page = page -1;
//		}
//
//		if (pageSize <= 0) {
//			pageSize = 10;
//		}
//		// 排序
//		Sort sort = new Sort(Direction.DESC, "sortDate");
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(page, pageSize, sort);
//
//		// 设置查询条件
//		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//		// 患者标志
//		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//		if(sortDate != null){
//			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
//		}
//		// 未作废
//		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//		Specification<PatientHealthRecordMedication> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientHealthRecordMedication.class);
//		return patientHealthRecordMedicationDao.findAll(spec, pageRequest);
//	}
//
//
//
//	/**
//	 * 按分类查询患者饮食记录
//	 * @param patient 患者标识
//	 * @param
//	 * @param pageSize 分页大小
//	 * @return
//	 */
//	public Page<PatientHealthRecordDiet> findDietByPatient(String patient, Date sortDate, int pageSize) {
//		if (pageSize <= 0) {
//			pageSize = 10;
//		}
//		// 排序
//		Sort sort = new Sort(Direction.DESC, "sortDate");
//		// 分页信息
//		PageRequest pageRequest = new PageRequest(0, pageSize, sort);
//		// 设置查询条件
//		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
//		// 患者标志
//		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
//		if(sortDate != null){
//			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
//		}
//		// 未作废
//		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
//		Specification<PatientHealthRecordDiet> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientHealthRecordDiet.class);
//		return patientHealthRecordDietDao.findAll(spec, pageRequest);
//	}
//
//	/**
//	 * 查询患者最近填写的运动、用药、饮食内容
//	 * @param patient
//	 * @return
//	 */
//	public JSONObject findRecentByPatient(String patient) {
//		JSONObject jsonObject = new JSONObject();
//		// 查询最近的运动
//		Page<PatientHealthRecordSports> sports = patientHealthRecordSportsDao.findRecentByPatient(patient, new PageRequest(0, 1));
//		// 查询最近的用药
//		Page<PatientHealthRecordMedication> medication = patientHealthRecordMedicationDao.findRecentByPatient(patient, new PageRequest(0, 1));
//		// 查询最近的饮食
//		Page<PatientHealthRecordDiet> diet = patientHealthRecordDietDao.findRecentByPatient(patient, new PageRequest(0, 1));
//		// 查询最近的药盒使用记录
//		Page<KitDrugUseRecord> kitDrugUseRecords = kitDrugUseRecordDao.findRecentByPatient(patient, new PageRequest(0, 1));
//		if (sports != null && sports.getSize() > 0) {
//			JSONObject sportObject = new JSONObject();
//			for (PatientHealthRecordSports temp : sports) {
//				sportObject.put("sports", temp.getSportsName());
//				sportObject.put("sports_time", temp.getSportsTime());
//				sportObject.put("sports_type", temp.getSportsType());
//				sportObject.put("sports_typeName", temp.getSportsTypeName());
//				sportObject.put("czrq", DateUtil.dateToStr(temp.getCzrq(), DateUtil.YYYY_MM_DD));
//				sportObject.put("recordDate", DateUtil.dateToStr(temp.getRecordDate(), DateUtil.YYYY_MM_DD));
//				sportObject.put("source","1".equals(temp.getSource())?1:0);
//			}
//			jsonObject.put("sprot",sportObject);
//		}
//		if (medication != null) {
//			JSONObject medicationObject = new JSONObject();
//			for (PatientHealthRecordMedication temp : medication) {
//				medicationObject.put("medication", temp.getMedicinesName());
//				medicationObject.put("recordDate",DateUtil.dateToStr(temp.getRecordDate(), DateUtil.YYYY_MM_DD));
//				medicationObject.put("source","1".equals(temp.getSource())?1:0);
//
//			}
//			jsonObject.put("medication",medicationObject);
//
//		}
//		if (diet != null) {
//			JSONObject dietObject = new JSONObject();
//			for (PatientHealthRecordDiet temp : diet) {
//				dietObject.put("diet", temp.getContent());
//				dietObject.put("recordDate",DateUtil.dateToStr(temp.getRecordDate(), DateUtil.YYYY_MM_DD));
//				dietObject.put("images",temp.getImages());
//				dietObject.put("source","1".equals(temp.getSource())?1:0);
//
//			}
//			jsonObject.put("diet",dietObject);
//
//		}
//		if(kitDrugUseRecords!=null){
//			JSONObject dietObject = new JSONObject();
//			for (KitDrugUseRecord temp : kitDrugUseRecords) {
//				dietObject.put("recordDate",DateUtil.dateToStr(temp.getUseTime(), DateUtil.YYYY_MM_DD));
//				dietObject.put("deviceSn",temp.getDeviceSn());
//				List<KitDrugDetail> kitDrugDetailList = kitDrugDetailDao.findByRelationCodeAndType(temp.getCode(),1);
//				if(kitDrugDetailList.size()>0){
//					dietObject.put("drugDetail",kitDrugDetailList.get(0).getDrugName());
//				}else{
//					dietObject.put("drugDetail","");
//				}
//			}
//			jsonObject.put("kitDrugUseRecords",dietObject);
//		}
//		return jsonObject;
//	}
//
//	//根据居民饮食记录ID查看详情
//    public JSONObject findById(Long id) {
//		JSONObject res = new JSONObject();
//		List<FoodComp> patientFoodCompList = new ArrayList<>();
//		//居民记录详情
//		PatientHealthRecordDiet patientHealthRecordDiet = patientHealthRecordDietDao.findOne(id);
//		if(patientHealthRecordDiet != null){
//			com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
//			json.put("dietDetail", patientHealthRecordDiet);
//			//查看居民吃的相关食物热量
//			List<FoodComp> foodCompList = foodCompDao.findAllFoodByPidNot(0L);
//			String content = patientHealthRecordDiet.getContent();
//			for(FoodComp foodComp : foodCompList){
//				//判断居民所吃的食物是否在热量字典表
//				if(content.contains(foodComp.getName())){
//					patientFoodCompList.add(foodComp);
//				}
//			}
//			if(patientFoodCompList.size() > 0){
//				json.put("foodCompList", patientFoodCompList);
//			}
//			res.put("status", 200);
//			res.put("data", json);
//		}else {
//			res.put("status", -1);
//			res.put("msg", "居民饮食记录详情不存在");
//		}
//		return res;
//    }
//}

+ 1478 - 0
business/base-service/src/main/java/com/yihu/jw/iot/IotDeviceService.java

@ -0,0 +1,1478 @@
package com.yihu.jw.iot;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.device.dao.DevicePatientHealthIndexDao;
import com.yihu.jw.device.dao.PatientDeviceDao;
import com.yihu.jw.entity.care.device.DeviceHealthyInfoMapping;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.patient.PatientDevice;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
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.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
 * 物联网设备对接
 *
 * @author yeshijie on 2018/1/3.
 */
@Service
public class IotDeviceService {
    private Logger logger = LoggerFactory.getLogger(IotDeviceService.class);
//    @Value("${iot.url}")
    private String baseUrl;
    //   @Value("${iot.appid}")
    private String appid;
    //   @Value("${iot.appsecret}")
    private String appSecret;
    //  @Value("${spring.profiles}")
    private String profiles;
    public static Map<String,String> tokenMap = new HashMap<>();
    private String grantType = "client_credentials";
    private String clientId = "Va5yQRHlA4Fq4eR3LT0vuXV4";
    private String clientSecret = "0rDSjzQ20XUj5itV7WRtznPQSzr5pVw2";
    private String dataSource = "iHealth";
    private String accessToken = "iHealth";
    private String bloodSugarUnit = "mmol/L";
    private String bloodPressureUnit = "mmHg";
    private String pulseUnit = "bpm";
    private String heightUnit = "cm";
    private String weightUnit = "kg";
    private String bmiUnit = "kg/m^2";
    private String waistUnit = "cm";
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PatientDeviceDao patientDeviceDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DevicePatientHealthIndexDao devicePatientHealthIndexDao;
//    @Autowired
//    private WlyyIotUploadDataLogDao wlyyIotUploadDataLogDao;
//    @Autowired
//    private MyJdbcTemplate myJdbcTemplate;
//    @Autowired
//    private SignFamilyDao signFamilyDao;
//    @Autowired
//    private SystemDictDao systemDictDao;
//    @Autowired
//    private DeviceHealthyInfoMappingDao deviceHealthyInfoMappingDao;
//    @Autowired
//    private SkJsonFormDao skJsonFormDao;
    /**
     * 判断是否数据上传到物联网
     * @return
     */
//    public Boolean isUploadIot(){
//        String value = systemDictDao.findByDictNameAndCode("SYSTEM_PARAMS","DEVICE_UPLOAD_IOT");
//        return "1".equals(value)?true:false;
//    }
//
//    public Boolean isIotSearch(){
//        String value = systemDictDao.findByDictNameAndCode("SYSTEM_PARAMS","isIotSearch");
//        return "1".equals(value)?true:false;
//    }
//
    public String getOauthAccessToken(){
        String url = baseUrl+"/oauth/2.0/token";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("grant_type",grantType));
        params.add(new BasicNameValuePair("client_id",clientId));
        params.add(new BasicNameValuePair("client_secret",clientSecret));
        String response = httpClientUtil.post(url, params, "UTF-8");
        return null;
    }
    /**
     * 设备注册及绑定
     * @return
     */
    public String registedevice(JSONObject json){
        json.put("access_token",accessToken);
        json.put("data_source",dataSource);
        String url = baseUrl+"/dataInput/userBind";
        String response = sendPost(url, json.toString());
        return response;
    }
    /**
     * 设备绑定
     * @param patientDevice
     * @param address
     * @param name
     * @param diseaseCondition 病情:0绿标,1黄标,2红标
     * @return
     */
    public String saveDevice(PatientDevice patientDevice, String address, String name, Integer diseaseCondition, String hospitalName){
        JSONObject json = new JSONObject();
        json.put("categoryCode",patientDevice.getCategoryCode());
        json.put("address",address);
        json.put("hospitalName",hospitalName);
        json.put("patient",patientDevice.getUser());
        json.put("patientName",name);
        json.put("diseaseCondition",diseaseCondition);
        json.put("idcard",patientDevice.getUserIdcard());
        json.put("deviceId",patientDevice.getDeviceId());
        json.put("deviceName",patientDevice.getDeviceName());
        json.put("deviceSn",patientDevice.getDeviceSn());
        json.put("userType",patientDevice.getUserType());
        json.put("sim",patientDevice.getSim());
        json.put("agent",patientDevice.getAgent());
        json.put("doctor",patientDevice.getDoctor());
        return saveDevice(json.toString());
    }
    private String saveDevice(String json){
        String url = baseUrl+"/open/monitorPlatform/addPatientDevice";
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("jsonData",json));
        String response = httpClientUtil.post(url, params, "UTF-8");
        return response;
    }
    /**
     * 数据上传
     * @param json
     * @return
     */
    public String upload(JSONObject json){
        json.put("data_source",dataSource);
        String url = baseUrl+"/open/gc/uploadData";
        String response = sendPost(url, json.toString());
        return response;
    }
    /**
     * 保存i健康查询体征记录的记录
     */
    @Async
//    public void iHealthDataSearch(){
//        try{
//            if(isIotSearch()){
//                JSONObject json = new JSONObject();
//                String url = baseUrl+"/open/gc/iHealthDataSearch";
//                String response = sendPost(url, json.toString());
//            }
//        }catch (Exception e){
//            logger.error("调物联网接口报错:"+e.getMessage());
//            e.printStackTrace();
//        }
//    }
    /**
     * 访问i健康接口,自带登录信息
     * @param url
     * @return
     */
    private String sendGet(String url,String jsonData){
        String response = null;
        try{
            Map<String, Object> params = new HashMap();
            params.put("accesstoken",getAccessToken());
            params.put("jsonData",jsonData);
            params.put("appId",appid);
            List<BasicNameValuePair> jsonParams = new ArrayList<>();
            //配置参数
            if(params!=null) {
                for (String key : params.keySet()) {
                    if (!StringUtils.isEmpty(String.valueOf(params.get(key))) && !"null".equals( String.valueOf(params.get(key)))) {
                        jsonParams.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                    }
                }
            }
            response = httpClientUtil.get(url+"?"+ URLEncodedUtils.format(jsonParams, Consts.UTF_8),"utf-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }
    private String sendPost(String url,String jsonData){
        String response = null;
        try{
            Map<String, Object> params = new HashMap();
            params.put("accesstoken",getAccessToken());
            List<NameValuePair> jsonParams = new ArrayList<>();
            if(StringUtils.isNotEmpty(jsonData)){
                jsonParams.add(new BasicNameValuePair("jsonData", jsonData));
            }
            jsonParams.add(new BasicNameValuePair("appId", appid));
            response = httpClientUtil.headerPost(url, jsonParams,"utf-8",params);
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     *  查询重复数据
     * @return
     */
    public String findRepeat(String user,String deviceSn,String value1,String value2,String type,String time){
        JSONArray jsonArray = new JSONArray();
        field("and","usercode","=",user,jsonArray);
        field("and","sn","=",deviceSn,jsonArray);
        field("and","del","=","1",jsonArray);
        if("1".equals(type)){
            //血糖
            field("and","value1","=",value1,jsonArray);
        }else {
            //血压
            field("and","value1","=",value1,jsonArray);
            if(StringUtils.isNotBlank(value2)){
                field("and","value2","=",value2,jsonArray);
            }
        }
        field("and","measure_time","=",time,jsonArray);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        String url = baseUrl+"/dataSearch/getById";
        String response = sendPost(url, jsonObject.toString());
        return response;
    }
    /**
     * 按条件统计数量
     * @param start
     * @param end
     * @param status
     * @param patientCode
     * @return
     */
    public int getCountByTimeAndStatusAndPatient(String start,String end,Integer status,String patientCode){
        int re = 0;
        JSONArray jsonArray = new JSONArray();
        field("and","usercode","=",patientCode,jsonArray);
        field("and","status","=",String.valueOf(status),jsonArray);
        field("and","del","=","1",jsonArray);
        field("and","measure_time",">=",start,jsonArray);
        field("and","measure_time","<=",end,jsonArray);
        field("and","type",">=","1",jsonArray);
        field("and","type","<=","2",jsonArray);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("filter",jsonArray);
        jsonObject.put("page","1");
        jsonObject.put("size","50");
        String url = baseUrl+"/dataSearch/getById";
        String response = sendPost(url, jsonObject.toString());
        JSONObject json = JSONObject.parseObject(response);
        JSONArray ja = json.getJSONArray("obj");
        if(ja!=null){
            re = ja.size();
        }
        return re;
    }
    /**
     * 按居民code和类型查找
     * @param patient
     * @param type
     * @return
     */
//    public List<DevicePatientHealthIndex> findByPatientAndType(String patient, Integer type, Integer size){
//        List<DevicePatientHealthIndex> list = new ArrayList<>();
//        JSONArray jsonArray = new JSONArray();
//        field("and","usercode","=",patient,jsonArray);
//        field("and","del","=","1",jsonArray);
//        if(type!=null){
//            field("and","type","=",String.valueOf(type),jsonArray);
//        }
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("filter",jsonArray);
//        jsonObject.put("page","1");
//        jsonObject.put("size",size);
//
//        JSONArray sort = new JSONArray();
//        sort(sort,"measure_time","desc");
//        jsonObject.put("sort",sort);
//        String url = baseUrl+"/dataSearch/getById";
//        String response = sendPost(url, jsonObject.toString());
//
//        try {
//            JSONObject json = JSONObject.parseObject(response);
//            JSONArray obj = json.getJSONArray("obj");
//            if(obj!=null&&obj.size()>0){
//                for (int i=0;i<obj.size();i++){
//                    DevicePatientHealthIndex index = transforHealthIndex(obj.getJSONObject(i),null);
//                    list.add(index);
//                }
//            }
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        return list;
//    }
    /**
     * 按时间段查找
     * @param patient 居民code
     * @param type    健康指标类型(1血糖,2血压,3体重,4腰围)
     * @param gi_type 血糖就餐时间段(早餐前,早餐后等)
     * @param begin   开始时间
     * @param end     结束时间
     * @return
     */
//    public List<DevicePatientHealthIndex> findByPatientAndTime(String patient,Integer type,Integer page,Integer size,Integer gi_type, String begin, String end){
//        List<DevicePatientHealthIndex> list = new ArrayList<>();
//        JSONArray jsonArray = new JSONArray();
//        field("and","usercode","=",patient,jsonArray);
//        field("and","del","=","1",jsonArray);
//        if(type!=null){
//            field("and","type","=",String.valueOf(type),jsonArray);
//        }
//        if(gi_type!=null){
//            field("and","value2","=",String.valueOf(gi_type),jsonArray);
//        }
//        field("and","measure_time",">=",begin,jsonArray);
//        field("and","measure_time","<=",end,jsonArray);
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("filter",jsonArray);
//        jsonObject.put("page",page);
//        jsonObject.put("size",size);
//
//        JSONArray sort = new JSONArray();
//        sort(sort,"measure_time","desc");
//        jsonObject.put("sort",sort);
//        String url = baseUrl+"/dataSearch/getById";
//        String response = sendPost(url, jsonObject.toString());
//
//        try {
//            JSONObject json = JSONObject.parseObject(response);
//            JSONArray obj = json.getJSONArray("obj");
//            if(obj!=null&&obj.size()>0){
//                for (int i=0;i<obj.size();i++){
//                    DevicePatientHealthIndex index = transforHealthIndex(obj.getJSONObject(i),null);
//                    list.add(index);
//                }
//            }
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        return list;
//    }
    /**
     * 添加条件
     * 参数格式:[{"andOr":"and|or","condition":">|=|<|>=|<=|?","field":"<field>","value":"<value>"},<{...}>]
     * @param andOr
     * @param field
     * @param condition
     * @param value
     * @param jsonArray
     */
    private void field(String andOr,String field,String condition,String value,JSONArray jsonArray){
        JSONObject json = new JSONObject();
        json.put("andOr",andOr);
        json.put("field",field);
        json.put("condition",condition);
        json.put("value",value);
        jsonArray.add(json);
    }
    /**
     * 排序[{"key1":{"order":"asc|desc"}},{"key2":{"order":"asc|desc"}}]
     * @param jsonArray
     * @param key
     * @param order
     */
    private void sort(JSONArray jsonArray,String key,String order){
        JSONObject json = new JSONObject();
        json.put("order",order);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key,json);
        jsonArray.add(jsonObject);
    }
    /**
     * 查询单条
     * @param rid
     * @return
     */
    public String getById(String rid){
        JSONObject json = new JSONObject();
        JSONArray filters = new JSONArray();
        field("and","rid","=",rid,filters);
        json.put("filter",filters);
        String url = baseUrl+"/dataSearch/getById";
        String response = sendPost(url, json.toString());
        return response;
    }
    /**
     * 查询
     * filter
     * - 参数格式:[{"andOr":"and|or","condition":">|=|<|>=|<=|?","field":"<field>","value":"<value>"},<{...}>]
     * - 参数说明:andOr跟数据库的中的AND和OR相似;condition指条件匹配程度,?相当于数据库中的like;filed指检索的字段;value为检索的值
     * page - 参数说明:页码
     * size - 参数说明:分页大小 默认1
     * sort - 参数格式:排序,key要排序的字段,order固定,取值asc或desc,不需要排序,传""
     *  排序[{"key1":{"order":"asc|desc"}},{"key2":{"order":"asc|desc"}}]
     * @param json
     * @return
     */
    public String searchList(JSONObject json){
        String url = baseUrl+"/dataSearch/searchList";
        String response = sendPost(url, json.toString());
        return response;
    }
    /**
     *
     * @param json
     * @return
     */
//    public String listPage(JSONObject json){
//        String url = baseUrl+"/dataSearch/listPage";
//        String response = httpClientUtil.iotPostBody(url, json.toString());
//        return response;
//    }
    /**
     * 获取最近5条数据
     * @param json
     * @param sort
     * @return
     */
    public String recent5(JSONObject json,JSONObject sort){
        json.put("access_token",accessToken);
        String url = baseUrl+"/dataSearch/recent5";
        String response = sendPost(url, json.toString());
        return response;
    }
    /**
     * 获取居民一周内体征数据异常次数
     * @param json
     * @param sort
     * @return
     */
    public String recent1(JSONObject json,JSONObject sort){
        json.put("access_token",accessToken);
        String url = baseUrl+"/dataSearch/recent1";
        String response = sendPost(url, json.toString());
        return response;
    }
    /**
     * 初始化设备绑定数据
     * @return
     */
//    public void initPatientDevice(){
//        List<PatientDevice> list = patientDeviceDao.findAll();
//        list.forEach(patientDevice -> {
//            Patient patient = patientDao.findByCode(patientDevice.getUser());
//            if(patient!=null){
//                String address = patient.getAddress();
//                String hospital = null;
//                if(StringUtils.isBlank(address)){
//                    //居民地址为空,默认取居民的社区,如果社区为空默认填写签约的社区医院
//                    SignFamily signFamily = signFamilyDao.findByPatient(patientDevice.getUser());
//                    if(signFamily!=null){
//                        hospital = StringUtils.isBlank(signFamily.getSickVillageName())?signFamily.getHospitalName():signFamily.getSickVillageName();
//                    }
//                }
//                String response = saveDevice(patientDevice,address,patient.getName(),patient.getDiseaseCondition(),hospital);
//                if(StringUtils.isNotBlank(response)){
//                    JSONObject re = JSONObject.parseObject(response);
//                    if(re.getInteger("status")!=200){
//                        logger.error("id:"+patientDevice.getId()+" "+re.getString("errorMsg"));
//                    }
//                }
//            }
//        });
//    }
    /**
     * 导入正式环境的坐标信息
     * @return
     */
//    public void exportNormalPatientDevice(){
//        String sql = "SELECT * from wlyy_device_location_tmp";
//        List<JSONObject> list = myJdbcTemplate.queryJson(sql);
//        list.forEach(device -> {
//            JSONObject json = new JSONObject();
//            json.put("categoryCode",device.getString("category_code"));
//            json.put("hospitalName",device.getString("hospital_name"));
//            json.put("address",device.getString("address"));
//            json.put("patient",device.getString("user"));
//            json.put("patientName",device.getString("name"));
//            json.put("diseaseCondition",device.getString("disease_condition"));
//            json.put("idcard",device.getString("user_idcard"));
//            json.put("deviceId",device.getString("device_id"));
//            json.put("deviceName",device.getString("device_name"));
//            json.put("deviceSn",device.getString("device_sn"));
//            json.put("userType",device.getString(""));
//            json.put("sim",device.getString("sim"));
//            json.put("agent",device.getString("agent"));
//            json.put("doctor",device.getString("doctor"));
//            saveDevice(json.toString());
//        });
//    }
    /**
     * 测试设备绑定
     * @return
     */
//    public String testSaveDevice(){
//        List<PatientDevice> list = patientDeviceDao.findAll();
//        PatientDevice patientDevice = list.get(0);
//        Patient patient = patientDao.findByCode(patientDevice.getUser());
//        SignFamily signFamily = signFamilyDao.findByPatient(patientDevice.getUser());
//        String hospital = null;
//        if(signFamily!=null){
//            hospital = StringUtils.isBlank(signFamily.getSickVillageName())?signFamily.getHospitalName():signFamily.getSickVillageName();
//        }
//        String response = saveDevice(patientDevice,patient.getAddress(),patient.getName(),patient.getDiseaseCondition(),hospital);
//        return response;
//    }
    /**
     * 初始化上传
     * @param jsonObject
     * @return
     */
    public String initUpload(JSONObject jsonObject){
        JSONObject json = new JSONObject();
        Integer type = jsonObject.getInteger("type");
        json.put("data_source","iHealth");
        json.put("sn",StringUtils.trimToEmpty(jsonObject.getString("device_sn")));
        json.put("ext_code",StringUtils.trimToEmpty(jsonObject.getString("user_type")));
        if(StringUtils.isNotEmpty(jsonObject.getString("device_name"))){
            json.put("device_name",StringUtils.trimToEmpty(jsonObject.getString("device_name")));
            json.put("device_model",StringUtils.trimToEmpty(jsonObject.getString("device_name")));
        }else{
            //历史数据未绑定居民
            if(StringUtils.isNotEmpty(jsonObject.getString("device_sn"))){
                String sql = "SELECT i.device_code,i.device_model,i.device_name from device.wlyy_devices i WHERE device_code = '"+jsonObject.getString("device_sn")+"'";
                List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
                if(list.size()>0){
                    json.put("device_name",StringUtils.trimToEmpty(list.get(0).get("device_name").toString()));
                    json.put("device_model",StringUtils.trimToEmpty(list.get(0).get("device_model").toString()));
                }
            }
        }
        json.put("idcard",StringUtils.trimToEmpty(jsonObject.getString("idcard")));
        json.put("username",StringUtils.trimToEmpty(jsonObject.getString("name")));
        json.put("usercode",StringUtils.trimToEmpty(jsonObject.getString("user")));
        json.put("del",StringUtils.trimToEmpty(jsonObject.getString("del")));
        json.put("status",getStatus(jsonObject.getString("status")));
        JSONArray jsonArray = new JSONArray();
        String measure_time = subStringTime(jsonObject.getString("record_date"));
        switch (type){
            case 1:
                //血糖
                JSONObject blood_sugar = new JSONObject();
                blood_sugar.put("measure_time",measure_time);
                blood_sugar.put("type","BloodSugar");
                blood_sugar.put("sign_name","blood_sugar");
                blood_sugar.put("sign_value",jsonObject.getString("value1"));
                blood_sugar.put("sign_unit",bloodSugarUnit);
                jsonArray.add(blood_sugar);
                JSONObject blood_sugar_result = new JSONObject();
                blood_sugar_result.put("measure_time",measure_time);
                blood_sugar_result.put("type","BloodSugar");
                blood_sugar_result.put("sign_name","blood_sugar_result");
                blood_sugar_result.put("sign_value",jsonObject.getString("value2"));
                jsonArray.add(blood_sugar_result);
                break;
            case 2:
                //血压
                JSONObject systolic = new JSONObject();
                systolic.put("measure_time",measure_time);
                systolic.put("type","BloodPressure");
                systolic.put("sign_name","systolic");
                systolic.put("sign_value",jsonObject.getString("value1"));
                systolic.put("sign_unit",bloodPressureUnit);
                jsonArray.add(systolic);
                JSONObject diastolic = new JSONObject();
                diastolic.put("measure_time",measure_time);
                diastolic.put("type","BloodPressure");
                diastolic.put("sign_name","diastolic");
                diastolic.put("sign_value",jsonObject.getString("value2"));
                diastolic.put("sign_unit",bloodPressureUnit);
                jsonArray.add(diastolic);
                if(StringUtils.isNotBlank(jsonObject.getString("value3"))){
                    JSONObject pulse = new JSONObject();
                    pulse.put("measure_time",measure_time);
                    pulse.put("type","BloodPressure");
                    pulse.put("sign_name","pulse");
                    pulse.put("sign_value",jsonObject.getString("value3"));
                    pulse.put("sign_unit",pulseUnit);
                    jsonArray.add(pulse);
                }
                break;
            case 3:
                //体重/身高/BMI
                JSONObject height = new JSONObject();
                height.put("measure_time",measure_time);
                height.put("type","Height");
                height.put("sign_name","height");
                height.put("sign_value",jsonObject.getString("value1"));
                height.put("sign_unit",heightUnit);
                jsonArray.add(height);
                JSONObject weight = new JSONObject();
                weight.put("measure_time",measure_time);
                weight.put("type","Height");
                weight.put("sign_name","weight");
                weight.put("sign_value",jsonObject.getString("value2"));
                weight.put("sign_unit",weightUnit);
                jsonArray.add(weight);
                if(StringUtils.isNotBlank(jsonObject.getString("value3"))){
                    JSONObject bmi = new JSONObject();
                    bmi.put("measure_time",measure_time);
                    bmi.put("type","Height");
                    bmi.put("sign_name","bmi");
                    bmi.put("sign_value",jsonObject.getString("value3"));
                    bmi.put("sign_unit",bmiUnit);
                    jsonArray.add(bmi);
                }
                break;
            case 4:
                //腰围
                JSONObject waist = new JSONObject();
                waist.put("measure_time",measure_time);
                waist.put("type","Waist");
                waist.put("sign_name","waist");
                waist.put("sign_value",jsonObject.getString("value1"));
                waist.put("sign_unit",waistUnit);
                jsonArray.add(waist);
                break;
            default:
                break;
        }
        json.put("measure_data",jsonArray);
        //上传
        return json.toJSONString();
    }
    /************************************i健康业务相关 start************************************************************/
    /**
     * 更新状态
     * @param id
     */
//    public void updateStatus(Long id,String status){
//        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(id,id);
//        if(mapping == null){
//            logger.error("未找到映射关系,id:"+id);
//        }else {
//            JSONObject json = new JSONObject();
//            json.put("rid",mapping.getRid());
//            json.put("status",status);
//            String url = baseUrl+"/open/gc/updateData";
//            String response = sendPost(url, json.toString());
//            JSONObject res = JSONObject.parseObject(response);
//        }
//    }
    /**
     * 查询单条
     * @param id
     * @return
     */
//    public DevicePatientHealthIndex getById(Long id){
//        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(id,id);
//        if(mapping == null){
//            logger.error("未找到映射关系,id:"+id);
//            return null;
//        }else {
//            return transforOne(getById(mapping.getRid()),id);
//        }
//    }
    /**
     * 更新
     * @param obj
     * @return
     */
//    public DevicePatientHealthIndex update(DevicePatientHealthIndex obj){
//
//        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(obj.getId(),obj.getId());
//        if(mapping == null){
//            logger.error("未找到映射关系,id:"+obj.getId());
//        }else {
//            JSONObject json = new JSONObject();
//            json.put("rid",mapping.getRid());
//            json.put("del",obj.getDel());
//            transforIot(obj,json);
//            String url = baseUrl+"/open/gc/updateData";
//            String response = sendPost(url, json.toString());
//            JSONObject res = JSONObject.parseObject(response);
//        }
//
//        return obj;
//    }
    /**
     * 删除
     * @param id
     */
//    public void delete(Long id){
//        DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByIndexId(id,id);
//        if(mapping == null){
//            logger.error("未找到映射关系,id:"+id);
//        }else {
//            JSONObject json = new JSONObject();
//            json.put("rid",mapping.getRid());
//            json.put("del","0");
//            String url = baseUrl+"/open/gc/deleteData";
//            String response = sendPost(url, json.toString());
//
//            JSONObject res = JSONObject.parseObject(response);
//            if("true".equals(res.getString("obj"))){
//                logger.info("删除成功!");
//            }else {
//                logger.error("删除失败,id="+id+",rid="+mapping.getRid()+",msg="+res.getString("errorMsg"));
//            }
//
//        }
//    }
    /**
     * 测试上传
     * @param id
     */
//    public void testUpload(Long id){
//        DevicePatientHealthIndex index = devicePatientHealthIndexDao.findOne(id);
//        save(index);
//    }
    /**
     * 体征上传
     * @param obj
     * @return
     */
//    public DevicePatientHealthIndex save(DevicePatientHealthIndex obj){
//        JSONObject json = new JSONObject();
//        if(StringUtils.isNotBlank(obj.getDeviceSn())){
//            json.put("sn",obj.getDeviceSn());
//            List<PatientDevice> devices = patientDeviceDao.findByPatientAndDeviceSn(obj.getUser(),obj.getDeviceSn());
//            if(devices!=null&&devices.size()>0){
//                PatientDevice device = devices.get(0);
//                json.put("ext_code",device.getUserType());
//                json.put("device_name",transfor(device.getDeviceName(),1,obj.getType()));
//                json.put("device_model",transfor(device.getDeviceName(),2,obj.getType()));
//            }
//        }
//        Patient patient = patientDao.findByCode(obj.getUser());
//        json.put("idcard",patient.getIdcard());
//        json.put("idcard_type","1");
//        json.put("username",patient.getName());
//        json.put("usercode",patient.getCode());
//        json.put("del",obj.getDel());
//        json.put("status",obj.getStatus());
//        transforIot(obj,json);
//        //上传
//        String response = upload(json);
//        JSONObject re = JSONObject.parseObject(response);
//        String errorMsg = re.getString("errorMsg");//错误信息(请求失败才有错误消息)
//        if(StringUtils.isBlank(errorMsg)){
//            String rid = re.getJSONObject("obj").getJSONArray("rid").getString(0);
//            DeviceHealthyInfoMapping mapping = new DeviceHealthyInfoMapping();
//            mapping.setCreateTime(new Date());
//            mapping.setRid(rid);
//            deviceHealthyInfoMappingDao.save(mapping);
//            obj.setId(mapping.getId());
//        }else {
//            logger.error(errorMsg);
//            return null;
//        }
//        return obj;
//    }
    /************************************i健康业务相关 end  ************************************************************/
    /*****************************************工具方法 start************************************************************/
    /**
     * 单条转换
     * @param res
     * @return
     */
//    public DevicePatientHealthIndex transforOne(String res,Long id){
//        if(StringUtils.isBlank(res)){
//            return null;
//        }
//        JSONObject jsonObject = JSONObject.parseObject(res);
//        if(jsonObject.getInteger("status")!=200||jsonObject.getJSONArray("obj").size()==0){
//            logger.error(jsonObject.getString("errorMsg"));
//            return null;
//        }
//        JSONObject obj = jsonObject.getJSONArray("obj").getJSONObject(0);
//        return transforHealthIndex(obj,id);
//    }
    /**
     * 转化成数据库对象
     * @param obj
     * @param id
     * @return
     */
//    private DevicePatientHealthIndex transforHealthIndex(JSONObject obj,Long id){
//        DevicePatientHealthIndex index = new DevicePatientHealthIndex();
//
//        index.setDeviceSn(obj.getString("sn"));
//        index.setUser(obj.getString("usercode"));
//        index.setIdcard(obj.getString("idcard"));
//
//        //{"errorCode":null,"errorMsg":null,"successMsg":"search success","status":200,"pageSize":10,"currPage":0,"totalPage":0,"totalCount":0,"detailModelList":null,
//        // "obj":[{"access_token":"test","data_source":"iHealth","sn":"867967022337804","ext_code":"","device_name":"","device_model":"",
//        // "data":[{"rid":"lwKBG349zj/XBIJOP8CpyoFxFKl0xyxLLzxpN/l9+1U=","del":1,"measure_time":"2016-08-26 12:32:04","systolic":"115.00","systolic_unit":"mmHg","diastolic":"105.00","pulse":"105.00","pulse_unit":"bpm"}],
//        // "idCard":"350122198601145513","username":"谢挺盛","usercode":"443a196ef8744536a531260eb26c05d7"}]}
//
//        JSONObject data = obj.getJSONArray("data").getJSONObject(0);
//        if(id==null){
//            //从数据库中取id
//            DeviceHealthyInfoMapping mapping = deviceHealthyInfoMappingDao.findByRid(data.getString("rid"));
//            if(mapping!=null){
//                id = mapping.getIndexId()==null?mapping.getId():mapping.getIndexId();
//            }
//        }
//        index.setId(id);
//        index.setRecordDate(DateUtil.strToDate(data.getString("measure_time")));
//        index.setSortDate(index.getRecordDate());
//        index.setType(data.getInteger("type"));
//        index.setDel(data.getString("del"));
//        index.setStatus(data.getInteger("status"));
//        if(data.getInteger("type")==1){
//            index.setValue1(data.getString("value1"));
//            index.setValue2(data.getString("value2"));
//        }else if(data.getInteger("type")==2){
//            index.setValue1(data.getString("value1"));
//            index.setValue2(data.getString("value2"));
//            index.setValue3(data.getString("value3"));
//        }else if(data.getInteger("type")==3){
//            index.setValue1(data.getString("value1"));
//            index.setValue2(data.getString("value2"));
//            index.setValue3(data.getString("value3"));
//        }else if(data.getInteger("type")==4){
//            index.setValue1(data.getString("value1"));
//        }
//        return index;
//    }
    /**
     * 字符串分割
     * @param name
     * @param type 1品牌,2 型号
     * @param deviceType 1血糖,2 血压
     * @return
     */
    private String transfor(String name,Integer type,Integer deviceType){
        String re = "";
        String[] brand = {"康为","爱奥乐","优瑞恩","三诺","云湃"};
        String[] model = {"A206G","G-777G","U80EH","亲智","RBP-980"};
        String model2 = "G-426-3";
        if(StringUtils.isBlank(name)){
            return re;
        }
        for(int i=0;i<brand.length;i++){
            String one = brand[i];
            if(name.contains(one)){
                re = type == 1? one:((i==0&&deviceType==1)?model2:model[i]);
            }
        }
        return re;
    }
    /**
     * 时间处理
     * @param time
     * @return
     */
    private String subStringTime(String time){
        return StringUtils.isBlank(time)? "":time.substring(0,19);
    }
    /**
     * 状态默认值
     * @param status
     * @return
     */
    private String getStatus(String status){
        return StringUtils.isBlank(status)?"0":status;
    }
    /**
     * 转化成物联网格式
     * @param obj
     * @param json
     * @return
     */
    public JSONObject transforIot(DevicePatientHealthIndex obj,JSONObject json){
        JSONArray jsonArray = new JSONArray();
        String measure_time = DateUtil.dateToStrLong(obj.getRecordDate());
        switch (obj.getType()){
            case 1:
                //血糖
                JSONObject blood_sugar = new JSONObject();
                blood_sugar.put("measure_time",measure_time);
                blood_sugar.put("type","BloodSugar");
                blood_sugar.put("sign_name","blood_sugar");
                blood_sugar.put("sign_value",obj.getValue1());
                blood_sugar.put("sign_unit",bloodSugarUnit);
                jsonArray.add(blood_sugar);
                JSONObject blood_sugar_result = new JSONObject();
                blood_sugar_result.put("measure_time",measure_time);
                blood_sugar_result.put("type","BloodSugar");
                blood_sugar_result.put("sign_name","blood_sugar_result");
                blood_sugar_result.put("sign_value",obj.getValue2());
                jsonArray.add(blood_sugar_result);
                break;
            case 2:
                //血压
                JSONObject systolic = new JSONObject();
                systolic.put("measure_time",measure_time);
                systolic.put("type","BloodPressure");
                systolic.put("sign_name","systolic");
                systolic.put("sign_value",obj.getValue1());
                systolic.put("sign_unit",bloodPressureUnit);
                jsonArray.add(systolic);
                JSONObject diastolic = new JSONObject();
                diastolic.put("measure_time",measure_time);
                diastolic.put("type","BloodPressure");
                diastolic.put("sign_name","diastolic");
                diastolic.put("sign_value",obj.getValue2());
                diastolic.put("sign_unit",bloodPressureUnit);
                jsonArray.add(diastolic);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    JSONObject pulse = new JSONObject();
                    pulse.put("measure_time",measure_time);
                    pulse.put("type","BloodPressure");
                    pulse.put("sign_name","pulse");
                    pulse.put("sign_value",obj.getValue3());
                    pulse.put("sign_unit",pulseUnit);
                    jsonArray.add(pulse);
                }
                break;
            case 3:
                //体重/身高/BMI
                JSONObject height = new JSONObject();
                height.put("measure_time",measure_time);
                height.put("type","Height");
                height.put("sign_name","height");
                height.put("sign_value",obj.getValue1());
                height.put("sign_unit",heightUnit);
                jsonArray.add(height);
                JSONObject weight = new JSONObject();
                weight.put("measure_time",measure_time);
                weight.put("type","Height");
                weight.put("sign_name","weight");
                weight.put("sign_value",obj.getValue2());
                weight.put("sign_unit",weightUnit);
                jsonArray.add(weight);
                if(StringUtils.isNotBlank(obj.getValue3())){
                    JSONObject bmi = new JSONObject();
                    bmi.put("measure_time",measure_time);
                    bmi.put("type","Height");
                    bmi.put("sign_name","bmi");
                    bmi.put("sign_value",obj.getValue3());
                    bmi.put("sign_unit",bmiUnit);
                    jsonArray.add(bmi);
                }
                break;
            case 4:
                //腰围
                JSONObject waist = new JSONObject();
                waist.put("measure_time",measure_time);
                waist.put("type","Waist");
                waist.put("sign_name","waist");
                waist.put("sign_value",obj.getValue1());
                waist.put("sign_unit",waistUnit);
                jsonArray.add(waist);
                break;
            default:
                break;
        }
        json.put("measure_data",jsonArray);
        return json;
    }
    /**
     * 返回accessToken
     * @return
     */
    private synchronized String getAccessToken(){
        String token = "";
        if(tokenMap.get("token")!=null){
            token = tokenMap.get("token");
            Long outTime = Long.valueOf(tokenMap.get("outTime"));
            if(new Date().getTime()<outTime){
                return token;
            }
        }
        try {
            Map params = new HashMap();
            params.put("appid", appid);
            params.put("appSecret", appSecret);
            String url = "/open/gc/accesstoken";
            String response = httpClientUtil.httpPost(baseUrl + url, params);
            JSONObject jsonObject = JSON.parseObject(response);
            if(jsonObject.getInteger("status")==10000){
                String accesstoken = jsonObject.getJSONObject("result").getString("accesstoken");
                tokenMap.put("token",accesstoken);
                tokenMap.put("outTime", jsonObject.getJSONObject("result").getLong("outTime")+"");
                return accesstoken;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
//    public String iotDataImportJob(String idcard){
//        try {
//            String dayStr = DateUtil.getStringDateShort();
//            List<DevicePatientHealthIndex> healthIndices = new ArrayList<>();
//
//            logger.info(":start IOT_DATA_IMPORT_JOB===============");
////            获取access token
//            String tokenUrl = "http://iot.xmtyw.cn:9660/cityihealth/iot/svr-iot/open/gc/accesstoken";
//            if ("prod".equals(profiles)){
//                tokenUrl = "http://27.155.102.211:9660/cityihealth/iot/svr-iot/open/gc/accesstoken";
//            }
//            if ("local".equals(profiles)){
//                tokenUrl = "http://10.95.22.10:9661/cityihealth/iot/svr-iot/open/gc/accesstoken";
//            }
//
//            Map params = new HashMap();
//            params.put("appid", "b5125656570011ec8771005056ab2351");
//            params.put("appSecret", "b5125668570011ec8771005056ab2351");
//            String response = httpClientUtil.httpPost(tokenUrl, params);
//            JSONObject jsonObject = JSON.parseObject(response);
//            if(jsonObject.getInteger("status")==10000){
//                String accesstoken = jsonObject.getJSONObject("result").getString("accesstoken");
//                //获取体征数据
//                String searchUrl = "http://iot.xmtyw.cn:9660/cityihealth/iot/svr-iot/open/gc/searchList";
//                if ("prod".equals(profiles)){//外网
//                    searchUrl = "http://27.155.102.211:9660/cityihealth/iot/svr-iot/open/gc/searchList2";
//                }
//                if ("local".equals(profiles)){//内网
//                    searchUrl = "http://10.95.22.10:9661/cityihealth/iot/svr-iot/open/gc/searchList";
//                }
//                params = new HashMap();
//                params.put("accesstoken",accesstoken);
//                List<NameValuePair> bodyParams = new ArrayList<>();
//                if (StringUtils.isNotBlank(idcard)){
//                    bodyParams.add(new BasicNameValuePair("idcard", idcard));
//                }
//                bodyParams.add(new BasicNameValuePair("startTime", dayStr+" 00:00:00"));
//                bodyParams.add(new BasicNameValuePair("endTime", dayStr+" 23:59:59"));
//                response = httpClientUtil.headerPost(searchUrl, bodyParams,"utf-8",params);
//                jsonObject = JSONObject.parseObject(response);
//
//                if(jsonObject.getInteger("status")==200){
//                    JSONArray array = jsonObject.getJSONArray("detailModelList");
//                    for (int i=0;i<array.size();i++){
//                        try {
//                            JSONObject tmp = array.getJSONObject(i);
//                            String sn = tmp.getString("sn");
//                            String userName = tmp.getString("username");
//                            idcard = tmp.getString("idcard");
//                            Patient patient = patientDao.findByIdcard(idcard);
//                            SignFamily sf = signFamilyDao.findByIdcard(idcard);
//                            if (null!=patient){
//                                JSONArray measureDatas = tmp.getJSONArray("measure_data");
//                                if (measureDatas.size()>0){
//                                    try {
//                                        JSONObject dataInfo = measureDatas.getJSONObject(0);
//                                        //血压 BloodPressure  收缩压systolic  舒张压diastolic
//                                        //血糖 BloodSugar  blood_sugar
//                                        //数据类型
//                                        String dataType = dataInfo.getString("type");
//                                        String sign_value = dataInfo.get("sign_value").toString();
//                                        String sign_name = dataInfo.get("sign_name").toString();
//                                        String measure_time = dataInfo.get("measure_time").toString();
//                                        Date measureDate = DateUtil.strToDate(measure_time);
//                                        String sign_unit = dataInfo.get("sign_unit").toString();
//                                        if ("BloodPressure".equals(dataType)){
//                                            DevicePatientHealthIndex index = new DevicePatientHealthIndex();
//                                            index.setUser(patient.getCode());
//                                            index.setDel("1");
//                                            index.setRecordDate(measureDate);    //记录时间
//                                            index.setSortDate(measureDate);      //排序时间
//                                            index.setCzrq(measureDate);      //排序时间
//                                            index.setDeviceSn(sn);
//                                            index.setIdcard(idcard);
//                                            index.setStatus(0);
//                                            index.setName(userName);
//                                            if (null!=sf){
//                                                index.setHospital(sf.getHospital());
//                                                index.setHospitalName(sf.getHospitalName());
//                                            }
//                                            if ("systolic".equals(sign_name)){
//                                                index.setValue1(sign_value);//收缩压
//                                            }
//                                            if ("diastolic".equals(sign_name)){
//                                                index.setValue2(sign_value);//舒张压
//                                            }
//                                            if (measureDatas.size()>1){
//                                                JSONObject dataInfo2 = measureDatas.getJSONObject(1);
//                                                String sign_value2 = dataInfo2.get("sign_value").toString();
//                                                String sign_name2 = dataInfo2.get("sign_name").toString();
//                                                if ("systolic".equals(sign_name2)){
//                                                    index.setValue1(sign_value2);//收缩压
//                                                }
//                                                if ("diastolic".equals(sign_name2)){
//                                                    index.setValue2(sign_value2);//舒张压
//                                                }
//                                            }
//                                            index.setType(2);//1血糖,2血压
//                                            String sql = " select count(id) from device.wlyy_patient_health_index where `user`='"+patient.getCode()+"' " +
//                                                    "and type='2' and value1='"+index.getValue1()+"' and value2='"+index.getValue2()+"' and record_date='"+measure_time+"' ";
//                                            if (0==jdbcTemplate.queryForObject(sql,Integer.class)){
//                                                healthIndices.add(index);
//                                            }
//                                        } else if ("BloodSugar".equals(dataType)) {
//                                            DevicePatientHealthIndex index = new DevicePatientHealthIndex();
//                                            index.setUser(patient.getCode());
//                                            index.setDel("1");
//                                            index.setRecordDate(measureDate);    //记录时间
//                                            index.setSortDate(measureDate);      //排序时间
//                                            index.setCzrq(measureDate);      //排序时间
//                                            index.setDeviceSn(sn);
//                                            index.setIdcard(idcard);
//                                            index.setStatus(0);
//                                            index.setName(userName);
//                                            if (null!=sf){
//                                                index.setHospital(sf.getHospital());
//                                                index.setHospitalName(sf.getHospitalName());
//                                            }
//                                            index.setValue1(sign_value);//血糖
//                                            index.setValue2("1");//血糖类型
//                                            index.setType(1);//1血糖,2血压
//                                            String sql = " select count(id) from device.wlyy_patient_health_index where `user`='"+patient.getCode()+"' " +
//                                                    "and type='1' and value1='"+index.getValue1()+"' and value2='1' and record_date='"+measure_time+"' ";
//                                            if (0==jdbcTemplate.queryForObject(sql,Integer.class)){
//                                                healthIndices.add(index);
//                                            }
//                                        }
//                                    }catch (Exception e){}
//                                }
//                            }
//                        }catch (Exception e){}
//                    }
//                }
//            }else {
//                throw new Exception("获取access token失败");
//            }
//            if (healthIndices.size()>0){
//                devicePatientHealthIndexDao.save(healthIndices);
//            }
//            logger.info(":start IOT_DATA_IMPORT_JOB success===============");
//        }catch (Exception e){
//            e.printStackTrace();
//            logger.info(":start IOT_DATA_IMPORT_JOB error==============message:"+e.getMessage());
//        }
//        return "success";
//    }
//    public String iotDataImportData(String json){
//        List<DevicePatientHealthIndex> healthIndices = new ArrayList<>();
//        try {
//            WlyyIotUploadDataLogDO uploadDataLogDO = new WlyyIotUploadDataLogDO();
//
//            JSONObject jsonObject = null;
//            try {
//                jsonObject = JSONObject.parseObject(json);
//            } catch (Exception e) {
//                uploadDataLogDO.setJson(json);
//                uploadDataLogDO.setCreateTime(new Date());
//                wlyyIotUploadDataLogDao.save(uploadDataLogDO);
//                throw new Exception("json参数转换失败");
//            }
//            String deviceSn = jsonObject.getString("sn");
//            String userName = jsonObject.getString("username");
//            String idcard = jsonObject.getString("idcard");
//            uploadDataLogDO.setJson(json);
//            uploadDataLogDO.setDeviceSn(deviceSn);
//            uploadDataLogDO.setUserName(userName);
//            uploadDataLogDO.setIdcard(idcard);
//            uploadDataLogDO.setCreateTime(new Date());
//            wlyyIotUploadDataLogDao.save(uploadDataLogDO);
//
//            Patient patient = patientDao.findByIdcard(idcard);
//            SignFamily sf = signFamilyDao.findByIdcard(idcard);
//            if (null!=patient){
//                JSONArray measureDatas = jsonObject.getJSONArray("measure_data");
//                if (measureDatas.size()>0){
//                    try {
//                        JSONObject dataInfo = measureDatas.getJSONObject(0);
//                        //数据类型
//                        String dataType = dataInfo.getString("type");
//                        if (StringUtils.isNotBlank(dataType)){
//                            switch (dataType){
//                                case "BloodPressure": //血压
//                                    healthIndices.addAll(BloodPressureHandle(patient,sf,deviceSn,idcard,userName,measureDatas));
//                                    break;
//                                case "BloodSugar"://血糖
//                                    healthIndices.addAll(BloodSugarHandle(patient,sf,deviceSn,idcard,userName,measureDatas));
//                                    break;
//                            }
//                        }
//                    }catch (Exception e){}
//                }
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        if (healthIndices.size()>0){
//            devicePatientHealthIndexDao.save(healthIndices);
//        }
//        return "success";
//    }
//    public List<DevicePatientHealthIndex> BloodPressureHandle(Patient patient,SignFamily sf,String deviceSn,String idcard,String userName,JSONArray measureDatas){
//        List<DevicePatientHealthIndex> result = new ArrayList<>();
//        DevicePatientHealthIndex index = new DevicePatientHealthIndex();
//        JSONObject dataInfo = measureDatas.getJSONObject(0);
//
//        String sign_value = dataInfo.get("sign_value").toString();
//        String sign_name = dataInfo.get("sign_name").toString();
//        String measure_time = dataInfo.get("measure_time").toString();
//        Date measureDate = DateUtil.strToDate(measure_time);
//        String sign_unit = dataInfo.get("sign_unit").toString();
//        //血压 BloodPressure  收缩压systolic  舒张压diastolic
//
//        index.setUser(patient.getCode());
//        index.setDel("1");
//        index.setRecordDate(measureDate);    //记录时间
//        index.setSortDate(measureDate);      //排序时间
//        index.setCzrq(measureDate);      //排序时间
//        index.setDeviceSn(deviceSn);
//        index.setIdcard(idcard);
//        index.setStatus(0);
//        index.setName(userName);
//        if (null!=sf){
//            index.setHospital(sf.getHospital());
//            index.setHospitalName(sf.getHospitalName());
//        }
//        if ("systolic".equals(sign_name)){
//            index.setValue1(sign_value);//收缩压
//        }
//        if ("diastolic".equals(sign_name)){
//            index.setValue2(sign_value);//舒张压
//        }
//        if (measureDatas.size()>1){
//            JSONObject dataInfo2 = measureDatas.getJSONObject(1);
//            String sign_value2 = dataInfo2.get("sign_value").toString();
//            String sign_name2 = dataInfo2.get("sign_name").toString();
//            if ("systolic".equals(sign_name2)){
//                index.setValue1(sign_value2);//收缩压
//            }
//            if ("diastolic".equals(sign_name2)){
//                index.setValue2(sign_value2);//舒张压
//            }
//        }
//        index.setType(2);//1血糖,2血压
//        String sql = " select count(id) from device.wlyy_patient_health_index where `user`='"+patient.getCode()+"' " +
//                "and type='2' and value1='"+index.getValue1()+"' and value2='"+index.getValue2()+"' and record_date='"+measure_time+"' ";
//        if (0==jdbcTemplate.queryForObject(sql,Integer.class)){
//            result.add(index);
//        }
//        return result;
//    }
//    public List<DevicePatientHealthIndex> BloodSugarHandle(Patient patient,SignFamily sf,String deviceSn,String idcard,String userName,JSONArray measureDatas){
//        List<DevicePatientHealthIndex> result = new ArrayList<>();
//        DevicePatientHealthIndex index = new DevicePatientHealthIndex();
//        JSONObject dataInfo = measureDatas.getJSONObject(0);
//        //血糖 BloodSugar     blood_sugar
//
//        String sign_value = dataInfo.get("sign_value").toString();
//        String sign_name = dataInfo.get("sign_name").toString();
//        String measure_time = dataInfo.get("measure_time").toString();
//        Date measureDate = DateUtil.strToDate(measure_time);
//        String sign_unit = dataInfo.get("sign_unit").toString();
//
//
//        index.setUser(patient.getCode());
//        index.setDel("1");
//        index.setRecordDate(measureDate);    //记录时间
//        index.setSortDate(measureDate);      //排序时间
//        index.setCzrq(measureDate);      //排序时间
//        index.setDeviceSn(deviceSn);
//        index.setIdcard(idcard);
//        index.setStatus(0);
//        index.setName(userName);
//        if (null!=sf){
//            index.setHospital(sf.getHospital());
//            index.setHospitalName(sf.getHospitalName());
//        }
//        index.setValue1(sign_value);//血糖
//        index.setValue2("1");//血糖类型
//        index.setType(1);//1血糖,2血压
//        String sql = " select count(id) from device.wlyy_patient_health_index where `user`='"+patient.getCode()+"' " +
//                "and type='1' and value1='"+index.getValue1()+"' and value2='1' and record_date='"+measure_time+"' ";
//        if (0==jdbcTemplate.queryForObject(sql,Integer.class)){
//            result.add(index);
//        }
//        return result;
//    }
    /*****************************************工具方法 end  ************************************************************/
    /*****************************************塞克上传接口***********************************************************/
//    @Transactional(rollbackFor = Exception.class)
//    public void skJsonSave(String idcard, Integer type, String json) {
//        SkJsonFormEntity skJsonFormEntity = new SkJsonFormEntity();
//        skJsonFormEntity.setJson(json);
//        skJsonFormEntity.setIdcard(idcard);
//        skJsonFormEntity.setType(type);
//        skJsonFormEntity.setStatus(0);
//        skJsonFormEntity.setCreateTime(new Date());
//        skJsonFormDao.save(skJsonFormEntity);
//    }
    public JSONObject getJoinPatient(String startTime,String endTime,String status,Integer page,Integer pageSize,String idcard) {
        JSONObject jsonObject = new JSONObject();
        String sql = "SELECT " +
                "  DISTINCT cp.idcard,cp.`name`,cp.hospital,cp.hospital_name AS hospitalName,DATE_FORMAT(cp.create_time,'%Y-%m-%d %H:%i:%S') AS createTime" +
                ",DATE_FORMAT(cp.update_time,'%Y-%m-%d %H:%i:%S') AS updateTime" +
                ",cp.group_screening_code as groupScreeningCode,cp.status,cp.group_screening_status groupScreeningStatus," +
                " IF(mod(MID(cp.idcard,17,1),2),1,2) AS sex,p.birthday,p.mobile,cp.entry_time,cp.group_watch,cp.exit_time " +
                ",vi1.bracelet_date,rr2.return_time return_time2,rr3.return_time return_time3,rr4.return_time return_time4" +
                ",rr5.return_time return_time5,rr6.return_time return_time6,vi6.fill_date " +
                "FROM wlyy_copd_patient cp " +
                "LEFT JOIN wlyy_patient p ON cp.patient = p.`code` " +
                "LEFT JOIN wlyy_followup f1 on f1.patient_code = cp.patient and f1.type='4' and f1.visit_count='1' " +
                "LEFT JOIN wlyy_followup f2 on f2.patient_code = cp.patient and f2.type='4' and f2.visit_count='2' " +
                "LEFT JOIN wlyy_followup f3 on f3.patient_code = cp.patient and f3.type='4' and f3.visit_count='3' " +
                "LEFT JOIN wlyy_followup f4 on f4.patient_code = cp.patient and f4.type='4' and f4.visit_count='4' " +
                "LEFT JOIN wlyy_followup f5 on f5.patient_code = cp.patient and f5.type='4' and f5.visit_count='5' " +
                "LEFT JOIN wlyy_followup f6 on f6.patient_code = cp.patient and f6.type='4' and f6.visit_count='6' " +
                "LEFT JOIN copd_information_of_this_visit vi1 on f1.id = vi1.followup_id " +
                "LEFT JOIN copd_information_of_this_visit vi6 on f6.id = vi6.followup_id " +
                "LEFT JOIN copd_device_return_record rr2 on f2.id = rr2.followup_id " +
                "LEFT JOIN copd_device_return_record rr3 on f3.id = rr3.followup_id " +
                "LEFT JOIN copd_device_return_record rr4 on f4.id = rr4.followup_id " +
                "LEFT JOIN copd_device_return_record rr5 on f5.id = rr5.followup_id " +
                "LEFT JOIN copd_device_return_record rr6 on f6.id = rr6.followup_id " +
                " WHERE 1=1 ";
        String sqlTotal = "SELECT " +
                " count(DISTINCT idcard) " +
                "FROM " +
                " wlyy_copd_patient  " +
                "WHERE 1=1 ";
        if("1".equals(status)){
            sql += " and cp.status = '1'";
            sqlTotal += " and status = '1'";
        }else if("2".equals(status)){
            sql +=  " AND group_screening_status <> '0'  " +
                    " AND group_screening_status IS NOT NULL  " +
                    " AND group_screening_status <> '' " ;
            sqlTotal += " AND group_screening_status <> '0'  " +
                    " AND group_screening_status IS NOT NULL  " +
                    " AND group_screening_status <> '' " ;
        }
        if (StringUtils.isNotBlank(startTime)&&StringUtils.isNotBlank(endTime)) {
//            String start = startTime.replace("-","").substring(0,8);
//            String end = endTime.replace("-","").substring(0,8);
            endTime += " 23:59:59";
            sql += " and ((cp.update_time >= '"+startTime+"' and cp.update_time <= '"+endTime+"') " +
                    " or (cp.inclusion_time>='"+startTime+"' and cp.inclusion_time <='"+endTime+"') " +
                    " or (cp.exit_time>='"+startTime+"' and cp.exit_time <='"+endTime+"') " +
                    " or (vi6.fill_date>='"+startTime+"' and vi6.fill_date <='"+endTime+"') " +
                    " or (second_inclusion_time>='"+startTime+"' and second_inclusion_time <='"+endTime+"')) ";
            sqlTotal += " and ((update_time >= '"+startTime+"' and update_time <= '"+endTime+"') " +
                    " or (inclusion_time>='"+startTime+"' and inclusion_time <='"+endTime+"') " +
                    " or (exit_time>='"+startTime+"' and exit_time <='"+endTime+"') " +
                    " or (second_inclusion_time>='"+startTime+"' and second_inclusion_time <='"+endTime+"')) ";
        }
        if(StringUtils.isNotBlank(idcard)){
            sql += " and cp.idcard='"+idcard+"'";
            sqlTotal += " and idcard='"+idcard+"'";
        }
        sql +=" and hospital <> '5351e9756eb011e69f7c005056850d66' and hospital <> 'ac02a9b87a3611e69f7c005056850d66' and hospital is not null ";
        sql += " order by cp.id ";
        if (page==null&&pageSize==null) {
            page = 1;
            pageSize = 100;
        }
        sql += " LIMIT "+(page-1)*pageSize+","+pageSize;
        Integer total = jdbcTemplate.queryForObject(sqlTotal, Integer.class);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        jsonObject.put("total",total);
        jsonObject.put("listData",list);
        jsonObject.put("pageNum",Math.ceil(Double.valueOf(total)/Double.valueOf(pageSize)));
        return jsonObject;
    }
}

+ 2151 - 0
business/base-service/src/main/java/com/yihu/jw/scheme/DoctorSchemeService.java

@ -0,0 +1,2151 @@
package com.yihu.jw.scheme;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.device.dao.DevicePatientHealthIndexDao;
import com.yihu.jw.device.dao.PatientAimBloodPressureDao;
import com.yihu.jw.device.dao.PatientAimBloodSuggerDao;
import com.yihu.jw.device.dao.PatientAimSportsDao;
import com.yihu.jw.entity.base.device.PatientAimBloodPressure;
import com.yihu.jw.entity.base.device.PatientAimBloodSugger;
import com.yihu.jw.entity.base.device.PatientAimSports;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.care.device.DevicePatientHealthIndex;
import com.yihu.jw.entity.scheme.*;
import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodPressureVO;
import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodSuggerVO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.restmodel.patient.PatientVO;
import com.yihu.jw.util.date.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.*;
/**
 * 医生监测方案相关业务层方法
 * @author huangwenjie
 * @date 2017/9/13 15:46
 */
@Service
@Transactional
public class DoctorSchemeService {
    private static Logger logger = LoggerFactory.getLogger(DoctorSchemeService.class);
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctrorSchemeBloodSuggerDao doctroSchemeBloodSuggerDao;
    @Autowired
    private DoctoreSchemeBloodPressureDao doctoreSchemeBloodPressureDao;
    @Autowired
    private JpaTransactionManager transactionManager;
    @Autowired
    private PatientSchemeListDao patientSchemeListDao;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private DevicePatientHealthIndexDao devicePatientHealthIndexDao;
    @Autowired
    private PatientAimBloodSuggerDao patientAimBloodSuggerDao;
    @Autowired
    private PatientAimBloodPressureDao patientAimBloodPressureDao;
    @Autowired
    private DoctorSwitchDao doctorSwitchDao;
    @Autowired
    private TrackPatientDao trackPatientDao;
    @Autowired
    private PatientAimSportsDao patientAimSportsDao;
    @Value("${im.data_base_name}")
    private String im_dataBase_name;
    /**
     * 根据团队CODE/居民标签/病情/设备绑定状态查询团队具名CODE列表
     * @param teamCode 团队CODE
     * @param disease  病情
     * @param diseaseCondition 居民标签
     * @param deviceType 设备绑定状态
     * @author huangwenjie
     * @date 2017/9/13 16:23
     * @return
     */
    public List<String> getPatientsByDiseaseConditionDiseaseDeviceType(String teamCode, Integer disease, String diseaseCondition, Integer deviceType,String doctorcode,String trackFlag) throws Exception{
        String sql = "select DISTINCT p.code from wlyy_patient p ";
        //1.4.2加入跟踪居民过滤
        if(StringUtils.isNotBlank(trackFlag)&&"1".equals(trackFlag)){
            sql = sql + " JOIN wlyy_track_patient tp ON tp.patient_code = p.code ";
        }
        if(-1 != deviceType){
            sql = sql + " LEFT JOIN wlyy_patient_device dev on dev.user = p.code ";
        }
        sql = sql+ " RIGHT JOIN wlyy_sign_patient_label_info sp on sp.patient = p.code and sp.status =1 ";
        sql = sql+ " LEFT JOIN wlyy_sign_family sf on sf.patient = p.code where sf.admin_team_code = "+teamCode;
        if(-1 != disease && 3 != disease){
            sql = sql + " and sp.label ="+disease;
        }else{
            sql = sql + " and (sp.label = 1 or sp.label = 2) ";
        }
        if(StringUtils.isNotBlank(diseaseCondition) && !"-1".equals(diseaseCondition)){
            sql = sql + " and p.disease_condition IN ("+diseaseCondition +")";
        }
        if(-1 != deviceType){
            if( 0 == deviceType){
                sql = sql + " and dev.user is null ";
            }else{
                sql = sql + " and dev.user is not null ";
            }
        }
        sql = sql + " and (sf.doctor = '"+doctorcode+"' or sf.doctor_health ='"+doctorcode+"')";
        sql = sql + " and p.status > 0 and sp.label_type = 3 and sf.status > 0 ";
        //1.4.2加入跟踪居民过滤
        if(StringUtils.isNotBlank(trackFlag)&&"1".equals(trackFlag)){
            sql = sql + " AND tp.del='1' AND tp.doctor_code = '"+doctorcode+"' AND tp.team_code = "+teamCode;
        }
        List<String> result = jdbcTemplate.queryForList(sql,new Object[]{},String.class);
        return result;
    }
    /**
     * 获取医生的血糖监测方案,根据创建时间降序排序,系统方案放最后
     * @param doctorcode
     * @return
     * @throws Exception
     */
    public List<DoctorSchemeBloodSuggerVO> getDoctorScheBloodSuggerList(String doctorcode)  throws Exception {
        List<DoctorSchemeBloodSuggerVO> result = new ArrayList<>();
        HashMap<String,List<DoctorSchemeBloodSugger>> mapresult = new HashMap<>();
        LinkedList<String> keys = new LinkedList<>();
        List<DoctorSchemeBloodSugger> schemelist = doctroSchemeBloodSuggerDao.getListByDoctorcode(doctorcode);
        if(!schemelist.isEmpty()){
            for (DoctorSchemeBloodSugger doctorSchemeBloodSugger : schemelist) {
                if(keys.contains(doctorSchemeBloodSugger.getCode())){
                    mapresult.get(doctorSchemeBloodSugger.getCode()).add(doctorSchemeBloodSugger);
                }else{
                    List<DoctorSchemeBloodSugger> list = new ArrayList<>();
                    list.add(doctorSchemeBloodSugger);
                    mapresult.put(doctorSchemeBloodSugger.getCode(),list);
                    keys.add(doctorSchemeBloodSugger.getCode());
                }
            }
            for (String key :keys) {
                DoctorSchemeBloodSuggerVO doctorSchemeBloodSuggerVO = new DoctorSchemeBloodSuggerVO();
                doctorSchemeBloodSuggerVO.setCode(key);
                doctorSchemeBloodSuggerVO.setName(mapresult.get(key).get(0).getName());
                doctorSchemeBloodSuggerVO.setContent(mapresult.get(key).get(0).getContent());
                doctorSchemeBloodSuggerVO.setList(mapresult.get(key));
                result.add(doctorSchemeBloodSuggerVO);
            }
        }
        return result;
    }
    /**
     * 获取医生的血压监测方案,根据创建时间降序排序,系统方案放最后
     * @param doctorcode
     * @return
     * @throws Exception
     */
    public  List<DoctorSchemeBloodPressureVO>  getDoctorSchemeBloodPressureList(String doctorcode) throws Exception{
        List<DoctorSchemeBloodPressureVO> result = new ArrayList<>();
        HashMap<String,List<DoctorSchemeBloodPressure>> mapresult = new HashMap<>();
        List<DoctorSchemeBloodPressure> schemelist = doctoreSchemeBloodPressureDao.getListByDoctorcode(doctorcode);
        LinkedList<String> keys = new LinkedList<>();
        if(!schemelist.isEmpty()){
            for (DoctorSchemeBloodPressure doctorSchemeBloodPressure : schemelist) {
                if(keys.contains(doctorSchemeBloodPressure.getCode())){
                    mapresult.get(doctorSchemeBloodPressure.getCode()).add(doctorSchemeBloodPressure);
                }else{
                    List<DoctorSchemeBloodPressure> list = new ArrayList<>();
                    list.add(doctorSchemeBloodPressure);
                    mapresult.put(doctorSchemeBloodPressure.getCode(),list);
                    keys.add(doctorSchemeBloodPressure.getCode());
                }
            }
            for (String key :keys) {
                DoctorSchemeBloodPressureVO doctorSchemeBloodPressureVO = new DoctorSchemeBloodPressureVO();
                doctorSchemeBloodPressureVO.setCode(key);
                doctorSchemeBloodPressureVO.setName(mapresult.get(key).get(0).getName());
                doctorSchemeBloodPressureVO.setContent(mapresult.get(key).get(0).getContent());
                doctorSchemeBloodPressureVO.setList(mapresult.get(key));
                result.add(doctorSchemeBloodPressureVO);
            }
        }
        return result;
    }
    /**
     * 医生保存血糖监测方案
     * @param data
     * @throws Exception
     */
    public void saveDoctorSchemeBloodSugger(String data) throws Exception{
        JSONObject dataObj =  JSON.parseObject(data);
        List<DoctorSchemeBloodSugger> results = new ArrayList<>();
        String code = dataObj.getString("code");
        if(StringUtils.isBlank(code)){
            code = UUID.randomUUID().toString();
        }
        String name = dataObj.getString("name");
        String content = dataObj.getString("content");
        String doctorcode = dataObj.getString("doctorcode");
        JSONArray datalist = dataObj.getJSONArray("list");
        for (int i = 0; i < datalist.size(); i++) {
            DoctorSchemeBloodSugger doctorSchemeBloodSugger = new DoctorSchemeBloodSugger();
            long id = 0;
            if(datalist.getJSONObject(i).containsKey("id")){
                id=datalist.getJSONObject(i).getLong("id");
            }
            if(id != 0){
                doctorSchemeBloodSugger.setId(datalist.getJSONObject(i).getLong("id"));
            }
            doctorSchemeBloodSugger.setName(name);
            doctorSchemeBloodSugger.setCode(code);
            doctorSchemeBloodSugger.setDoctorcode(doctorcode);
            doctorSchemeBloodSugger.setDayofweek(datalist.getJSONObject(i).getShort("dayofweek"));
            doctorSchemeBloodSugger.setBeforeBreakfast(datalist.getJSONObject(i).getShort("beforeBreakfast"));
            doctorSchemeBloodSugger.setBeforeBreakfastTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("beforeBreakfastTime")));
            doctorSchemeBloodSugger.setAfterBreakfast(datalist.getJSONObject(i).getShort("afterBreakfast"));
            doctorSchemeBloodSugger.setAfterBreakfastTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("afterBreakfastTime")));
            doctorSchemeBloodSugger.setBeforeLunch(datalist.getJSONObject(i).getShort("beforeLunch"));
            doctorSchemeBloodSugger.setBeforeLunchTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("beforeLunchTime")));
            doctorSchemeBloodSugger.setAfterLunch(datalist.getJSONObject(i).getShort("afterLunch"));
            doctorSchemeBloodSugger.setAfterLunchTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("afterLunchTime")));
            doctorSchemeBloodSugger.setBeforeDinner(datalist.getJSONObject(i).getShort("beforeDinner"));
            doctorSchemeBloodSugger.setBeforeDinnerTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("beforeDinnerTime")));
            doctorSchemeBloodSugger.setAfterDinner(datalist.getJSONObject(i).getShort("afterDinner"));
            doctorSchemeBloodSugger.setAfterDinnerTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("afterDinnerTime")));
            doctorSchemeBloodSugger.setBeforeSleep(datalist.getJSONObject(i).getShort("beforeSleep"));
            doctorSchemeBloodSugger.setBeforeSleepTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("beforeSleepTime")));
            doctorSchemeBloodSugger.setAlertTag(datalist.getJSONObject(i).getShort("alertTag"));
            doctorSchemeBloodSugger.setContent(content);
            doctorSchemeBloodSugger.setCreateTime(DateUtil.getNowTimestamp());
            doctorSchemeBloodSugger.setDel(0);
            results.add(doctorSchemeBloodSugger);
        }
        if(!results.isEmpty()) {
            doctroSchemeBloodSuggerDao.saveAll(results);
        }
    }
    /**
     * 医生保存血压监测方案
     * @param data
     * @throws Exception
     */
    public void saveDoctorSchemeBloodPressure(String data) throws Exception{
        JSONObject dataObj =  JSON.parseObject(data);
        List<DoctorSchemeBloodPressure> results = new ArrayList<>();
        String code = dataObj.getString("code");
        if(StringUtils.isBlank(code)){
            code = UUID.randomUUID().toString();
        }
        String name = dataObj.getString("name");
        String content = dataObj.getString("content");
        String doctorcode = dataObj.getString("doctorcode");
        JSONArray datalist = dataObj.getJSONArray("list");
        for (int i = 0; i < datalist.size(); i++) {
            DoctorSchemeBloodPressure doctorSchemeBloodPressure = new DoctorSchemeBloodPressure();
            long id = 0;
            if(datalist.getJSONObject(i).containsKey("id")){
                id=datalist.getJSONObject(i).getLong("id");
            }
            if(id != 0){
                doctorSchemeBloodPressure.setId(datalist.getJSONObject(i).getLong("id"));
            }
            doctorSchemeBloodPressure.setName(name);
            doctorSchemeBloodPressure.setCode(code);
            doctorSchemeBloodPressure.setDoctorcode(doctorcode);
            doctorSchemeBloodPressure.setDayofweek(datalist.getJSONObject(i).getShort("dayofweek"));
            doctorSchemeBloodPressure.setEarlyMorning(datalist.getJSONObject(i).getShort("earlyMorning"));
            doctorSchemeBloodPressure.setEarlyMorningTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("earlyMorningTime")));
            doctorSchemeBloodPressure.setMorning(datalist.getJSONObject(i).getShort("morning"));
            doctorSchemeBloodPressure.setMorningTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("morningTime")));
            doctorSchemeBloodPressure.setNoon(datalist.getJSONObject(i).getShort("noon"));
            doctorSchemeBloodPressure.setNoonTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("noonTime")));
            doctorSchemeBloodPressure.setAfterNoon(datalist.getJSONObject(i).getShort("afterNoon"));
            doctorSchemeBloodPressure.setAfterNoonTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("afterNoonTime")));
            doctorSchemeBloodPressure.setNight(datalist.getJSONObject(i).getShort("night"));
            doctorSchemeBloodPressure.setNightTime(DateUtil.hhmmStrToTime(datalist.getJSONObject(i).getString("nightTime")));
            doctorSchemeBloodPressure.setAlertTag(datalist.getJSONObject(i).getShort("alertTag"));
            doctorSchemeBloodPressure.setContent(content);
            doctorSchemeBloodPressure.setCreateTime(DateUtil.getNowTimestamp());
            doctorSchemeBloodPressure.setDel(0);
            results.add(doctorSchemeBloodPressure);
        }
        if(!results.isEmpty()) {
            doctoreSchemeBloodPressureDao.saveAll(results);
        }
    }
    /**
     * 医生保存居民监测方案
     *
     * @param doctorcode
     * @param schemecode
     * @param patientcodes
     * @param type
     * @throws Exception
     */
    @Transactional
    public void savePatientScheme(String doctorcode, String schemecode, String type,String patientcodes) throws Exception {
        List<String> patientcodeList = new ArrayList<>();
        String[] codes = patientcodes.split(",");
        if(patientcodes.contains(",")){
            for (String code : codes) {
                patientcodeList.add(code);
            }
        }else{
            patientcodeList.add(patientcodes);
        }
        if (!patientcodeList.isEmpty()) {
            //使用事务控制批量更新
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务
            TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
            try {
                for (String patientcode : patientcodeList) {
                    patientSchemeListDao.delByPatientCode(patientcode, Integer.parseInt(type));
                    PatientSchemeList patientSchemeListObj = new PatientSchemeList();
                    patientSchemeListObj.setCode(UUID.randomUUID().toString());
                    patientSchemeListObj.setPatientcode(patientcode);
                    patientSchemeListObj.setSchemecode(schemecode);
                    patientSchemeListObj.setDoctorcode(doctorcode);
                    patientSchemeListObj.setType(Integer.parseInt(type));
                    patientSchemeListObj.setCreateTime(DateUtil.getNowTimestamp());
                    patientSchemeListDao.save(patientSchemeListObj);
                }
                //事务提交
                transactionManager.commit(status);
            } catch (Exception ex) {
                ex.printStackTrace();
                //报错事务回滚
                transactionManager.rollback(status);
            }
        }
    }
    /**
     * 医生端-获取慢病管理居民管理端数据
     * @param teamCode
     * @param getcolor
     * @param getstands
     * @param gethealthindex
     * @param startdate
     * @param enddate
     * @return
     */
    public JSONObject getSlowDiseaseTeaminfos(String teamCode, int getcolor, int getstands, int gethealthindex, String startdate, String enddate,String doctorcode) throws Exception{
//        List<Patient> patients = patientDao.findAllSignPatientTeamcode(teamCode,doctorcode);
        List<PatientVO> patients = new ArrayList<>();
        String patientsql = "select p.code,p.standard_status,p.disease_condition,group_concat(sp.label) as disease " +
                " from wlyy_patient p " +
                " LEFT JOIN wlyy_sign_family s on s.patient = p.code " +
                " RIGHT JOIN wlyy_sign_patient_label_info sp on sp.patient = p.code and sp.label_type = 3 and (sp.label = 1 or sp.label = 2) and sp.status =1" +
                " WHERE s.status > 0 " +
                " and s.admin_team_code ='"+teamCode+"' and (s.doctor = '"+doctorcode+"' or s.doctor_health ='"+doctorcode+"') " +
                " GROUP BY p.code ";
        patients= jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        JSONObject result = new JSONObject();
        JSONObject green = new JSONObject();//绿标
        JSONObject yellow = new JSONObject();//黄标
        JSONObject red = new JSONObject();//红标
        JSONObject pressure_standard =  new JSONObject();//血压预警
        JSONObject sugar_standard =  new JSONObject();//血糖预警
        JSONObject pressure_count =  new JSONObject();//血压体征总数
        JSONObject pressure_unusual_ount =  new JSONObject();//血压体征总数
        JSONObject sugar_count =  new JSONObject();//血糖体征总数
        JSONObject sugar_unusual_count =  new JSONObject();//血糖体征总数
        int count = patients.size();
        //绿标居民
        List<PatientVO> green_patients = new ArrayList<>();
        //黄标居民
        List<PatientVO> yellow_patients = new ArrayList<>();
        //红标居民
        List<PatientVO> red_patients = new ArrayList<>();
        //高血压居民预警居民CODE
        List<String> bloodpressure_patientcodes = new ArrayList<>();
        //高血糖居民预警居民CODE
        List<String> bloodsugar_patientcodes = new ArrayList<>();
        if(!patients.isEmpty()){
            for (PatientVO patient : patients) {
                //获取居民颜色标签
                if(1 == getcolor && patient.getDiseaseCondition() != null){
                    switch (patient.getDiseaseCondition()){
                        case 0:
                            green_patients.add(patient);
                            break;
                        case 1:
                            yellow_patients.add(patient);
                            break;
                        case 2:
                            red_patients.add(patient);
                            break;
                    }
                }
                //获取预警居民CODES
                if(1 == getstands && (patient.getStandardStatus() !=null && patient.getStandardStatus() ==1)){
                    if(patient.getDisease() != null){
                        if( "1".equals(patient.getDisease()) || "1,2".equals(patient.getDisease()) || "2,1".equals(patient.getDisease())){
                            bloodpressure_patientcodes.add(patient.getCode());
                        }
                        if( "2".equals(patient.getDisease()) || "1,2".equals(patient.getDisease()) || "2,1".equals(patient.getDisease())){
                            bloodsugar_patientcodes.add(patient.getCode());
                        }
                    }
                }
            }
        }
        if(1 == getcolor){
            result.put("greencount",green_patients.size());
            result.put("yellowcount",yellow_patients.size());
            result.put("redcount",red_patients.size());
//            result.add(green);
//            result.add(yellow);
//            result.add(red);
        }
        if(1 == getstands){
            result.put("pressure_standard",bloodpressure_patientcodes);
            result.put("sugar_standard",bloodsugar_patientcodes);
//            result.add(pressure_standard);
//            result.add(sugar_standard);
        }
        if(1 == gethealthindex){
            Date start = DateUtil.strToDate(startdate);
            Date end = DateUtil.strToDate(enddate);
            List<DevicePatientHealthIndex> devicePatientHealthIndices = devicePatientHealthIndexDao.findByTeamcodeAndRecordDate(start,end,teamCode,doctorcode);
            int sugar = 0;
            int sugar_unusual = 0;
            int pressure = 0;
            int pressure_unusual = 0;
            if(!devicePatientHealthIndices.isEmpty()){
                for (DevicePatientHealthIndex devicePatientHealthIndex : devicePatientHealthIndices) {
                    if( 1 == devicePatientHealthIndex.getType()){
                        sugar++;
                        if( devicePatientHealthIndex.getStatus() !=null && 0 == devicePatientHealthIndex.getStatus()){
                            sugar_unusual++;
                        }
                    }
                    if( 2 == devicePatientHealthIndex.getType()){
                        pressure++;
                        if(devicePatientHealthIndex.getStatus() !=null && 0 == devicePatientHealthIndex.getStatus()){
                            pressure_unusual++;
                        }
                    }
                }
            }
            result.put("pressure_count",pressure);
            result.put("pressure_unusual_count",pressure_unusual);
            result.put("sugar_count",sugar);
            result.put("sugar_unusual_count",sugar_unusual);
//            result.add(pressure_count);
//            result.add(pressure_unusual_ount);
//            result.add(sugar_count);
//            result.add(sugar_unusual_count);
        }
        //1.4.2 重点关注居民
        List<TrackPatient> list = trackPatientDao.findByDoctorCodeAndTeamCodeAndDel(doctorcode,Integer.parseInt(teamCode),"1");
        if(list!=null&&list.size()>0){
            result.put("trackPatientCount",list.size());
        }else{
            result.put("trackPatientCount",0);
        }
        return result;
    }
    /**
     * 删除医生监测方案
     * @param doctorcode
     * @param schemecode
     * @param type
     */
    @Transactional
    public void delDoctorScheme(String doctorcode, String schemecode, String type) throws Exception{
        if("1".equals(type)){
            doctroSchemeBloodSuggerDao.updateDelStatus(1,doctorcode,schemecode);
        }
        if("2".equals(type)){
            doctoreSchemeBloodPressureDao.updateDelStatus(1,doctorcode,schemecode);
        }
        List<PatientSchemeList> list = patientSchemeListDao.findBySchemecode(schemecode);
        if(list!=null&&list.size()>0){
            patientSchemeListDao.deleteAll(list);
        }
    }
    public Map<String,Object> getPatientHealthIndex(String patient,String startDate,String endDate,String type){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String highSql ="SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS highCount " +
                " FROM " +
                " ( " +
                " SELECT " +
                " COUNT(1) AS befHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(1,3,5,7) " +
                " AND i.value1 > 7 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'" +
                " ) bf, " +
                " (  " +
                " SELECT " +
                " COUNT(1) AS aftHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(2,4,6) " +
                " AND i.value1 > 11.1 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'" +
                " ) aft";
        String stdSql ="SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS stdCount " +
                " FROM " +
                " ( " +
                " SELECT " +
                " COUNT(1) AS befHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(1,3,5,7) " +
                " AND i.value1 <= 7 " +
                " AND i.value1 >= 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'" +
                " ) bf, " +
                " (  " +
                " SELECT " +
                " COUNT(1) AS aftHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(2,4,6) " +
                " AND i.value1 <= 11.1 " +
                " AND i.value1 >= 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'" +
                " ) aft";
        String lowSql ="SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS lowCount " +
                " FROM " +
                " ( " +
                " SELECT " +
                " COUNT(1) AS befHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(1,3,5,7) " +
                " AND i.value1 < 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'" +
                " ) bf, " +
                " (  " +
                " SELECT " +
                " COUNT(1) AS aftHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(2,4,6) " +
                " AND i.value1 < 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'" +
                " ) aft";
        String pHighSql ="SELECT " +
                " count(1) AS highCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '2' " +
                " AND i.value1 > 139 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'";
        String  pStdSql ="SELECT " +
                " count(1) AS stdCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '2' " +
                " AND i.value1 <= 139 " +
                " AND i.value1 >= 90 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'";
        String pLowSql ="SELECT " +
                " count(1) AS lowCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '2' " +
                " AND i.value1 < 90 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user ='"+patient+"'";
        Map<String,Object> rs = new HashedMap();
        //0血檀
        if ("0".equals(type)){
            //1.高
            List<Map<String,Object>> high = jdbcTemplate.queryForList(highSql);
            if(high!=null&&high.size()>0){
                Map<String,Object> h = high.get(0);
                rs.put("highCount",h.get("highCount"));
            }
            //2.正常
            List<Map<String,Object>> std = jdbcTemplate.queryForList(stdSql);
            if(std!=null&&std.size()>0){
                Map<String,Object> st = std.get(0);
                rs.put("stdCount",st.get("stdCount"));
            }
            //3.偏低
            List<Map<String,Object>> low = jdbcTemplate.queryForList(lowSql);
            if(low!=null&&low.size()>0){
                Map<String,Object> lw = low.get(0);
                rs.put("lowCount",lw.get("lowCount"));
            }
            //其他血压
        }else{
            //1.高
            List<Map<String,Object>> high = jdbcTemplate.queryForList(pHighSql);
            if(high!=null&&high.size()>0){
                Map<String,Object> h = high.get(0);
                rs.put("highCount",h.get("highCount"));
            }
            //2.正常
            List<Map<String,Object>> std = jdbcTemplate.queryForList(pStdSql);
            if(std!=null&&std.size()>0){
                Map<String,Object> st = std.get(0);
                rs.put("stdCount",st.get("stdCount"));
            }
            //3.偏低
            List<Map<String,Object>> low = jdbcTemplate.queryForList(pLowSql);
            if(low!=null&&low.size()>0){
                Map<String,Object> lw = low.get(0);
                rs.put("lowCount",lw.get("lowCount"));
            }
        }
        return rs;
    }
    public Map<String,Object> getPatientHealthIndex(String startDate,String endDate,String type,Long teamCode,String doctor){
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        String highSql ="SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS highCount " +
                " FROM " +
                " ( " +
                " SELECT " +
                " COUNT(1) AS befHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(1,3,5,7) " +
                " AND i.value1 > 7 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")" +
                " ) bf, " +
                " (  " +
                " SELECT " +
                " COUNT(1) AS aftHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(2,4,6) " +
                " AND i.value1 > 11.1 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")" +
                " ) aft";
        String stdSql ="SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS stdCount " +
                " FROM " +
                " ( " +
                " SELECT " +
                " COUNT(1) AS befHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(1,3,5,7) " +
                " AND i.value1 <= 7 " +
                " AND i.value1 >= 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")" +
                " ) bf, " +
                " (  " +
                " SELECT " +
                " COUNT(1) AS aftHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(2,4,6) " +
                " AND i.value1 <= 11.1 " +
                " AND i.value1 >= 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")" +
                " ) aft";
        String lowSql ="SELECT  " +
                " (bf.befHighCount + aft.aftHighCount) AS lowCount " +
                " FROM " +
                " ( " +
                " SELECT " +
                " COUNT(1) AS befHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(1,3,5,7) " +
                " AND i.value1 < 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")" +
                " ) bf, " +
                " (  " +
                " SELECT " +
                " COUNT(1) AS aftHighCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.type = '1' " +
                " AND i.del = '1' " +
                " AND i.value2 in(2,4,6) " +
                " AND i.value1 < 4 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")" +
                " ) aft";
        String pHighSql ="SELECT " +
                " count(1) AS highCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '2' " +
                " AND i.value1 > 139 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")";
        String  pStdSql ="SELECT " +
                " count(1) AS stdCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '2' " +
                " AND i.value1 <= 139 " +
                " AND i.value1 >= 90 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")";
        String pLowSql ="SELECT " +
                " count(1) AS lowCount " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '2' " +
                " AND i.value1 < 90 " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'" +
                " AND i.user IN (SELECT t.patient_code FROM wlyy.wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +teamCode+")";
        Map<String,Object> rs = new HashedMap();
        //0血檀
        if ("0".equals(type)){
            //1.高
            List<Map<String,Object>> high = jdbcTemplate.queryForList(highSql);
            if(high!=null&&high.size()>0){
                Map<String,Object> h = high.get(0);
                rs.put("highCount",h.get("highCount"));
            }
            //2.正常
            List<Map<String,Object>> std = jdbcTemplate.queryForList(stdSql);
            if(std!=null&&std.size()>0){
                Map<String,Object> st = std.get(0);
                rs.put("stdCount",st.get("stdCount"));
            }
            //3.偏低
            List<Map<String,Object>> low = jdbcTemplate.queryForList(lowSql);
            if(low!=null&&low.size()>0){
                Map<String,Object> lw = low.get(0);
                rs.put("lowCount",lw.get("lowCount"));
            }
        //其他血压
        }else{
            //1.高
            List<Map<String,Object>> high = jdbcTemplate.queryForList(pHighSql);
            if(high!=null&&high.size()>0){
                Map<String,Object> h = high.get(0);
                rs.put("highCount",h.get("highCount"));
            }
            //2.正常
            List<Map<String,Object>> std = jdbcTemplate.queryForList(pStdSql);
            if(std!=null&&std.size()>0){
                Map<String,Object> st = std.get(0);
                rs.put("stdCount",st.get("stdCount"));
            }
            //3.偏低
            List<Map<String,Object>> low = jdbcTemplate.queryForList(pLowSql);
            if(low!=null&&low.size()>0){
                Map<String,Object> lw = low.get(0);
                rs.put("lowCount",lw.get("lowCount"));
            }
        }
        return rs;
    }
    public Map<String,Object> getTrackPatientInfo(String patient){
        Map<String,Object> rs = new HashedMap();
        rs.put("wxSport",0);
        String hsql = "SELECT " +
                " i.value1 AS weight, " +
                " i.value2 AS height, " +
                " i.value3 AS BMI " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = '3'  " +
                " AND i.user ='"+patient+"'" +
                " ORDER BY " +
                " i.record_date DESC LIMIT 0,1";
        String xtSchSql="SELECT " +
                " l.*," +
                " s.name " +
                " FROM " +
                " wlyy_patient_scheme_list l JOIN wlyy_doctor_scheme_blood_sugger s ON s.code = l.schemecode  " +
                " WHERE " +
                " l.type = 1 " +
                " AND l.patientcode = '"+patient+"'";
        String xySchSql="SELECT " +
                " l.*," +
                " s.name " +
                " FROM " +
                " wlyy_patient_scheme_list l JOIN wlyy_doctor_scheme_blood_pressure s ON s.code = l.schemecode" +
                " WHERE " +
                " l.type = 2 " +
                " AND l.patientcode = '"+patient+"'";
        List<Map<String,Object>> hList = jdbcTemplate.queryForList(hsql);
        if(hList!=null&&hList.size()>0){
            Map<String,Object> body = hList.get(0);
            rs.put("body",body);
        }else{
            rs.put("body",null);
        }
        List<Map<String,Object>> xtList = jdbcTemplate.queryForList(xtSchSql);
        if(xtList!=null&&xtList.size()>0){
            rs.put("sugger",xtList.get(0));
        }else{
            rs.put("sugger",null);
        }
        List<Map<String,Object>> xyList = jdbcTemplate.queryForList(xySchSql);
        if(xyList!=null&&xyList.size()>0){
            rs.put("pressure",xyList.get(0));
        }else{
            rs.put("pressure",null);
        }
        return  rs;
    }
    public Map<String,Object> getControlObjectives(String patient){
        Map<String,Object> rs = new HashedMap();
        PatientAimBloodSugger patientAimBloodSugger =  patientAimBloodSuggerDao.findByPatientcode(patient);
        PatientAimBloodPressure patientAimBloodPressure = patientAimBloodPressureDao.findByPatientcode(patient);
        PatientAimSports patientAimSports = patientAimSportsDao.getPatientAimSportsByPatientCode(patient);
        rs.put("patientAimBloodSugger",patientAimBloodSugger);
        rs.put("patientAimBloodPressure",patientAimBloodPressure);
        rs.put("patientAimSports",patientAimSports);
        return rs;
    }
    public List<Map<String,Object>> getBodyInfo(String patient,String startDate,String endDate,Integer page,Integer size){
        startDate = startDate+" 00:00:00";
        endDate = endDate + " 23:59:59";
        String sql = "SELECT " +
                " i.record_date, " +
                " i.value1 AS weight, " +
                " i.value2 AS height, " +
                " i.value3 AS BMI " +
                " FROM " +
                " device.wlyy_patient_health_index i " +
                " WHERE " +
                " i.del = '1' " +
                " AND i.type = 3 " +
                " AND i.`user` = '"+patient+"' " +
                " AND i.record_date >='"+startDate+"'" +
                " AND i.record_date <='"+endDate+"'"+
                " ORDER BY " +
                " i.record_date DESC LIMIT "+(page-1)*size+","+size;
        List<Map<String,Object>> rs = jdbcTemplate.queryForList(sql);
        return rs;
    }
    public String setDoctorSwitchTrackPatient(String doctor,String state){
        DoctorSwitch doctorSwitch =doctorSwitchDao.findByDoctor(doctor);
        if(doctorSwitch!=null){
            doctorSwitch.setAlertPatientSwitch(state);
        }else{
            DoctorSwitch dw = new DoctorSwitch();
            dw.setDoctor(doctor);
            dw.setAlertPatientSwitch(state);
            dw.setCreateTime(new Date());
            doctorSwitchDao.save(dw);
        }
        return "0";
    }
    public Map<String,Object> getDoctorSwitchTrackPatient(String doctor){
        DoctorSwitch doctorSwitch = doctorSwitchDao.findByDoctor(doctor);
        Map<String,Object> rs = new HashedMap();
        if(doctorSwitch!=null){
            rs.put("alertPatientSwitch",doctorSwitch.getAlertPatientSwitch());
        }else{
            DoctorSwitch dw = new DoctorSwitch();
            dw.setDoctor(doctor);
            dw.setAlertPatientSwitch("0");
            dw.setCreateTime(new Date());
            doctorSwitchDao.save(dw);
            rs.put("alertPatientSwitch","0");
        }
        return rs;
    }
    public Map<String,Object> getTrackPatientCountTitle(Integer teamCode,String doctor,String startDate,String endDate){
        List<TrackPatient> trackPatients = trackPatientDao.findByDoctorCodeAndTeamCodeAndDel(doctor,teamCode,"1");
        Map<String,Object> rs = new HashedMap();
        rs.put("trackPatientCount",trackPatients.size());
        String sql = "SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wlyy_track_patient t " +
                " WHERE " +
                " t.del='1' " +
                " AND t.doctor_code = '"+doctor+"' " +
                " AND t.team_code = "+teamCode +
                " AND t.create_time >= '"+startDate+" 00:00:00' " +
                " AND t.create_time <= '"+endDate+" 23:59:59'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
            Long total = (Long)list.get(0).get("total");
            rs.put("trackPatientAddCount",total);
        }else{
            rs.put("trackPatientAddCount",0);
        }
        return rs;
    }
    public  Map<String,Object> getTrackPatientServerCount(Long teamCode,String doctor,String startDate,String endDate){
        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";
        Map<String,Object> rs = new  HashedMap();
        //咨询
        rs.put("consultCount",getConsultByteam(teamCode,doctor,startDate,endDate));
        //随访
        rs.put("followupCount",getFollowByTeam(teamCode,doctor,startDate,endDate));
        //获取健康指导
        rs.put("guidanceCount",getGuidanceByTeam(teamCode,doctor,startDate,endDate));
        //获取待预约
        rs.put("reservationCount",getReservationByteam(teamCode,doctor,startDate,endDate));
        //续方审核
        rs.put("reviewedCount",getPresCount(teamCode,doctor,startDate,endDate));
        return rs;
    }
    /**
     * 获取咨询数
     *
     * @param id
     * @param startDate
     * @param endDate
     * @return
     */
    public Long getConsultByteam(Long id, String doctor,String startDate, String endDate) {
        String imDataBaseName = im_dataBase_name;
        //咨询量
        String consult_sql = "SELECT " +
                "  COUNT(1) consultCount " +
                "  FROM " +
                " wlyy_admin_team_member m JOIN(" +
                " SELECT d.id,t.create_time FROM " +
                "  " + imDataBaseName + ".Topics t, " +
                "  " + imDataBaseName + ".Participants p, " +
                "  " + imDataBaseName + ".Doctors d, " +
                "  Wlyy_Consult_Team c, " +
                "  " + imDataBaseName + ".Patients s " +
                "  WHERE " +
                "  d.id = p.participant_id " +
                " AND c.type <> 8  " +
                " AND c.consult = t.id " +
                " AND c.patient = s.id " +
                " AND p.session_id = t.session_id " +
                " AND c.admin_team_code =" + id +
                " AND t.create_time >= '" + startDate + "' " +
                " AND t.create_time <= '" + endDate + "'" +
                " AND c.patient IN(" +
                "  SELECT t.patient_code FROM wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +id+
                " )" +
                " )c ON c.id = m.doctor_code " +
                " WHERE " +
                " m.team_id = "  + id+
                " AND m.doctor_code ='"+doctor+"'" ;
        //获取咨詢數
        Map<String, Object> consultCout = jdbcTemplate.queryForMap(consult_sql);
        if (consultCout.get("consultCount") == null) {
            consultCout.put("consultCount", 0);
        }
        return (Long)consultCout.get("consultCount");
    }
    public Long getReservationByteam(Long id,String doctor, String startDate, String endDate) {
        //获取待预约
        String reservation_sql = "SELECT COUNT(1) AS reservationCount FROM wlyy_patient_reservation  w WHERE w.admin_team_code =" + id + " AND w.czrq <='" + endDate + "' AND w.czrq >='" + startDate + "' " +
                " AND w.doctor ='"+doctor+"' AND w.patient IN (SELECT t.patient_code FROM wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +id+") ";
        //获取待预约
        Map<String, Object> reservationCout = jdbcTemplate.queryForMap(reservation_sql);
        if (reservationCout.get("reservationCount") == null) {
            reservationCout.put("reservationCount", 0);
        }
        return (Long)reservationCout.get("reservationCount");
    }
    public Long getEduArticleByTeam(Long id,String doctor, String startDate, String endDate) {
        //获取健康教育
        String article_sql = "SELECT COUNT(1) AS articleCount FROM wlyy_health_edu_article_patient w WHERE  w.admin_team_code =" + id + " AND w.czrq <='" + endDate + "' AND w.czrq >='" + startDate + "'" +
                " AND w.doctor ='"+doctor+"' AND w.patient IN (SELECT t.patient_code FROM wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +id+") ";
        //获取健康教育
        Map<String, Object> articleCout = jdbcTemplate.queryForMap(article_sql);
        if (articleCout.get("articleCount") == null) {
            articleCout.put("articleCount", 0);
        }
        return (Long)articleCout.get("articleCount");
    }
    public Long getGuidanceByTeam(Long id,String doctor, String startDate, String endDate) {
        //获取健康指导
        String guidance_sql = "SELECT COUNT(1) AS guidanceCount  FROM wlyy_patient_health_guidance w WHERE w.admin_team_code =" + id + " AND w.czrq <='" + endDate + "' AND w.czrq >='" + startDate + "' " +
                " AND w.doctor ='"+doctor+"' AND w.patient IN (SELECT t.patient_code FROM wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +id+") ";
        //获取健康指导
        Map<String, Object> guidanceCout = jdbcTemplate.queryForMap(guidance_sql);
        if (guidanceCout.get("guidanceCount") == null) {
            guidanceCout.put("guidanceCount", 0);
        }
        return (Long)guidanceCout.get("guidanceCount");
    }
    public Long getFollowByTeam(Long id,String doctor, String startDate, String endDate) {
        //随访数目
        String followup_sql = "SELECT COUNT(1) AS followupCount from wlyy_followup w WHERE w.admin_team_code=" + id + " AND  w.create_time >='" + startDate + "' AND w.create_time<='" + endDate + "' " +
                " AND w.doctor_code ='"+doctor+"' AND w.patient_code IN (SELECT t.patient_code FROM wlyy_track_patient t WHERE t.del='1' AND t.doctor_code ='"+doctor+"' AND t.team_code = " +id+") ";
        //随访数目
        Map<String, Object> followupCout = jdbcTemplate.queryForMap(followup_sql);
        if (followupCout.get("followupCount") == null) {
            followupCout.put("followupCount", 0);
        }
        return (Long)followupCout.get("followupCount");
    }
    public Long getPresCount(Long id,String doctor, String startDate, String endDate){
        String sql ="SELECT " +
                " count(1) AS reviewedCount " +
                " FROM " +
                " wlyy_prescription p " +
                " JOIN wlyy_prescription_reviewed r ON r.prescription_code = p.`code` " +
                " WHERE " +
                " r.doctor = '"+doctor+"' " +
                " AND p.admin_team_id = " + id +
                " AND r.reviewed_time >= '"+startDate+"' " +
                " AND r.reviewed_time <= '"+endDate+"' " +
                " AND p.patient IN ( " +
                " SELECT t.patient_code " +
                " FROM wlyy_track_patient t " +
                " WHERE t.del='1' AND t.doctor_code ='"+doctor+"' " +
                " AND t.team_code = " +id+")";
        //审核数目
        Map<String, Object> reviewedCount = jdbcTemplate.queryForMap(sql);
        if (reviewedCount.get("reviewedCount") == null) {
            reviewedCount.put("reviewedCount", 0);
        }
        return (Long)reviewedCount.get("reviewedCount");
    }
    public Map<String,Object> getTrackPatientAimByteam(String doctor ,Long teamCode,String startDate,String endDate){
        startDate = startDate +" 00:00:00";
        endDate = endDate +" 23:59:59";
        String presSql="SELECT " +
                " COUNT(1) AS dbCount " +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   i.`user`, " +
                "   COUNT(1) AS total " +
                "  FROM " +
                "   device.wlyy_patient_health_index i " +
                "    WHERE  " +
                "   i.`user` in  " +
                "    ( " +
                "     SELECT p.patient_code AS `user` FROM wlyy_track_patient p WHERE p.del='1' AND p.doctor_code='"+doctor+"' AND p.team_code =" +teamCode+
                "    ) " +
                "  AND i.del ='1' " +
                "  AND i.type = 2  " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                "  GROUP BY " +
                "   i.`user` " +
                " ) tt " +
                " LEFT JOIN  " +
                " ( " +
                " SELECT " +
                "  i.`user`, " +
                "  COUNT(1) AS dbtotal " +
                " FROM " +
                "  device.wlyy_patient_health_index i " +
                " JOIN wlyy_patient_aim_blood_pressure p ON p.patientcode = i.`user` " +
                " WHERE " +
                "  i.`user` in  " +
                "    ( " +
                "     SELECT p.patient_code AS `user` FROM wlyy_track_patient p WHERE p.del='1' AND p.doctor_code='"+doctor+"' AND p.team_code =" +teamCode+
                "    ) " +
                "  AND i.value1 <= cast(p.sbp as SIGNED INTEGER) " +
                "  AND i.value1 >= cast(p.sbp_min as SIGNED INTEGER) "+
                "  AND i.del ='1'  " +
                "  AND i.type = 2   " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) dbt ON tt.`user`=dbt.`user` " +
                " WHERE dbt.dbtotal/tt.total > 0.7";
        Map<String,Object> rs = new HashedMap();
        List<Map<String,Object>> presTotal = jdbcTemplate.queryForList(presSql);
        if(presTotal!=null&&presTotal.size()>0){
            rs.put("dbPresCount",presTotal.get(0).get("dbCount"));
        }else {
            rs.put("dbPresCount",0);
        }
        //血糖达标数量
        List<Map<String,Object>> cqXT = jdbcTemplate.queryForList(getXTAimSQL( doctor , teamCode, startDate, endDate));
        Long dbSuggerCount;
        if(cqXT!=null&&cqXT.size()>0){
            dbSuggerCount = (Long)cqXT.get(0).get("total");
        }else{
            dbSuggerCount = 0L;
        }
        rs.put("dbSuggerCount",dbSuggerCount);
        return rs;
    }
    /**
     *
     * @param doctor
     * @param teamCode
     * @param startDate
     * @param endDate
     * @param state 0 餐前,1餐_后
     * @return
     */
    public String getXTSql(String doctor ,Long teamCode,String startDate,String endDate,String state){
        String value1 ="cast(p.fbg as SIGNED INTEGER)";
        String value1min ="cast(p.fbg_min as SIGNED INTEGER)";
        String value2 ="1,3,5,7";
        if("1".equals(state)){
            value2 = "2,4,6";
            value1 = "cast(p.hpg AS SIGNED INTEGER)";
            value1min ="cast(p.hpg_min AS SIGNED INTEGER)";
        }
        //餐前血糖达标数
        String xtSql = "SELECT " +
                " tt.`user` " +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   i.`user`, " +
                "   COUNT(1) AS total " +
                "  FROM " +
                "   device.wlyy_patient_health_index i " +
                "    WHERE  " +
                "   i.`user` in  " +
                "    ( " +
                "     SELECT p.patient_code AS `user` FROM wlyy_track_patient p WHERE p.del='1' AND p.doctor_code='"+doctor+"' AND p.team_code =" +teamCode+
                "    ) " +
                "  AND i.del ='1' " +
                "  AND i.value2 in("+value2+") " +
                "  AND i.type = 1  " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                "  GROUP BY " +
                "   i.`user` " +
                " ) tt " +
                " LEFT JOIN  " +
                " ( " +
                " SELECT " +
                "  i.`user`, " +
                "  COUNT(1) AS dbtotal " +
                " FROM " +
                "  device.wlyy_patient_health_index i " +
                " JOIN wlyy_patient_aim_blood_sugger p ON p.patientcode = i.`user` " +
                " WHERE " +
                "  i.`user` in  " +
                "    ( " +
                "     SELECT p.patient_code AS `user` FROM wlyy_track_patient p WHERE p.del='1' AND p.doctor_code='"+doctor+"' AND p.team_code =" +teamCode+
                "    ) " +
                "  AND " +
                "  i.value1 <= " +value1+
                "  AND  " +
                "  i.value1 >= " +value1min +
                "  AND i.value2 in("+value2+") " +
                "  AND i.del ='1'  " +
                "  AND i.type = 1   " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) dbt ON tt.`user`=dbt.`user` " +
                " WHERE dbt.dbtotal/tt.total > 0.7";
        return xtSql;
    }
    public String getXTAimSQL(String doctor ,Long teamCode,String startDate,String endDate){
        String sql = "SELECT " +
                " COUNT(1) total " +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   i.`user`, " +
                "   COUNT(1) AS total " +
                "  FROM " +
                "   device.wlyy_patient_health_index i " +
                "  WHERE " +
                "   i.`user` IN ( " +
                "    SELECT " +
                "     p.patient_code AS `user` " +
                "    FROM " +
                "     wlyy_track_patient p " +
                "    WHERE " +
                "     p.del = '1' " +
                "    AND p.doctor_code = '"+doctor+"' " +
                "    AND p.team_code = " +teamCode+
                "   ) " +
                "  AND i.del = '1' " +
                "  AND i.type = 1 " +
                "  AND i.record_date >= '"+startDate+"' " +
                "  AND i.record_date <= '"+endDate+"' " +
                "  GROUP BY " +
                "   i.`user` " +
                " ) tt " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  i.`user`, " +
                "  COUNT(1) AS dbtotal " +
                " FROM " +
                "  device.wlyy_patient_health_index i " +
                " JOIN wlyy_patient_aim_blood_sugger p ON p.patientcode = i.`user` " +
                " WHERE " +
                "  i.`user` IN ( " +
                "   SELECT " +
                "    p.patient_code AS `user` " +
                "   FROM " +
                "    wlyy_track_patient p " +
                "   WHERE " +
                "    p.del = '1' " +
                "   AND p.doctor_code = '"+doctor+"' " +
                "   AND p.team_code = " +teamCode+
                "  ) " +
                " AND i.value1 <= cast(p.fbg AS SIGNED INTEGER) " +
                " AND i.value1 >= cast(p.fbg_min AS SIGNED INTEGER) " +
                " AND i.value2 IN (1,3,5,7)  " +
                " AND i.del = '1' " +
                " AND i.type = 1 " +
                " AND i.record_date >= '"+startDate+"' " +
                " AND i.record_date <= '"+endDate+"' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) dbt ON tt.`user` = dbt.`user`  " +
                " LEFT JOIN ( " +
                " SELECT " +
                "  i.`user`, " +
                "  COUNT(1) AS dbtotal " +
                " FROM " +
                "  device.wlyy_patient_health_index i " +
                " JOIN wlyy_patient_aim_blood_sugger p ON p.patientcode = i.`user` " +
                " WHERE " +
                "  i.`user` IN ( " +
                "   SELECT " +
                "    p.patient_code AS `user` " +
                "   FROM " +
                "    wlyy_track_patient p " +
                "   WHERE " +
                "    p.del = '1' " +
                "   AND p.doctor_code = '"+doctor+"' " +
                "   AND p.team_code =  " +teamCode +
                "  ) " +
                " AND i.value1 <= cast(p.hpg AS SIGNED INTEGER) " +
                " AND i.value1 >= cast(p.hpg_min AS SIGNED INTEGER) " +
                " AND i.value2 IN (2,4,6)  " +
                " AND i.del = '1' " +
                " AND i.type = 1 " +
                " AND i.record_date >= '"+startDate+"' " +
                " AND i.record_date <= '"+endDate+"' " +
                " GROUP BY " +
                "  i.`user` " +
                " ) cht ON tt.`user` = cht.`user` " +
                " WHERE " +
                " (IFNULL(dbt.dbtotal,0)+IFNULL(cht.dbtotal,0))/ tt.total > 0.7";
        return sql;
    }
    public Map<String,Object> getDeviceStateByTeam(String doctor ,Long teamCode){
        String sql ="SELECT " +
                " COUNT(1) AS total " +
                " FROM " +
                " wlyy_patient_device d JOIN  " +
                " wlyy_track_patient t ON t.patient_code = d.`user` " +
                " WHERE  " +
                " t.del='1' " +
                " AND d.category_code = ? " +
                " AND t.doctor_code = '"+doctor+"' " +
                " AND t.team_code = "+teamCode;
        Map<String,Object> rs = new HashedMap();
        //血糖仪
        List<Map<String,Object>> xt = jdbcTemplate.queryForList(sql,new Object[]{"1"});
        if(xt!=null&&xt.size()>0){
            rs.put("suggerDevCount",xt.get(0).get("total"));
        }else{
            rs.put("suggerDevCount",0);
        }
        //血压计
        List<Map<String,Object>> xh = jdbcTemplate.queryForList(sql,new Object[]{"2"});
        if(xh!=null&&xh.size()>0){
            rs.put("presDevCount",xh.get(0).get("total"));
        }else{
            rs.put("presDevCount",0);
        }
        return rs;
    }
    public String setSinglePatientAim(String patient ,String suggerJson,String presJson,String sportJson ){
        PatientAimBloodSugger sugger = patientAimBloodSuggerDao.findByPatientcode(patient);
        if(sugger!=null){
            patientAimBloodSuggerDao.delete(sugger);
        }
        PatientAimBloodPressure pres = patientAimBloodPressureDao.findByPatientcode(patient);
        if(pres!=null){
            patientAimBloodPressureDao.delete(pres);
        }
        PatientAimSports sport = patientAimSportsDao.getPatientAimSportsByPatientCode(patient);
        if(sport!=null){
            patientAimSportsDao.delete(sport);
        }
        net.sf.json.JSONObject sj  = net.sf.json.JSONObject.fromObject(suggerJson);
        net.sf.json.JSONObject pj  = net.sf.json.JSONObject.fromObject(presJson);
        net.sf.json.JSONObject spj  = net.sf.json.JSONObject.fromObject(sportJson);
        PatientAimBloodSugger patientAimBloodSugger = (PatientAimBloodSugger)net.sf.json.JSONObject.toBean(sj,PatientAimBloodSugger.class);
        PatientAimBloodPressure patientAimBloodPressure = (PatientAimBloodPressure)net.sf.json.JSONObject.toBean(pj,PatientAimBloodPressure.class);
        PatientAimSports patientAimSports = (PatientAimSports)net.sf.json.JSONObject.toBean(spj,PatientAimSports.class);
        patientAimBloodSugger.setPatientcode(patient);
        patientAimBloodSugger.setCode(getCode());
        patientAimBloodSugger.setCreateTime(new Date());
        patientAimBloodSuggerDao.save(patientAimBloodSugger);
        patientAimBloodPressure.setPatientcode(patient);
        patientAimBloodPressure.setCode(getCode());
        patientAimBloodPressure.setCreateTime(new Date());
        patientAimBloodPressureDao.save(patientAimBloodPressure);
        patientAimSports.setPatientcode(patient);
        patientAimSports.setCode(getCode());
        patientAimSports.setCreateTime(new Date());
        patientAimSportsDao.save(patientAimSports);
        return "1";
    }
    public String setPatientAim(String patients ,String suggerJson,String presJson,String sportJson){
        if(StringUtils.isNotBlank(patients)){
            String[] patient = patients.split(",");
            for(String p : patient){
                PatientAimBloodSugger sugger = patientAimBloodSuggerDao.findByPatientcode(p);
                if(sugger!=null){
                    patientAimBloodSuggerDao.delete(sugger);
                }
                PatientAimBloodPressure pres = patientAimBloodPressureDao.findByPatientcode(p);
                if(pres!=null){
                    patientAimBloodPressureDao.delete(pres);
                }
                PatientAimSports sport = patientAimSportsDao.getPatientAimSportsByPatientCode(p);
                if(sport!=null){
                    patientAimSportsDao.delete(sport);
                }
                net.sf.json.JSONObject sj  = net.sf.json.JSONObject.fromObject(suggerJson);
                net.sf.json.JSONObject pj  = net.sf.json.JSONObject.fromObject(presJson);
                net.sf.json.JSONObject spj  = net.sf.json.JSONObject.fromObject(sportJson);
                PatientAimBloodSugger patientAimBloodSugger = (PatientAimBloodSugger)net.sf.json.JSONObject.toBean(sj,PatientAimBloodSugger.class);
                PatientAimBloodPressure patientAimBloodPressure = (PatientAimBloodPressure)net.sf.json.JSONObject.toBean(pj,PatientAimBloodPressure.class);
                PatientAimSports patientAimSports = (PatientAimSports)net.sf.json.JSONObject.toBean(spj,PatientAimSports.class);
                patientAimBloodSugger.setPatientcode(p);
                patientAimBloodSugger.setCode(getCode());
                patientAimBloodSugger.setCreateTime(new Date());
                patientAimBloodSuggerDao.save(patientAimBloodSugger);
                patientAimBloodPressure.setPatientcode(p);
                patientAimBloodPressure.setCode(getCode());
                patientAimBloodPressure.setCreateTime(new Date());
                patientAimBloodPressureDao.save(patientAimBloodPressure);
                patientAimSports.setPatientcode(p);
                patientAimSports.setCode(getCode());
                patientAimSports.setCreateTime(new Date());
                patientAimSportsDao.save(patientAimSports);
            }
        }
        return "0";
    }
    public Map<String,Object> getPatientScheme(String patient,String type){
        Map<String,Object> rs = new HashedMap();
        String sql =null;
        if("1".equals(type)){
            sql =  "SELECT " +
                    " s.* " +
                    " FROM " +
                    " wlyy_patient_scheme_list l " +
                    " JOIN wlyy_doctor_scheme_blood_sugger s ON s. CODE = l.schemecode " +
                    " WHERE " +
                    " l.type = 1  " +
                    " AND l.patientcode='"+patient+"'" +
                    " ORDER BY s.dayofweek ASC";
        }else{
            sql =  "SELECT " +
                    " s.* " +
                    " FROM " +
                    " wlyy_patient_scheme_list l " +
                    " JOIN wlyy_doctor_scheme_blood_pressure s ON s. CODE = l.schemecode " +
                    " WHERE " +
                    " l.type = 2 " +
                    " AND l.patientcode='"+patient+"'" +
                    " ORDER BY s.dayofweek ASC";
        }
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        if(list!=null&&list.size()>0){
            rs.put("code",list.get(0).get("code"));
            rs.put("name",list.get(0).get("name"));
            rs.put("content",list.get(0).get("content"));
            rs.put("list",list);
        }
        return rs;
    }
    public List<Map<String,Object>> getTrackPatientIndexCountList(String doctor,Integer teamCode,String type,String startDate,String endDate,String keyword,Integer page,Integer size){
        startDate = startDate+" 00:00:00";
        endDate = endDate + " 23:59:59";
        // /血糖查询
        if("1".equals(type)){
            List<Map<String,Object>> list = jdbcTemplate.queryForList(getXTTrackPatientIndexCountListSql(doctor,teamCode,startDate,endDate,keyword, page, size));
            return list;
        }else{
            List<Map<String,Object>> list = jdbcTemplate.queryForList(getXYTrackPatientIndexCountListSql(doctor,teamCode,startDate,endDate,keyword, page, size));
            return list;
        }
    }
    public String getXTTrackPatientIndexCountListSql(String doctor,Integer teamCode,String startDate,String endDate,String keyword,Integer page,Integer size){
        String sql = "SELECT  " +
                " tt1.patient_code, " +
                " tt1.highCount, " +
                " tt2.lowCount, " +
                " tt3.stdCount, " +
                " p.`name`, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.photo, " +
                " p.idcard," +
                " p.sex " +
                " FROM " +
                " " +
                "( " +
                " " +
                " SELECT " +
                " t1.patient_code, " +
                " t2.total + t1.total AS highCount " +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   t.patient_code, " +
                "   IFNULL(pid.total, 0) AS total " +
                "  FROM " +
                "   ( " +
                "    SELECT " +
                "     tp.patient_code " +
                "    FROM " +
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "    AND tp.doctor_code = '"+doctor+"' " +
                "    AND tp.team_code = " +teamCode+
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
                "    i. USER, " +
                "    COUNT(1) AS total " +
                "   FROM " +
                "    device.wlyy_patient_health_index i " +
                "   WHERE " +
                "    i.del = '1' " +
                "   AND i.type = 1 " +
                "   AND i.value2 IN (2, 4, 6) " +
                "   AND i.value1 > 11.1 " +
                "   AND i.record_date >='"+startDate+"'" +
                "   AND i.record_date <='"+endDate+"'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
                " ) t1  " +
                " " +
                " JOIN  " +
                " " +
                " ( " +
                " SELECT " +
                "  t.patient_code, " +
                "  IFNULL(pid.total, 0) AS total " +
                " FROM " +
                "  ( " +
                "   SELECT " +
                "    tp.patient_code " +
                "   FROM " +
                "    wlyy_track_patient tp " +
                "   WHERE " +
                "    tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code =" +teamCode+
                "  ) t " +
                " LEFT JOIN ( " +
                "  SELECT " +
                "   i. USER, " +
                "   COUNT(1) AS total " +
                "  FROM " +
                "   device.wlyy_patient_health_index i " +
                "  WHERE " +
                "   i.del = '1' " +
                "  AND i.type = 1 " +
                "  AND i.value2 IN (1, 3, 5, 7) " +
                "  AND i.value1 > 7 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "  GROUP BY " +
                "   i. USER " +
                " ) pid ON pid. USER = t.patient_code " +
                ") t2 ON t1.patient_code = t2.patient_code " +
                " " +
                ") tt1  " +
                " " +
                " JOIN  " +
                " " +
                "( " +
                "  SELECT " +
                " t1.patient_code, " +
                " t1.total + t2.total AS lowCount " +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   t.patient_code, " +
                "   IFNULL(pid.total, 0) AS total " +
                "  FROM " +
                "   ( " +
                "    SELECT " +
                "     tp.patient_code " +
                "    FROM " +
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "    AND tp.doctor_code = '"+doctor+"' " +
                "    AND tp.team_code =  " +teamCode+
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
                "    i. USER, " +
                "    COUNT(1) AS total " +
                "   FROM " +
                "    device.wlyy_patient_health_index i " +
                "   WHERE " +
                "    i.del = '1' " +
                "   AND i.type = 1 " +
                "   AND i.value2 IN (2, 4, 6) " +
                "   AND i.value1 < 4 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
                " ) t1  " +
                " " +
                " JOIN  " +
                " " +
                "( " +
                " SELECT " +
                "  t.patient_code, " +
                "  IFNULL(pid.total, 0) AS total " +
                " FROM " +
                "  ( " +
                "   SELECT " +
                "    tp.patient_code " +
                "   FROM " +
                "    wlyy_track_patient tp " +
                "   WHERE " +
                "    tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code =  " +teamCode+
                "  ) t " +
                " LEFT JOIN ( " +
                "  SELECT " +
                "   i. USER, " +
                "   COUNT(1) AS total " +
                "  FROM " +
                "   device.wlyy_patient_health_index i " +
                "  WHERE " +
                "   i.del = '1' " +
                "  AND i.type = 1 " +
                "  AND i.value2 IN (1, 3, 5, 7) " +
                "  AND i.value1 < 4 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "  GROUP BY " +
                "   i. USER " +
                " ) pid ON pid. USER = t.patient_code " +
                ") t2 ON t1.patient_code = t2.patient_code " +
                " " +
                ") tt2 ON tt1.patient_code = tt2.patient_code  " +
                " " +
                "JOIN  " +
                " " +
                "( " +
                "   " +
                " SELECT " +
                " t1.patient_code, " +
                " t1.total + t2.total AS stdCount " +
                " FROM " +
                " ( " +
                "  SELECT " +
                "   t.patient_code, " +
                "   IFNULL(pid.total, 0) AS total " +
                "  FROM " +
                "   ( " +
                "    SELECT " +
                "     tp.patient_code " +
                "    FROM " +
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "    AND tp.doctor_code = '"+doctor+"' " +
                "    AND tp.team_code = " +teamCode +
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
                "    i. USER, " +
                "    COUNT(1) AS total " +
                "   FROM " +
                "    device.wlyy_patient_health_index i " +
                "   WHERE " +
                "    i.del = '1' " +
                "   AND i.type = 1 " +
                "   AND i.value2 IN (2, 4, 6) " +
                "   AND i.value1 >= 4 " +
                "   AND i.value1 <= 11.1 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
                " ) t1  " +
                " " +
                " JOIN  " +
                " " +
                " ( " +
                " SELECT " +
                "  t.patient_code, " +
                "  IFNULL(pid.total, 0) AS total " +
                " FROM " +
                "  ( " +
                "   SELECT " +
                "    tp.patient_code " +
                "   FROM " +
                "    wlyy_track_patient tp " +
                "   WHERE " +
                "    tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "  ) t " +
                " LEFT JOIN ( " +
                "  SELECT " +
                "   i. USER, " +
                "   COUNT(1) AS total " +
                "  FROM " +
                "   device.wlyy_patient_health_index i " +
                "  WHERE " +
                "   i.del = '1' " +
                "  AND i.type = 1 " +
                "  AND i.value2 IN (1, 3, 5, 7) " +
                "  AND i.value1 >= 4 " +
                "  AND i.value1 <= 7 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "  GROUP BY " +
                "   i. USER " +
                " ) pid ON pid. USER = t.patient_code " +
                " ) t2 ON t1.patient_code = t2.patient_code " +
                " " +
                " )tt3 ON tt1.patient_code = tt3.patient_code " +
                " " +
                " JOIN wlyy_patient p On tt1.patient_code =p.code";
        if(StringUtils.isNotBlank(keyword)){
            BasePatientDO p = patientDao.findByIdcard(keyword);
            if(p!=null){
                sql =sql + " WHERE p.idcard ='"+keyword+"'";
            }else{
                sql =sql + " WHERE p.name like '%"+keyword+"%' ";
            }
        }
        sql += " ORDER BY highCount DESC LIMIT "+(page-1)*size+","+size;
        return sql ;
    }
    public String getXYTrackPatientIndexCountListSql(String doctor,Integer teamCode,String startDate,String endDate,String keyword,Integer page,Integer size){
        String sql ="SELECT  " +
                " t1.patient_code, " +
                " t1.total AS lowCount, " +
                " t2.total AS stdCount, " +
                " t3.total AS highCount, " +
                " p.`name`, " +
                " IFNULL(year( from_days( datediff( now(), p.birthday))),'未知') age, " +
                " p.photo, " +
                " p.sex" +
                " FROM " +
                " " +
                " ( " +
                "  SELECT " +
                "   t.patient_code, " +
                "   IFNULL(pid.total, 0) AS total " +
                "  FROM " +
                "   ( " +
                "    SELECT " +
                "     tp.patient_code " +
                "    FROM " +
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
                "    i. USER, " +
                "    COUNT(1) AS total " +
                "   FROM " +
                "    device.wlyy_patient_health_index i " +
                "   WHERE " +
                "    i.del = '1' " +
                "   AND i.type = 2 " +
                "   AND i.value1 < 90 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
                " ) t1  " +
                " JOIN " +
                " ( " +
                "  SELECT " +
                "   t.patient_code, " +
                "   IFNULL(pid.total, 0) AS total " +
                "  FROM " +
                "   ( " +
                "    SELECT " +
                "     tp.patient_code " +
                "    FROM " +
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
                "    i. USER, " +
                "    COUNT(1) AS total " +
                "   FROM " +
                "    device.wlyy_patient_health_index i " +
                "   WHERE " +
                "    i.del = '1' " +
                "   AND i.type = 2 " +
                "   AND i.value1 >= 90 " +
                "   AND i.value1 <=139 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
                "  " +
                " ) t2 ON t1.patient_code = t2.patient_code " +
                " JOIN  " +
                " ( " +
                "  SELECT " +
                "   t.patient_code, " +
                "   IFNULL(pid.total, 0) AS total " +
                "  FROM " +
                "   ( " +
                "    SELECT " +
                "     tp.patient_code " +
                "    FROM " +
                "     wlyy_track_patient tp " +
                "    WHERE " +
                "     tp.del = '1' " +
                "   AND tp.doctor_code = '"+doctor+"' " +
                "   AND tp.team_code = " +teamCode+
                "   ) t " +
                "  LEFT JOIN ( " +
                "   SELECT " +
                "    i. USER, " +
                "    COUNT(1) AS total " +
                "   FROM " +
                "    device.wlyy_patient_health_index i " +
                "   WHERE " +
                "    i.del = '1' " +
                "   AND i.type = 2 " +
                "   AND i.value1 >139 " +
                "  AND i.record_date >='"+startDate+"'" +
                "  AND i.record_date <='"+endDate+"'" +
                "   GROUP BY " +
                "    i. USER " +
                "  ) pid ON pid. USER = t.patient_code " +
                " ) t3 ON t1.patient_code = t3.patient_code " +
                " JOIN wlyy_patient p ON t1.patient_code = p.`code`";
        if(StringUtils.isNotBlank(keyword)){
            BasePatientDO p = patientDao.findByIdcard(keyword);
            if(p!=null){
                sql =sql + " WHERE p.idcard ='"+keyword+"'";
            }else{
                sql =sql + " WHERE p.name like '%"+keyword+"%' ";
            }
        }
        sql += " ORDER BY highCount DESC LIMIT "+(page-1)*size+","+size;
        return sql;
    }
    public Map<String,Object> getDefaultScheme(String type){
        Map<String,Object> rs = new HashedMap();
        //1. 血糖2.血压
        if("1".equals(type)){
            String sql = " SELECT p.* FROM wlyy_doctor_scheme_blood_sugger p where p.code='default' and p.del=0 order by p.doctorcode,p.code desc,p.dayofweek asc";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            rs.put("code","default");
            rs.put("name",list.get(0).get("name"));
            rs.put("content",list.get(0).get("content"));
            rs.put("list",list);
        }else{
            String sql = " SELECT p.* FROM wlyy_doctor_scheme_blood_pressure p where p.code='default' and p.del=0 order by p.doctorcode,p.code desc,p.dayofweek asc";
            List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
            rs.put("code","default");
            rs.put("name",list.get(0).get("name"));
            rs.put("content",list.get(0).get("content"));
            rs.put("list",list);
        }
        return rs;
    }
    @Transactional
    public String setPatientDefaultScheme(String patient,String type){
        PatientSchemeList pl = new PatientSchemeList();
        if("1".equals(type)){
            List<PatientSchemeList> list = patientSchemeListDao.findByPatientcodeAndSchemecodeAndType(patient,"default",1);
            if(list!=null&&list.size()>0){
                return "-1";
            }
            pl.setType(1);
        }else{
            List<PatientSchemeList> list = patientSchemeListDao.findByPatientcodeAndSchemecodeAndType(patient,"default",2);
            if(list!=null&&list.size()>0){
                return "-1";
            }
            pl.setType(2);
        }
        pl.setPatientcode(patient);
        pl.setCode(getCode());
        pl.setSchemecode("default");
        pl.setCreateTime(new Date());
        patientSchemeListDao.save(pl);
        return "0";
    }
    /**
     * 查看指定医生是否开启分派订单功能
     * @param doctor
     * @return
     */
    public String findDispatchStatusByDoctor(String doctor) {
        DoctorSwitch doctorSwitch = doctorSwitchDao.findByDoctor(doctor);
        if (null == doctorSwitch) {
            return "0";
        }
        return StringUtils.isNotEmpty(doctorSwitch.getDispatchOrderSwitch()) ? doctorSwitch.getDispatchOrderSwitch() : "0";
    }
    /**
     * 修改指定医生的分派订单开关,不存在该医生的开关,则创建
     * @param doctor
     * @param dispatchOrderStatus
     */
    public void updateDispatchStatusByDoctor(String doctor, String dispatchOrderStatus) {
        DoctorSwitch doctorSwitch =doctorSwitchDao.findByDoctor(doctor);
        if (null != doctorSwitch) {
            doctorSwitch.setDispatchOrderSwitch(dispatchOrderStatus);
            doctorSwitch.setUpdateTime(new Date());
        } else {
            doctorSwitch = new DoctorSwitch();
            doctorSwitch.setDoctor(doctor);
            doctorSwitch.setDispatchOrderSwitch(dispatchOrderStatus);
            doctorSwitch.setCreateTime(new Date());
        }
        doctorSwitchDao.save(doctorSwitch);
    }
    public JSONObject patientsByDoctorAndLabelCode(String labelCode, String doctorCode){//1,2改变。
        StringBuilder sqlLabelStr = new StringBuilder();
        sqlLabelStr.append(" sp.label in ('").append(labelCode.replace(",","','")).append("') ");
        List<PatientVO> patients = new ArrayList<>();
        String patientsql = "select * from (select p.code,p.standard_status,p.disease_condition,group_concat(DISTINCT sp.label order by sp.label asc ) as disease from wlyy_patient p " +
                "  LEFT JOIN wlyy_sign_family s on s.patient = p.code " +
                "  RIGHT JOIN wlyy_sign_patient_label_info sp on sp.patient = p.code and sp.label_type = 3 and "+sqlLabelStr.toString()+" and sp.status =1" +
                " WHERE s.status > 0 and (s.doctor = '"+doctorCode+"' or s.doctor_health ='"+doctorCode+"') GROUP BY p.code " +
                "order by sp.label asc)tmp where tmp.disease='"+labelCode+"'";
        patients= jdbcTemplate.query(patientsql,new BeanPropertyRowMapper(PatientVO.class));
        JSONObject result = new JSONObject();
        //绿标居民
        List<PatientVO> green_patients = new ArrayList<>();
        //黄标居民
        List<PatientVO> yellow_patients = new ArrayList<>();
        //红标居民
        List<PatientVO> red_patients = new ArrayList<>();
        if(!patients.isEmpty()){
            for (PatientVO patient : patients) {
                //获取居民颜色标签
                if(patient.getDiseaseCondition() != null){
                    switch (patient.getDiseaseCondition()){
                        case 0:
                            green_patients.add(patient);
                            break;
                        case 1:
                            yellow_patients.add(patient);
                            break;
                        case 2:
                            red_patients.add(patient);
                            break;
                    }
                }
            }
        }
        result.put("greencount",green_patients.size());
        result.put("yellowcount",yellow_patients.size());
        result.put("redcount",red_patients.size());
        // 重点关注居民
        List<TrackPatient> list = trackPatientDao.findByDoctorCodeAndDel(doctorCode,"1");
        if(list!=null&&list.size()>0){
            result.put("trackPatientCount",list.size());
        }else{
            result.put("trackPatientCount",0);
        }
        return result;
    }
    public String getCode() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

+ 14 - 0
business/base-service/src/main/java/com/yihu/jw/scheme/DoctorSwitchDao.java

@ -0,0 +1,14 @@
package com.yihu.jw.scheme;
import com.yihu.jw.entity.scheme.DoctorSwitch;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/1/5.
 */
public interface DoctorSwitchDao extends PagingAndSortingRepository<DoctorSwitch, Long>, JpaSpecificationExecutor<DoctorSwitch> {
    public DoctorSwitch findByDoctor(String doctor);
}

+ 31 - 0
business/base-service/src/main/java/com/yihu/jw/scheme/DoctoreSchemeBloodPressureDao.java

@ -0,0 +1,31 @@
package com.yihu.jw.scheme;
import com.yihu.jw.entity.scheme.DoctorSchemeBloodPressure;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 血压监测方案底层相关方法
 * @author huangwenjie
 * @date 2017/9/13 20:24
 */
public interface DoctoreSchemeBloodPressureDao extends
        PagingAndSortingRepository<DoctorSchemeBloodPressure, Long>,
        JpaSpecificationExecutor<DoctorSchemeBloodPressure> {
    @Query(value =" select * from wlyy_doctor_scheme_blood_pressure where (doctorcode=?1 or code = 'default') and del != 1 ORDER BY create_time desc,code,dayofweek asc",nativeQuery = true)
    List<DoctorSchemeBloodPressure> getListByDoctorcode(String doctorCode);
    @Query(" from DoctorSchemeBloodPressure p where p.code=?1 and p.del != 1 order by p.doctorcode,p.code desc,p.dayofweek asc")
    List<DoctorSchemeBloodPressure> findByCode(String code);
    @Modifying
    @Query("update DoctorSchemeBloodPressure set del=?1 where doctorcode=?2 and code=?3")
    void updateDelStatus(int del, String doctorcode, String schemecode);
}

+ 33 - 0
business/base-service/src/main/java/com/yihu/jw/scheme/DoctrorSchemeBloodSuggerDao.java

@ -0,0 +1,33 @@
package com.yihu.jw.scheme;
import com.yihu.jw.entity.scheme.DoctorSchemeBloodSugger;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.List;
/**
 * 医生血糖监测方案底层相关方法
 * @author huangwenjie
 * @date 2017/9/13 20:08
 */
public interface DoctrorSchemeBloodSuggerDao extends
        PagingAndSortingRepository<DoctorSchemeBloodSugger, Long>,
        JpaSpecificationExecutor<DoctorSchemeBloodSugger> {
    @Query(value =" select * from wlyy_doctor_scheme_blood_sugger where (doctorcode=?1 or code = 'default') and del != 1 ORDER BY create_time desc,code,dayofweek asc",nativeQuery = true)
    List<DoctorSchemeBloodSugger> getListByDoctorcode(String doctorCode);
    @Query(" from DoctorSchemeBloodSugger p where p.code=?1 and p.del != 1 order by p.doctorcode,p.code desc,p.dayofweek asc")
    List<DoctorSchemeBloodSugger> findByCode(String code);
    @Modifying
    @Query("update DoctorSchemeBloodSugger set del=?1 where doctorcode=?2 and code=?3")
    void updateDelStatus(int del, String doctorcode, String schemecode);
}

+ 30 - 0
business/base-service/src/main/java/com/yihu/jw/scheme/PatientSchemeListDao.java

@ -0,0 +1,30 @@
package com.yihu.jw.scheme;
import com.yihu.jw.entity.scheme.PatientSchemeList;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * 监测方案关联关系表
 * @author huangwenjie
 * @date 2017/9/13 23:21
 */
public interface PatientSchemeListDao extends
        PagingAndSortingRepository<PatientSchemeList, Long>,
        JpaSpecificationExecutor<PatientSchemeList> {
    @Modifying
    @Query("delete PatientSchemeList where patientcode=?1 and type=?2")
    void delByPatientCode(String patientcode, int i);
    List<PatientSchemeList> findByPatientcodeAndSchemecodeAndType(String patientcode, String schemecode, Integer type);
    List<PatientSchemeList> findBySchemecode(String schemecode);
}

+ 19 - 0
business/base-service/src/main/java/com/yihu/jw/scheme/TrackPatientDao.java

@ -0,0 +1,19 @@
package com.yihu.jw.scheme;
import com.yihu.jw.entity.scheme.TrackPatient;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2018/1/4.
 */
public interface TrackPatientDao extends PagingAndSortingRepository<TrackPatient, String>, JpaSpecificationExecutor<TrackPatient> {
    public TrackPatient findByDoctorCodeAndPatientCode(String doctorCode, String patientCode);
    public List<TrackPatient> findByDoctorCodeAndTeamCodeAndDel(String doctorCode, Integer teamCode, String del);
    List<TrackPatient> findByDoctorCodeAndDel(String doctorCode, String del);
}

+ 9 - 0
business/es-service/src/main/java/com/yihu/jw/es/service/StatisticsEsService.java

@ -7898,4 +7898,13 @@ public class StatisticsEsService {
        }
        return resultMap;
    }
    public Map<String, Object> getChronicDiseaseData() {
        String param = "";
        JSONObject re = wlyyHttpService.sendWlyyMesGet("getChronicDiseaseData", param);
        System.out.println("re==>" + JSON.toJSONString(re));
        System.out.println(JSON.toJSONString(re));
        return re;
    }
}

File diff suppressed because it is too large
+ 45 - 0
common/common-entity/src/db/2024.sql


+ 44 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/care/device/DeviceHealthyInfoMapping.java

@ -0,0 +1,44 @@
package com.yihu.jw.entity.care.device;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * @author yeshijie on 2018/1/12.
 */
@Entity
@Table(name = "wlyy_device_healthy_info_mapping")
public class DeviceHealthyInfoMapping extends IdEntity {
    private Long indexId;//如果和id不一致,那是旧体征信息表id
    private String rid;//es的rowkey
    private Date createTime;//创建时间
    public Long getIndexId() {
        return indexId;
    }
    public void setIndexId(Long indexId) {
        this.indexId = indexId;
    }
    public String getRid() {
        return rid;
    }
    public void setRid(String rid) {
        this.rid = rid;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 223 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/DoctorSchemeBloodPressure.java

@ -0,0 +1,223 @@
package com.yihu.jw.entity.scheme;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Time;
import java.sql.Timestamp;
/**
 * 医生监测方案-血压
 * @author huangwenjie
 * @date 2017/9/7 20:14
 */
@Entity
@Table(name = "wlyy_doctor_scheme_blood_pressure")
public class DoctorSchemeBloodPressure extends IdEntity {
    private String name;                //方案名称
    private String code;
    private String doctorcode;          //医生CODE
    private Short dayofweek;            //星期几
    private Short earlyMorning;
    private Time earlyMorningTime;
    private Short morning;
    private Time morningTime;
    private Short noon;
    private Time noonTime;
    private Short afterNoon;
    private Time afterNoonTime;
    private Short night;
    private Time nightTime;
    private Timestamp createTime;      //创建时间
    private Short alertTag;            //是否提醒用户
    private String content;            //方案说明
    private Integer del;          //0为正常,1为删除
    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Basic
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Basic
    @Column(name = "doctorcode")
    public String getDoctorcode() {
        return doctorcode;
    }
    public void setDoctorcode(String doctorcode) {
        this.doctorcode = doctorcode;
    }
    @Basic
    @Column(name = "dayofweek")
    public Short getDayofweek() {
        return dayofweek;
    }
    public void setDayofweek(Short dayofweek) {
        this.dayofweek = dayofweek;
    }
    @Basic
    @Column(name = "early_morning")
    public Short getEarlyMorning() {
        return earlyMorning;
    }
    public void setEarlyMorning(Short earlyMorning) {
        this.earlyMorning = earlyMorning;
    }
    @Basic
    @Column(name = "early_morning_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getEarlyMorningTime() {
        return earlyMorningTime;
    }
    public void setEarlyMorningTime(Time earlyMorningTime) {
        this.earlyMorningTime = earlyMorningTime;
    }
    @Basic
    @Column(name = "morning")
    public Short getMorning() {
        return morning;
    }
    public void setMorning(Short morning) {
        this.morning = morning;
    }
    @Basic
    @Column(name = "morning_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getMorningTime() {
        return morningTime;
    }
    public void setMorningTime(Time morningTime) {
        this.morningTime = morningTime;
    }
    @Basic
    @Column(name = "noon")
    public Short getNoon() {
        return noon;
    }
    public void setNoon(Short noon) {
        this.noon = noon;
    }
    @Basic
    @Column(name = "noon_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getNoonTime() {
        return noonTime;
    }
    public void setNoonTime(Time noonTime) {
        this.noonTime = noonTime;
    }
    @Basic
    @Column(name = "after_noon")
    public Short getAfterNoon() {
        return afterNoon;
    }
    public void setAfterNoon(Short afterNoon) {
        this.afterNoon = afterNoon;
    }
    @Basic
    @Column(name = "after_noon_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getAfterNoonTime() {
        return afterNoonTime;
    }
    public void setAfterNoonTime(Time afterNoonTime) {
        this.afterNoonTime = afterNoonTime;
    }
    @Basic
    @Column(name = "night")
    public Short getNight() {
        return night;
    }
    public void setNight(Short night) {
        this.night = night;
    }
    @Basic
    @Column(name = "night_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getNightTime() {
        return nightTime;
    }
    public void setNightTime(Time nightTime) {
        this.nightTime = nightTime;
    }
    @Basic
    @Column(name = "create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Timestamp getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }
    @Basic
    @Column(name = "alert_tag")
    public Short getAlertTag() {
        return alertTag;
    }
    public void setAlertTag(Short alertTag) {
        this.alertTag = alertTag;
    }
    @Basic
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
}

+ 269 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/DoctorSchemeBloodSugger.java

@ -0,0 +1,269 @@
package com.yihu.jw.entity.scheme;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.sql.Time;
import java.sql.Timestamp;
/**
 * 医生监测方案-血糖
 * @author huangwenjie
 * @date 2017/9/7 20:14
 */
@Entity
@Table(name = "wlyy_doctor_scheme_blood_sugger")
public class DoctorSchemeBloodSugger extends IdEntity {
    private String name;                    //方案名称
    private String code;
    private String doctorcode;
    private Short dayofweek;                //星期几:1-7,1代表周日,7代表周六
    private Short beforeBreakfast;
    private Time beforeBreakfastTime;
    private Short afterBreakfast;
    private Time afterBreakfastTime;
    private Short beforeLunch;
    private Time beforeLunchTime;
    private Short afterLunch;
    private Time afterLunchTime;
    private Short beforeDinner;
    private Time beforeDinnerTime;
    private Short afterDinner;
    private Time afterDinnerTime;
    private Short beforeSleep;
    private Time beforeSleepTime;
    private Timestamp createTime;
    private Short alertTag;                 //是否提醒用户
    private String content;                 //方案说明
    private Integer del;          //0为正常,1为删除
    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Basic
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Basic
    @Column(name = "doctorcode")
    public String getDoctorcode() {
        return doctorcode;
    }
    public void setDoctorcode(String doctorcode) {
        this.doctorcode = doctorcode;
    }
    @Basic
    @Column(name = "dayofweek")
    public Short getDayofweek() {
        return dayofweek;
    }
    public void setDayofweek(Short dayofweek) {
        this.dayofweek = dayofweek;
    }
    @Basic
    @Column(name = "before_breakfast")
    public Short getBeforeBreakfast() {
        return beforeBreakfast;
    }
    public void setBeforeBreakfast(Short beforeBreakfast) {
        this.beforeBreakfast = beforeBreakfast;
    }
    @Basic
    @Column(name = "before_breakfast_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getBeforeBreakfastTime() {
        return beforeBreakfastTime;
    }
    public void setBeforeBreakfastTime(Time beforeBreakfastTime) {
        this.beforeBreakfastTime = beforeBreakfastTime;
    }
    @Basic
    @Column(name = "after_breakfast")
    public Short getAfterBreakfast() {
        return afterBreakfast;
    }
    public void setAfterBreakfast(Short afterBreakfast) {
        this.afterBreakfast = afterBreakfast;
    }
    @Basic
    @Column(name = "after_breakfast_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getAfterBreakfastTime() {
        return afterBreakfastTime;
    }
    public void setAfterBreakfastTime(Time afterBreakfastTime) {
        this.afterBreakfastTime = afterBreakfastTime;
    }
    @Basic
    @Column(name = "before_lunch")
    public Short getBeforeLunch() {
        return beforeLunch;
    }
    public void setBeforeLunch(Short beforeLunch) {
        this.beforeLunch = beforeLunch;
    }
    @Basic
    @Column(name = "before_lunch_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getBeforeLunchTime() {
        return beforeLunchTime;
    }
    public void setBeforeLunchTime(Time beforeLunchTime) {
        this.beforeLunchTime = beforeLunchTime;
    }
    @Basic
    @Column(name = "after_lunch")
    public Short getAfterLunch() {
        return afterLunch;
    }
    public void setAfterLunch(Short afterLunch) {
        this.afterLunch = afterLunch;
    }
    @Basic
    @Column(name = "after_lunch_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getAfterLunchTime() {
        return afterLunchTime;
    }
    public void setAfterLunchTime(Time afterLunchTime) {
        this.afterLunchTime = afterLunchTime;
    }
    @Basic
    @Column(name = "before_dinner")
    public Short getBeforeDinner() {
        return beforeDinner;
    }
    public void setBeforeDinner(Short beforeDinner) {
        this.beforeDinner = beforeDinner;
    }
    @Basic
    @Column(name = "before_dinner_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getBeforeDinnerTime() {
        return beforeDinnerTime;
    }
    public void setBeforeDinnerTime(Time beforeDinnerTime) {
        this.beforeDinnerTime = beforeDinnerTime;
    }
    @Basic
    @Column(name = "after_dinner")
    public Short getAfterDinner() {
        return afterDinner;
    }
    public void setAfterDinner(Short afterDinner) {
        this.afterDinner = afterDinner;
    }
    @Basic
    @Column(name = "after_dinner_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getAfterDinnerTime() {
        return afterDinnerTime;
    }
    public void setAfterDinnerTime(Time afterDinnerTime) {
        this.afterDinnerTime = afterDinnerTime;
    }
    @Basic
    @Column(name = "before_sleep")
    public Short getBeforeSleep() {
        return beforeSleep;
    }
    public void setBeforeSleep(Short beforeSleep) {
        this.beforeSleep = beforeSleep;
    }
    @Basic
    @Column(name = "before_sleep_time")
    @JsonFormat(pattern = "HH:mm", timezone = "GMT+08:00")
    public Time getBeforeSleepTime() {
        return beforeSleepTime;
    }
    public void setBeforeSleepTime(Time beforeSleepTime) {
        this.beforeSleepTime = beforeSleepTime;
    }
    @Basic
    @Column(name = "create_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Timestamp getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }
    @Basic
    @Column(name = "alert_tag")
    public Short getAlertTag() {
        return alertTag;
    }
    public Integer getDel() {
        return del;
    }
    public void setDel(Integer del) {
        this.del = del;
    }
    public void setAlertTag(Short alertTag) {
        this.alertTag = alertTag;
    }
    @Basic
    @Column(name = "content")
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

+ 62 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/DoctorSwitch.java

@ -0,0 +1,62 @@
package com.yihu.jw.entity.scheme;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Trick on 2018/1/4.
 */
@Entity
@Table(name = "wlyy_doctor_switch")
public class DoctorSwitch extends IdEntity {
    private String doctor;//关联医生
    private String alertPatientSwitch;//0不自动跟踪居民,1自动跟踪预警居民
    private String dispatchOrderSwitch; // 0关闭分派订单功能,1开启分派订单功能
    private Date createTime;//创建时间
    private Date updateTime;//更新时间
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    public String getAlertPatientSwitch() {
        return alertPatientSwitch;
    }
    public void setAlertPatientSwitch(String alertPatientSwitch) {
        this.alertPatientSwitch = alertPatientSwitch;
    }
    public String getDispatchOrderSwitch() {
        return dispatchOrderSwitch;
    }
    public void setDispatchOrderSwitch(String dispatchOrderSwitch) {
        this.dispatchOrderSwitch = dispatchOrderSwitch;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

+ 86 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/PatientSchemeList.java

@ -0,0 +1,86 @@
package com.yihu.jw.entity.scheme;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * 患者-医生监测方案关联关系表
 * @author huangwenjie
 * @date 2017/9/7 20:07
 */
@Entity
@Table(name = "wlyy_patient_scheme_list")
public class PatientSchemeList extends IdEntity {
    private String code;
    private String patientcode;
    private String schemecode;
    private Integer type;//方案类型:1为血糖,2为血压
    private String doctorcode;
    private Date createTime;
    @Basic
    @Column(name = "code")
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @Basic
    @Column(name = "patientcode")
    public String getPatientcode() {
        return patientcode;
    }
    public void setPatientcode(String patientcode) {
        this.patientcode = patientcode;
    }
    @Basic
    @Column(name = "schemecode")
    public String getSchemecode() {
        return schemecode;
    }
    public void setSchemecode(String schemecode) {
        this.schemecode = schemecode;
    }
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    @Basic
    @Column(name = "doctorcode")
    public String getDoctorcode() {
        return doctorcode;
    }
    public void setDoctorcode(String doctorcode) {
        this.doctorcode = doctorcode;
    }
    @Basic
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

+ 108 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/TrackPatient.java

@ -0,0 +1,108 @@
package com.yihu.jw.entity.scheme;
import com.yihu.jw.entity.IdEntity;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 * Created by Trick on 2018/1/4.
 */
@Entity
@Table(name = "wlyy_track_patient")
public class TrackPatient extends IdEntity {
    private String patientCode;//关联居民code,医生的重点关注对象
    private String patientName;//患者姓名
    private String doctorCode;//所属医生
    private String doctorName;//所属医生名
    private Integer teamCode;//居民签约团队
    private String idcard;//身份证号
    private String ssc;//社保卡号
    private String del;//删除
    private Date createTime;//创建时间
    private Date updateTime;//更新时间
    public String getPatientCode() {
        return patientCode;
    }
    public void setPatientCode(String patientCode) {
        this.patientCode = patientCode;
    }
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    public String getDoctorCode() {
        return doctorCode;
    }
    public void setDoctorCode(String doctorCode) {
        this.doctorCode = doctorCode;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public Integer getTeamCode() {
        return teamCode;
    }
    public void setTeamCode(Integer teamCode) {
        this.teamCode = teamCode;
    }
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getSsc() {
        return ssc;
    }
    public void setSsc(String ssc) {
        this.ssc = ssc;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
}

+ 52 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/vo/DoctorSchemeBloodPressureVO.java

@ -0,0 +1,52 @@
package com.yihu.jw.entity.scheme.vo;
import com.yihu.jw.entity.scheme.DoctorSchemeBloodPressure;
import java.util.List;
/**
 * 医生血压监测VO类
 * @author huangwenjie
 * @date 2017/9/13 21:28
 */
public class DoctorSchemeBloodPressureVO {
    private String                          code;
    private String                          name;       //名字
    private String                          content;    //说明
    private List<DoctorSchemeBloodPressure> list;       //详情
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public List<DoctorSchemeBloodPressure> getList() {
        return list;
    }
    public void setList(List<DoctorSchemeBloodPressure> list) {
        this.list = list;
    }
}

+ 52 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/scheme/vo/DoctorSchemeBloodSuggerVO.java

@ -0,0 +1,52 @@
package com.yihu.jw.entity.scheme.vo;
import com.yihu.jw.entity.scheme.DoctorSchemeBloodSugger;
import java.util.List;
/**
 * 医生血糖VO类
 * @author huangwenjie
 * @date 2017/9/13 21:40
 */
public class DoctorSchemeBloodSuggerVO {
    private String                          code;
    private String                          name;       //名字
    private String                          content;    //说明
    private List<DoctorSchemeBloodSugger> list;       //详情
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public List<DoctorSchemeBloodSugger> getList() {
        return list;
    }
    public void setList(List<DoctorSchemeBloodSugger> list) {
        this.list = list;
    }
}

+ 212 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/conf/SystemConf.java

@ -0,0 +1,212 @@
package com.yihu.jw.restmodel.conf;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
@Component
public class SystemConf {
    // 别处登录
    public static final int LOGIN_OTHER = 999;
    // 登录超时
    public static final int LOGIN_TIMEOUT = 998;
    // 未登录
    public static final int NOT_LOGIN = 997;
    //未认证
    public static final int NOT_CERTIFIED = 996;
    //未修改默认密码
    public static final int NOT_UPD_PWD = 995;
    // 文件保存临时路径
    private static final String TEMP_PATH = "upload_temp_path";
    // 血糖餐前最小值
    public static final double HEALTH_STANDARD_ST_MIN_BEFORE = 4;
    // 血糖餐前最大值
    public static final double HEALTH_STANDARD_ST_MAX_BEFORE = 7;
    // 血糖餐后最小值
    public static final double HEALTH_STANDARD_ST_MIN_AFTER = 4;
    // 血糖餐后最大值
    public static final double HEALTH_STANDARD_ST_MAX_AFTER = 11.1;
    // 舒张压最小值
    public static final double HEALTH_STANDARD_SZY_MIN = 60;
    // 舒张压最大值
    public static final double HEALTH_STANDARD_SZY_MAX = 90;
    // 收缩压最小值
    public static final double HEALTH_STANDARD_SSY_MIN = 90;
    // 收缩压最大值
    public static final double HEALTH_STANDARD_SSY_MAX = 140;
    // 同一手机号大最短信数
    public static final int MAX_SMS_MOBILE = 5;
    // 发送短信验证码间隔(分钟)
    public static final int SMS_INTERVAL = 2;
    private static Object lock = new Object();
    // 全局系统配置信息
    private static SystemConf systemConf;
    // 系统配置文件
    private Properties systemProperties;
    //im列表
    private String imListGet;
    public static SystemConf getInstance() {
        if (systemConf == null) {
            synchronized (lock) {
                systemConf = new SystemConf();
            }
        }
        return systemConf;
    }
    /**
     * 加载系统配置文件
     *
     * @return
     */
    public Properties getSystemProperties() {
        if (systemProperties == null) {
            InputStream is = null;
            try {
                is = this.getClass().getResourceAsStream("/system.properties");
                systemProperties = new Properties();
                systemProperties.load(is);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return systemProperties;
    }
    /**
     * 短信接口地址
     */
    public String getSmsUrl() {
        return getSystemProperties().getProperty("yihu_sms_url");
    }
    /**
     * 短信企业编号
     */
    public String getSmsCode() {
        return getSystemProperties().getProperty("yihu_sms_code");
    }
    /**
     * 短信用户名
     */
    public String getSmsName() {
        return getSystemProperties().getProperty("yihu_sms_name");
    }
    /**
     * 短信登录密码
     */
    public String getSmsPassword() {
        return getSystemProperties().getProperty("yihu_sms_password");
    }
    ;
    /**
     * 挂号接口地址
     */
    public String getGuahaoUrl() {
        return getSystemProperties().getProperty("yihu_guahao_url");
    }
    /**
     * 挂号接口对接appid
     */
    public String getGuahaoAppid() {
        return getSystemProperties().getProperty("yihu_guahao_appid");
    }
    /**
     * 挂号接口对接app secret
     */
    public String getGuahaoSecret() {
        return getSystemProperties().getProperty("yihu_guahao_secret");
    }
    /**
     * 获取文件保存的临时路径
     *
     * @return
     */
    public String getTempPath() {
        return getSystemProperties().getProperty(TEMP_PATH);
    }
    /**
     * 获取图片存在地址
     *
     * @return
     */
    /**
     * 获取服务全路径
     *
     * @return
     */
    /******************************** 挂号配置 ********************************************/
    /**
     * 获取厦门预约服务地址
     */
    public String getXMGuahaoUrl() {
        return getSystemProperties().getProperty("guahao_url");
    }
    /**
     * 获取厦门预约服务命名空间
     */
    public String getXMGuahaoNamespace() {
        return getSystemProperties().getProperty("guahao_namespace");
    }
    /****************************************************************************************/
    /********************************* EHR配置 **********************************************/
    /**
     * 是否启用EHR演示
     */
    public Boolean getEhrUsed() {
        return Boolean.valueOf(getSystemProperties().getProperty("ehr_used"));
    }
    /**
     * EHR档案服务地址
     */
    public String getEhrServices() {
        return getSystemProperties().getProperty("ehr_services");
    }
    /**
     * EHR底层地址
     */
    public String getEhrServicesBase() {
        return getSystemProperties().getProperty("ehr_services_base");
    }
    /**************************************************************************************/
    /**************************************************************************************/
}

+ 446 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/patient/PatientVO.java

@ -0,0 +1,446 @@
package com.yihu.jw.restmodel.patient;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
 * 居民VO类
 * @author huangwenjie
 * @date 2017/11/21 08:57
 */
public class PatientVO {
	
	// 业务主键
	private String code;
	// 身份证号
	private String idcard;
	// 登录密码
	private String password;
	private String salt;
	// 姓名
	private String name;
	// 生日
	private Date birthday;
	// 性別,1男,2女
	private Integer sex;
	// 手機號
	private String mobile;
	// (基卫)手機號
	private String mobileRemarks;
	// 聯繫電話
	private String phone;
	// 社保卡號
	private String ssc;
	// 頭像HTTP地址
	private String photo;
	// 省代碼
	private String province;
	// 城市代碼
	private String city;
	// 區縣代碼
	private String town;
	// 街道代码
	private String street;
	// 省名
	private String provinceName;
	// 市名
	private String cityName;
	// 區縣名
	private String townName;
	// 街道名称
	private String streetName;
	// 地址
	private String address;
	// 疾病类型,0健康,1高血压,2糖尿病,(1,2)高血压+糖尿病
	private String disease;
	private Integer diseasesum;
	// 病情:0绿标,1黄标,2红标
	private Integer diseaseCondition;
	// 病历记录总数
	private Integer recordAmount;
	// 總積分
	private Integer points;
	// 更新時間
	private Date czrq;
	// 微信编号
	private String openid;
	//微信时间
	private Date openidTime;
	// 用户状态:1正常,0禁用,-1恶意注册,2审核中
	private Integer status;
	// 居委会字段id
	private String sickVillage;
	// 居委会字段名称
	private String sickVillageName;
	//	绑定电子社保卡主体(本人为本人code,共济为操作人code)
	private String principalCode;
	//	是否绑定电子社保卡
	private Integer sicardStatus;
	//	绑定电子社保卡时间
	private Date sicardTime;
	//是否分配过微信标签  1分配过 0或者空没有
	private Integer isWxtag;
	//微信iagId
	private Integer wxtagid;
	//居民预警状态:0为标准,1为预警状态
	private Integer standardStatus;
	//档案状态(-2冻结 1未管理 2死亡3 正常4 高危)
	private String archiveStatus;
	//设备类型(1血糖,2血压,3血糖+血压)
	private String deviceType;
	//医疗保险号
	private String medicareNumber;
	//专病类型,专病名称
	private String specialistDisease;
	private String specialistDiseaseName;
	
	public String getCode() {
		return code;
	}
	
	public void setCode(String code) {
		this.code = code;
	}
	
	public String getIdcard() {
		return idcard;
	}
	
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getSalt() {
		return salt;
	}
	
	public void setSalt(String salt) {
		this.salt = salt;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08:00")
	public Date getBirthday() {
		return birthday;
	}
	
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	public Integer getSex() {
		return sex;
	}
	
	public void setSex(Integer sex) {
		this.sex = sex;
	}
	
	public String getMobile() {
		return mobile;
	}
	
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	
	public String getMobileRemarks() {
		return mobileRemarks;
	}
	
	public void setMobileRemarks(String mobileRemarks) {
		this.mobileRemarks = mobileRemarks;
	}
	
	public String getPhone() {
		return phone;
	}
	
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	public String getSsc() {
		return ssc;
	}
	
	public void setSsc(String ssc) {
		this.ssc = ssc;
	}
	
	public String getPhoto() {
		return photo;
	}
	
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	
	public String getProvince() {
		return province;
	}
	
	public void setProvince(String province) {
		this.province = province;
	}
	
	public String getCity() {
		return city;
	}
	
	public void setCity(String city) {
		this.city = city;
	}
	
	public String getTown() {
		return town;
	}
	
	public void setTown(String town) {
		this.town = town;
	}
	
	public String getStreet() {
		return street;
	}
	
	public void setStreet(String street) {
		this.street = street;
	}
	
	public String getProvinceName() {
		return provinceName;
	}
	
	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}
	
	public String getCityName() {
		return cityName;
	}
	
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	
	public String getTownName() {
		return townName;
	}
	
	public void setTownName(String townName) {
		this.townName = townName;
	}
	
	public String getStreetName() {
		return streetName;
	}
	
	public void setStreetName(String streetName) {
		this.streetName = streetName;
	}
	
	public String getAddress() {
		return address;
	}
	
	public void setAddress(String address) {
		this.address = address;
	}
	
	public Integer getDiseaseCondition() {
		return diseaseCondition;
	}
	
	public void setDiseaseCondition(Integer diseaseCondition) {
		this.diseaseCondition = diseaseCondition;
	}
	
	public Integer getRecordAmount() {
		return recordAmount;
	}
	
	public void setRecordAmount(Integer recordAmount) {
		this.recordAmount = recordAmount;
	}
	
	public Integer getPoints() {
		return points;
	}
	
	public void setPoints(Integer points) {
		this.points = points;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getCzrq() {
		return czrq;
	}
	
	public void setCzrq(Date czrq) {
		this.czrq = czrq;
	}
	
	public String getOpenid() {
		return openid;
	}
	
	public void setOpenid(String openid) {
		this.openid = openid;
	}
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getOpenidTime() {
		return openidTime;
	}
	
	public void setOpenidTime(Date openidTime) {
		this.openidTime = openidTime;
	}
	
	public Integer getStatus() {
		return status;
	}
	
	public void setStatus(Integer status) {
		this.status = status;
	}
	
	public String getSickVillage() {
		return sickVillage;
	}
	
	public void setSickVillage(String sickVillage) {
		this.sickVillage = sickVillage;
	}
	
	public String getSickVillageName() {
		return sickVillageName;
	}
	
	public void setSickVillageName(String sickVillageName) {
		this.sickVillageName = sickVillageName;
	}
	
	public String getPrincipalCode() {
		return principalCode;
	}
	
	public void setPrincipalCode(String principalCode) {
		this.principalCode = principalCode;
	}
	
	public Integer getSicardStatus() {
		return sicardStatus;
	}
	
	public void setSicardStatus(Integer sicardStatus) {
		this.sicardStatus = sicardStatus;
	}
	
	public Date getSicardTime() {
		return sicardTime;
	}
	
	public void setSicardTime(Date sicardTime) {
		this.sicardTime = sicardTime;
	}
	
	public Integer getIsWxtag() {
		return isWxtag;
	}
	
	public void setIsWxtag(Integer isWxtag) {
		this.isWxtag = isWxtag;
	}
	
	public Integer getWxtagid() {
		return wxtagid;
	}
	
	public void setWxtagid(Integer wxtagid) {
		this.wxtagid = wxtagid;
	}
	
	public Integer getStandardStatus() {
		return standardStatus;
	}
	
	public void setStandardStatus(Integer standardStatus) {
		this.standardStatus = standardStatus;
	}
	
	public String getDeviceType() {
		return deviceType;
	}
	
	public void setDeviceType(String deviceType) {
		this.deviceType = deviceType;
	}
	
	public String getDisease() {
		return disease;
	}
	
	public void setDisease(String disease) {
		this.disease = disease;
	}
	
	public Integer getDiseasesum() {
		return diseasesum;
	}
	
	public void setDiseasesum(Integer diseasesum) {
		this.diseasesum = diseasesum;
	}
	public String getMedicareNumber() {
		return medicareNumber;
	}
	public void setMedicareNumber(String medicareNumber) {
		this.medicareNumber = medicareNumber;
	}
	public String getArchiveStatus() {
		return archiveStatus;
	}
	public void setArchiveStatus(String archiveStatus) {
		this.archiveStatus = archiveStatus;
	}
	public String getSpecialistDisease() {
		return specialistDisease;
	}
	public void setSpecialistDisease(String specialistDisease) {
		this.specialistDisease = specialistDisease;
	}
	public String getSpecialistDiseaseName() {
		return specialistDiseaseName;
	}
	public void setSpecialistDiseaseName(String specialistDiseaseName) {
		this.specialistDiseaseName = specialistDiseaseName;
	}
}

+ 1218 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthController.java

@ -0,0 +1,1218 @@
package com.yihu.jw.hospital.endpoint.health;
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.health.service.PatientHealthIndexService;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.restmodel.conf.SystemConf;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.util.date.DateUtil;
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.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping(value = "/doctor/health_index", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-患者指标")
public class DoctorHealthController extends EnvelopRestEndpoint {
//	@Autowired
//	private PatientHealthIndexService healthIndexService;
//
//	@Autowired
//	private BasePatientService patientService;
//	@Autowired
//	private JdbcTemplate jdbcTemplate;
//	@Autowired
//	private IotService iotService;
//	@Autowired
//	private IotDeviceService iotDeviceService;
//	@Autowired
//	private WlyyIotTzDictDao wlyyIotTzDictDao;
//	@Autowired
//	private WlyyCopdHuamiDeviceDao wlyyCopdHuamiDeviceDao;
//	@Autowired
//	private WlyyCopdHuamiRealtimeDateDao wlyyCopdHuamiRealtimeDateDao;
//
//	@Autowired
//	private CopdHuaMiService copdHuaMiService;
//
//
//	@RequestMapping(value = "getPatientSteps", method = RequestMethod.GET)
//	@ApiOperation("获取居民最近一次的步数")
//	public String getPatientSteps(@ApiParam(name="patient",value="患者code")
//								  @RequestParam(value="patient",required = true) String patient) {
//		try {
//			return write(200, "查询成功!", "data", copdHuaMiService.getPatientSteps(patient));
//		} catch (Exception e) {
//			e.printStackTrace();
//			return error(-1, "查询失败!");
//		}
//	}
//
//	@RequestMapping(value = "watchDetail", method = RequestMethod.GET)
//	@ApiOperation("手表数据")
//	public String watchDetail(@ApiParam(name="patient",value="患者code")
//								  @RequestParam(value="patient",required = true) String patient) {
//		try {
//			return write(200, "查询成功!", "data", copdHuaMiService.watchDetail(patient));
//		} catch (Exception e) {
//			e.printStackTrace();
//			return error(-1, "查询失败!");
//		}
//	}
//
//
//	@RequestMapping(value = "watchDeviceDetail", method = RequestMethod.GET)
//	@ApiOperation("手表体征数据")
//	public String watchDeviceDetail(@ApiParam(name="patient",value="患者code")
//								  @RequestParam(value="patient",required = true) String patient,
//									@ApiParam(name="date",value="日期非必传(yyyy-MM-dd)",required = false)
//									@RequestParam(value="date",required = false) String date) {
//		try {
//			return write(200, "查询成功!", "data", copdHuaMiService.watchDeviceDetail(patient,date));
//		} catch (Exception e) {
//			e.printStackTrace();
//			return error(-1, "查询失败!");
//		}
//	}
//
//
//	/**
//	 * @param patient 患者标识
//	 * @param type 1运动(当日步数) 2睡眠(睡眠时长(结束时间-开始时间),睡眠得分) 3心率(心率值) 4PAI(每日PAI值)
//	 *      *             5血氧(血氧) 6健康分(周健康分/月健康分)
//	 * @return 操作结果
//	 */
//	@RequestMapping(value = "copdChart",method = RequestMethod.GET)
//	@ApiOperation("按时间段查询患者手表数据")
//	public String copdChart(@ApiParam(name="patient",value="患者代码")
//							@RequestParam(value="patient",required = true) String patient,
//							@ApiParam(name="type",value="指标类型")
//							@RequestParam(value="type",required = true) String type,
//							@ApiParam(name="begin",value="开始时间")
//							@RequestParam(value="begin",required = true) String begin,
//							@ApiParam(name="end",value="结束时间")
//							@RequestParam(value="end",required = true) String end) {
//		try {
//			return write(200, "查询成功", "data", copdHuaMiService.findChartByPatient(patient,type,begin,end));
//		} catch (Exception e) {
//			e.printStackTrace();
//			return error( -1, "查询失败!");
//		}
//	}
//
//
//	/**
//	 * 患者标识
//	 *(当日步数) 2睡眠(睡眠时长(结束时间-开始时间),睡眠得分) 3心率(心率值) 4PAI(每日PAI值)
//	 *         5血氧(血氧) 6健康分(周健康分/月健康分)
//	 * @return 操作结果
//	 */
//	@RequestMapping(value = "copdList",method = RequestMethod.GET)
//	@ApiOperation("按时间段查询患者手表数据")
//	public Envelop copdChart(@ApiParam(name="patient",value="患者代码")
//							 @RequestParam(value="patient",required = true) String patient,
//							 @ApiParam(name="type",value="指标类型")
//							 @RequestParam(value="type",required = true) String type,
//							 @ApiParam(name="begin",value="开始时间")
//							 @RequestParam(value="begin",required = true) String begin,
//							 @ApiParam(name="end",value="结束时间")
//							 @RequestParam(value="end",required = true) String end,
//							 @ApiParam(name="page",value="第几页",defaultValue = "1")
//								 @RequestParam(value="page",required = true) int page,
//							 @ApiParam(name="size",value="每页几行",defaultValue = "10")
//								 @RequestParam(value="size",required = true) int size) {
//		try {
//			return copdHuaMiService.findListByPatient(patient,type,begin,end,page,size);
//		} catch (Exception e) {
//			e.printStackTrace();
//			return Envelop.getError( "查询失败!");
//		}
//	}
//
//	@RequestMapping(value = "recent",method = RequestMethod.GET)
//	@ApiOperation("患者最近填写的健康指标")
//	public String recent(
//			@ApiParam("患者代码") @RequestParam String patient) {
//		try {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			JSONArray array = healthIndexService.findRecentByPatient(patient);
//			if (array != null) {
//				return write(200, "查询成功", "list", array);
//			} else {
//				return error(-1, "查询失败");
//			}
//		} catch (Exception e) {
//			return error(-1,e.getMessage());
//		}
//	}
//
//	/**
//	 * 根据患者标志获取健康指标
//	 * @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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			JSONArray jsonArray = healthIndexService.findChartByPatient(patient,type,gi_type,begin,end);
//			List<Map<String,Object>> maps = new ArrayList<>();
//			if (type==1){
//				if (gi_type ==1||gi_type==3||gi_type==5){
//					maps = iotService.selectByTypeAndCode(patient,"BloodSugar",1,begin,end);
//				}else if (gi_type==2||gi_type==4||gi_type==6){
//					maps = iotService.selectByTypeAndCode(patient,"BloodSugar",2,begin,end);
//				}else {
//					maps =iotService.selectByTypeAndCode(patient,"BloodSugar",3,begin,end);
//				}
//				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){
//				JSONArray array = iotService.getDataByTypeNoPage(patient,"BloodPressure",begin,end);
//				for (int i=0;i<array.length();i++){
//					JSONObject jsonObject = new JSONObject();
//					JSONObject object = array.getJSONObject(i);
//					if (object!=null){
//						JSONObject object1 = object.getJSONObject("result");
//						jsonObject.put("date",object1.getString("measureTime"));
//						jsonObject.put("device_sn",object1.getString("device_sn"));
//						JSONArray array1 = object.getJSONArray("data");
//						jsonObject.put("flag","xiaowu");
//						for (int j=0;j<array1.length();j++){
//							JSONObject object2 = array1.getJSONObject(j);
//							if (object2.getString("code").equalsIgnoreCase("HighPressure")){
//								jsonObject.put("value1",object2.getString("value"));
//							}else if (object2.getString("code").equalsIgnoreCase("LowPressure")){
//								jsonObject.put("value2",object2.getString("value"));
//							}else if (object2.getString("code").equalsIgnoreCase("Pulse")){
//								jsonObject.put("value3",object2.getString("value"));
//							}
//						}
//					}
//					jsonArray.put(jsonObject);
//				}
//			}else if (type==3){
//				JSONArray array = iotService.getDataByTypeNoPage(patient,"Height",begin,end);
//				for (int i=0;i<array.length();i++){
//					JSONObject jsonObject = new JSONObject();
//					JSONObject object = array.getJSONObject(i);
//					if (object!=null){
//						JSONObject object1 = object.getJSONObject("result");
//						jsonObject.put("date",object1.getString("measureTime"));
//						jsonObject.put("device_sn",object1.getString("device_sn"));
//						JSONArray array1 = object.getJSONArray("data");
//						jsonObject.put("flag","xiaowu");
//						for (int j=0;j<array1.length();j++){
//							JSONObject object2 = array1.getJSONObject(j);
//							if (object2.getString("code").equalsIgnoreCase("Height")){
//								jsonObject.put("value1",object2.getString("value"));
//							}else if (object2.getString("code").equalsIgnoreCase("Weight")){
//								jsonObject.put("value2",object2.getString("value"));
//							}else if (object2.getString("code").equalsIgnoreCase("BMI")){
//								jsonObject.put("value3",object2.getString("value"));
//							}else if (object2.getString("code").equalsIgnoreCase("IdealWeight")){
//								jsonObject.put("value4",object2.getString("value"));
//							}
//						}
//					}
//					jsonArray.put(jsonObject);
//				}
//			}
//			if (jsonArray.length()==0) {
//				return success("查询成功!");
//			}
//			return write(200, "查询成功", "list", jsonArray);
//		} catch (Exception ex) {
//			return error(-1,ex.getMessage());
//		}
//	}
//
//	/**
//	 * 根据患者标志获取健康指标
//	 * @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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//			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 error(-1,ex.getMessage());
//		}
//	}
//
//	/**
//	 * 根据患者标志获取健康指标
//	 * @param patient 患者指标
//	 * @param type 健康指标类型(1血糖,2血压,3体重,4腰围)
//	 * @return 操作结果
//	 */
//	@RequestMapping(value = "list",method = RequestMethod.POST)
//	@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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			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);
//				JSONArray jsonArray1 = new JSONArray();
//				if (list!=null&&list.size()!=0)
//					if (list.size()<pagesize){
//						if (page>1){
//							page=page-1;
//						}
//						JSONArray array = iotService.getDataByType(patient,"BloodSugar",page,pagesize-list.size(),begin, end);
//						for (int i=0;i<array.length();i++){
//							JSONObject jsonObject = new JSONObject();
//							JSONObject object = array.getJSONObject(i);
//							if (object!=null){
//								JSONObject object1 = object.getJSONObject("result");
//								jsonObject.put("time", DateUtil.stringToDate(object1.getString("measureTime"),"yyyy-MM-dd"));
//								jsonObject.put("time1",object1.getString("measureTime"));
//								jsonObject.put("device_sn",object1.getString("device_sn"));
//								JSONArray array1 = object.getJSONArray("data");
//								jsonObject.put("flag","xiaowu");
//								for (int j=0;j<array1.length();j++){
//									JSONObject object2 = array1.getJSONObject(j);
//									if (object2.getString("code").equalsIgnoreCase("BloodSugar")){
//										jsonObject.put("value1",object2.getString("value"));
//										jsonObject.put("valuedata1",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("BloodsugarType")){
//										jsonObject.put("valueDataName",object2.getString("value"));
//									}
//								}
//								jsonObject.put("result",object1.getString("valueName"));
//								jsonObject.put("mid",object1.getString("mid"));
//							}
//							jsonArray1.put(jsonObject);
//						}
//					}else if (pagesize!=list.size()){
//						JSONArray array = iotService.getDataByType(patient,"BloodSugar",page,pagesize-list.size(),begin,end);
//						for (int i=0;i<array.length();i++){
//							JSONObject jsonObject = new JSONObject();
//							JSONObject object = array.getJSONObject(i);
//							if (object!=null){
//								JSONObject object1 = object.getJSONObject("result");
//								jsonObject.put("time",object1.getString("measureTime"));
//								jsonObject.put("device_sn",object1.getString("device_sn"));
//								JSONArray array1 = object.getJSONArray("data");
//								jsonObject.put("flag","xiaowu");
//								for (int j=0;j<array1.length();j++){
//									JSONObject object2 = array1.getJSONObject(j);
//									if (object2.getString("code").equalsIgnoreCase("BloodSugar")){
//										jsonObject.put("value1",object2.getString("value"));
//										jsonObject.put("valuedata",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("BloodsugarType")){
//										jsonObject.put("valueDataName",object2.getString("value"));
//									}
//								}
//								jsonObject.put("result",object1.getString("valueName"));
//								jsonObject.put("mid",object1.getString("mid"));
//							}
//							jsonArray1.put(jsonObject);
//						}
//					}
//				jsonObject2.put("xiaowu",jsonArray1);
///*
//				jsonArray = new JSONArray(list);*/
//			}else{
//				jsonArray = healthIndexService.findIndexByPatient(patient, type, begin, end, page, pagesize);
//				JSONArray jsonArray1 = new JSONArray();
//				jsonObject2.put("data",jsonArray);
//				if (type==2){
//					if (jsonArray!=null&&jsonArray.length()!=0){
//						if (jsonArray.length()<pagesize){
//							if (page>1){
//								page=page-1;
//							}
//							JSONArray array = iotService.getDataByType(patient,"BloodPressure",page,pagesize-jsonArray.length(),begin, end);
//							for (int i=0;i<array.length();i++){
//								JSONObject jsonObject = new JSONObject();
//								JSONObject object = array.getJSONObject(i);
//								if (object!=null){
//									JSONObject object1 = object.getJSONObject("result");
//									jsonObject.put("time",object1.getString("measureTime"));
//									jsonObject.put("device_sn",object1.getString("device_sn"));
//									JSONArray array1 = object.getJSONArray("data");
//									jsonObject.put("flag","xiaowu");
//									for (int j=0;j<array1.length();j++){
//										JSONObject object2 = array1.getJSONObject(j);
//										if (object2.getString("code").equalsIgnoreCase("HighPressure")){
//											jsonObject.put("value1",object2.getString("value"));
//										}else if (object2.getString("code").equalsIgnoreCase("LowPressure")){
//											jsonObject.put("value2",object2.getString("value"));
//										}else if (object2.getString("code").equalsIgnoreCase("Pulse")){
//											jsonObject.put("value3",object2.getString("value"));
//										}
//									}
//									jsonObject.put("result",object1.getString("valueName"));
//									jsonObject.put("mid",object1.getString("mid"));
//								}
//								jsonArray1.put(jsonObject);
//							}
//						}
//					}else {
//						JSONArray array = iotService.getDataByType(patient,"BloodPressure",page,pagesize-jsonArray.length(),begin,end);
//						for (int i=0;i<array.length();i++){
//							JSONObject jsonObject = new JSONObject();
//							JSONObject object = array.getJSONObject(i);
//							if (object!=null){
//								JSONObject object1 = object.getJSONObject("result");
//								jsonObject.put("time",object1.getString("measureTime"));
//								jsonObject.put("device_sn",object1.getString("device_sn"));
//								JSONArray array1 = object.getJSONArray("data");
//								jsonObject.put("flag","xiaowu");
//								for (int j=0;j<array1.length();j++){
//									JSONObject object2 = array1.getJSONObject(j);
//									if (object2.getString("code").equalsIgnoreCase("HighPressure")){
//										jsonObject.put("value1",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("LowPressure")){
//										jsonObject.put("value2",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("Pulse")){
//										jsonObject.put("value3",object2.getString("value"));
//									}
//								}
//								jsonObject.put("result",object1.getString("valueName"));
//								jsonObject.put("mid",object1.getString("mid"));
//							}
//							jsonArray1.put(jsonObject);
//						}
//					}
//				}else if (type==3){
//					if (jsonArray!=null&&jsonArray.length()!=0){
//						if (jsonArray.length()<pagesize){
//							if (page>1){
//								page=page-1;
//							}
//							JSONArray array = iotService.getDataByType(patient,"Height",page,pagesize-jsonArray.length(),begin, end);
//							for (int i=0;i<array.length();i++){
//								JSONObject jsonObject = new JSONObject();
//								JSONObject object = array.getJSONObject(i);
//								if (object!=null){
//									JSONObject object1 = object.getJSONObject("result");
//									jsonObject.put("time",object1.getString("measureTime"));
//									jsonObject.put("device_sn",object1.getString("device_sn"));
//									JSONArray array1 = object.getJSONArray("data");
//									jsonObject.put("flag","xiaowu");
//									for (int j=0;j<array1.length();j++){
//										JSONObject object2 = array1.getJSONObject(j);
//										if (object2.getString("code").equalsIgnoreCase("Height")){
//											jsonObject.put("value1",object2.getString("value"));
//										}else if (object2.getString("code").equalsIgnoreCase("Weight")){
//											jsonObject.put("value2",object2.getString("value"));
//										}else if (object2.getString("code").equalsIgnoreCase("BMI")){
//											jsonObject.put("value3",object2.getString("value"));
//										}else if (object2.getString("code").equalsIgnoreCase("IdealWeight")){
//											jsonObject.put("value4",object2.getString("value"));
//										}
//									}
//									jsonObject.put("result",object1.getString("valueName"));
//									jsonObject.put("mid",object1.getString("mid"));
//								}
//								jsonArray1.put(jsonObject);
//							}
//						}
//					}else {
//						JSONArray array = iotService.getDataByType(patient,"Height",page,pagesize-jsonArray.length(),begin,end);
//						for (int i=0;i<array.length();i++){
//							JSONObject jsonObject = new JSONObject();
//							JSONObject object = array.getJSONObject(i);
//							if (object!=null){
//								JSONObject object1 = object.getJSONObject("result");
//								jsonObject.put("time",object1.getString("measureTime"));
//								jsonObject.put("device_sn",object1.getString("device_sn"));
//								JSONArray array1 = object.getJSONArray("data");
//								jsonObject.put("flag","xiaowu");
//								for (int j=0;j<array1.length();j++){
//									JSONObject object2 = array1.getJSONObject(j);
//									if (object2.getString("code").equalsIgnoreCase("Height")){
//										jsonObject.put("value1",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("Weight")){
//										jsonObject.put("value2",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("BMI")){
//										jsonObject.put("value3",object2.getString("value"));
//									}else if (object2.getString("code").equalsIgnoreCase("IdealWeight")){
//										jsonObject.put("value4",object2.getString("value"));
//									}
//								}
//								jsonObject.put("result",object1.getString("valueName"));
//								jsonObject.put("mid",object1.getString("mid"));
//							}
//							jsonArray1.put(jsonObject);
//						}
//					}
//				}
//				jsonObject2.put("xiaowu",jsonArray1);
//			}
//
//			return write(200, "查询成功", "list", jsonObject2);
//		} catch (Exception ex) {
//			return error(-1,ex.getMessage());
//		}
//	}
//
//	/**
//	 * 根据患者标志获取健康指标
//	 * @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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			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 error(-1,ex.getMessage());
//		}
//	}
//
//
//	/**
//	 * 根据患者标志获取健康指标
//	 * @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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			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 error(-1,ex.getMessage());
//		}
//	}
//
//	/**
//	 *
//	 * @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:"+ SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
//					"min_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
//			// 默认血压(收缩压,舒张压)
//			sb.append("{min_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MAX +", " +
//					"min_value_2:"+ SystemConf.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ SystemConf.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 error(-1,e.getMessage());
//		}
//	}
//
//
//	@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 error(-1,e.getMessage());
//
//		}
//	}
//
//
//	@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);
//			}
//			List<Map<String,Object>> mapList = healthIndexService.selectByTypeOfXiaoWu(patient,"BloodSugar");
//			if (mapList!=null&&mapList.size()!=0){
//				String measureTime = mapList.get(0).get("measure_time").toString();
//				com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
//				object.put("recordDate",mapList.get(0).get("measure_time"));
//				object.put("deviceSn",mapList.get(0).get("sn"));
//				object.put("mid",mapList.get(0).get("mid"));
//				object.put("idcard",mapList.get(0).get("id_card_no"));
//				object.put("type",1);
//				for (Map<String,Object> map1:mapList){
//					if (map1.get("code").toString().equalsIgnoreCase("BloodSugar")){
//						object.put("value1",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("BloodsugarType")){
//						object.put("value2",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("Result")){
//						object.put("value3",map1.get("value"));
//					}
//				}
//				if (xt==null){
//					map.put("xt",object);
//				}else {
//					if (xt.getCzrq().compareTo(DateUtil.strToDate(measureTime))==1){
//						xt.setFlag(1);//1是智能设备 2是健康小屋
//						map.put("xt",xt);
//					} else if (xt.getCzrq().compareTo(DateUtil.strToDate(measureTime))==0) {
//						object.put("flag",2);
//						map.put("xt",object);
//					}else if (xt.getCzrq().compareTo(DateUtil.strToDate(measureTime))==-1){
//						object.put("flag",2);
//						map.put("xt",object);
//					}
//				}
//
//			}
////            DevicePatientHealthIndex xy = healthIndexService.findLastByPatien(patient, 2);
//			DevicePatientHealthIndex xy = healthIndexService.findLastByPatienIot(patient, 2);
//			if (xy != null) {
//				map.put("xy", xy);
//			}
//			List<Map<String,Object>> mapList1 = healthIndexService.selectByTypeOfXiaoWu(patient,"BloodPressure");
//			if (mapList1!=null&&mapList1.size()!=0){
//				String measureTime = mapList1.get(0).get("measure_time").toString();
//				com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
//				object.put("recordDate",mapList1.get(0).get("measure_time"));
//				object.put("deviceSn",mapList1.get(0).get("sn"));
//				object.put("mid",mapList1.get(0).get("mid"));
//				object.put("idcard",mapList1.get(0).get("id_card_no"));
//				object.put("type",2);
//				for (Map<String,Object> map1:mapList){
//					if (map1.get("code").toString().equalsIgnoreCase("HighPressure")){
//						object.put("value1",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("LowPressure")){
//						object.put("value2",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("Pulse")){
//						object.put("value3",map1.get("value"));
//					}
//				}
//				if (xy==null){
//					map.put("xy",object);
//				}else {
//					if (xy.getCzrq().compareTo(DateUtil.strToDate(measureTime))==1){
//						xy.setFlag(1);//1是智能设备 2是健康小屋
//						map.put("xy",xy);
//					} else if (xy.getCzrq().compareTo(DateUtil.strToDate(measureTime))==0) {
//						object.put("flag",2);
//						map.put("xy",object);
//					}else if (xy.getCzrq().compareTo(DateUtil.strToDate(measureTime))==-1){
//						object.put("flag",2);
//						map.put("xy",object);
//					}
//				}
//
//			}
////            DevicePatientHealthIndex tz = healthIndexService.findLastByPatien(patient, 3);
//			DevicePatientHealthIndex tz = healthIndexService.findLastByPatienIot(patient, 3);
//			if (tz != null) {
//				map.put("tz", tz);
//			}
//			List<Map<String,Object>> mapList2 = healthIndexService.selectByTypeOfXiaoWu(patient,"Height");
//			if (mapList2!=null&&mapList2.size()!=0){
//				String measureTime = mapList2.get(0).get("measure_time").toString();
//				com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
//				object.put("recordDate",mapList2.get(0).get("measure_time"));
//				object.put("deviceSn",mapList2.get(0).get("sn"));
//				object.put("mid",mapList2.get(0).get("mid"));
//				object.put("idcard",mapList2.get(0).get("id_card_no"));
//				object.put("type",3);
//				for (Map<String,Object> map1:mapList){
//					if (map1.get("code").toString().equalsIgnoreCase("Height")){
//						object.put("value1",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("Weight")){
//						object.put("value2",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("BMI")){
//						object.put("value3",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("IdealWeight")){
//						object.put("value4",map1.get("value"));
//					}else if (map1.get("code").toString().equalsIgnoreCase("Result")){
//						object.put("value5",map1.get("value"));
//					}
//				}
//				if (tz==null){
//					map.put("tz",object);
//				}else {
//					if (tz.getCzrq().compareTo(DateUtil.strToDate(measureTime))==1){
//						tz.setFlag(1);//1是智能设备 2是健康小屋
//						map.put("tz",tz);
//					} else if (tz.getCzrq().compareTo(DateUtil.strToDate(measureTime))==0) {
//						object.put("flag",2);
//						map.put("tz",object);
//					}else if (tz.getCzrq().compareTo(DateUtil.strToDate(measureTime))==-1){
//						object.put("flag",2);
//						map.put("tz",object);
//					}
//				}
//
//			}
////            DevicePatientHealthIndex sg = healthIndexService.findLastByPatien(patient, 4);
//			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);
//			}
//
//			List<Map<String,Object>> array = healthIndexService.selectByXiaoWu(patient);
//			if (array!=null&& array.size()!=0){
//				map.put("xiaowu",array);
//			}
//
//			//慢阻肺呼吸数据
//			String sql = " select count(DISTINCT lu.id ) count,lu.inspect_time recordDate,lu.patient,p.idcard,de.parameter,lu.id,lu.device_type deviceType,lu.device_sn deviceSn,de.unit,de.pre_value preValue," +
//					" de.best_value bestValue,de.best_pre bestPre,de.lln,de.z_score zScore,de.test1_value value1,de.test2_value value2,de.test3_value value3 from xmiot.wlyy_copd_xeek_lung lu " +
//					"INNER JOIN xmiot.wlyy_copd_xeek_lung_detail de on lu.id = de.`code` INNER JOIN wlyy.wlyy_patient p on p.code = lu.patient INNER JOIN xmiot.wlyy_iot_tz_dict dict on dict.del=1 and  dict.code='COPD_PARAMETER' and " +
//					" dict.value = de.parameter where lu.patient='"+patient+"' " +
//					"ORDER BY lu.inspect_time desc ";
//			Map<String,Object> sqlResult = jdbcTemplate.queryForMap(sql);
//			if (Integer.parseInt(sqlResult.get("count").toString())!=0){
//				com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
//				sqlResult.put("name","呼吸训练");
//				String parameterName = wlyyIotTzDictDao.selectByCodeAndValueAndDel("COPD_PARAMETER",sqlResult.get("parameter").toString(),1);
//				if (StringUtils.isNotBlank(parameterName)){
//					sqlResult.put("parameterName",parameterName);
//				}
//			}
//			else {
//				sqlResult = new HashMap<>();
//			}
//			sqlResult.put("type",21);//呼吸训练
//			map.put("hxxl",sqlResult);
//
//			sqlResult = new HashMap<>();
//			//运动数据 取步数
//			sqlResult.put("type",22);//运动数据
//			map.put("ydsj",copdHuaMiService.getPatientSteps(patient));
//
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			return write(200, "查询成功", "data", map);
//		}  catch (Exception ex) {
//			return error(-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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			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 error(-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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//
//			List<Map<String,String>> list = healthIndexService.getHealthIndexHistory(patient, type, page, pagesize);
//
//			return write(200, "获取患者健康指标历史记录成功", "data", list);
//		} catch (Exception ex) {
//			return error(-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:"+ SystemConf.HEALTH_STANDARD_ST_MIN_BEFORE +", max_value_1: "+ SystemConf.HEALTH_STANDARD_ST_MAX_BEFORE +", " +
//					"min_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MIN_AFTER +", max_value_2:"+ SystemConf.HEALTH_STANDARD_ST_MAX_AFTER +", type:1},");
//			// 默认血压(收缩压,舒张压)
//			sb.append("{min_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MIN +", max_value_1:"+ SystemConf.HEALTH_STANDARD_SSY_MAX +", " +
//					"min_value_2:"+ SystemConf.HEALTH_STANDARD_SZY_MIN +", max_value_2:"+ SystemConf.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 error(-1,e.getMessage());
//		}
//	}
//
//	@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 = patientService.findAllSignPatientTeamcode(teamcode,getUID());
//
//
//			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.getCode());
//						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 error(-1,e.getMessage());
//		}
//	}
//
//	@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{
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//			String sql = "select DISTINCT(DATE_FORMAT(a.record_date,'%Y-%m-%d')) result from device.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 error(-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 {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//			List<Map<String,String>> list = healthIndexService.getHealthIndexByPatientAndDate(patientCode,deviceSn,choseDay,type);
//			return write(200, "获取健康指标历史记录成功", "data", list);
//		} catch (Exception ex) {
//			return error(-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 {
//		//新增查询物联网
//		iotDeviceService.iHealthDataSearch();
//		return write(200, "查询成功", "data", iotService.getDataByType(patient, type,page,size,beginTime,endTime));
//	}
//
//	@RequestMapping(value = "getHealthIndexById",method = RequestMethod.GET)
//	@ApiOperation("根据体征记录id获取体征记录详情")
//	public String getHealthIndexById(@ApiParam("体征记录id")
//						 @RequestParam Long id) {
//		try {
//			//新增查询物联网
//			iotDeviceService.iHealthDataSearch();
//			DevicePatientHealthIndex patientHealthIndex = healthIndexService.getHealthIndexById(id);
//			return write(200, "查询成功", "data", patientHealthIndex);
//		} catch (Exception e) {
//			return error(-1,e.getMessage());
//		}
//	}
}

+ 601 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthEduArticleController.java

@ -0,0 +1,601 @@
//package com.yihu.jw.hospital.endpoint.health;
//
//import com.yihu.wlyy.aop.ObserverRequired;
//import com.yihu.wlyy.entity.doctor.profile.Doctor;
//import com.yihu.wlyy.entity.education.*;
//import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.entity.patient.SignFamily;
//import com.yihu.wlyy.logs.BusinessLogs;
//import com.yihu.wlyy.repository.patient.SignFamilyDao;
//import com.yihu.wlyy.service.ServiceException;
//import com.yihu.wlyy.service.app.consult.ConsultService;
//import com.yihu.wlyy.service.app.health.*;
//import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
//import com.yihu.wlyy.service.common.account.DoctorService;
//import com.yihu.wlyy.service.common.account.PatientService;
//import com.yihu.wlyy.task.PushMsgTask;
//import com.yihu.wlyy.util.DateUtil;
//import com.yihu.wlyy.util.ImUtill;
//import com.yihu.wlyy.web.WeixinBaseController;
//import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang3.StringUtils;
//import org.htmlparser.Parser;
//import org.htmlparser.util.ParserException;
//import org.htmlparser.visitors.TextExtractingVisitor;
//import org.json.JSONArray;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.BeanUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.domain.Page;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.*;
//
///**
// * 医生端:健康教育控制类
// *
// * @author George
// */
//@Controller
//@RestController
//@RequestMapping(value = "/doctor/health/edu", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//@Api(description = "健康教育")
//public class DoctorHealthEduArticleController extends WeixinBaseController {
//
//    private Logger logger = LoggerFactory.getLogger(DoctorHealthEduArticleController.class);
//    @Autowired
//    private HealthEduArticleService healthEduArticleService;
//    @Autowired
//    private DoctorService doctorService;
//    @Autowired
//    private HealthEduArticleOpHistoryService healthEduArticleOpHistoryService;
//
//    @Autowired
//    private SignPatientLabelInfoService signPatientLabelInfoService;
//
//    @Autowired
//    private HealthEduArticlePatientService healthEduArticlePatientService;
//
//    @Autowired
//    private HealthEduArticleDoctorService healthEduArticleDoctorService;
//
//    @Autowired
//    private HealthEduArticleLabelService healthEduArticleLabelService;
//
//    @Autowired
//    private PatientService patientService;
//
//    @Autowired
//    SignFamilyDao signFamilyDao;
//
//    @Autowired
//    ConsultService consultService;
//    @Autowired
//    WeiXinOpenIdUtils weiXinOpenIdUtils;
//    @Autowired
//    private PushMsgTask pushMsgTask;
//
//
//    /**
//     * 查询
//     *
//     * @param pagesize 分页大小
//     * @param wheaType 文章类型
//     * @return 列表
//     */
//    @ApiOperation("查询健康教育")
//    @RequestMapping(value = "list",method = {RequestMethod.GET, RequestMethod.POST})
//    @ResponseBody
//    public String list(@RequestParam(value = "page", required = true) int page,
//                       @RequestParam(value = "pagesize", required = true) int pagesize,
//                       @RequestParam(value = "wheaType", required = true) int wheaType,
//                       @RequestParam(value = "filter", required = false) String filter,
//                       @RequestParam(value = "patient", required = false) String patient) {
//        try {
//            List<Map<String, Object>> list = healthEduArticleService.findAll(page, pagesize, filter, getUID(), patient,wheaType);
//            JSONArray jsonArray = new JSONArray();
//            if (list != null) {
//                for (Map<String, Object> map : list) {
//                    JSONObject json = new JSONObject();
//                    json.put("id", map.get("id"));
//                    // 文章标识
//                    json.put("code", map.get("code"));
//                    // 文章标题
//                    json.put("title", map.get("title"));
//                    // 文章查看URL
//                    json.put("url", map.get("url"));
//                    // 文章简介
//                    //json.put("content", parsrHtml(map.get("content").toString()));
//                    json.put("content", String.valueOf(map.get("content"))==null?"":map.get("content"));
//                    // 添加日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) map.get("czrq")));
//
//                    json.put("keyword", map.get("keyword") == null ? "" : map.get("keyword"));
//
//                    json.put("send", map.get("send"));
//                    //阅读量
//                    json.put("readAmount", map.get("readAmount"));
//                    //收藏量
//                    json.put("collectionAmount", map.get("collectionAmount"));
//                    //转发量
//                    json.put("repeatAmount", map.get("repeatAmount"));
//
//                    json.put("collection", map.get("collection"));
//                    jsonArray.put(json);
//                }
//            }
//            return write(200, "查询成功", "list", jsonArray);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 查询发送给居民的文章列表
//     *
//     * @param pagesize 分页大小
//     * @return 列表
//     */
//    @RequestMapping(value = "list_by_team", method = {RequestMethod.GET, RequestMethod.POST})
//    @ResponseBody
//    @ApiOperation(value = "查询发送给居民的文章列表")
//    public String listByTeam(@RequestParam @ApiParam(value = "第几页") int page,
//                             @RequestParam @ApiParam(value = "页大小") int pagesize,
//                             @RequestParam @ApiParam(value = "居民code") String patient,
//                             @RequestParam @ApiParam(value = "团队code") Long teamCode) {
//        try {
//            if (StringUtils.isEmpty(patient)) {
//                return error(-1, "请输入需查询的居民");
//            }
//            if (teamCode == null || teamCode < 1) {
//                return error(-1, "请输入需查询的居民的团队");
//            }
//            page = page > 0 ? page - 1 : 0;
//            List<Map<String, Object>> list = healthEduArticleService.findByPatientAndTeam(patient, teamCode, page, pagesize);
//            JSONArray jsonArray = new JSONArray();
//            if (list != null) {
//                for (Map<String, Object> map : list) {
//                    JSONObject json = new JSONObject();
//                    // 文章标识
//                    json.put("doctorCode", map.get("code"));
//                    // 文章标识
//                    json.put("doctorName", map.get("name"));
//                    // 文章标识
//                    json.put("doctorPhoto", map.get("photo"));
//                    // 文章标识
//                    json.put("code", map.get("article"));
//                    // 文章标题
//                    json.put("title", map.get("title"));
//                    // 文章查看URL
//                    json.put("url", map.get("url"));
//                    // 文章简介
//                    //json.put("content", parsrHtml(map.get("content").toString()));
//                    json.put("content", map.get("content").toString());
//
//                    json.put("read", map.get("is_read"));
//
//                    json.put("attached_content", map.get("attached_content"));
//                    // 发送日期
//                    json.put("czrq", DateUtil.dateToStrLong((Date) map.get("czrq")));
//                    // 发送团队
//                    json.put("adminTeamCode", map.get("admin_team_code"));
//                    jsonArray.put(json);
//                }
//            }
//            return write(200, "查询成功", "data", jsonArray);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 查询医生收藏列表
//     *
//     * @param pagesize 分页大小
//     * @return 列表
//     */
//    @RequestMapping(value = "listDoctor",method = RequestMethod.POST)
//    @ApiOperation("查询医生收藏列表")
//    @ResponseBody
//    public String listDoctor(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize, @RequestParam(value = "filter", required = false) String filter, @RequestParam(value = "patient", required = false) String patient, @RequestParam(value = "wheaType", required = false) Integer wheaType) {
//        try {
//            List<Map<String, Object>> list = healthEduArticleDoctorService.list(page, pagesize, filter, getUID(), patient,wheaType);
//            JSONArray jsonArray = new JSONArray();
//            for (Map<String, Object> map : list) {
//                JSONObject json = new JSONObject();
//                json.put("id", map.get("id"));
//                // 文章标识
//                json.put("code", map.get("article"));
//                // 文章标题
//                json.put("title", map.get("title"));
//                // 文章查看URL
//                json.put("url", map.get("url"));
//
//                // 文章简介
//                //json.put("content", parsrHtml(map.get("content").toString()));
//                json.put("content", map.get("content").toString());
//                // 添加日期
//                json.put("czrq", DateUtil.dateToStrLong((Date) map.get("czrq")));
//
//                json.put("keyword", map.get("keyword"));
//
//                json.put("send", map.get("send"));
//                //阅读量
//                json.put("readAmount", map.get("readAmount"));
//                //收藏量
//                json.put("collectionAmount", map.get("collectionAmount"));
//                //转发量
//                json.put("repeatAmount", map.get("repeatAmount"));
//                //是否收藏(医生收藏的列表肯定是收藏的无需额外校验)
//                json.put("collection", 1);
//
//                jsonArray.put(json);
//            }
//            return write(200, "查询成功", "list", jsonArray);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 查询标签列表
//     *
//     * @param pagesize 分页大小
//     * @return 列表
//     */
//    @RequestMapping(value = "listLabel",method = RequestMethod.POST)
//    @ApiOperation("查询标签列表")
//    @ResponseBody
//    public String listLabel(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize, @RequestParam(value = "type", required = false, defaultValue = "0") int type) {
//        try {
//            Page<HealthEduArticleLabel> list = healthEduArticleLabelService.findAll(page, pagesize, type, getUID());
//            return write(200, "查询成功", "list", list);
//        } catch (Exception ex) {
//            error(ex);
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//    /**
//     * 查询文章列表
//     *
//     * @param code 数据文章唯一标示code
//     * @return 列表
//     */
//    @RequestMapping(value = "article",method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("查询文章列表")
//    public String article(@RequestParam(value = "code", required = true) String code) {
//        try {
//            //获取单条文章记录
//            HealthEduArticle healthEduArticle = healthEduArticleService.findArticleByCode(code);
//            int isRead = healthEduArticleOpHistoryService.countByUserStatus(getUID(), HealthEduArticleOpHistory.READ_STATUS);
//            //插入文章读取状态第一次阅读记录浏览数量
//            if (isRead == 0) {
//                //更新浏览量
//                healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS, healthEduArticle.getCode(), healthEduArticle.getTitle(), getUID());
//            }
//            JSONObject json = new JSONObject();
//            json.put("id", healthEduArticle.getId());
//            // 文章标识
//            json.put("code", healthEduArticle.getCode());
//            // 文章标题
//            json.put("title", healthEduArticle.getTitle());
//
//            json.put("url", healthEduArticle.getUrl() == null ? "" : healthEduArticle.getUrl());
//            // 文章内容
//            json.put("content", healthEduArticle.getContent());
//            // 添加日期
//            json.put("czrq", DateUtil.dateToStrLong(healthEduArticle.getCzrq()));
//            int readAmount = healthEduArticleOpHistoryService.countReadAmount(code);
//            json.put("readAmount", readAmount);
//            HealthEduArticleDoctor healthEduArticleDoctor = healthEduArticleDoctorService.findByArticle(healthEduArticle.getCode(), getUID());
//            if (healthEduArticleDoctor == null) {
//                json.put("collection", 0);
//            } else {
//                json.put("collection", 1);
//            }
//            return write(200, "查询成功", "data", json);
//        } catch (Exception ex) {
//            return invalidUserException(ex, -1, "查询失败!");
//        }
//    }
//
//
//    /**
//     * 发送文章给患者
//     *
//     * @param code    文章标识,多个以逗号分隔
//     * @param patient 患者标识,多个以逗号分隔
//     * @param group   所选群组,多个用逗号分隔
//     * @param  attachedContent 附加内容
//     * @return
//     */
//    @RequestMapping(value = "send",method = RequestMethod.POST)
//    @ApiOperation("发送文章给患者")
//    @ResponseBody
//    @ObserverRequired
//    public String send(@RequestParam(value = "code") String code,
//                       @RequestParam(value = "patient", required = false) String patient,
//                       @RequestParam(value = "group", required = false, defaultValue = "") String group,
//                       @RequestParam(value = "labelType", required = false) String labelType,
//                       @RequestParam(value = "teamCode", required = false) long teamCode,
//                       @RequestParam(value = "attachedContent", required = false) String attachedContent) {
//        try {
//            List<HealthEduArticlePatient> list = new ArrayList<HealthEduArticlePatient>();
//            if (StringUtils.isEmpty(code)) {
//                return error(-1, "请至少选择一篇文章!");
//            }
//            if (StringUtils.isEmpty(patient) && StringUtils.isEmpty(group)) {
//                return error(-1, "请至少选择一个患者!");
//            }
//            String[] articles = code.split(",");
//            String[] patients = patient.split(",");
//            String[] groups = group.split(",");
//            if (articles.length == 0) {
//                return error(-1, "请至少选择一篇文章!");
//            }
//            if (patients.length == 0 && groups.length == 0) {
//                return error(-1, "请至少选择一个患者!");
//            }
//            Map<String, HealthEduArticle> maps = new HashMap<String, HealthEduArticle>();
//            Set<String> patientSet = new HashSet<>();
//            if (StringUtils.isNotBlank(group) && groups.length > 0) {
//                //递归患者数据
//                for (String g : groups) {
//                    getPatientByGroup(g, labelType, teamCode, patientSet, 0, 100);
//                }
//            }
//            //去重操作
//            for (String p : patients) {
//                if (StringUtils.isNotBlank(p)) {
//                    patientSet.add(p);
//                }
//            }
//            if (patientSet.size() == 0) {
//                return error(-1, "请至少选择一个患者!");
//            }
//            // 查询医生信息
//            Doctor doctor = doctorService.findDoctorByCode(getUID());
//            String msgHead = doctor.getName() + "医生给您发来了一篇患教文章";
//            String endMsg = "";//"为了您的健康," + doctor.getName() + "医生给您发送了一篇患教文章,请仔细查阅,如有问题,可随时咨询医生。";
//            if(StringUtils.isNotBlank(attachedContent)){
//                endMsg = attachedContent;
//            }
//            Map<String, Map<String, Object>> msgs = new HashMap<>();
//            String batchNo = UUID.randomUUID().toString();
//            Date createTime = new Date();
//            for (String p : patientSet) {
//                try{
//                    Patient patientTemp = patientService.findByCode(p);
//                    SignFamily signFamily = signFamilyDao.findByjiatingPatient(p);
//                    if (signFamily == null) {
//                        throw new Exception("can not find patient's family sign info");
//                    }
//                    for (String a : articles) {
//                        // 查询文章信息
//                        HealthEduArticle temp = maps.get(a);
//                        if (temp == null) {
//                            temp = healthEduArticleService.findArticleByCode(a);
//                            // 添加到缓存
//                            maps.put(a, temp);
//                        }
//
//                        HealthEduArticlePatient heap = new HealthEduArticlePatient();
//                        // 设置文章标识
//                        heap.setArticle(a);
//                        // 设置文章简介
//                        //heap.setContent(temp.getContent());
//                        // 设置文章标题
//                        //heap.setTitle(temp.getTitle());
//                        // 设置文章查看URL
//                        //heap.setUrl(temp.getUrl());
//                        // 设置发送时间
//                        heap.setCzrq(new Date());
//                        // 设置医生标识
//                        heap.setDoctor(doctor.getCode());
//                        // 设置医生姓名
//                        heap.setDoctorName(doctor.getName());
//                        // 设置患者标识
//                        heap.setPatient(p);
//                        // 设置为示读
//                        heap.setRead(1);
//                        // 签约类型
//                        heap.setSignType(2);
//                        // 行政团队
//                        heap.setAdminTeamCode(signFamily.getAdminTeamId());
//                        //附加内容
//                        heap.setAttachedContent(attachedContent);
//                        //批次号记录发送批次
//                        heap.setBatchNo(batchNo);
//                        //创建时间
//                        heap.setCzrq(createTime);
//                        heap.setSignCode(patientService.getSignCodeByPatient(p));
//                        heap.setSendType(1);//i健康推送
//                        heap.setTitle(temp.getTitle());
//                        list.add(heap);
//                        consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p, "{\"title\":\"" + temp.getTitle()+ "\",\"type\":0,\"id\":\"" + temp.getCode() + "\",\"img\":\"" + temp.getUrl() + "\",\"content\":\"为了您的健康,我给您发送了一篇文章,请咨询查阅,如有问题,可随时与我沟通\"}", "4", patientTemp.getName());
//                        if(StringUtils.isNotBlank(attachedContent)){
//                            //发送备注
//                            consultService.sendMucMessageBySingnType(doctor.getCode(), doctor.getName(), p, attachedContent, ImUtill.CONTENT_TYPE_TEXT, patientTemp.getName());
//                        }
//                        // 推送消息给微信端
//                        JSONObject json = new JSONObject();
//                        json.put("first", patientTemp.getName() + ",您好!\n" + msgHead);
//                        json.put("toUser", p);
//                        json.put("article", temp.getCode() + "");
//                        json.put("title", temp.getTitle());
//                        json.put("doctorName", doctor.getName());
//                        json.put("represented",p);//被代理人
//                        json.put("date", DateUtil.dateToStrLong(DateUtil.getNowDate()));
//                        json.put("remark", endMsg);
//                        Map<String, Object> content = new HashMap<>();
//                        content.put("openid", patientTemp.getOpenid());
//                        content.put("name", patientTemp.getName());
//                        content.put("json", json);
//                        content.put("code",patientTemp.getCode());
//                        msgs.put(patientTemp.getCode(), content);
//                    }
//                } catch (ServiceException se) {
//                    return write(-1,se.getMessage());
//                } catch (Exception e){
//                    logger.info("eduArticle_doctor:"+doctor.getCode()+" patient:"+p +" error:"+e.getMessage());
//                    error(e);
//                }
//            }
//            // 保存到数据库
//            int row = healthEduArticleService.send(list);
//            if (row <= 0) {
//                return error(-1, "发送失败!");
//            } else {
//                for (String key : msgs.keySet()) {
//
//                    Map<String, Object> map = msgs.get(key);
//                    String openid = (String)map.get("openid");
//                    if(StringUtils.isNotBlank(openid)){
//                        pushMsgTask.putWxMsg(getAccessToken(), 9,
//                                map.get("openid") == null ? "" : map.get("openid").toString(),
//                                map.get("name") == null ? "" : map.get("name").toString(),
//                                (JSONObject) map.get("json"));
//                    }else {
//                        //发送代理人
//                        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId((String) map.get("code"), openid);
//                        if (jsonArray != null && jsonArray.length() > 0) {
//                            Patient p = patientService.findByCode((String) map.get("code"));
//                            for (int i = 0; i < jsonArray.length(); i++) {
//                                JSONObject j = jsonArray.getJSONObject(i);
//                                Patient member = (Patient) j.get("member");
//                                JSONObject data = (JSONObject) map.get("json");
//                                data.remove("toUser");
//                                data.put("toUser", member.getCode());
//                                String first = (String) data.get("first");
//                                data.remove("first");
//                                data.put("first", weiXinOpenIdUtils.getTitleMes(p, j.isNull("relation") ? 1 : j.getInt("relation"), p.getName()));
//                                if (StringUtils.isNotBlank(member.getOpenid())) {
//                                    pushMsgTask.putWxMsg(getAccessToken(), 9, member.getOpenid(), p.getName(), data);
//                                }
//                            }
//                        }
//                    }
//
//                }
//                for (HealthEduArticlePatient heap : list) {
//                    BusinessLogs.info(BusinessLogs.BusinessType.article, getUID(), heap.getPatient(), new JSONObject(heap));
//                }
//                return success("发送成功!");
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    private void getPatientByGroup(String labelCode, String labelType, Long teamCode, Set<String> patientSet, int page, int pagesize) throws Exception {
//        JSONArray result = signPatientLabelInfoService.getPatientByLabel(getUID(), labelCode, labelType, teamCode, page, pagesize, false, "",false,null,null,null);
//        for (Object o : result) {
//            JSONObject json = (JSONObject) o;
//            String patient = (String) json.get("code");
//            patientSet.add(patient);
//        }
//        if (result.length() == 100) {
//            getPatientByGroup(labelCode, labelType, teamCode, patientSet, page + 1, pagesize);
//        }
//    }
//
//    /**
//     * 文章收藏
//     *
//     * @param article 文章CODE
//     * @return
//     */
//
//    @RequestMapping(value = "collectionArticle",method = RequestMethod.POST)
//    @ApiOperation("文章收藏")
//    @ResponseBody
//    @ObserverRequired
//    public String collectionArticle(@RequestParam(value = "article", required = true) String article) {
//        HealthEduArticleDoctor healthEduArticleDoctor = healthEduArticleDoctorService.findByArticle(article, getUID());
//        if (healthEduArticleDoctor != null) {
//            return error(-1, "收藏失败,该文章已经收藏!");
//        }
//        HealthEduArticle healthEduArticle = healthEduArticleService.findArticleByCode(article);
//        healthEduArticleDoctor = new HealthEduArticleDoctor();
//        try {
//            BeanUtils.copyProperties(healthEduArticle, healthEduArticleDoctor);
//            healthEduArticleDoctor.setDoctor(getUID());
//            healthEduArticleDoctor.setArticle(healthEduArticle.getCode());
//            healthEduArticleDoctorService.save(healthEduArticleDoctor);
//            //更新收藏量
//            healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.COLLECTION_STATUS, healthEduArticle.getCode(), healthEduArticle.getTitle(), getUID());
//            return success("收藏成功!");
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    /**
//     * 文章取消收藏
//     *
//     * @param article 文章CODE
//     * @return
//     */
//    @RequestMapping(value = "uncollectionArticle",method = RequestMethod.POST)
//    @ApiOperation("文章取消收藏")
//    @ResponseBody
//    @ObserverRequired
//    public String uncollectionArticle(@RequestParam(value = "article", required = true) String article) {
//        try {
//            healthEduArticleDoctorService.delete(article, getUID());
//
//            return success("取消收藏成功!");
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//
//    @RequestMapping(value = "logs",method = RequestMethod.POST)
//    @ApiOperation("查询多个患者文章 ")
//    @ResponseBody
//    public String getPatientHealthLogs(@RequestParam(value = "page", required = true) int page, @RequestParam(value = "pagesize", required = true) int pagesize){
//       try{
//           List<Map<String,Object>> result  =  healthEduArticlePatientService.findByDoctor(getUID(),page,pagesize);
//           return write(200,"查询成功!","list",result);
//       }catch (Exception e){
//           return write(-1,"查询失败!");
//       }
//    }
//    @RequestMapping(value = "log",method = RequestMethod.POST)
//    @ApiOperation("查询单个患者文章")
//    @ResponseBody
//    public String getPatientHealthLog(@RequestParam(value = "article", required = true) String article, @RequestParam(value = "batchNo", required = false) String batchNo){
//        try{
//            List<Map<String,Object>> result  =   healthEduArticlePatientService.findByBatchNo(getUID(),article,batchNo);
//            return write(200,"查询成功!","list",result);
//        }catch (Exception e){
//            return errorResult(e);
//        }
//    }
//
//    private String parsrHtml(String html) {
//        html = ("<span>" + html + "</span>");//拼接一个HTML标签,防止纯文字字符串转换在linux下面出现的异常。
//        Parser parser = null;
//        try {
//            parser = new Parser(html);
//            TextExtractingVisitor visitor = new TextExtractingVisitor();
//            parser.visitAllNodesWith(visitor);
//            return StringUtils.isNotBlank(visitor.getExtractedText()) ? visitor.getExtractedText() : "内容为图集,请点击查看";
//        } catch (ParserException e) {
//            return html;//纯文本内容会转换失败,直接返回文本内容
//        }
//
//    }
//
//}

+ 299 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthGuidanceController.java

@ -0,0 +1,299 @@
//package com.yihu.jw.hospital.endpoint.health;
//
//import com.yihu.wlyy.aop.ObserverRequired;
//import com.yihu.wlyy.entity.doctor.profile.Doctor;
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
//import com.yihu.wlyy.entity.template.DoctorGuidanceTemp;
//import com.yihu.wlyy.logs.BusinessLogs;
//import com.yihu.wlyy.service.ServiceException;
//import com.yihu.wlyy.service.app.consult.ConsultService;
//import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
//import com.yihu.wlyy.service.common.account.DoctorService;
//import com.yihu.wlyy.service.common.account.PatientService;
//import com.yihu.wlyy.service.template.DoctorGuidanceTempService;
//import com.yihu.wlyy.service.template.DoctorTeamGuidanceService;
//import com.yihu.wlyy.util.CommonUtil;
//import com.yihu.wlyy.web.WeixinBaseController;
//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.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.ResponseBody;
//
///**
// * 医生端:健康指导控制类
// *
// * @author George
// */
//@Controller
//@RequestMapping(value = "/doctor/health/guidance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//@Api(description = "健康指导")
//public class DoctorHealthGuidanceController extends WeixinBaseController {
//
//    private static final Logger logger = LoggerFactory.getLogger(DoctorHealthGuidanceController.class);
//
//    @Autowired
//    private PatientHealthGuidanceService patientHealthGuidanceService;
//
//    @Autowired
//    private DoctorService doctorService;
//
//    @Autowired
//    private PatientService patientService;
//
//    @Autowired
//    private ConsultService consultService;
//    @Autowired
//    private CommonUtil CommonUtil;
//    //======================
//    @Autowired
//    DoctorGuidanceTempService doctorGuidanceTempService;
//    @Autowired
//    private DoctorTeamGuidanceService doctorTeamGuidanceService;
////	=======================
//
//    /**
//     * 获取某个健康指导
//     *
//     * @param id
//     * @return
//     */
//    @RequestMapping(value = "/id", method = RequestMethod.POST)
//    @ApiOperation("获取某个健康指导")
//    @ResponseBody
//    public String getHealthGuidance(@RequestParam String id) {
//        Long idl = Long.parseLong(id);
//        try {
//            if (idl == null || idl < 1) {
//                return error(-1, "参数错误");
//            }
//
//            JSONObject guidance = patientHealthGuidanceService.findById(idl);
//            return write(200, "查询成功", "data", guidance);
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//	/*/**
//     * 添加患者健康指导
//	 * @param patient 患者标识
//	 * @param content 指导内容
//	 * @return
//	 */
//	/*@RequestMapping(value = "add")
//	@ResponseBody
//	public String add(String patient, String content, @RequestParam(required = false) String images, @RequestParam(required = false) String voice) {
//		try {
//			PatientHealthGuidance guidance = new PatientHealthGuidance();
//			guidance.setContent(content);
//			guidance.setDoctor(getUID());
//			guidance.setPatient(patient);
//			Doctor doctor = doctorService.findDoctorByCode(getUID());
//			if (StringUtils.isNotEmpty(images)) {
//				images = CommonUtil.copyTempImage(images);
//			}
//			guidance.setImages(images);
//
//			if (StringUtils.isNotEmpty(voice)) {
//				images = CommonUtil.copyTempVoice(voice);
//			}
//			guidance.setVoice(voice);
//
//			// 保存
//			if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
//				Patient p = patientService.findByCode(patient);
//				consultService.sendMucMessageBySingnType(getUID(),doctor.getName(),patient,content,"1",p.getName());
//				BusinessLogs.info(BusinessLogs.BusinessType.guidance, patient, new JSONObject(guidance));
//				return success("保存成功!");
//			} else {
//				return error(-1, "保存失败!");
//			}
//		} catch (Exception e) {
//			error(e);
//			return error(-1, "保存失败!");
//		}
//	}*/
//    //  ====================修改代码========================
//
//    /**
//     * 添加患者健康指导(modelCode不为空判断为使用模板)
//     *
//     * @param patient   患者标识
//     * @param content   指导内容
//     * @param modelCode 指导模板编码
//     * @param images    指导图片
//     * @param voice     指导语音
//     * @return
//     */
//    @RequestMapping(value = "/add", method = RequestMethod.POST)
//    @ApiOperation("添加患者健康指导")
//    @ResponseBody
//    @ObserverRequired
//    public String add(@RequestParam String patient,
//                      @RequestParam String content,
//                      @RequestParam(required = false) String modelCode,
//                      @RequestParam(required = false) String images,
//                      @RequestParam(required = false) String voice,
//                      @RequestParam(required = false) String tzCode) {
//
//        String imageUrls = "";
//        String imageRow = "";
//        JSONObject resultMap = new JSONObject();
//        Patient p = patientService.findByCode(patient);
//        if(null==p||(null!=p.getArchiveStatus()&&2==p.getArchiveStatus())){
//            resultMap.put("id","");
//            resultMap.put("msg","居民不存在,或者居民档案状态为死亡。");
//            return write(200,"保存成功!","data",resultMap);
//        }
//        if (StringUtils.isBlank(modelCode) || "undefined".equals(modelCode)) {
////			不使用模板指导,旧版手工指导
//            try {
//                PatientHealthGuidance guidance = new PatientHealthGuidance();
//                guidance.setContent(content);
//                guidance.setDoctor(getUID());
//                guidance.setPatient(patient);
////				找到当前医生
//                Doctor doctor = doctorService.findDoctorByCode(getUID());
//
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.validateImages(images);
//                }
//                logger.info("========================================> "+images);
//                guidance.setImages(images);
//
//                // 保存到居民端健康指导
//                PatientHealthGuidance pp = patientHealthGuidanceService.add(guidance, getAccessToken(),tzCode, null) ;
//                if (pp != null) {
//                    String imcotent = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + guidance.getImages() + "\",\"content\":\"" + CommonUtil.getSubString(guidance.getContent(), 0, 30) + "\"}";
//                    consultService.sendMucMessageBySingnType(getUID(), doctor.getName(), patient, imcotent, "4", p.getName());
//                    BusinessLogs.info(BusinessLogs.BusinessType.guidance, getUID(), patient, new JSONObject(guidance));
//                    resultMap.put("id",pp.getId());
//                    return write(200,"保存成功!","data",resultMap);
//                } else {
//                    return error(-1, "居民签约已到期,请使用文字回复。");
//                }
//            } catch (ServiceException se) {
//                return write(-1,se.getMessage());
//            } catch (Exception e) {
//                return errorResult(e);
//            }
//        } else {
//            try {
//                DoctorGuidanceTemp guidanceTemp = doctorGuidanceTempService.findByCode(modelCode);
//                PatientHealthGuidance guidance = new PatientHealthGuidance();
//                guidance.setContent(content);
//                guidance.setDoctor(getUID());
//                guidance.setPatient(patient);
//                Doctor doctor = doctorService.findDoctorByCode(getUID());
//                if (StringUtils.isNotEmpty(images)) {
//                    images = CommonUtil.validateImages(images);
//                }
//
//                logger.info("========================================> "+images);
//                guidance.setImages(images);
//
//                // 保存
//                PatientHealthGuidance pp = patientHealthGuidanceService.add(guidance, getAccessToken(),tzCode, guidanceTemp.getModelName()) ;
//                if (pp != null) {
//                    String sendImgs = "";
//                    if (StringUtils.isNotBlank(images)) {
//                        sendImgs = images;
//                    }
//                    String imcotent = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + sendImgs + "\",\"content\":\"" + CommonUtil.getSubString(guidance.getContent(), 0, 30) + "\"}";
//                    consultService.sendMucMessageBySingnType(getUID(), doctor.getName(), patient, imcotent, "4", p.getName());
//                    BusinessLogs.info(BusinessLogs.BusinessType.guidance, getUID(), patient, new JSONObject(guidance));
//                    //发送成功记录模板发送次数
//                    doctorGuidanceTempService.countSend(modelCode);
//                    resultMap.put("id",pp.getId());
//                    return write(200,"保存成功!","data",resultMap);
//                } else {
//                    return error(-1, "居民签约已到期,请使用文字回复。");
//                }
//            } catch (ServiceException se) {
//                return write(-1,se.getMessage());
//            } catch (Exception e) {
//                return errorResult(e);
//            }
//        }
//    }
//    //  ============================================
//
//    /**
//     * 查询患者的健康指导
//     *
//     * @param patient  患者标识
//     * @param begin    开始时间
//     * @param end      结束时间
//     * @param id       指导编码
//     * @param pagesize 展示页数
//     * @return
//     */
//    @RequestMapping(value = "/list", method = {RequestMethod.POST, RequestMethod.GET})
//    @ApiOperation("添加患者健康指导")
//    @ResponseBody
//    public String list(@RequestParam(required = false) String patient,
//                       @RequestParam(required = false) String begin,
//                       @RequestParam(required = false) String end,
//                       @RequestParam String id,
//                       @RequestParam String pagesize) {
//        try {
//            Long idl = Long.parseLong(id);
//            int page = Integer.parseInt(pagesize);
//            if (StringUtils.isNotEmpty(begin)) {
//                begin = begin + " 00:00:00";
//            }
//            if (StringUtils.isNotEmpty(end)) {
//                end = end + " 23:59:59";
//            }
//            JSONArray array = patientHealthGuidanceService.findPatientGuidanceByDoctor(getUID(), patient, begin, end, idl, page);
//            return write(200, "查询成功!", "list", array);
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//
//    /**
//     * 查询患者的健康指导
//     *
//     * @param patient
//     * @param teamCode
//     * @param page
//     * @param pagesize
//     * @return
//     */
//    @RequestMapping(value = "list_by_team", method = {RequestMethod.GET, RequestMethod.POST})
//    @ResponseBody
//    @ApiOperation(value = "查询居民健康指导记录")
//    public String list(@RequestParam @ApiParam(value = "居民code") String patient,
//                       @RequestParam @ApiParam(value = "团队Code") Long teamCode,
//                       @RequestParam @ApiParam(value = "第几页") int page,
//                       @RequestParam @ApiParam(value = "页大小") int pagesize) {
//        try {
//            if (StringUtils.isEmpty(patient)) {
//                return error(-1, "请输入需查询的居民");
//            }
//            if (teamCode == null || teamCode < 1) {
//                return error(-1, "请输入需查询的居民的团队");
//            }
//            page = page > 0 ? page - 1 : 0;
//            JSONArray result = patientHealthGuidanceService.findByPatientAndGuidanceAndTeam(patient, teamCode, page, pagesize);
//            return write(200, "查询成功!", "data", result);
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//}

+ 380 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/DoctorHealthRecordController.java

@ -0,0 +1,380 @@
//package com.yihu.jw.hospital.endpoint.health;
//
//import com.yihu.wlyy.entity.patient.Patient;
//import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
//import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
//import com.yihu.wlyy.entity.patient.PatientHealthRecordSports;
//import com.yihu.wlyy.service.ServiceException;
//import com.yihu.wlyy.service.app.archives.PatientRecordService;
//import com.yihu.wlyy.service.app.health.PatientHealthRecordService;
//import com.yihu.wlyy.service.common.account.PatientService;
//import com.yihu.wlyy.service.third.jw.JwArchivesService;
//import com.yihu.wlyy.util.DateUtil;
//import com.yihu.wlyy.web.BaseController;
//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.beans.factory.annotation.Value;
//import org.springframework.data.domain.Page;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.*;
//
///**
// * 医生端:健康记录控制类
// *
// * @author George
// */
//@Controller
//@RequestMapping(value = "/doctor/health_record", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//@Api(description = "健康记录")
//public class DoctorHealthRecordController extends BaseController {
//
//    @Autowired
//    private PatientHealthRecordService patientHealthRecordService;
//    @Autowired
//    private JwArchivesService jwArchivesService;
//    @Autowired
//    private PatientService patientService;
//    @Value("${demo.flag}")
//    private Boolean demoFlag;
//    @Autowired
//    private PatientRecordService patientRecordService;
//
//
//    /**
//     * 患者最近填写的运动、用药、饮食内容
//     *
//     * @param patient 患者标识
//     * @return
//     */
//    @RequestMapping(value = "recent", method = RequestMethod.GET)
//    @ApiOperation("根据患者标志获取最近的保健记录")
//    @ResponseBody
//    public String recent(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
//                         @RequestParam(value = "patient", required = true) String patient) {
//        try {
//            JSONObject json = patientHealthRecordService.findRecentByPatient(patient);
//            if (json != null) {
//                return write(200, "查询成功", "data", json);
//            } else {
//                return error(-1, "查询失败");
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    /**
//     * 运动记录查询接口
//     *
//     * @param patient  患者标识
//     * @param pagesize 分页大小
//     * @return
//     */
//    @RequestMapping(value = "list_sports", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("获取患者运动记录")
//    public String sports(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
//                         @RequestParam(value = "patient", required = true) String patient,
//                         @ApiParam(name = "start", value = "开始时间", defaultValue = "2017-05-15 00:00:00")
//                         @RequestParam(value = "start", required = true) String start,
//                         @ApiParam(name = "end", value = "结束时间", defaultValue = "2017-05-15 12: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 {
//            //Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatient(patient, DateUtil.strToDateLong(sortDate), pagesize);
//            Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatientPage(patient, start, end, page, pagesize);
//            if (data != null) {
//                JSONArray array = new JSONArray();
//                for (PatientHealthRecordSports record : data) {
//                    if (record == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", record.getId());
//                    // 设置记录标识
//                    json.put("code", record.getCode());
//                    // 设置记录日期
//                    json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
//                    json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
//                    // 设置运动时长(分钟)
//                    json.put("sports_time", record.getSportsTime());
//                    // 设置运动强度
//                    json.put("sports_type", record.getSportsTypeName());
//                    // 设置运动类型
//                    json.put("sports", record.getSportsName());
//                    array.put(json);
//                }
//                return write(200, "查询成功", "list", array);
//            } else {
//                return error(-1, "查询失败");
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    /**
//     * 用药记录查询接口
//     *
//     * @param patient  患者标识
//     * @param pagesize 分页大小
//     * @return
//     */
//    @RequestMapping(value = "list_medication", method = {RequestMethod.POST, RequestMethod.GET})
//    @ResponseBody
//    @ApiOperation("获取患者用药记录")
//    public String medication(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
//                             @RequestParam(value = "patient", required = true) String patient,
//                             @ApiParam(name = "start", value = "开始")
//                             @RequestParam(required = false) String start,
//                             @ApiParam(name = "end", value = "结束")
//                             @RequestParam(required = false) String end,
//                             @ApiParam(name = "page", value = "第几页", defaultValue = "1")
//                             @RequestParam(required = false) Integer page,
//                             @ApiParam(name = "sortDate", value = "日期")
//                             @RequestParam(required = false) String sortDate,
//                             @ApiParam(name = "pagesize", value = "每页记录数", defaultValue = "10")
//                             @RequestParam(required = true) int pagesize) {
//        try {
//            Page<PatientHealthRecordMedication> data = null;
//            if (!StringUtils.isEmpty(sortDate)) {
//                data = patientHealthRecordService.findMedicationByPatient(patient, DateUtil.strToDateLong(sortDate), page, pagesize);
//            } else {
//                data = patientHealthRecordService.findMedicalByPatientPage(patient, start, end, page, pagesize);
//            }
//
//            if (data != null) {
//                JSONArray array = new JSONArray();
//                for (PatientHealthRecordMedication record : data) {
//                    if (record == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", record.getId());
//                    // 设置记录标识
//                    json.put("code", record.getCode());
//                    // 设置记录日期
//                    json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
//                    json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
//                    // 药品名称
//                    json.put("medicines", record.getMedicinesName());
//                    array.put(json);
//                }
//                return write(200, "查询成功", "list", array);
//            } else {
//                return error(-1, "查询失败");
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    /**
//     * 饮食记录查询接口
//     *
//     * @param patient  患者标识
//     * @param page     页码
//     * @param pagesize 分页大小
//     * @return
//     */
//    @RequestMapping(value = "list_diet", method = RequestMethod.POST)
//    @ApiOperation("饮食记录查询接口")
//    @ResponseBody
//    public String diet(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
//                       @RequestParam(value = "patient", required = true) String patient,
//                       @ApiParam(name = "start", value = "开始")
//                       @RequestParam(required = true) String start,
//                       @ApiParam(name = "end", value = "结束")
//                       @RequestParam(required = false) String end,
//                       @ApiParam(name = "page", value = "第几页", defaultValue = "1")
//                       @RequestParam(required = true) int page,
//                       @ApiParam(name = "pagesize", value = "每页记录数", defaultValue = "10")
//                       @RequestParam(required = true) int pagesize) {
//        try {
//            Page<PatientHealthRecordDiet> data = patientHealthRecordService.findDietByPatientPage(patient, start, end, page, pagesize);
//            if (data != null) {
//                JSONArray array = new JSONArray();
//                for (PatientHealthRecordDiet record : data) {
//                    if (record == null) {
//                        continue;
//                    }
//                    JSONObject json = new JSONObject();
//                    json.put("id", record.getId());
//                    // 设置记录标识
//                    json.put("code", record.getCode());
//                    // 设置记录日期
//                    json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
//                    json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
//                    // 设置饮食内容
//                    json.put("content", record.getContent());
//                    // 设置图片URL,多图以逗号分隔
//                    json.put("images", record.getImages());
//                    array.put(json);
//                }
//                return write(200, "查询成功", "list", array);
//            } else {
//                return error(-1, "查询失败");
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    @RequestMapping(value = "list_medical", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("查询居民健康体检列表")
//    public String medical(@ApiParam(name = "patient", value = "患者代码", defaultValue = "P20160901001")
//                          @RequestParam(value = "patient", required = true) String patient,
//                          @ApiParam(name = "pageIndex", value = "第几页", defaultValue = "")
//                          @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
//                          @ApiParam(name = "pageSize", value = "每页记录数", defaultValue = "")
//                          @RequestParam(value = "pageSize", required = false) Integer pageSize) {
//        try {
//
//            if (demoFlag) {
//                String res = patientRecordService.getJosnFileResullt("list_medical");
//                return res;
//            } else {
//                Patient p = patientService.findByCode(patient);
//                if (p != null) {
//                    JSONArray re = jwArchivesService.getEhrSickMedicalList(p.getIdcard(), pageIndex, pageSize);
//                    return write(200, "查询成功", "list", re);
//                } else {
//                    return error(-1, "患者不存在");
//                }
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//    @RequestMapping(value = "medical_detail", method = RequestMethod.POST)
//    @ResponseBody
//    @ApiOperation("查询居民健康体检详情信息")
//    public String medical_detail(@ApiParam(name = "medicalNo", value = "体检ID", defaultValue = "1249652")
//                                 @RequestParam(value = "medicalNo", required = true) String medicalNo) {
//        try {
//            if (demoFlag) {
//                String res = patientRecordService.getJosnFileResullt("medical_detail");
//                return res;
//            } else {
//                JSONObject json = jwArchivesService.getEhrSickMedicalRecord(medicalNo);
//                return write(200, "查询成功", "medical_detail", json);
//            }
//        } catch (ServiceException se) {
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//
//    /**
//     * 根据区域查询体检详情信息
//     */
//    @ApiOperation("根据区域查询体检详情信息")
//    @ResponseBody
//    @PostMapping(value = "areaMedicalDetail")
//    public String areaMedicalDetail(@ApiParam(name = "areaCode", value = "区域code", defaultValue = "350205")
//                                    @RequestParam(value = "areaCode", required = false) String areaCode,
//                                    @ApiParam(name = "patientId", value = "用户id", defaultValue = "")
//                                    @RequestParam(value = "patientId", required = false) String patientId) {
//        try {
//            //查询出区域的签约人
//            if (StringUtils.isBlank(areaCode) && StringUtils.isBlank(patientId)) {
//                return write(-1, "参数为空");
//            }
//            String result = patientRecordService.areaMedicalDetail(areaCode, patientId, demoFlag);
//            return result;
//        } catch (ServiceException se) {
//            System.out.println(se);
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            System.out.println(e);
//            return errorResult(e);
//        }
//    }
//
//
//    /**
//     * 保存体检详情信息
//     */
//    @ApiOperation("保存体检详情信息")
//    @ResponseBody
//    @PostMapping(value = "saveMedicalDetail")
//    public String saveMedicalDetail(@ApiParam(name = "medicalNo", value = "体检号", defaultValue = "10891028")
//                                    @RequestParam(value = "medicalNo", required = false) String medicalNo,
//                                    @ApiParam(name = "findType", value = "查询类型 1查本地2查远程", defaultValue = "1")
//                                    @RequestParam(value = "findType", required = false) String findType,
//                                    @ApiParam(name = "findAll", value = "是否查全部,yes是 temp走补录", defaultValue = "yes")
//                                    @RequestParam(value = "findAll", required = false) String findAll) {
//        try {
//            //查询出区域的签约人
//            if (StringUtils.isBlank(medicalNo) && StringUtils.isBlank(findAll)) {
//                return write(-1, "参数为空");
//            }
//            String result = patientRecordService.saveMedicalDetailMethod(findType, findAll);
//            return result;
//
//        } catch (ServiceException se) {
//            System.out.println(se);
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            System.out.println(e);
//            return errorResult(e);
//        }
//    }
//
//
//    /**
//     * patient/archives/event
//     * /smjk/GetResidentEventListJson
//     * 接口地址 /base/CallEhrInterface
//     */
//    @ApiOperation("保存健康档案信息")
//    @ResponseBody
//    @PostMapping(value = "saveHealthRecord")
//    public String saveHealthRecord(
//            @ApiParam(name = "idcard", value = "身份证号", defaultValue = "") @RequestParam(value = "idcard", required = false) String idcard) {
//        try {
//            String result = patientRecordService.saveHealthRecord(idcard);
//            return result;
//        } catch (ServiceException se) {
//            System.out.println(se);
//            return write(-1, se.getMessage());
//        } catch (Exception e) {
//            System.out.println(e);
//            return errorResult(e);
//        }
//    }
//
//    @RequestMapping(value = "dietDetail", method = RequestMethod.GET)
//    @ResponseBody
//    @ApiOperation("饮食记录详情接口")
//    public String dietDetail(@ApiParam(name = "id", value = "饮食记录ID")
//                             @RequestParam(value = "id") Long dietId) {
//        try {
//            JSONObject json = patientHealthRecordService.findById(dietId);
//            if (json.getInt("status") == 200) {
//                return write(200, "查询成功!", "data", json.getJSONObject("data"));
//            } else {
//                return error(-1, json.getString("msg"));
//            }
//        } catch (Exception e) {
//            return errorResult(e);
//        }
//    }
//
//
//}

+ 2403 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/vo/MedicalDetailVo.java

@ -0,0 +1,2403 @@
package com.yihu.jw.hospital.endpoint.health.vo;
import java.util.List;
/**
 * @author suqinyi
 * @Date 2023/6/12
 */
public class MedicalDetailVo {
    private String medicalNo;
    private String medicalInfoId;
    private String skinOthers;
    private String renalOthers;
    private String fastingPlasmaGlucoseDL;
    private String abdoShiftingDull;
    private String eyegroundException;
    private String abdoHepatomegalyOth;
    private String electrocardiogram;
    private String typeBUltrasonic;
    private String height;
    private String abdoMassesOthers;
    private String liverFunctionTotalBilirubin;
    private String bloodFatHdlc;
    private String heartChf;
    private String renalDn;
    private String bloodRoutineOthers;
    private String eyeDiseaseCataract;
    private String vulvaException;
    private String poisonOthers;
    private String cardiacSouffle;
    private String heartPrecordialpain;
    private String isDryOut;
    private String poisonPhysicalfactor;
    private String healthGuidanceOther;
    private String hazardLoseWeight;
    private String poisonDustPreStr;
    private String breastOthersStr;
    private String angiosisUndiscovered;
    private String bloodPressureLeftD;
    private String vulva;
    private String renalFunctionBun;
    private String cvdSah;
    private String sclera;
    private String ket;
    private String renalFunctionCreatinine;
    private String audition;
    private String miniMentalStateExamination;
    private String drinkOthers;
    private String hardeningFrequency;
    private String occupationalDiseaseWorkTime;
    private String asymptomatic;
    private String abdoHepatomegaly;
    private String fastingPlasmaGlucoseL;
    private String visionRightEye;
    private String symptomBreastBursting;
    private String poisonChemicalPreStr;
    private String eatHobbySugar;
    private String lips;
    private String vaginaException;
    private String everyHardeningTime;
    private String upcr;
    private String angiosisOthers;
    private String occupationalDisease;
    private String motorFunction;
    private String corporeityQiDepression;
    private String heartOthers;
    private String cvdOthers;
    private String poisonChemical;
    private String lungBreathSoundExcep;
    private String angiosisDa;
    private String corpus;
    private String cervicalPapSmears;
    private String breastOthers;
    private String elderlyAffectiveState;
    private String cvdIschemicStroke;
    private String lymphNodeRrmprt;
    private String isExaminationExcep;
    private String symptomPalpitation;
    private String heartOthersStr;
    private String hardeningMode;
    private String cxr;
    private String lymphNodeNotTouch;
    private String lymphNodeClavicle;
    private String elderlyHealthStatus;
    private String othersSystemDisease;
    private String symptomDazzle;
    private String symptomJointGall;
    private String lungBarrelChest;
    private String symptomChestPain;
    private String abdoPressPain;
    private String symptomWeightLoss;
    private String occDiseaseTrades;
    private String fundamentFingerpOth;
    private String weight;
    private String symptomUrinaryUrgency;
    private String drinkFrequency;
    private String poisonOthersPreStr;
    private String dentitiondentureNormal;
    private String glycolatedHemoglobin;
    private String bloodFatLdlc;
    private String hazardHealthDrink;
    private String othersSystemDiseaseStr;
    private String poisonOthersIspre;
    private String dorsumOfFootArteriopalmus;
    private String renalFunctionNatremia;
    private String breastMastectomy;
    private String proteinuria;
    private String symptomDysuria;
    private String corporeityTeBing;
    private String bloodFatTriglyceride;
    private String urinaryOccultBlood;
    private String doctorName;
    private String symptomDiarrhea;
    private String poisonRadiogenPreStr;
    private String abdoSplenomegalyOth;
    private String breastAbnormalLactation;
    private String dentitiondentureDentalCaries;
    private String symptomChronicCough;
    private String symptomOther;
    private String stoolOccultBlood;
    private String renalFailure;
    private String symptomDizziness;
    private String respiratoryRate;
    private String lungRhonchusException;
    private String beginSmokingAge;
    private String abdoMasses;
    private String eatMeatdietFlash;
    private String poisonPhysicalPreStr;
    private String renalFunctionBloodPotassium;
    private String platelet;
    private String liverFunctionSgot;
    private String uricAcid;
    private String renalCgn;
    private String assistantInvesOth;
    private String symptomHandFootNumbness;
    private String papilledema;
    private String eatHobbyOil;
    private String symptomTinnitus;
    private String abdoSplenomegaly;
    private String retinalHemorrhage;
    private String corporeityYangDeficiency;
    private String liverFunctionCb;
    private String healthGuidanceOtherStr;
    private String pulseFrequency;
    private String elderlyDepressionCheck;
    private String dryOutAge;
    private String smokingCircumstance;
    private String heartUndiscovered;
    private String cvdUndiscovered;
    private String drinkRedWine;
    private String eyeDiseaseOthers;
    private String quitSmokingAge;
    private String cardiacSouffleOthers;
    private String hazardOthersStr;
    private String scleraOthers;
    private String lungRhonchus;
    private String urineRoutineOthers;
    private String symptomHeadache;
    private String eatVegetarianFlash;
    private String cvdOthersStr;
    private String symptomConstipation;
    private String breastNotTroubleFind;
    private String poisonRadiogen;
    private String leukocyte;
    private String waist;
    private String cvdCerebralHemorrhage;
    private String corpusException;
    private String abdoShiftingDullOth;
    private String nervousSystemDiseaseStr;
    private String drinkOthersStr;
    private String skin;
    private String cervicalPapSmearsExcep;
    private String healthGuidanceInhospital;
    private String hazardOthers;
    private String healthRegularFollowUp;
    private String hazardVaccination;
    private String poisonChemicalIspre;
    private String abdoPressPainOth;
    private String healthGuidanceSlowDisease;
    private String bloodPressureRigthD;
    private String cervix;
    private String poisonDustIspre;
    private String breastMasses;
    private String attachmentException;
    private String nervousSystemDisease;
    private String hazardHardening;
    private String cervixException;
    private String symptomPolyuria;
    private String lungBreathSound;
    private String symptomDyspnea;
    private String cxrException;
    private String everyAlcohol_tolerance;
    private String microalbuminuria;
    private String corporeityYinDeficiency;
    private String fundamentFingerp;
    private String elderlyCognitiveFun;
    private String dentitiondentureMissTeeth;
    private String hbsag;
    private String eyeground;
    private String renalAgn;
    private String cardiacRhythm;
    private String bmi;
    private String oneYearIsTemulentia;
    private String corporeityQiAsthenia;
    private String pharyngealportionYes;
    private String straightenVisionRightEye;
    private String symptomExpectoration;
    private String hazardVaccinationStr;
    private String bloodFatTc;
    private String symptomChestStuffiness;
    private String lymphNodeOthers;
    private String bodyTemperature;
    private String typeBUltrasonicExcep;
    private String immersionFoot;
    private String renalOthersStr;
    private String beginDrinkAge;
    private String symptomNauseaVomiting;
    private String corporeityGentle;
    private String corporeityDampHeat;
    private String orgName;
    private String vagina;
    private String heartAnginaPectoris;
    private String urineSugar;
    private String poisonRadiogenIspre;
    private String drinkWhiteSpirits;
    private String bloodPressureRigthU;
    private String liverFunctionAlbumin;
    private String visionLeftEye;
    private String straightenVisionLeftEye;
    private String heartRate;
    private String symptomPolydipsia;
    private String bloodPressureLeftU;
    private String physicalExaminationOth;
    private String dailySmokingQuantity;
    private String drinkYellowWine;
    private String drinkBeer;
    private String eatHobbySalt;
    private String pharyngealportionAdd;
    private String symptomOtherStr;
    private String elderlySelfCare;
    private String dentitiondentureDenture;
    private String angiosisOthersStr;
    private String eyeDiseaseOthersStr;
    private String hazardQuitSmocking;
    private String symptomLackOfPower;
    private String lymphNode;
    private String angiosisOcclusionArteries;
    private String hemoglobin;
    private String eyeDiseaseUndiscovered;
    private String insistHardeningTime;
    private String renalUndiscovered;
    private String attachment;
    private String healthGuidanceReview;
    private String liverFunctionSalt;
    private String cvdTia;
    private String medicalTime;
    private String hazardFood;
    private String symptomBlurredVision;
    private String corporeityPhlegmDamp;
    private String hazardLoseWeightTarget;
    private String poisonPhysicalIspre;
    private String corporeityHaemostasis;
    private String heartCoronaryArtery;
    private String poisonDust;
    private String pharyngealportionNo;
    private String eatClitocybineEqualization;
    private String heartMyocardialInfarction;
    private String electrocardiogramExcep;
    private List<String> fpList;
    private List<String> examinationList;
//    private List<String> inhospitalList;
//    private List<String> niVaccinationList;
    //    private List<String> drugList;
//    private String[] drugList;
    public String getSkinOthers() {
        return skinOthers;
    }
    public void setSkinOthers(String skinOthers) {
        this.skinOthers = skinOthers;
    }
    public String getRenalOthers() {
        return renalOthers;
    }
    public void setRenalOthers(String renalOthers) {
        this.renalOthers = renalOthers;
    }
    public String getFastingPlasmaGlucoseDL() {
        return fastingPlasmaGlucoseDL;
    }
    public void setFastingPlasmaGlucoseDL(String fastingPlasmaGlucoseDL) {
        this.fastingPlasmaGlucoseDL = fastingPlasmaGlucoseDL;
    }
    public String getAbdoShiftingDull() {
        return abdoShiftingDull;
    }
    public void setAbdoShiftingDull(String abdoShiftingDull) {
        this.abdoShiftingDull = abdoShiftingDull;
    }
    public String getEyegroundException() {
        return eyegroundException;
    }
    public void setEyegroundException(String eyegroundException) {
        this.eyegroundException = eyegroundException;
    }
    public String getAbdoHepatomegalyOth() {
        return abdoHepatomegalyOth;
    }
    public void setAbdoHepatomegalyOth(String abdoHepatomegalyOth) {
        this.abdoHepatomegalyOth = abdoHepatomegalyOth;
    }
    public String getElectrocardiogram() {
        return electrocardiogram;
    }
    public void setElectrocardiogram(String electrocardiogram) {
        this.electrocardiogram = electrocardiogram;
    }
    public String getTypeBUltrasonic() {
        return typeBUltrasonic;
    }
    public void setTypeBUltrasonic(String typeBUltrasonic) {
        this.typeBUltrasonic = typeBUltrasonic;
    }
    public String getHeight() {
        return height;
    }
    public void setHeight(String height) {
        this.height = height;
    }
    public String getAbdoMassesOthers() {
        return abdoMassesOthers;
    }
    public void setAbdoMassesOthers(String abdoMassesOthers) {
        this.abdoMassesOthers = abdoMassesOthers;
    }
    public String getLiverFunctionTotalBilirubin() {
        return liverFunctionTotalBilirubin;
    }
    public void setLiverFunctionTotalBilirubin(String liverFunctionTotalBilirubin) {
        this.liverFunctionTotalBilirubin = liverFunctionTotalBilirubin;
    }
    public String getBloodFatHdlc() {
        return bloodFatHdlc;
    }
    public void setBloodFatHdlc(String bloodFatHdlc) {
        this.bloodFatHdlc = bloodFatHdlc;
    }
    public String getHeartChf() {
        return heartChf;
    }
    public void setHeartChf(String heartChf) {
        this.heartChf = heartChf;
    }
    public String getRenalDn() {
        return renalDn;
    }
    public void setRenalDn(String renalDn) {
        this.renalDn = renalDn;
    }
    public String getBloodRoutineOthers() {
        return bloodRoutineOthers;
    }
    public void setBloodRoutineOthers(String bloodRoutineOthers) {
        this.bloodRoutineOthers = bloodRoutineOthers;
    }
    public String getEyeDiseaseCataract() {
        return eyeDiseaseCataract;
    }
    public void setEyeDiseaseCataract(String eyeDiseaseCataract) {
        this.eyeDiseaseCataract = eyeDiseaseCataract;
    }
    public String getVulvaException() {
        return vulvaException;
    }
    public void setVulvaException(String vulvaException) {
        this.vulvaException = vulvaException;
    }
    public String getPoisonOthers() {
        return poisonOthers;
    }
    public void setPoisonOthers(String poisonOthers) {
        this.poisonOthers = poisonOthers;
    }
    public String getCardiacSouffle() {
        return cardiacSouffle;
    }
    public void setCardiacSouffle(String cardiacSouffle) {
        this.cardiacSouffle = cardiacSouffle;
    }
    public String getHeartPrecordialpain() {
        return heartPrecordialpain;
    }
    public void setHeartPrecordialpain(String heartPrecordialpain) {
        this.heartPrecordialpain = heartPrecordialpain;
    }
    public String getIsDryOut() {
        return isDryOut;
    }
    public void setIsDryOut(String isDryOut) {
        this.isDryOut = isDryOut;
    }
    public String getPoisonPhysicalfactor() {
        return poisonPhysicalfactor;
    }
    public void setPoisonPhysicalfactor(String poisonPhysicalfactor) {
        this.poisonPhysicalfactor = poisonPhysicalfactor;
    }
    public String getHealthGuidanceOther() {
        return healthGuidanceOther;
    }
    public void setHealthGuidanceOther(String healthGuidanceOther) {
        this.healthGuidanceOther = healthGuidanceOther;
    }
    public String getHazardLoseWeight() {
        return hazardLoseWeight;
    }
    public void setHazardLoseWeight(String hazardLoseWeight) {
        this.hazardLoseWeight = hazardLoseWeight;
    }
    public String getPoisonDustPreStr() {
        return poisonDustPreStr;
    }
    public void setPoisonDustPreStr(String poisonDustPreStr) {
        this.poisonDustPreStr = poisonDustPreStr;
    }
    public String getBreastOthersStr() {
        return breastOthersStr;
    }
    public void setBreastOthersStr(String breastOthersStr) {
        this.breastOthersStr = breastOthersStr;
    }
    public String getAngiosisUndiscovered() {
        return angiosisUndiscovered;
    }
    public void setAngiosisUndiscovered(String angiosisUndiscovered) {
        this.angiosisUndiscovered = angiosisUndiscovered;
    }
    public String getBloodPressureLeftD() {
        return bloodPressureLeftD;
    }
    public void setBloodPressureLeftD(String bloodPressureLeftD) {
        this.bloodPressureLeftD = bloodPressureLeftD;
    }
    public String getVulva() {
        return vulva;
    }
    public void setVulva(String vulva) {
        this.vulva = vulva;
    }
    public String getRenalFunctionBun() {
        return renalFunctionBun;
    }
    public void setRenalFunctionBun(String renalFunctionBun) {
        this.renalFunctionBun = renalFunctionBun;
    }
    public String getCvdSah() {
        return cvdSah;
    }
    public void setCvdSah(String cvdSah) {
        this.cvdSah = cvdSah;
    }
    public String getSclera() {
        return sclera;
    }
    public void setSclera(String sclera) {
        this.sclera = sclera;
    }
    public String getKet() {
        return ket;
    }
    public void setKet(String ket) {
        this.ket = ket;
    }
    public String getRenalFunctionCreatinine() {
        return renalFunctionCreatinine;
    }
    public void setRenalFunctionCreatinine(String renalFunctionCreatinine) {
        this.renalFunctionCreatinine = renalFunctionCreatinine;
    }
    public String getAudition() {
        return audition;
    }
    public void setAudition(String audition) {
        this.audition = audition;
    }
    public String getMiniMentalStateExamination() {
        return miniMentalStateExamination;
    }
    public void setMiniMentalStateExamination(String miniMentalStateExamination) {
        this.miniMentalStateExamination = miniMentalStateExamination;
    }
    public String getDrinkOthers() {
        return drinkOthers;
    }
    public void setDrinkOthers(String drinkOthers) {
        this.drinkOthers = drinkOthers;
    }
    public String getHardeningFrequency() {
        return hardeningFrequency;
    }
    public void setHardeningFrequency(String hardeningFrequency) {
        this.hardeningFrequency = hardeningFrequency;
    }
    public String getOccupationalDiseaseWorkTime() {
        return occupationalDiseaseWorkTime;
    }
    public void setOccupationalDiseaseWorkTime(String occupationalDiseaseWorkTime) {
        this.occupationalDiseaseWorkTime = occupationalDiseaseWorkTime;
    }
    public String getAsymptomatic() {
        return asymptomatic;
    }
    public void setAsymptomatic(String asymptomatic) {
        this.asymptomatic = asymptomatic;
    }
    public String getAbdoHepatomegaly() {
        return abdoHepatomegaly;
    }
    public void setAbdoHepatomegaly(String abdoHepatomegaly) {
        this.abdoHepatomegaly = abdoHepatomegaly;
    }
    public String getFastingPlasmaGlucoseL() {
        return fastingPlasmaGlucoseL;
    }
    public void setFastingPlasmaGlucoseL(String fastingPlasmaGlucoseL) {
        this.fastingPlasmaGlucoseL = fastingPlasmaGlucoseL;
    }
    public String getVisionRightEye() {
        return visionRightEye;
    }
    public void setVisionRightEye(String visionRightEye) {
        this.visionRightEye = visionRightEye;
    }
    public String getSymptomBreastBursting() {
        return symptomBreastBursting;
    }
    public void setSymptomBreastBursting(String symptomBreastBursting) {
        this.symptomBreastBursting = symptomBreastBursting;
    }
    public String getPoisonChemicalPreStr() {
        return poisonChemicalPreStr;
    }
    public void setPoisonChemicalPreStr(String poisonChemicalPreStr) {
        this.poisonChemicalPreStr = poisonChemicalPreStr;
    }
    public String getEatHobbySugar() {
        return eatHobbySugar;
    }
    public void setEatHobbySugar(String eatHobbySugar) {
        this.eatHobbySugar = eatHobbySugar;
    }
    public String getLips() {
        return lips;
    }
    public void setLips(String lips) {
        this.lips = lips;
    }
    public String getVaginaException() {
        return vaginaException;
    }
    public void setVaginaException(String vaginaException) {
        this.vaginaException = vaginaException;
    }
    public String getEveryHardeningTime() {
        return everyHardeningTime;
    }
    public void setEveryHardeningTime(String everyHardeningTime) {
        this.everyHardeningTime = everyHardeningTime;
    }
    public String getUpcr() {
        return upcr;
    }
    public void setUpcr(String upcr) {
        this.upcr = upcr;
    }
    public String getAngiosisOthers() {
        return angiosisOthers;
    }
    public void setAngiosisOthers(String angiosisOthers) {
        this.angiosisOthers = angiosisOthers;
    }
    public String getOccupationalDisease() {
        return occupationalDisease;
    }
    public void setOccupationalDisease(String occupationalDisease) {
        this.occupationalDisease = occupationalDisease;
    }
    public String getMotorFunction() {
        return motorFunction;
    }
    public void setMotorFunction(String motorFunction) {
        this.motorFunction = motorFunction;
    }
    public String getCorporeityQiDepression() {
        return corporeityQiDepression;
    }
    public void setCorporeityQiDepression(String corporeityQiDepression) {
        this.corporeityQiDepression = corporeityQiDepression;
    }
    public String getHeartOthers() {
        return heartOthers;
    }
    public void setHeartOthers(String heartOthers) {
        this.heartOthers = heartOthers;
    }
    public String getCvdOthers() {
        return cvdOthers;
    }
    public void setCvdOthers(String cvdOthers) {
        this.cvdOthers = cvdOthers;
    }
    public String getPoisonChemical() {
        return poisonChemical;
    }
    public void setPoisonChemical(String poisonChemical) {
        this.poisonChemical = poisonChemical;
    }
    public String getLungBreathSoundExcep() {
        return lungBreathSoundExcep;
    }
    public void setLungBreathSoundExcep(String lungBreathSoundExcep) {
        this.lungBreathSoundExcep = lungBreathSoundExcep;
    }
    public String getAngiosisDa() {
        return angiosisDa;
    }
    public void setAngiosisDa(String angiosisDa) {
        this.angiosisDa = angiosisDa;
    }
    public String getCorpus() {
        return corpus;
    }
    public void setCorpus(String corpus) {
        this.corpus = corpus;
    }
    public String getCervicalPapSmears() {
        return cervicalPapSmears;
    }
    public void setCervicalPapSmears(String cervicalPapSmears) {
        this.cervicalPapSmears = cervicalPapSmears;
    }
    public String getBreastOthers() {
        return breastOthers;
    }
    public void setBreastOthers(String breastOthers) {
        this.breastOthers = breastOthers;
    }
    public String getElderlyAffectiveState() {
        return elderlyAffectiveState;
    }
    public void setElderlyAffectiveState(String elderlyAffectiveState) {
        this.elderlyAffectiveState = elderlyAffectiveState;
    }
    public String getCvdIschemicStroke() {
        return cvdIschemicStroke;
    }
    public void setCvdIschemicStroke(String cvdIschemicStroke) {
        this.cvdIschemicStroke = cvdIschemicStroke;
    }
    public String getLymphNodeRrmprt() {
        return lymphNodeRrmprt;
    }
    public void setLymphNodeRrmprt(String lymphNodeRrmprt) {
        this.lymphNodeRrmprt = lymphNodeRrmprt;
    }
    public String getIsExaminationExcep() {
        return isExaminationExcep;
    }
    public void setIsExaminationExcep(String isExaminationExcep) {
        this.isExaminationExcep = isExaminationExcep;
    }
    public String getSymptomPalpitation() {
        return symptomPalpitation;
    }
    public void setSymptomPalpitation(String symptomPalpitation) {
        this.symptomPalpitation = symptomPalpitation;
    }
    public String getHeartOthersStr() {
        return heartOthersStr;
    }
    public void setHeartOthersStr(String heartOthersStr) {
        this.heartOthersStr = heartOthersStr;
    }
    public String getHardeningMode() {
        return hardeningMode;
    }
    public void setHardeningMode(String hardeningMode) {
        this.hardeningMode = hardeningMode;
    }
    public String getCxr() {
        return cxr;
    }
    public void setCxr(String cxr) {
        this.cxr = cxr;
    }
    public String getLymphNodeNotTouch() {
        return lymphNodeNotTouch;
    }
    public void setLymphNodeNotTouch(String lymphNodeNotTouch) {
        this.lymphNodeNotTouch = lymphNodeNotTouch;
    }
    public String getLymphNodeClavicle() {
        return lymphNodeClavicle;
    }
    public void setLymphNodeClavicle(String lymphNodeClavicle) {
        this.lymphNodeClavicle = lymphNodeClavicle;
    }
    public String getElderlyHealthStatus() {
        return elderlyHealthStatus;
    }
    public void setElderlyHealthStatus(String elderlyHealthStatus) {
        this.elderlyHealthStatus = elderlyHealthStatus;
    }
    public String getOthersSystemDisease() {
        return othersSystemDisease;
    }
    public void setOthersSystemDisease(String othersSystemDisease) {
        this.othersSystemDisease = othersSystemDisease;
    }
    public String getSymptomDazzle() {
        return symptomDazzle;
    }
    public void setSymptomDazzle(String symptomDazzle) {
        this.symptomDazzle = symptomDazzle;
    }
    public String getSymptomJointGall() {
        return symptomJointGall;
    }
    public void setSymptomJointGall(String symptomJointGall) {
        this.symptomJointGall = symptomJointGall;
    }
    public String getLungBarrelChest() {
        return lungBarrelChest;
    }
    public void setLungBarrelChest(String lungBarrelChest) {
        this.lungBarrelChest = lungBarrelChest;
    }
    public String getSymptomChestPain() {
        return symptomChestPain;
    }
    public void setSymptomChestPain(String symptomChestPain) {
        this.symptomChestPain = symptomChestPain;
    }
    public String getAbdoPressPain() {
        return abdoPressPain;
    }
    public void setAbdoPressPain(String abdoPressPain) {
        this.abdoPressPain = abdoPressPain;
    }
    public String getSymptomWeightLoss() {
        return symptomWeightLoss;
    }
    public void setSymptomWeightLoss(String symptomWeightLoss) {
        this.symptomWeightLoss = symptomWeightLoss;
    }
    public String getOccDiseaseTrades() {
        return occDiseaseTrades;
    }
    public void setOccDiseaseTrades(String occDiseaseTrades) {
        this.occDiseaseTrades = occDiseaseTrades;
    }
    public String getFundamentFingerpOth() {
        return fundamentFingerpOth;
    }
    public void setFundamentFingerpOth(String fundamentFingerpOth) {
        this.fundamentFingerpOth = fundamentFingerpOth;
    }
    public String getWeight() {
        return weight;
    }
    public void setWeight(String weight) {
        this.weight = weight;
    }
    public String getSymptomUrinaryUrgency() {
        return symptomUrinaryUrgency;
    }
    public void setSymptomUrinaryUrgency(String symptomUrinaryUrgency) {
        this.symptomUrinaryUrgency = symptomUrinaryUrgency;
    }
    public String getDrinkFrequency() {
        return drinkFrequency;
    }
    public void setDrinkFrequency(String drinkFrequency) {
        this.drinkFrequency = drinkFrequency;
    }
    public String getPoisonOthersPreStr() {
        return poisonOthersPreStr;
    }
    public void setPoisonOthersPreStr(String poisonOthersPreStr) {
        this.poisonOthersPreStr = poisonOthersPreStr;
    }
    public String getDentitiondentureNormal() {
        return dentitiondentureNormal;
    }
    public void setDentitiondentureNormal(String dentitiondentureNormal) {
        this.dentitiondentureNormal = dentitiondentureNormal;
    }
    public String getGlycolatedHemoglobin() {
        return glycolatedHemoglobin;
    }
    public void setGlycolatedHemoglobin(String glycolatedHemoglobin) {
        this.glycolatedHemoglobin = glycolatedHemoglobin;
    }
    public String getBloodFatLdlc() {
        return bloodFatLdlc;
    }
    public void setBloodFatLdlc(String bloodFatLdlc) {
        this.bloodFatLdlc = bloodFatLdlc;
    }
    public String getHazardHealthDrink() {
        return hazardHealthDrink;
    }
    public void setHazardHealthDrink(String hazardHealthDrink) {
        this.hazardHealthDrink = hazardHealthDrink;
    }
    public String getOthersSystemDiseaseStr() {
        return othersSystemDiseaseStr;
    }
    public void setOthersSystemDiseaseStr(String othersSystemDiseaseStr) {
        this.othersSystemDiseaseStr = othersSystemDiseaseStr;
    }
    public String getPoisonOthersIspre() {
        return poisonOthersIspre;
    }
    public void setPoisonOthersIspre(String poisonOthersIspre) {
        this.poisonOthersIspre = poisonOthersIspre;
    }
    public String getDorsumOfFootArteriopalmus() {
        return dorsumOfFootArteriopalmus;
    }
    public void setDorsumOfFootArteriopalmus(String dorsumOfFootArteriopalmus) {
        this.dorsumOfFootArteriopalmus = dorsumOfFootArteriopalmus;
    }
    public String getRenalFunctionNatremia() {
        return renalFunctionNatremia;
    }
    public void setRenalFunctionNatremia(String renalFunctionNatremia) {
        this.renalFunctionNatremia = renalFunctionNatremia;
    }
    public String getBreastMastectomy() {
        return breastMastectomy;
    }
    public void setBreastMastectomy(String breastMastectomy) {
        this.breastMastectomy = breastMastectomy;
    }
    public String getProteinuria() {
        return proteinuria;
    }
    public void setProteinuria(String proteinuria) {
        this.proteinuria = proteinuria;
    }
    public String getSymptomDysuria() {
        return symptomDysuria;
    }
    public void setSymptomDysuria(String symptomDysuria) {
        this.symptomDysuria = symptomDysuria;
    }
    public String getCorporeityTeBing() {
        return corporeityTeBing;
    }
    public void setCorporeityTeBing(String corporeityTeBing) {
        this.corporeityTeBing = corporeityTeBing;
    }
    public String getBloodFatTriglyceride() {
        return bloodFatTriglyceride;
    }
    public void setBloodFatTriglyceride(String bloodFatTriglyceride) {
        this.bloodFatTriglyceride = bloodFatTriglyceride;
    }
    public String getUrinaryOccultBlood() {
        return urinaryOccultBlood;
    }
    public void setUrinaryOccultBlood(String urinaryOccultBlood) {
        this.urinaryOccultBlood = urinaryOccultBlood;
    }
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    public String getSymptomDiarrhea() {
        return symptomDiarrhea;
    }
    public void setSymptomDiarrhea(String symptomDiarrhea) {
        this.symptomDiarrhea = symptomDiarrhea;
    }
    public String getPoisonRadiogenPreStr() {
        return poisonRadiogenPreStr;
    }
    public void setPoisonRadiogenPreStr(String poisonRadiogenPreStr) {
        this.poisonRadiogenPreStr = poisonRadiogenPreStr;
    }
    public String getAbdoSplenomegalyOth() {
        return abdoSplenomegalyOth;
    }
    public void setAbdoSplenomegalyOth(String abdoSplenomegalyOth) {
        this.abdoSplenomegalyOth = abdoSplenomegalyOth;
    }
    public String getBreastAbnormalLactation() {
        return breastAbnormalLactation;
    }
    public void setBreastAbnormalLactation(String breastAbnormalLactation) {
        this.breastAbnormalLactation = breastAbnormalLactation;
    }
    public String getDentitiondentureDentalCaries() {
        return dentitiondentureDentalCaries;
    }
    public void setDentitiondentureDentalCaries(String dentitiondentureDentalCaries) {
        this.dentitiondentureDentalCaries = dentitiondentureDentalCaries;
    }
    public String getSymptomChronicCough() {
        return symptomChronicCough;
    }
    public void setSymptomChronicCough(String symptomChronicCough) {
        this.symptomChronicCough = symptomChronicCough;
    }
    public String getSymptomOther() {
        return symptomOther;
    }
    public void setSymptomOther(String symptomOther) {
        this.symptomOther = symptomOther;
    }
    public String getStoolOccultBlood() {
        return stoolOccultBlood;
    }
    public void setStoolOccultBlood(String stoolOccultBlood) {
        this.stoolOccultBlood = stoolOccultBlood;
    }
    public String getRenalFailure() {
        return renalFailure;
    }
    public void setRenalFailure(String renalFailure) {
        this.renalFailure = renalFailure;
    }
    public String getSymptomDizziness() {
        return symptomDizziness;
    }
    public void setSymptomDizziness(String symptomDizziness) {
        this.symptomDizziness = symptomDizziness;
    }
    public String getRespiratoryRate() {
        return respiratoryRate;
    }
    public void setRespiratoryRate(String respiratoryRate) {
        this.respiratoryRate = respiratoryRate;
    }
    public String getLungRhonchusException() {
        return lungRhonchusException;
    }
    public void setLungRhonchusException(String lungRhonchusException) {
        this.lungRhonchusException = lungRhonchusException;
    }
    public String getBeginSmokingAge() {
        return beginSmokingAge;
    }
    public void setBeginSmokingAge(String beginSmokingAge) {
        this.beginSmokingAge = beginSmokingAge;
    }
    public String getAbdoMasses() {
        return abdoMasses;
    }
    public void setAbdoMasses(String abdoMasses) {
        this.abdoMasses = abdoMasses;
    }
    public String getEatMeatdietFlash() {
        return eatMeatdietFlash;
    }
    public void setEatMeatdietFlash(String eatMeatdietFlash) {
        this.eatMeatdietFlash = eatMeatdietFlash;
    }
    public String getPoisonPhysicalPreStr() {
        return poisonPhysicalPreStr;
    }
    public void setPoisonPhysicalPreStr(String poisonPhysicalPreStr) {
        this.poisonPhysicalPreStr = poisonPhysicalPreStr;
    }
    public String getRenalFunctionBloodPotassium() {
        return renalFunctionBloodPotassium;
    }
    public void setRenalFunctionBloodPotassium(String renalFunctionBloodPotassium) {
        this.renalFunctionBloodPotassium = renalFunctionBloodPotassium;
    }
    public String getPlatelet() {
        return platelet;
    }
    public void setPlatelet(String platelet) {
        this.platelet = platelet;
    }
    public String getLiverFunctionSgot() {
        return liverFunctionSgot;
    }
    public void setLiverFunctionSgot(String liverFunctionSgot) {
        this.liverFunctionSgot = liverFunctionSgot;
    }
    public String getUricAcid() {
        return uricAcid;
    }
    public void setUricAcid(String uricAcid) {
        this.uricAcid = uricAcid;
    }
    public String getRenalCgn() {
        return renalCgn;
    }
    public void setRenalCgn(String renalCgn) {
        this.renalCgn = renalCgn;
    }
    public String getAssistantInvesOth() {
        return assistantInvesOth;
    }
    public void setAssistantInvesOth(String assistantInvesOth) {
        this.assistantInvesOth = assistantInvesOth;
    }
    public String getSymptomHandFootNumbness() {
        return symptomHandFootNumbness;
    }
    public void setSymptomHandFootNumbness(String symptomHandFootNumbness) {
        this.symptomHandFootNumbness = symptomHandFootNumbness;
    }
    public String getPapilledema() {
        return papilledema;
    }
    public void setPapilledema(String papilledema) {
        this.papilledema = papilledema;
    }
    public String getEatHobbyOil() {
        return eatHobbyOil;
    }
    public void setEatHobbyOil(String eatHobbyOil) {
        this.eatHobbyOil = eatHobbyOil;
    }
    public String getSymptomTinnitus() {
        return symptomTinnitus;
    }
    public void setSymptomTinnitus(String symptomTinnitus) {
        this.symptomTinnitus = symptomTinnitus;
    }
    public String getAbdoSplenomegaly() {
        return abdoSplenomegaly;
    }
    public void setAbdoSplenomegaly(String abdoSplenomegaly) {
        this.abdoSplenomegaly = abdoSplenomegaly;
    }
    public String getRetinalHemorrhage() {
        return retinalHemorrhage;
    }
    public void setRetinalHemorrhage(String retinalHemorrhage) {
        this.retinalHemorrhage = retinalHemorrhage;
    }
    public String getCorporeityYangDeficiency() {
        return corporeityYangDeficiency;
    }
    public void setCorporeityYangDeficiency(String corporeityYangDeficiency) {
        this.corporeityYangDeficiency = corporeityYangDeficiency;
    }
    public String getLiverFunctionCb() {
        return liverFunctionCb;
    }
    public void setLiverFunctionCb(String liverFunctionCb) {
        this.liverFunctionCb = liverFunctionCb;
    }
    public String getHealthGuidanceOtherStr() {
        return healthGuidanceOtherStr;
    }
    public void setHealthGuidanceOtherStr(String healthGuidanceOtherStr) {
        this.healthGuidanceOtherStr = healthGuidanceOtherStr;
    }
    public String getPulseFrequency() {
        return pulseFrequency;
    }
    public void setPulseFrequency(String pulseFrequency) {
        this.pulseFrequency = pulseFrequency;
    }
    public String getElderlyDepressionCheck() {
        return elderlyDepressionCheck;
    }
    public void setElderlyDepressionCheck(String elderlyDepressionCheck) {
        this.elderlyDepressionCheck = elderlyDepressionCheck;
    }
    public String getDryOutAge() {
        return dryOutAge;
    }
    public void setDryOutAge(String dryOutAge) {
        this.dryOutAge = dryOutAge;
    }
    public String getSmokingCircumstance() {
        return smokingCircumstance;
    }
    public void setSmokingCircumstance(String smokingCircumstance) {
        this.smokingCircumstance = smokingCircumstance;
    }
    public String getHeartUndiscovered() {
        return heartUndiscovered;
    }
    public void setHeartUndiscovered(String heartUndiscovered) {
        this.heartUndiscovered = heartUndiscovered;
    }
    public String getCvdUndiscovered() {
        return cvdUndiscovered;
    }
    public void setCvdUndiscovered(String cvdUndiscovered) {
        this.cvdUndiscovered = cvdUndiscovered;
    }
    public String getDrinkRedWine() {
        return drinkRedWine;
    }
    public void setDrinkRedWine(String drinkRedWine) {
        this.drinkRedWine = drinkRedWine;
    }
    public String getEyeDiseaseOthers() {
        return eyeDiseaseOthers;
    }
    public void setEyeDiseaseOthers(String eyeDiseaseOthers) {
        this.eyeDiseaseOthers = eyeDiseaseOthers;
    }
    public String getQuitSmokingAge() {
        return quitSmokingAge;
    }
    public void setQuitSmokingAge(String quitSmokingAge) {
        this.quitSmokingAge = quitSmokingAge;
    }
    public String getCardiacSouffleOthers() {
        return cardiacSouffleOthers;
    }
    public void setCardiacSouffleOthers(String cardiacSouffleOthers) {
        this.cardiacSouffleOthers = cardiacSouffleOthers;
    }
    public String getHazardOthersStr() {
        return hazardOthersStr;
    }
    public void setHazardOthersStr(String hazardOthersStr) {
        this.hazardOthersStr = hazardOthersStr;
    }
    public String getScleraOthers() {
        return scleraOthers;
    }
    public void setScleraOthers(String scleraOthers) {
        this.scleraOthers = scleraOthers;
    }
    public String getLungRhonchus() {
        return lungRhonchus;
    }
    public void setLungRhonchus(String lungRhonchus) {
        this.lungRhonchus = lungRhonchus;
    }
    public String getUrineRoutineOthers() {
        return urineRoutineOthers;
    }
    public void setUrineRoutineOthers(String urineRoutineOthers) {
        this.urineRoutineOthers = urineRoutineOthers;
    }
    public String getSymptomHeadache() {
        return symptomHeadache;
    }
    public void setSymptomHeadache(String symptomHeadache) {
        this.symptomHeadache = symptomHeadache;
    }
    public String getEatVegetarianFlash() {
        return eatVegetarianFlash;
    }
    public void setEatVegetarianFlash(String eatVegetarianFlash) {
        this.eatVegetarianFlash = eatVegetarianFlash;
    }
    public String getCvdOthersStr() {
        return cvdOthersStr;
    }
    public void setCvdOthersStr(String cvdOthersStr) {
        this.cvdOthersStr = cvdOthersStr;
    }
    public String getSymptomConstipation() {
        return symptomConstipation;
    }
    public void setSymptomConstipation(String symptomConstipation) {
        this.symptomConstipation = symptomConstipation;
    }
    public String getBreastNotTroubleFind() {
        return breastNotTroubleFind;
    }
    public void setBreastNotTroubleFind(String breastNotTroubleFind) {
        this.breastNotTroubleFind = breastNotTroubleFind;
    }
    public String getPoisonRadiogen() {
        return poisonRadiogen;
    }
    public void setPoisonRadiogen(String poisonRadiogen) {
        this.poisonRadiogen = poisonRadiogen;
    }
    public String getLeukocyte() {
        return leukocyte;
    }
    public void setLeukocyte(String leukocyte) {
        this.leukocyte = leukocyte;
    }
    public String getWaist() {
        return waist;
    }
    public void setWaist(String waist) {
        this.waist = waist;
    }
    public String getCvdCerebralHemorrhage() {
        return cvdCerebralHemorrhage;
    }
    public void setCvdCerebralHemorrhage(String cvdCerebralHemorrhage) {
        this.cvdCerebralHemorrhage = cvdCerebralHemorrhage;
    }
    public String getCorpusException() {
        return corpusException;
    }
    public void setCorpusException(String corpusException) {
        this.corpusException = corpusException;
    }
    public String getAbdoShiftingDullOth() {
        return abdoShiftingDullOth;
    }
    public void setAbdoShiftingDullOth(String abdoShiftingDullOth) {
        this.abdoShiftingDullOth = abdoShiftingDullOth;
    }
    public String getNervousSystemDiseaseStr() {
        return nervousSystemDiseaseStr;
    }
    public void setNervousSystemDiseaseStr(String nervousSystemDiseaseStr) {
        this.nervousSystemDiseaseStr = nervousSystemDiseaseStr;
    }
    public String getDrinkOthersStr() {
        return drinkOthersStr;
    }
    public void setDrinkOthersStr(String drinkOthersStr) {
        this.drinkOthersStr = drinkOthersStr;
    }
    public String getSkin() {
        return skin;
    }
    public void setSkin(String skin) {
        this.skin = skin;
    }
    public String getCervicalPapSmearsExcep() {
        return cervicalPapSmearsExcep;
    }
    public void setCervicalPapSmearsExcep(String cervicalPapSmearsExcep) {
        this.cervicalPapSmearsExcep = cervicalPapSmearsExcep;
    }
    public String getHealthGuidanceInhospital() {
        return healthGuidanceInhospital;
    }
    public void setHealthGuidanceInhospital(String healthGuidanceInhospital) {
        this.healthGuidanceInhospital = healthGuidanceInhospital;
    }
    public String getHazardOthers() {
        return hazardOthers;
    }
    public void setHazardOthers(String hazardOthers) {
        this.hazardOthers = hazardOthers;
    }
    public String getHealthRegularFollowUp() {
        return healthRegularFollowUp;
    }
    public void setHealthRegularFollowUp(String healthRegularFollowUp) {
        this.healthRegularFollowUp = healthRegularFollowUp;
    }
    public String getHazardVaccination() {
        return hazardVaccination;
    }
    public void setHazardVaccination(String hazardVaccination) {
        this.hazardVaccination = hazardVaccination;
    }
    public String getPoisonChemicalIspre() {
        return poisonChemicalIspre;
    }
    public void setPoisonChemicalIspre(String poisonChemicalIspre) {
        this.poisonChemicalIspre = poisonChemicalIspre;
    }
    public String getAbdoPressPainOth() {
        return abdoPressPainOth;
    }
    public void setAbdoPressPainOth(String abdoPressPainOth) {
        this.abdoPressPainOth = abdoPressPainOth;
    }
    public String getHealthGuidanceSlowDisease() {
        return healthGuidanceSlowDisease;
    }
    public void setHealthGuidanceSlowDisease(String healthGuidanceSlowDisease) {
        this.healthGuidanceSlowDisease = healthGuidanceSlowDisease;
    }
    public String getBloodPressureRigthD() {
        return bloodPressureRigthD;
    }
    public void setBloodPressureRigthD(String bloodPressureRigthD) {
        this.bloodPressureRigthD = bloodPressureRigthD;
    }
    public String getCervix() {
        return cervix;
    }
    public void setCervix(String cervix) {
        this.cervix = cervix;
    }
    public String getPoisonDustIspre() {
        return poisonDustIspre;
    }
    public void setPoisonDustIspre(String poisonDustIspre) {
        this.poisonDustIspre = poisonDustIspre;
    }
    public String getBreastMasses() {
        return breastMasses;
    }
    public void setBreastMasses(String breastMasses) {
        this.breastMasses = breastMasses;
    }
    public String getAttachmentException() {
        return attachmentException;
    }
    public void setAttachmentException(String attachmentException) {
        this.attachmentException = attachmentException;
    }
    public String getNervousSystemDisease() {
        return nervousSystemDisease;
    }
    public void setNervousSystemDisease(String nervousSystemDisease) {
        this.nervousSystemDisease = nervousSystemDisease;
    }
    public String getHazardHardening() {
        return hazardHardening;
    }
    public void setHazardHardening(String hazardHardening) {
        this.hazardHardening = hazardHardening;
    }
    public String getCervixException() {
        return cervixException;
    }
    public void setCervixException(String cervixException) {
        this.cervixException = cervixException;
    }
    public String getSymptomPolyuria() {
        return symptomPolyuria;
    }
    public void setSymptomPolyuria(String symptomPolyuria) {
        this.symptomPolyuria = symptomPolyuria;
    }
    public String getLungBreathSound() {
        return lungBreathSound;
    }
    public void setLungBreathSound(String lungBreathSound) {
        this.lungBreathSound = lungBreathSound;
    }
    public String getSymptomDyspnea() {
        return symptomDyspnea;
    }
    public void setSymptomDyspnea(String symptomDyspnea) {
        this.symptomDyspnea = symptomDyspnea;
    }
    public String getCxrException() {
        return cxrException;
    }
    public void setCxrException(String cxrException) {
        this.cxrException = cxrException;
    }
    public String getEveryAlcohol_tolerance() {
        return everyAlcohol_tolerance;
    }
    public void setEveryAlcohol_tolerance(String everyAlcohol_tolerance) {
        this.everyAlcohol_tolerance = everyAlcohol_tolerance;
    }
    public String getMicroalbuminuria() {
        return microalbuminuria;
    }
    public void setMicroalbuminuria(String microalbuminuria) {
        this.microalbuminuria = microalbuminuria;
    }
    public String getCorporeityYinDeficiency() {
        return corporeityYinDeficiency;
    }
    public void setCorporeityYinDeficiency(String corporeityYinDeficiency) {
        this.corporeityYinDeficiency = corporeityYinDeficiency;
    }
    public String getFundamentFingerp() {
        return fundamentFingerp;
    }
    public void setFundamentFingerp(String fundamentFingerp) {
        this.fundamentFingerp = fundamentFingerp;
    }
    public String getElderlyCognitiveFun() {
        return elderlyCognitiveFun;
    }
    public void setElderlyCognitiveFun(String elderlyCognitiveFun) {
        this.elderlyCognitiveFun = elderlyCognitiveFun;
    }
    public String getDentitiondentureMissTeeth() {
        return dentitiondentureMissTeeth;
    }
    public void setDentitiondentureMissTeeth(String dentitiondentureMissTeeth) {
        this.dentitiondentureMissTeeth = dentitiondentureMissTeeth;
    }
    public String getHbsag() {
        return hbsag;
    }
    public void setHbsag(String hbsag) {
        this.hbsag = hbsag;
    }
    public String getEyeground() {
        return eyeground;
    }
    public void setEyeground(String eyeground) {
        this.eyeground = eyeground;
    }
    public String getRenalAgn() {
        return renalAgn;
    }
    public void setRenalAgn(String renalAgn) {
        this.renalAgn = renalAgn;
    }
    public String getCardiacRhythm() {
        return cardiacRhythm;
    }
    public void setCardiacRhythm(String cardiacRhythm) {
        this.cardiacRhythm = cardiacRhythm;
    }
    public String getBmi() {
        return bmi;
    }
    public void setBmi(String bmi) {
        this.bmi = bmi;
    }
    public String getOneYearIsTemulentia() {
        return oneYearIsTemulentia;
    }
    public void setOneYearIsTemulentia(String oneYearIsTemulentia) {
        this.oneYearIsTemulentia = oneYearIsTemulentia;
    }
    public String getCorporeityQiAsthenia() {
        return corporeityQiAsthenia;
    }
    public void setCorporeityQiAsthenia(String corporeityQiAsthenia) {
        this.corporeityQiAsthenia = corporeityQiAsthenia;
    }
    public String getPharyngealportionYes() {
        return pharyngealportionYes;
    }
    public void setPharyngealportionYes(String pharyngealportionYes) {
        this.pharyngealportionYes = pharyngealportionYes;
    }
    public String getStraightenVisionRightEye() {
        return straightenVisionRightEye;
    }
    public void setStraightenVisionRightEye(String straightenVisionRightEye) {
        this.straightenVisionRightEye = straightenVisionRightEye;
    }
    public String getSymptomExpectoration() {
        return symptomExpectoration;
    }
    public void setSymptomExpectoration(String symptomExpectoration) {
        this.symptomExpectoration = symptomExpectoration;
    }
    public String getHazardVaccinationStr() {
        return hazardVaccinationStr;
    }
    public void setHazardVaccinationStr(String hazardVaccinationStr) {
        this.hazardVaccinationStr = hazardVaccinationStr;
    }
    public String getBloodFatTc() {
        return bloodFatTc;
    }
    public void setBloodFatTc(String bloodFatTc) {
        this.bloodFatTc = bloodFatTc;
    }
    public String getSymptomChestStuffiness() {
        return symptomChestStuffiness;
    }
    public void setSymptomChestStuffiness(String symptomChestStuffiness) {
        this.symptomChestStuffiness = symptomChestStuffiness;
    }
    public String getLymphNodeOthers() {
        return lymphNodeOthers;
    }
    public void setLymphNodeOthers(String lymphNodeOthers) {
        this.lymphNodeOthers = lymphNodeOthers;
    }
    public String getBodyTemperature() {
        return bodyTemperature;
    }
    public void setBodyTemperature(String bodyTemperature) {
        this.bodyTemperature = bodyTemperature;
    }
    public String getTypeBUltrasonicExcep() {
        return typeBUltrasonicExcep;
    }
    public void setTypeBUltrasonicExcep(String typeBUltrasonicExcep) {
        this.typeBUltrasonicExcep = typeBUltrasonicExcep;
    }
    public String getImmersionFoot() {
        return immersionFoot;
    }
    public void setImmersionFoot(String immersionFoot) {
        this.immersionFoot = immersionFoot;
    }
    public String getRenalOthersStr() {
        return renalOthersStr;
    }
    public void setRenalOthersStr(String renalOthersStr) {
        this.renalOthersStr = renalOthersStr;
    }
    public String getBeginDrinkAge() {
        return beginDrinkAge;
    }
    public void setBeginDrinkAge(String beginDrinkAge) {
        this.beginDrinkAge = beginDrinkAge;
    }
    public String getSymptomNauseaVomiting() {
        return symptomNauseaVomiting;
    }
    public void setSymptomNauseaVomiting(String symptomNauseaVomiting) {
        this.symptomNauseaVomiting = symptomNauseaVomiting;
    }
    public String getCorporeityGentle() {
        return corporeityGentle;
    }
    public void setCorporeityGentle(String corporeityGentle) {
        this.corporeityGentle = corporeityGentle;
    }
    public String getCorporeityDampHeat() {
        return corporeityDampHeat;
    }
    public void setCorporeityDampHeat(String corporeityDampHeat) {
        this.corporeityDampHeat = corporeityDampHeat;
    }
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public String getVagina() {
        return vagina;
    }
    public void setVagina(String vagina) {
        this.vagina = vagina;
    }
    public String getHeartAnginaPectoris() {
        return heartAnginaPectoris;
    }
    public void setHeartAnginaPectoris(String heartAnginaPectoris) {
        this.heartAnginaPectoris = heartAnginaPectoris;
    }
    public String getUrineSugar() {
        return urineSugar;
    }
    public void setUrineSugar(String urineSugar) {
        this.urineSugar = urineSugar;
    }
    public String getPoisonRadiogenIspre() {
        return poisonRadiogenIspre;
    }
    public void setPoisonRadiogenIspre(String poisonRadiogenIspre) {
        this.poisonRadiogenIspre = poisonRadiogenIspre;
    }
    public String getDrinkWhiteSpirits() {
        return drinkWhiteSpirits;
    }
    public void setDrinkWhiteSpirits(String drinkWhiteSpirits) {
        this.drinkWhiteSpirits = drinkWhiteSpirits;
    }
    public String getBloodPressureRigthU() {
        return bloodPressureRigthU;
    }
    public void setBloodPressureRigthU(String bloodPressureRigthU) {
        this.bloodPressureRigthU = bloodPressureRigthU;
    }
    public String getLiverFunctionAlbumin() {
        return liverFunctionAlbumin;
    }
    public void setLiverFunctionAlbumin(String liverFunctionAlbumin) {
        this.liverFunctionAlbumin = liverFunctionAlbumin;
    }
    public String getVisionLeftEye() {
        return visionLeftEye;
    }
    public void setVisionLeftEye(String visionLeftEye) {
        this.visionLeftEye = visionLeftEye;
    }
    public String getStraightenVisionLeftEye() {
        return straightenVisionLeftEye;
    }
    public void setStraightenVisionLeftEye(String straightenVisionLeftEye) {
        this.straightenVisionLeftEye = straightenVisionLeftEye;
    }
    public String getHeartRate() {
        return heartRate;
    }
    public void setHeartRate(String heartRate) {
        this.heartRate = heartRate;
    }
    public String getSymptomPolydipsia() {
        return symptomPolydipsia;
    }
    public void setSymptomPolydipsia(String symptomPolydipsia) {
        this.symptomPolydipsia = symptomPolydipsia;
    }
    public String getBloodPressureLeftU() {
        return bloodPressureLeftU;
    }
    public void setBloodPressureLeftU(String bloodPressureLeftU) {
        this.bloodPressureLeftU = bloodPressureLeftU;
    }
    public String getPhysicalExaminationOth() {
        return physicalExaminationOth;
    }
    public void setPhysicalExaminationOth(String physicalExaminationOth) {
        this.physicalExaminationOth = physicalExaminationOth;
    }
    public String getDailySmokingQuantity() {
        return dailySmokingQuantity;
    }
    public void setDailySmokingQuantity(String dailySmokingQuantity) {
        this.dailySmokingQuantity = dailySmokingQuantity;
    }
    public String getDrinkYellowWine() {
        return drinkYellowWine;
    }
    public void setDrinkYellowWine(String drinkYellowWine) {
        this.drinkYellowWine = drinkYellowWine;
    }
    public String getDrinkBeer() {
        return drinkBeer;
    }
    public void setDrinkBeer(String drinkBeer) {
        this.drinkBeer = drinkBeer;
    }
    public String getEatHobbySalt() {
        return eatHobbySalt;
    }
    public void setEatHobbySalt(String eatHobbySalt) {
        this.eatHobbySalt = eatHobbySalt;
    }
    public String getPharyngealportionAdd() {
        return pharyngealportionAdd;
    }
    public void setPharyngealportionAdd(String pharyngealportionAdd) {
        this.pharyngealportionAdd = pharyngealportionAdd;
    }
    public String getSymptomOtherStr() {
        return symptomOtherStr;
    }
    public void setSymptomOtherStr(String symptomOtherStr) {
        this.symptomOtherStr = symptomOtherStr;
    }
    public String getElderlySelfCare() {
        return elderlySelfCare;
    }
    public void setElderlySelfCare(String elderlySelfCare) {
        this.elderlySelfCare = elderlySelfCare;
    }
    public String getDentitiondentureDenture() {
        return dentitiondentureDenture;
    }
    public void setDentitiondentureDenture(String dentitiondentureDenture) {
        this.dentitiondentureDenture = dentitiondentureDenture;
    }
    public String getAngiosisOthersStr() {
        return angiosisOthersStr;
    }
    public void setAngiosisOthersStr(String angiosisOthersStr) {
        this.angiosisOthersStr = angiosisOthersStr;
    }
    public String getEyeDiseaseOthersStr() {
        return eyeDiseaseOthersStr;
    }
    public void setEyeDiseaseOthersStr(String eyeDiseaseOthersStr) {
        this.eyeDiseaseOthersStr = eyeDiseaseOthersStr;
    }
    public String getHazardQuitSmocking() {
        return hazardQuitSmocking;
    }
    public void setHazardQuitSmocking(String hazardQuitSmocking) {
        this.hazardQuitSmocking = hazardQuitSmocking;
    }
    public String getSymptomLackOfPower() {
        return symptomLackOfPower;
    }
    public void setSymptomLackOfPower(String symptomLackOfPower) {
        this.symptomLackOfPower = symptomLackOfPower;
    }
    public String getLymphNode() {
        return lymphNode;
    }
    public void setLymphNode(String lymphNode) {
        this.lymphNode = lymphNode;
    }
    public String getAngiosisOcclusionArteries() {
        return angiosisOcclusionArteries;
    }
    public void setAngiosisOcclusionArteries(String angiosisOcclusionArteries) {
        this.angiosisOcclusionArteries = angiosisOcclusionArteries;
    }
    public String getHemoglobin() {
        return hemoglobin;
    }
    public void setHemoglobin(String hemoglobin) {
        this.hemoglobin = hemoglobin;
    }
    public String getEyeDiseaseUndiscovered() {
        return eyeDiseaseUndiscovered;
    }
    public void setEyeDiseaseUndiscovered(String eyeDiseaseUndiscovered) {
        this.eyeDiseaseUndiscovered = eyeDiseaseUndiscovered;
    }
    public String getInsistHardeningTime() {
        return insistHardeningTime;
    }
    public void setInsistHardeningTime(String insistHardeningTime) {
        this.insistHardeningTime = insistHardeningTime;
    }
    public String getRenalUndiscovered() {
        return renalUndiscovered;
    }
    public void setRenalUndiscovered(String renalUndiscovered) {
        this.renalUndiscovered = renalUndiscovered;
    }
    public String getAttachment() {
        return attachment;
    }
    public void setAttachment(String attachment) {
        this.attachment = attachment;
    }
    public String getHealthGuidanceReview() {
        return healthGuidanceReview;
    }
    public void setHealthGuidanceReview(String healthGuidanceReview) {
        this.healthGuidanceReview = healthGuidanceReview;
    }
    public String getLiverFunctionSalt() {
        return liverFunctionSalt;
    }
    public void setLiverFunctionSalt(String liverFunctionSalt) {
        this.liverFunctionSalt = liverFunctionSalt;
    }
    public String getCvdTia() {
        return cvdTia;
    }
    public void setCvdTia(String cvdTia) {
        this.cvdTia = cvdTia;
    }
    public String getMedicalTime() {
        return medicalTime;
    }
    public void setMedicalTime(String medicalTime) {
        this.medicalTime = medicalTime;
    }
    public String getHazardFood() {
        return hazardFood;
    }
    public void setHazardFood(String hazardFood) {
        this.hazardFood = hazardFood;
    }
    public String getSymptomBlurredVision() {
        return symptomBlurredVision;
    }
    public void setSymptomBlurredVision(String symptomBlurredVision) {
        this.symptomBlurredVision = symptomBlurredVision;
    }
    public String getCorporeityPhlegmDamp() {
        return corporeityPhlegmDamp;
    }
    public void setCorporeityPhlegmDamp(String corporeityPhlegmDamp) {
        this.corporeityPhlegmDamp = corporeityPhlegmDamp;
    }
    public String getHazardLoseWeightTarget() {
        return hazardLoseWeightTarget;
    }
    public void setHazardLoseWeightTarget(String hazardLoseWeightTarget) {
        this.hazardLoseWeightTarget = hazardLoseWeightTarget;
    }
    public String getPoisonPhysicalIspre() {
        return poisonPhysicalIspre;
    }
    public void setPoisonPhysicalIspre(String poisonPhysicalIspre) {
        this.poisonPhysicalIspre = poisonPhysicalIspre;
    }
    public String getCorporeityHaemostasis() {
        return corporeityHaemostasis;
    }
    public void setCorporeityHaemostasis(String corporeityHaemostasis) {
        this.corporeityHaemostasis = corporeityHaemostasis;
    }
    public String getHeartCoronaryArtery() {
        return heartCoronaryArtery;
    }
    public void setHeartCoronaryArtery(String heartCoronaryArtery) {
        this.heartCoronaryArtery = heartCoronaryArtery;
    }
    public String getPoisonDust() {
        return poisonDust;
    }
    public void setPoisonDust(String poisonDust) {
        this.poisonDust = poisonDust;
    }
    public String getPharyngealportionNo() {
        return pharyngealportionNo;
    }
    public void setPharyngealportionNo(String pharyngealportionNo) {
        this.pharyngealportionNo = pharyngealportionNo;
    }
    public String getEatClitocybineEqualization() {
        return eatClitocybineEqualization;
    }
    public void setEatClitocybineEqualization(String eatClitocybineEqualization) {
        this.eatClitocybineEqualization = eatClitocybineEqualization;
    }
    public String getHeartMyocardialInfarction() {
        return heartMyocardialInfarction;
    }
    public void setHeartMyocardialInfarction(String heartMyocardialInfarction) {
        this.heartMyocardialInfarction = heartMyocardialInfarction;
    }
    public String getElectrocardiogramExcep() {
        return electrocardiogramExcep;
    }
    public void setElectrocardiogramExcep(String electrocardiogramExcep) {
        this.electrocardiogramExcep = electrocardiogramExcep;
    }
    public String getMedicalInfoId() {
        return medicalInfoId;
    }
    public void setMedicalInfoId(String medicalInfoId) {
        this.medicalInfoId = medicalInfoId;
    }
//    public List<String> getInhospitalList() {
//        return inhospitalList;
//    }
//
//    public void setInhospitalList(List<String> inhospitalList) {
//        this.inhospitalList = inhospitalList;
//    }
    public List<String> getFpList() {
        return fpList;
    }
    public void setFpList(List<String> fpList) {
        this.fpList = fpList;
    }
    public List<String> getExaminationList() {
        return examinationList;
    }
    public void setExaminationList(List<String> examinationList) {
        this.examinationList = examinationList;
    }
//    public List<String> getNiVaccinationList() {
//        return niVaccinationList;
//    }
//
//    public void setNiVaccinationList(List<String> niVaccinationList) {
//        this.niVaccinationList = niVaccinationList;
//    }
//    public String[] getDrugList() {
//        return drugList;
//    }
//
//    public void setDrugList(String[] drugList) {
//        this.drugList = drugList;
//    }
    public String getMedicalNo() {
        return medicalNo;
    }
    public void setMedicalNo(String medicalNo) {
        this.medicalNo = medicalNo;
    }
}

+ 44 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/vo/MedicalQvo.java

@ -0,0 +1,44 @@
package com.yihu.jw.hospital.endpoint.health.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * @author suqinyi
 * @Date 2023/6/9
 */
@ApiModel(description = "查询Qvo")
public class MedicalQvo {
    @ApiModelProperty(value = "地区编码")
    private String areaCode;
    @ApiModelProperty(value = "patientId")
    private String patientId;
    @ApiModelProperty(value = "是否测试")
    private String g;
    public String getAreaCode() {
        return areaCode;
    }
    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }
    public String getPatientId() {
        return patientId;
    }
    public void setPatientId(String patientId) {
        this.patientId = patientId;
    }
    public String getG() {
        return g;
    }
    public void setG(String g) {
        this.g = g;
    }
}

+ 46 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/health/vo/MedicalVo.java

@ -0,0 +1,46 @@
package com.yihu.jw.hospital.endpoint.health.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * @author suqinyi
 * @Date 2023/6/9
 */
@ApiModel(description = "体检vo")
public class MedicalVo {
    @ApiModelProperty(value = "机构名称", required = true, access = "response")
    private String orgName;
    @ApiModelProperty(value = "体检id", required = true, access = "response")
    private String medicalNo;
    @ApiModelProperty(value = "体检时间", required = true, access = "response")
    private String medicalTime;
    public String getOrgName() {
        return orgName;
    }
    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }
    public String getMedicalNo() {
        return medicalNo;
    }
    public void setMedicalNo(String medicalNo) {
        this.medicalNo = medicalNo;
    }
    public String getMedicalTime() {
        return medicalTime;
    }
    public void setMedicalTime(String medicalTime) {
        this.medicalTime = medicalTime;
    }
}

+ 340 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/manbing/ChronicDiseaseController.java

@ -0,0 +1,340 @@
package com.yihu.jw.hospital.endpoint.manbing;
import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodPressureVO;
import com.yihu.jw.entity.scheme.vo.DoctorSchemeBloodSuggerVO;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.scheme.DoctorSchemeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
/**
 * @author suqinyi
 * @Date 2024/2/26
 */
@RestController
@RequestMapping(value = "/doctor/scheme")
@Api(value = "慢病管理", description = "慢病管理", tags = {"慢病管理"})
public class ChronicDiseaseController extends EnvelopRestEndpoint {
    @Autowired
    private DoctorSchemeService doctorSchemeService;
    /**
     * 获取i健康的数据-同安签约居民,并且是三院关系的,有慢病的
     */
    @RequestMapping(value = "getSignPatientDataByIjk", method = RequestMethod.GET)
    @ApiOperation("获取i健康的数据-同安签约居民,并且是三院关系的,有慢病的")
    public String getSignPatientDataByIjk() {
        return null;
    }
    @RequestMapping(value = "getDoctorSwitchTrackPatient", method = RequestMethod.GET)
    @ApiOperation("医生跟踪预警居民开关接口")
    public String getDoctorSwitchTrackPatient() {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getDoctorSwitchTrackPatient(getUID()));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "setDoctorSwitchTrackPatient", method = RequestMethod.POST)
    @ApiOperation("医生跟踪预警居民开关接口")
    public String setDoctorSwitchTrackPatient(@ApiParam(name = "state", value = "0不自动跟踪居民,1自动跟踪预警居民") @RequestParam(value = "state", required = true) String state) {
        try {
            return write(200, "操作成功", "data", doctorSchemeService.setDoctorSwitchTrackPatient(getUID(), state));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/slowdisease/get/teaminfos", method = RequestMethod.GET)
    @ApiOperation("医生端-获取慢病管理居民管理端数据")
    public String getDiseasePatientCodes(
            @ApiParam(name = "doctorId", value = "医生id") @RequestParam(value = "doctorId", required = false) String doctorId,
//            @ApiParam(name = "teamCode", value = "团队CODE") @RequestParam(value = "teamCode", required = true, defaultValue = "642") String teamCode,
            @ApiParam(name = "getcolor", value = "是否获取颜色标签") @RequestParam(value = "getcolor", required = true, defaultValue = "1") int getcolor,
            @ApiParam(name = "getstands", value = "是否获取预警人数数据") @RequestParam(value = "getstands", required = true, defaultValue = "1") int getstands,
            @ApiParam(name = "gethealthindex", value = "是否获取体征数据") @RequestParam(value = "gethealthindex", required = true, defaultValue = "1") int gethealthindex,
            @ApiParam(name = "startdate", value = "体征数据开始时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "startdate", required = false, defaultValue = "2017-9-10 00:00:00") String startdate,
            @ApiParam(name = "enddate", value = "体征数据结束时间yyyy-mm-dd hh:mm:ss") @RequestParam(value = "enddate", required = false, defaultValue = "2017-9-16 23:59:59") String enddate) {
        try {
//            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(teamCode, getcolor, getstands, gethealthindex, startdate, enddate, getUID());
            if (StringUtils.isBlank(doctorId)){
                doctorId=getUID();
            }
            com.alibaba.fastjson.JSONObject result = doctorSchemeService.getSlowDiseaseTeaminfos(doctorId, getcolor, getstands, gethealthindex, startdate, enddate, getUID());
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/get/disease/patientcodes", method = RequestMethod.GET)
    @ApiOperation("医生端-根据居民标签/病情/设备绑定状态查询团队居民CODE列表")
    public String getDiseasePatientCodes(
            @ApiParam(name = "teamCode", value = "团队CODE") @RequestParam(value = "teamCode", required = true, defaultValue = "642") String teamCode,
            @ApiParam(name = "disease", value = "疾病类型,-1全部,0健康,1高血压,2糖尿病,3高血压+糖尿病", defaultValue = "-1") @RequestParam(value = "disease", required = true) Integer disease,
            @ApiParam(name = "diseaseCondition", value = "居民标签:0绿标,1黄标,2红标", defaultValue = "0,1,2") @RequestParam(value = "diseaseCondition", required = true) String diseaseCondition,
            @ApiParam(name = "deviceType", value = "设备类型:-1全部,0未绑定,1已绑定", defaultValue = "-1") @RequestParam(value = "deviceType", required = true) Integer deviceType,
            @ApiParam(name = "trackFlag", value = "过滤跟踪居民:1为过滤跟踪,不传或其他值为不过滤", defaultValue = "-1") @RequestParam(value = "trackFlag", required = false) String trackFlag
    ) {
        try {
            List<String> result = doctorSchemeService.getPatientsByDiseaseConditionDiseaseDeviceType(teamCode, disease, diseaseCondition, deviceType, getUID(), trackFlag);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/get/bloodsugger/list", method = RequestMethod.GET)
    @ApiOperation("医生获取自己的血糖监测方案列表")
    public String getDoctorSchemeBloodSuggerList(
            @ApiParam(name = "doctorcode", value = "医生CODE") @RequestParam(value = "doctorcode", required = true) String doctorcode) {
        try {
            List<DoctorSchemeBloodSuggerVO> result = doctorSchemeService.getDoctorScheBloodSuggerList(doctorcode);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            //日志文件中记录异常信息
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/get/bloodpressure/list", method = RequestMethod.GET)
    @ApiOperation("医生获取自己的血压监测方案列表")
    public String getDoctorSchemeBloodPressureList(
            @ApiParam(name = "doctorcode", value = "医生CODE") @RequestParam(value = "doctorcode", required = true) String doctorcode) {
        try {
            List<DoctorSchemeBloodPressureVO> result = doctorSchemeService.getDoctorSchemeBloodPressureList(doctorcode);
            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/post/save/bloodpressure", method = RequestMethod.POST)
    @ApiOperation("医生保存血压监测方案")
    public String saveDoctorSchemeBloodPressure(
            @ApiParam(name = "data", value = "JSON数据") @RequestParam(value = "data", required = true) String data) {
        try {
            doctorSchemeService.saveDoctorSchemeBloodPressure(data);
            return write(200, "操作成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/post/save/bloodsugger", method = RequestMethod.POST)
    @ApiOperation("医生保存血糖监测方案")
    public String saveDoctorSchemeBloodSugger(
            @ApiParam(name = "data", value = "JSON数据") @RequestParam(value = "data", required = true) String data) {
        try {
            doctorSchemeService.saveDoctorSchemeBloodSugger(data);
            return write(200, "操作成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/post/save/patient/scheme", method = RequestMethod.POST)
    @ApiOperation("医生保存居民的血糖监测方案")
    public String savePatientScheme(
            @ApiParam(name = "doctorcode", value = "医生CODE") @RequestParam(value = "doctorcode", required = true) String doctorcode,
            @ApiParam(name = "schemecode", value = "方案CODE") @RequestParam(value = "schemecode", required = true) String schemecode,
            @ApiParam(name = "type", value = "血糖1、血压2") @RequestParam(value = "type", required = true) String type,
            @ApiParam(name = "patientcodes", value = "用户CODE,多个用逗号拼接") @RequestParam(value = "patientcodes", required = true) String patientcodes) {
        try {
            doctorSchemeService.savePatientScheme(doctorcode, schemecode, type, patientcodes);
            return write(200, "操作成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "/post/del/scheme", method = RequestMethod.POST)
    @ApiOperation("医生删除监测方案")
    public String doctorDelScheme(
            @ApiParam(name = "schemecode", value = "方案CODE") @RequestParam(value = "schemecode", required = true) String schemecode,
            @ApiParam(name = "type", value = "血糖1、血压2") @RequestParam(value = "type", required = true) String type,
            @ApiParam(name = "doctorcode", value = "医生CODE") @RequestParam(value = "doctorcode", required = true) String doctorcode) {
        try {
            doctorSchemeService.delDoctorScheme(doctorcode, schemecode, type);
            return write(200, "操作成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getPatientHealthIndex", method = RequestMethod.GET)
    @ApiOperation("获取最近一周血糖情况/血压情况")
    public String getPatientHealthIndex(@ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient,
                                        @ApiParam(name = "startDate", value = "开始时间,YYYY-MM-dd") @RequestParam(value = "startDate", required = true) String startDate,
                                        @ApiParam(name = "endDate", value = "结束时间,YYYY-MM-dd") @RequestParam(value = "endDate", required = true) String endDate,
                                        @ApiParam(name = "type", value = "0血糖,1.血压") @RequestParam(value = "type", required = true) String type) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getPatientHealthIndex(patient, startDate, endDate, type));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getTrackPatientInfo", method = RequestMethod.GET)
    @ApiOperation("获取:微信运动,身高体重,血糖监测方案,血压监测方案")
    public String getTrackPatientInfo(@ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientInfo(patient));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getControlObjectives", method = RequestMethod.GET)
    @ApiOperation("获取控制目标,血压,血糖")
    public String getControlObjectives(@ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getControlObjectives(patient));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getBodyInfo", method = RequestMethod.GET)
    @ApiOperation("获取身高体重详情列表")
    public String getBodyInfo(@ApiParam(name = "patient", value = "居民code") @RequestParam(value = "patient", required = true) String patient,
                              @ApiParam(name = "startDate", value = "开始时间,YYYY-MM-dd") @RequestParam(value = "startDate", required = true) String startDate,
                              @ApiParam(name = "endDate", value = "结束时间,YYYY—MM-dd") @RequestParam(value = "endDate", required = true) String endDate,
                              @ApiParam(name = "page", value = "起始页") @RequestParam(value = "page", required = true) Integer page,
                              @ApiParam(name = "size", value = "每页大小") @RequestParam(value = "size", required = true) Integer size) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getBodyInfo(patient, startDate, endDate, page, size));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getTrackPatientCountTitle", method = RequestMethod.GET)
    @ApiOperation("获取重点跟踪居民数,近一周增加数")
    public String getTrackPatientCountTitle(@ApiParam(name = "teamCode", value = "团队ID") @RequestParam(value = "teamCode", required = true) Integer teamCode,
                                            @ApiParam(name = "startDate", value = "开始时间") @RequestParam(value = "startDate", required = true) String startDate,
                                            @ApiParam(name = "endDate", value = "结束时间") @RequestParam(value = "endDate", required = true) String endDate) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientCountTitle(teamCode, getUID(), startDate, endDate));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getTrackPatientServerCount", method = RequestMethod.GET)
    @ApiOperation("团队医生下,居民近一周服务情况接口")
    public String getTrackPatientServerCount(@ApiParam(name = "teamCode", value = "团队ID") @RequestParam(value = "teamCode", required = true) Long teamCode,
                                             @ApiParam(name = "startDate", value = "开始时间") @RequestParam(value = "startDate", required = true) String startDate,
                                             @ApiParam(name = "endDate", value = "结束时间") @RequestParam(value = "endDate", required = true) String endDate) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientServerCount(teamCode, getUID(), startDate, endDate));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getPatientHealthIndexByTeam", method = RequestMethod.GET)
    @ApiOperation("获取医生团队最近一周血糖情况/血压情况")
    public String getPatientHealthIndexByTeam(@ApiParam(name = "startDate", value = "开始时间,YYYY-MM-dd") @RequestParam(value = "startDate", required = true) String startDate,
                                              @ApiParam(name = "endDate", value = "结束时间,YYYY-MM-dd") @RequestParam(value = "endDate", required = true) String endDate,
                                              @ApiParam(name = "type", value = "0血糖,1.血压") @RequestParam(value = "type", required = true) String type,
                                              @ApiParam(name = "teamCode", value = "团队code") @RequestParam(value = "teamCode", required = true) Long teamCode) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getPatientHealthIndex(startDate, endDate, type, teamCode, getUID()));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getTrackPatientAimByteam", method = RequestMethod.GET)
    @ApiOperation(" 获取团队医生下,居民近一周控制目标情况")
    public String getTrackPatientAimByteam(@ApiParam(name = "teamCode", value = "团队Code") @RequestParam(value = "teamCode", required = true) Long teamCode,
                                           @ApiParam(name = "startDate", value = "开始时间,YYYY-MM-dd") @RequestParam(value = "startDate", required = true) String startDate,
                                           @ApiParam(name = "endDate", value = "结束时间,YYYY-MM-dd") @RequestParam(value = "endDate", required = true) String endDate) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientAimByteam(getUID(), teamCode, startDate, endDate));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getDeviceStateByTeam", method = RequestMethod.GET)
    @ApiOperation("获取团队医生下,居民设备绑定情况")
    public String getDeviceStateByTeam(@ApiParam(name = "teamCode", value = "团队Code") @RequestParam(value = "teamCode", required = true) Long teamCode) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getDeviceStateByTeam(getUID(), teamCode));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "setPatientAim", method = RequestMethod.POST)
    @ApiOperation("批量控制目标设置")
    public String setPatientAim(@ApiParam(name = "patient", value = "患者code,用“,”分割") @RequestParam(value = "patient", required = true) String patient,
                                @ApiParam(name = "suggerJson", value = "血糖目标实体") @RequestParam(value = "suggerJson", required = true) String suggerJson,
                                @ApiParam(name = "pressureJson", value = "血压目标实体") @RequestParam(value = "pressureJson", required = true) String pressureJson,
                                @ApiParam(name = "sportJson", value = "运动目标实体") @RequestParam(value = "sportJson", required = true) String sportJson) {
        try {
            return write(200, "操作成功", "data", doctorSchemeService.setPatientAim(patient, suggerJson, pressureJson, sportJson));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "setSinglePatientAim", method = RequestMethod.POST)
    @ApiOperation("批量控制目标设置")
    public String setSinglePatientAim(@ApiParam(name = "patient", value = "患者code") @RequestParam(value = "patient", required = true) String patient,
                                      @ApiParam(name = "suggerJson", value = "血糖目标实体") @RequestParam(value = "suggerJson", required = true) String suggerJson,
                                      @ApiParam(name = "pressureJson", value = "血压目标实体") @RequestParam(value = "pressureJson", required = true) String pressureJson,
                                      @ApiParam(name = "sportJson", value = "运动目标实体") @RequestParam(value = "sportJson", required = true) String sportJson) {
        try {
            return write(200, "操作成功", "data", doctorSchemeService.setSinglePatientAim(patient, suggerJson, pressureJson, sportJson));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @RequestMapping(value = "getTrackPatientIndexCountList", method = RequestMethod.GET)
    @ApiOperation("获取关注居民测量数据列表")
    public String getTrackPatientIndexCountList(@ApiParam(name = "teamCode", value = "团队ID") @RequestParam(value = "teamCode", required = true) Integer teamCode,
                                                @ApiParam(name = "type", value = "1.糖尿病,其他为高血压") @RequestParam(value = "type", required = true) String type,
                                                @ApiParam(name = "startDate", value = "开始时间,YYYY-MM-dd") @RequestParam(value = "startDate", required = true) String startDate,
                                                @ApiParam(name = "endDate", value = "结束时间,YYYY-MM-dd") @RequestParam(value = "endDate", required = true) String endDate,
                                                @ApiParam(name = "keyword", value = "姓名模糊匹配,身份证号") @RequestParam(value = "keyword", required = false) String keyword,
                                                @ApiParam(name = "page", value = "起始页,1开始") @RequestParam(value = "page", required = true) Integer page,
                                                @ApiParam(name = "size", value = "每页大小") @RequestParam(value = "size", required = true) Integer size) {
        try {
            return write(200, "查询成功", "data", doctorSchemeService.getTrackPatientIndexCountList(getUID(), teamCode, type, startDate, endDate, keyword, page, size));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    // --------------------------------------------------------
}

+ 38 - 0
svr/svr-internet-hospital/src/main/java/com/yihu/jw/hospital/endpoint/statistics/EsStatisticsEndpoint.java

@ -1843,6 +1843,44 @@ class EsStatisticsEndpoint extends EnvelopRestEndpoint {
    }
    /**
     * 获取同安签约的慢病数据
     *  /wlyygc/tongan/hospital/getChronicDiseaseData
     */
    @GetMapping(value = "/getChronicDiseaseData")
    @ApiOperation(value = "获取同安签约的慢病数据")
    public Envelop getChronicDiseaseData() {
        try {
            System.out.println("调用==>获取同安签约的慢病数据");
            Map<String, Object> result = statisticsEsService.getChronicDiseaseData();
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("系统繁忙");
        }
    }
    /**
     * 将i健康慢病签约数据创建成用户
     */
    @GetMapping(value = "/createPatient")
    @ApiOperation(value = "将i健康慢病签约数据创建成用户")
    public Envelop createPatient() {
        try {
            System.out.println("调用==>将i健康慢病签约数据创建成用户");
            Map<String, Object> result = statisticsEsService.getChronicDiseaseData();
            Object data = result.get("data");
            //循环创建用户
            return success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return failed("系统繁忙");
        }
    }
}

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

@ -561,13 +561,13 @@ public class DoctorHealthController extends BaseController {
	@ApiOperation("医生保存团队下所有居民的预警方案")
	public String doctorSaveStandardByTeamCode(
			@ApiParam("团队代码") @RequestParam String teamcode,
			@ApiParam("预警值Json") @RequestParam String json) {
			@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()){
@ -596,7 +596,6 @@ public class DoctorHealthController extends BaseController {
						list.add(standard);
					}
					DoctorHealthStandard doctorHealthStandard = new DoctorHealthStandard();
					doctorHealthStandard.setDoctor(getUID());
					doctorHealthStandard.setMaxValue1(obj.has("max_value1") ? NumberUtils.toDouble(obj.getString("max_value1"), 0) : 0);
@ -620,15 +619,15 @@ public class DoctorHealthController extends BaseController {
				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,